text:
from __future__ import annotations

import os
import sys

import dynaconf

def test_djdt_382(tmpdir):
    settings_file = tmpdir.join("settings.py")
    settings_file.write("\n".join(["SECRET_KEY = 'dasfadfds2'"]))
    tmpdir.join("__init__.py").write("")
    os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
    sys.path.append(str(tmpdir))
    __import__("settings")
    settings = dynaconf.DjangoDynaconf("settings", environments=True)
    settings.configure(settings_module="settings")
    assert settings.SECRET_KEY == "dasfadfds2"
    assert settings.is_overridden("FOO") is False

def test_override_settings_596(tmpdir):
    settings_file = tmpdir.join("other_settings.py")
    settings_file.write("\n".join(["SECRET_KEY = 'abcdef'"]))
    tmpdir.join("__init__.py").write("")
    os.environ["DJANGO_SETTINGS_MODULE"] = "other_settings"
    sys.path.append(str(tmpdir))
    __import__("other_settings")
    settings = dynaconf.DjangoDynaconf("other_settings", environments=True)
    settings.configure(settings_module="other_settings")
    assert settings.SECRET_KEY == "abcdef"

    # mimic what django.test.utils.override_settings does
    class UserSettingsHolder(dynaconf.LazySettings):
        _django_override = True

    override = UserSettingsHolder(settings._wrapped)
    override.SECRET_KEY = "foobar"

    # overriden settings is changed
    assert override.SECRET_KEY == "foobar"

    # original not changed
    assert settings.SECRET_KEY == "abcdef"


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>SubcloneSeeker: SubcloneExplorer::SegmentalMutation Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

SubcloneSeeker
    1.0

Subclone deconvolution software framework

Main Page

Classes

Files

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

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Files Functions Variables Macros

Public Member Functions |
Public Attributes |
Protected Member Functions |
List of all members

SubcloneExplorer::SegmentalMutation Class Reference

Abstract data structure class that represents any segmental somatic mutation.
 More...

#include <SegmentalMutation.h>

Inheritance diagram for SubcloneExplorer::SegmentalMutation:

  <map id="SubcloneExplorer::SegmentalMutation_map" name="SubcloneExplorer::SegmentalMutation_map">
<area href="class_subclone_explorer_1_1_somatic_event.html" title="Abstract data structure class that represents any type of somatic mutation. " alt="SubcloneExplorer::SomaticEvent" shape="rect" coords="117,56,342,80"/>
<area href="class_subclone_explorer_1_1_archivable.html" title="Abstract class that defines the interface to handle archiving objects into sqlite3 database..." alt="SubcloneExplorer::Archivable" shape="rect" coords="117,0,342,24"/>
<area href="class_subclone_explorer_1_1_c_n_v.html" title="Copy Number Variation. " alt="SubcloneExplorer::CNV" shape="rect" coords="0,168,225,192"/>
<area href="class_subclone_explorer_1_1_l_o_h.html" title="Loss of Heterozygosity. " alt="SubcloneExplorer::LOH" shape="rect" coords="235,168,460,192"/>
</map>

Public Member Functions

 	SegmentalMutation ()

 Public Member Functions inherited from SubcloneExplorer::SomaticEvent

 	SomaticEvent ()

void 	setClusterID (sqlite3_int64 clusterID)

virtual bool 	isEqualTo (SomaticEvent *anotherEvent, unsigned long resolution=10000L)

sqlite3_int64 	clusterID ()

virtual DBObjectID_vec 	allObjectsOfCluster (sqlite3 *database, sqlite3_int64 clusterID)

 Public Member Functions inherited from SubcloneExplorer::Archivable

 	Archivable ()

sqlite3_int64 	getId ()

void 	setId (sqlite3_int64 nid)

bool 	createTableInDB (sqlite3 *database)

sqlite3_int64 	archiveObjectToDB (sqlite3 *database)

bool 	unarchiveObjectFromDB (sqlite3 *database, sqlite3_int64 id)

DBObjectID_vec 	vecAllObjectsID (sqlite3 *database)

Public Attributes

GenomicRange 	range

 Public Attributes inherited from SubcloneExplorer::SomaticEvent

double 	frequency

Protected Member Functions

virtual std::string 	createObjectStatementStr ()

virtual std::string 	updateObjectStatementStr ()

virtual std::string 	selectObjectColumnListStr ()

virtual int 	bindObjectToStatement (sqlite3_stmt *)

virtual void 	updateObjectFromStatement (sqlite3_stmt *)

 Protected Member Functions inherited from SubcloneExplorer::SomaticEvent

virtual std::string 	createTableStatementStr ()

 Protected Member Functions inherited from SubcloneExplorer::Archivable

virtual std::string 	getTableName ()=0

Additional Inherited Members

 Protected Attributes inherited from SubcloneExplorer::SomaticEvent

sqlite3_int64 	ofClusterID

 Protected Attributes inherited from SubcloneExplorer::Archivable

sqlite3_int64 	id

Detailed Description

Abstract data structure class that represents any segmental somatic mutation.

Mutations described by this class are segmental mutations, which means that they happen over a range of continuous genomic location. Such range is described by GenomicRange

See also

GenomicRange

Constructor & Destructor Documentation

          SubcloneExplorer::SegmentalMutation::SegmentalMutation
          (
          	)

inline

minimal constructor to reset all member variables

Member Function Documentation

          int SegmentalMutation::bindObjectToStatement
          (
          sqlite3_stmt *
          statement	)

protectedvirtual

Bind archivable properties to a prepared, unbound sqlite3 statement

Parameters

statement	A prepared, unbound sqlite3 statement instance

Returns

How many parameters are bound to the statement + 1

Implements SubcloneExplorer::Archivable.

          std::string SegmentalMutation::createObjectStatementStr
          (
          	)

protectedvirtual

return the unbound statement for record creation

Returns

unbound statement for record creation

Implements SubcloneExplorer::Archivable.

          std::string SegmentalMutation::selectObjectColumnListStr
          (
          	)

protectedvirtual

return the list of columns to be used in select statement for getting data from the database

Imagine the generic SQL select statement: SELECT <col1>, <col2>, ... FROM <tableName> WHERE id=?; The method should return the <col1>,<col2>,... part

Returns

the list of columns as string

Implements SubcloneExplorer::Archivable.

          void SegmentalMutation::updateObjectFromStatement
          (
          sqlite3_stmt *
          statement	)

protectedvirtual

Populate archivable properties from a prepared statement during unarchiving

Parameters

statement	A prepared statement contains the retrieved row

Implements SubcloneExplorer::Archivable.

          std::string SegmentalMutation::updateObjectStatementStr
          (
          	)

protectedvirtual

return the unbound statement for record update

Returns

unbound statement for record update

Implements SubcloneExplorer::Archivable.

Member Data Documentation

          GenomicRange SubcloneExplorer::SegmentalMutation::range

Genomic range over which the mutation occurred

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

src/SegmentalMutation.h

src/SegmentalMutation.cc

SubcloneExplorer

SegmentalMutation

Generated on Wed May 14 2014 15:29:42 for SubcloneSeeker by

     1.8.7

redpajama_set_name: RedPajamaGithub


text:
sap.ui.define([
	"sap/ui/test/generic/GenericTestCollection"
], function(GenericTestCollection) {
	"use strict";

	var oConfig = GenericTestCollection.createTestsuiteConfig({
		library: "sap.f",
		objectCapabilities: {
		}
	});

	return oConfig;
});


text:
import jwt from 'jsonwebtoken';
import model from '../models/';

const secret = process.env.SECRET || 'thisisasimplesecretkey';

export default {
  verifyToken(req, res, next) {
    const token = req.headers.authorization ||
      req.headers['x-access-token'];
    if (!token) {
      return res.status(401)
        .send({ message: 'Not Authorized' });
    }

    jwt.verify(token, secret, (error, decoded) => {
      if (error) {
        return res.status(401)
          .send({ message: 'Invalid Token' });
      }

      req.decoded = decoded;
      next();
    });
  },

  adminAccess(req, res, next) {
    model.Roles.findById(req.decoded.data.roleId)
      .then((foundRole) => {
        if (foundRole.title.toLowerCase() === 'administrator') {
          next();
        } else {
          return res.status(403)
            .send({ message: 'User is unauthorized for this request.' });
        }
      })
      .catch(error => res.status(400).send({
        err: error,
        message: 'Error authenticating'
      }));
  },
};


text:
using System;

namespace Tar
{
    class TarTime
    {
        public static long ToUnixTime(DateTime time, out uint nanoseconds)
        {
            var ticks = (time - UnixEpoch).Ticks;
            nanoseconds = (uint)(ticks % TicksPerSecond * 100);
            return ticks / TicksPerSecond;
        }

        public static long ToUnixTime(DateTime time)
        {
            uint nanoseconds;
            return ToUnixTime(time, out nanoseconds);
        }

        public static DateTime FromUnixTime(long time, uint nanoseconds)
        {
            int snano = (int)nanoseconds;
            if (time < 0)
            {
                snano = -snano;
            }

            return new DateTime(UnixEpoch.Ticks + time * TicksPerSecond + snano / NanoSecondsPerTick, DateTimeKind.Utc);
        }

        public static string ToPaxTime(DateTime time)
        {
            uint nanoseconds;
            long seconds = ToUnixTime(time, out nanoseconds);
            if (nanoseconds != 0)
            {
                return string.Format("{0}.{1:D7}", seconds, nanoseconds / 100);
            }
            else
            {
                return Convert.ToString(seconds);
            }
        }
        public static DateTime FromPaxTime(string str)
        {
            var point = str.IndexOf('.');
            long seconds;
            uint nanoseconds;
            if (point < 0)
            {
                seconds = Convert.ToInt64(str, 10);
                nanoseconds = 0;
            }
            else
            {
                seconds = Convert.ToInt64(str.Substring(0, point), 10);
                var nsStr = str.Substring(point + 1, Math.Min(9, str.Length - point - 1));
                if (nsStr.Length < 9)
                {
                    nsStr += new String('0', 9 - nsStr.Length);
                }

                nanoseconds = Convert.ToUInt32(nsStr, 10);
            }

            return FromUnixTime(seconds, nanoseconds);
        }

        public const int TicksPerSecond = 10 * 1000 * 1000;
        public const int NanoSecondsPerTick = 100;
        public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        public static readonly long MinUnixTime = ToUnixTime(DateTime.MinValue);
        public static readonly long MaxUnixTime = ToUnixTime(DateTime.MaxValue);
    }
}


text:
from setuptools import setup, find_packages

setup(
    name='superfeedr',
    version='1.0.0',
    author='Robert Neshanian',
    author_email='robert@hirobert.com',
    url='http://www.hirobert.com',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests'
    ],
    entry_points={
        'console_scripts': [
            'superfeedr = superfeedr:main'
        ]
    },
    classifiers=[
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Unix',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)


text:
import { AuthorizationServer } from './entities';
import { Credentials } from './utils';
export declare class AuthorizationServerClient {
    private readonly PATH_AUTHORIZATION_SERVERS;
    private credentials;
    private httpHelper;
    constructor(_credentials: Credentials);
    GetAll(filter?: string, top?: number, skip?: number): Promise<AuthorizationServer[]>;
    Get(authsid: string): Promise<AuthorizationServer>;
    GetMeta(authsid: string): Promise<number>;
    Create(authsid: string, payload: AuthorizationServer | string): Promise<any>;
    Update(authsid: string, ifMatch: string, payload: AuthorizationServer): Promise<any>;
    Delete(authsid: string, ifMatch: string): Promise<void>;
}


text:
template <typename T>
bool compareTrees(const NodePtr<T> &left, const NodePtr<T> &right);

template <typename T>
bool checkSubtree(const Tree<T> &tree, const Tree<T> &subtree)
{
    auto subtreeRoot = subtree.getRoot();
    if (!subtreeRoot)
        return true; // empty subtree
    auto subtreeRootValue = subtreeRoot->getValue();

    for (const auto &node : tree)
    {
        if (node->getValue() == subtreeRootValue)
            if (compareTrees<int>(node, subtreeRoot))
                return true;
    }
    return false;
}

template <typename T>
bool compareTrees(const NodePtr<T> &left, const NodePtr<T> &right)
{
    if (!left && !right)
        return true;
    else if (!left || !right) // one tree is not finished, another already finished
        return false;
    else if (left->getValue() == right->getValue())
        return compareTrees<T>(left->getLeft(), right->getLeft()) && compareTrees<T>(left->getRight(), right->getRight());
    return false;
}

int main()
{
    auto left = TestUtils::getSampleTree<int>(15);
    auto right = TestUtils::getSampleTree<int>(7);
    TestUtils::printTree(right);
    std::cout << (checkSubtree(left, right) ? "is subtree of\n" : "is not subtree of\n");
    TestUtils::printTree(left);

    right = TestUtils::getSampleTree<int>(8);
    TestUtils::printTree(right);
    std::cout << (checkSubtree(left, right) ? "is subtree of\n" : "is not subtree of\n");
    TestUtils::printTree(left);
}


text:
package com.amazonaws.services.elasticmapreduce.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.elasticmapreduce.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * FailureDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class FailureDetailsMarshaller {

    private static final MarshallingInfo<String> REASON_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Reason").build();
    private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Message").build();
    private static final MarshallingInfo<String> LOGFILE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("LogFile").build();

    private static final FailureDetailsMarshaller instance = new FailureDetailsMarshaller();

    public static FailureDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(FailureDetails failureDetails, ProtocolMarshaller protocolMarshaller) {

        if (failureDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(failureDetails.getReason(), REASON_BINDING);
            protocolMarshaller.marshall(failureDetails.getMessage(), MESSAGE_BINDING);
            protocolMarshaller.marshall(failureDetails.getLogFile(), LOGFILE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
import React, { Component, FunctionComponent } from 'react';

import { API, useStorybookApi } from '@storybook/api';

import { AboutScreen } from './about';

// Clear a notification on mount. This could be exported by core/notifications.js perhaps?
class NotificationClearer extends Component<{ api: API; notificationId: string }> {
  componentDidMount() {
    const { api, notificationId } = this.props;
    api.clearNotification(notificationId);
  }

  render() {
    const { children } = this.props;
    return children;
  }
}

const AboutPage: FunctionComponent<{}> = () => {
  const api = useStorybookApi();

  return (
    <NotificationClearer api={api} notificationId="update">
      <AboutScreen current={api.getCurrentVersion()} latest={api.getLatestVersion()} />
    </NotificationClearer>
  );
};

export { AboutPage };


text:
title: Natal, uma festa pagã - Guia Definitivo [2/3]
permalink: /natal-pagao-guia-definitivo-02/
layout: post
subtitle: "Certamente não somos OBRIGADOS a celebrar o natal. Mas não há como negar que esta época do ano nos dá uma oportunidade GIGANTE para lembrarmos do que Deus fez por nós..."
header-img: "img/bg/natal-2.jpg"
---

Certamente não somos OBRIGADOS a celebrar o natal. Mas não há como negar que esta época do ano nos dá uma oportunidade GIGANTE para lembrarmos do que Deus fez por nós.

Eu tenho como missão pessoal ser um facilitador entre Deus e os meus amigos. Muitos dos meus amigos são ateus. Muitos só ouviram o evangelho da boca de pregadores da TV. Muitos acham que o Deus de Israel é mal e vingativo. Que toda a história de Jesus não passa de uma fábula. E durante um  mês, eu tenho o mundo inteiro aberto e disposto a ouvir novamente a mensagem de quando Deus largou tudo e veio até aqui para nos salvar. Essa é uma oportunidade incrível que não pode ser desperdiçada.

Veja por exemplo o que acontecia no Velho Testamento. Deus instituiu festivais anuais que tinham como objetivo relembrar os feitos de Deus. Todos os anos, as pessoas paravam para relembrar o que Deus havia feito. Estas festas continuaram por séculos. Mesmo geração após geração eles ainda se lembravam da saída do Egito como se tivesse acontecido anteontem.

Abrindo um parenteses aqui. Há uma febre Judaizante que toma conta dos cristãos de tempos em tempos. Essa não é uma novidade e foi um problema que o próprio apóstolo Paulo teve que lidar logo no primeiro século. Não irei me alongar mais nisso porque este não é o objetivo desse texto, mas vale a pena lembrar aos judaizantes, que defendem apenas as celebrações que estão nas escrituras, que o Hanukkah não se encontra nas escrituras.

O foco do natal é JESUS! Como alguém pode falar que comemorar o natal tem um significado pagão?

Há, mas e a árvore de natal? E os presentes? Bem… já que você perguntou, vamos lá.

Uma das músicas mais famosas de natal é ***Oh Christmas Tree*** (https://www.youtube.com/watch?v=Zw_r2YLuFyc). Ouça essa música, leia a letra dela. É claro o propósito do compositor. Ele pega uma expressão cultural (pinheiros são muito comuns no inverno do hemisfério norte) e insere o evangelho nele. É nítido que o compositor está falando sobre Jesus, mas ele usa a árvore de natal para de maneira poética comunicar essa mensagem.

Da mesma maneira que Davi falava que Deus era uma Rocha, ou o Vento, ou um Pastor. Davi não estava adorando uma Rocha quando fala isso. Assim como os compositores atuais não acham que o Fogo, a Chuva, o Mar ou um Leão são deuses. Mas você lê os salmos de Davi sem esse preconceito, e canta as músicas da sua igreja sem problemas. Porque o problema é apenas com o pinheirinho?

De novo, um peso, duas medidas. Não confunda cocô de grilo com crocodilo.

E os presentes de Natal? Sim, pode ser que houvesse um significado pagão por trás disso. Mas não tem mais! Simples assim. A humanidade ganhou o maior presente da história quando Jesus nasceu e eu reflito isso dando um presente pra minha esposa, um jantar pra minha família, ou uma gorjeta maior para o garçom.

Temos LIBERDADE para REINVENTAR eventos culturais com um novo significado espiritual.

_Este é o segundo post de uma série de 3. Para ler o primeiro clique aqui, e para ler o ultimo aqui._


text:
export default function (plop) {
  plop.setHelper('tagWithoutPrefix', tag => tag.replace(/^sl-/, ''));

  plop.setHelper('tagToTitle', tag => {
    const withoutPrefix = plop.getHelper('tagWithoutPrefix');
    const titleCase = plop.getHelper('titleCase');
    return titleCase(withoutPrefix(tag).replace(/-/g, ' '));
  });

  plop.setGenerator('component', {
    description: 'Generate a new component',
    prompts: [
      {
        type: 'input',
        name: 'tag',
        message: 'Tag name? (e.g. sl-button)',
        validate: value => {
          // Start with sl- and include only a-z + dashes
          if (!/^sl-[a-z-+]+/.test(value)) {
            return false;
          }

          // No double dashes or ending dash
          if (value.includes('--') || value.endsWith('-')) {
            return false;
          }

          return true;
        }
      }
    ],
    actions: [
      {
        type: 'add',
        path: '../../src/components/{{ tagWithoutPrefix tag }}/{{ tagWithoutPrefix tag }}.ts',
        templateFile: 'templates/component/component.hbs'
      },
      {
        type: 'add',
        path: '../../src/components/{{ tagWithoutPrefix tag }}/{{ tagWithoutPrefix tag }}.styles.ts',
        templateFile: 'templates/component/styles.hbs'
      },
      {
        type: 'add',
        path: '../../src/components/{{ tagWithoutPrefix tag }}/{{ tagWithoutPrefix tag }}.test.ts',
        templateFile: 'templates/component/tests.hbs'
      },
      {
        type: 'add',
        path: '../../docs/components/{{ tagWithoutPrefix tag }}.md',
        templateFile: 'templates/component/docs.hbs'
      },
      {
        type: 'modify',
        path: '../../docs/_sidebar.md',
        pattern: /<!--plop:component-->/,
        template: `- [{{ tagToTitle tag }}](/components/{{ tagWithoutPrefix tag }})\n  <!--plop:component-->`
      },
      {
        type: 'modify',
        path: '../../src/shoelace.ts',
        pattern: /\/\* plop:component \*\//,
        template: `export { default as {{ properCase tag }} } from './components/{{ tagWithoutPrefix tag }}/{{ tagWithoutPrefix tag }}';\n/* plop:component */`
      }
    ]
  });
}


text:
<?php
require_once(dirname(__FILE__) . '/../model/sport.php');
// print_r($_FILES);
if(verifPost(array("category","sport","price","label","description","brand")))
{
	print_r($_POST);
	$category=$_POST['category'];
	$sport=$_POST['sport'];
	$price=$_POST['price'];
	$label=$_POST['label'];
	$description=$_POST['description'];
	$brand=$_POST['brand'];

	$sportLabel=getSportById($db,$sport);

	if($_FILES['selectedImage']['error']>0)
		echo "error image";
	else
	{
		// echo "TODO : add into db";
		//Save on the server
		$to ="./images/".$sportLabel."/".$_FILES['selectedImage']['name'];
		move_uploaded_file($_FILES['selectedImage']['tmp_name'], $to);
		echo "uploaded";

 		$productArray=array( 'libelle'     => $label,
                             'description' => $description,
                             'prix'        => $price,
                             'photo'       => $to,
                             'categorie'   => $category,
                             'sport'       => $sport,
                             'marque'      => $brand
                             );

 		// $sizes=array(
 		// 		''
 		// 	);

        if(addNewSingleProduct($db, $productArray/*,$sizes)*/))
			header('location: index.php?page=view/manageProducts');
		else
			echo "error";
        // echo addNewSingleProduct($db,$productArray);
	}
}
else
	echo "error";


text:
__all__ = ['PrivateGradValues']

import functools
from typing import Optional, Callable, Tuple

import jax
import jax.numpy as jn

from objax import random
from objax.gradient import GradValues
from objax.module import Function, Module, Vectorize
from objax.typing import JaxArray
from objax.util import repr_function, class_name
from objax.variable import VarCollection

class PrivateGradValues(Module):
    """Computes differentially private gradients as required by DP-SGD.
    This module can be used in place of GradVals, and automatically makes the optimizer differentially private."""

    def __init__(self,
                 f: Callable,
                 vc: VarCollection,
                 noise_multiplier: float,
                 l2_norm_clip: float,
                 microbatch: int,
                 batch_axis: Tuple[Optional[int], ...] = (0,),
                 keygen: random.Generator = random.DEFAULT_GENERATOR,
                 use_norm_accumulation: bool = False):
        """Constructs a PrivateGradValues instance.

        Args:
            f: the function for which to compute gradients.
            vc: the variables for which to compute gradients.
            noise_multiplier: scale of standard deviation for added noise in DP-SGD.
            l2_norm_clip: value of clipping norm for DP-SGD.
            microbatch: the size of each microbatch.
            batch_axis: the axis to use as batch during vectorization. Should be a tuple of 0s.
            keygen: a Generator for random numbers. Defaults to objax.random.DEFAULT_GENERATOR.
            use_norm_accumulation: whether to use norm accumulation as a first step to compute the clipped
              gradients (more details further). This is more memory efficient and often faster when the model
              is very deep and uses a large batch-size.
        """
        super().__init__()

        if not all(v == 0 for v in batch_axis):
            raise ValueError('batch_axis needs to be an all zero tuple for PrivateGradValues.')

        self.__wrapped__ = gv = GradValues(f, vc)

        self.batch_axis = batch_axis
        self.microbatch = microbatch
        self.l2_norm_clip = l2_norm_clip
        self.noise_multiplier = noise_multiplier
        self.keygen = keygen

        if use_norm_accumulation:
            self.clipped_grad = self._make_clipped_grad_fn_norm_accumulation(f, gv, vc)
        else:
            self.clipped_grad = self._make_clipped_grad_fn_simple(f, gv, vc)

    def _make_clipped_grad_fn_simple(self, f: Callable, gv: GradValues, vc: VarCollection) -> Callable:
        """Creates a function that computes gradients clipped per-sample.
        This algorithm vectorizes the computation of a clipped gradient defined over a single sample.

        Args:
          f: the function for which to compute gradients.
          gv: the GradValues object that computes non-clipped gradients.
          vc: the variables for which to compute gradients.

        Returns:
          clipped_grad: the function computing the average of gradients clipped per-sample.
        """
        @Function.with_vars(gv.vars())
        def clipped_grad_single_example(*args):
            grads, values = gv(*args)
            total_grad_norm = jn.linalg.norm([jn.linalg.norm(g) for g in grads])
            idivisor = 1 / jn.maximum(total_grad_norm / self.l2_norm_clip, 1.)
            return [g * idivisor for g in grads], values

        clipped_grad_vectorized = Vectorize(clipped_grad_single_example,
                                            batch_axis=self.batch_axis)

        def clipped_grad(*args):
            g, v = clipped_grad_vectorized(*args)
            g, v = jax.tree_map(functools.partial(jn.mean, axis=0), (g, v))
            return g, v

        return clipped_grad

    def _make_clipped_grad_fn_norm_accumulation(self, f: Callable, gv: GradValues, vc: VarCollection) -> Callable:
        """Creates a function that computes gradients clipped per-sample.
        This algorithm first accumulates the norm of the gradient per sample, and then
        performs an additional weighted backward pass that is equivalent to per-sample clipping.
        The accumulation allows jax to free up memory whenever the automatic differentiation engine
        is done processing a layer. This is more memory efficient and can be faster than the "simple" approach
        defined above, in particular at large batch-sizes for deep models.

        Reference: https://arxiv.org/abs/2009.03106.

        Args:
          f: the function for which to compute gradients.
          gv: the GradValues object that computes non-clipped gradients.
          vc: the variables for which to compute gradients.

        Returns:
          clipped_grad: the function computing the average of gradients clipped per-sample.
        """
        @Function.with_vars(gv.vars())
        def grad_norm_fn(*args):
            grads, values = gv(*args)
            total_grad_norm = jn.linalg.norm([jn.linalg.norm(g) for g in grads])
            return total_grad_norm, values

        grad_norm_fn_vectorized = Vectorize(grad_norm_fn, batch_axis=self.batch_axis)
        loss_fn_vectorized = Vectorize(Function.with_vars(gv.vars())(f), batch_axis=self.batch_axis)

        def weighted_loss_fn(weights, *args):
            returned = loss_fn_vectorized(*args)
            # the following assumes that the loss is the first element output by loss_fn_vectorized
            if isinstance(returned, jn.ndarray):
                loss_vector = returned
            else:
                loss_vector = returned[0]
            return jn.mean(loss_vector * weights)

        weighted_grad_fn = GradValues(weighted_loss_fn, vc)

        def clipped_grad(*args):
            grad_norms, values = grad_norm_fn_vectorized(*args)
            idivisor = 1 / jn.maximum(grad_norms / self.l2_norm_clip, 1.)
            clipped_grads, _ = weighted_grad_fn(idivisor, *args)
            return clipped_grads, jax.tree_map(functools.partial(jn.mean, axis=0), values)

        return clipped_grad

    def reshape_microbatch(self, x: JaxArray) -> JaxArray:
        """Reshapes examples into microbatches.
        DP-SGD requires that per-example gradients are clipped and noised, however this can be inefficient.
        To speed this up, it is possible to clip and noise a microbatch of examples, at a sight cost to privacy.
        If speed is not an issue, the microbatch size should be set to 1.

        If x has shape [D0, D1, ..., Dn], the reshaped output will
        have shape [number_of_microbatches, microbatch_size, D1, ..., DN].

        Args:
            x: items to be reshaped.

        Returns:
            The reshaped items.
        """
        s = x.shape
        return x.reshape([s[0] // self.microbatch, self.microbatch, *s[1:]])

    def __call__(self, *args):
        """Returns the computed DP-SGD gradients.

        Returns:
            A tuple (gradients, value of f)."""
        batch = args[0].shape[0]
        assert batch % self.microbatch == 0
        num_microbatches = batch // self.microbatch
        stddev = self.l2_norm_clip * self.noise_multiplier / num_microbatches
        g, v = self.clipped_grad(*[self.reshape_microbatch(x) for x in args])
        g = [gx + random.normal(gx.shape, stddev=stddev, generator=self.keygen) for gx in g]
        return g, v

    def __repr__(self):
        args = dict(f=repr_function(self.__wrapped__.f), noise_multiplier=self.noise_multiplier,
                    l2_norm_clip=self.l2_norm_clip, microbatch=self.microbatch, batch_axis=self.batch_axis)
        args = ', '.join(f'{k}={v}' for k, v in args.items())
        return f'{class_name(self)}({args})'


text:
"""Compose ACLs on ports."""

# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2018 The Contributors
#
# 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.

from faucet import valve_of
from faucet.conf import InvalidConfigError

def push_vlan(vlan_vid):
    """Push a VLAN tag with optional selection of eth type."""
    vid = vlan_vid
    vlan_eth_type = None
    if isinstance(vlan_vid, dict):
        vid = vlan_vid['vid']
        if 'eth_type' in vlan_vid:
            vlan_eth_type = vlan_vid['eth_type']
    if vlan_eth_type is None:
        return valve_of.push_vlan_act(vid)
    return valve_of.push_vlan_act(vid, eth_type=vlan_eth_type)

def rewrite_vlan(output_dict):
    """Implement actions to rewrite VLAN headers."""
    vlan_actions = []
    if 'pop_vlans' in output_dict:
        for _ in range(output_dict['pop_vlans']):
            vlan_actions.append(valve_of.pop_vlan())
    # if vlan tag is specified, push it.
    if 'vlan_vid' in output_dict:
        vlan_actions.extend(push_vlan(output_dict['vlan_vid']))
    # swap existing VID
    elif 'swap_vid' in output_dict:
        vlan_actions.append(
            valve_of.set_vlan_vid(output_dict['swap_vid']))
    # or, if a list, push them all (all with type Q).
    elif 'vlan_vids' in output_dict:
        for vlan_vid in output_dict['vlan_vids']:
            vlan_actions.extend(push_vlan(vlan_vid))
    return vlan_actions

def build_output_actions(output_dict):
    """Implement actions to alter packet/output."""
    output_actions = []
    output_port = None
    ofmsgs = []
    # rewrite any VLAN headers first always
    vlan_actions = rewrite_vlan(output_dict)
    if vlan_actions:
        output_actions.extend(vlan_actions)
    if 'set_fields' in output_dict:
        for set_fields in output_dict['set_fields']:
            output_actions.append(valve_of.set_field(**set_fields))
    if 'port' in output_dict:
        output_port = output_dict['port']
        output_actions.append(valve_of.output_port(output_port))
    if 'ports' in output_dict:
        for output_port in output_dict['ports']:
            output_actions.append(valve_of.output_port(output_port))
    if 'failover' in output_dict:
        failover = output_dict['failover']
        group_id = failover['group_id']
        buckets = []
        for port in failover['ports']:
            buckets.append(valve_of.bucket(
                watch_port=port, actions=[valve_of.output_port(port)]))
        ofmsgs.append(valve_of.groupdel(group_id=group_id))
        ofmsgs.append(valve_of.groupadd_ff(group_id=group_id, buckets=buckets))
        output_actions.append(valve_of.group_act(group_id=group_id))
    return (output_port, output_actions, ofmsgs)

# TODO: change this, maybe this can be rewritten easily
# possibly replace with a class for ACLs
def build_acl_entry(rule_conf, meters,
                    acl_allow_inst, acl_force_port_vlan_inst,
                    port_num=None, vlan_vid=None):
    acl_inst = []
    acl_act = []
    acl_match_dict = {}
    acl_ofmsgs = []
    acl_cookie = None
    allow_inst = acl_allow_inst

    for attrib, attrib_value in list(rule_conf.items()):
        if attrib == 'in_port':
            continue
        if attrib == 'cookie':
            acl_cookie = attrib_value
            continue
        if attrib == 'description':
            continue
        if attrib == 'actions':
            allow = False
            allow_specified = False
            if 'allow' in attrib_value:
                allow_specified = True
                if attrib_value['allow'] == 1:
                    allow = True
            if 'force_port_vlan' in attrib_value:
                if attrib_value['force_port_vlan'] == 1:
                    allow_inst = acl_force_port_vlan_inst
            if 'meter' in attrib_value:
                meter_name = attrib_value['meter']
                acl_inst.append(valve_of.apply_meter(meters[meter_name].meter_id))
            if 'mirror' in attrib_value:
                port_no = attrib_value['mirror']
                acl_act.append(valve_of.output_port(port_no))
                if not allow_specified:
                    allow = True
            if 'output' in attrib_value:
                output_port, output_actions, output_ofmsgs = build_output_actions(
                    attrib_value['output'])
                acl_act.extend(output_actions)
                acl_ofmsgs.extend(output_ofmsgs)

                # if port specified, output packet now and exit pipeline.
                if output_port is not None:
                    continue

            if allow:
                acl_inst.append(allow_inst)
        else:
            acl_match_dict[attrib] = attrib_value
    if port_num is not None:
        acl_match_dict['in_port'] = port_num
    if vlan_vid is not None:
        acl_match_dict['vlan_vid'] = valve_of.vid_present(vlan_vid)
    try:
        acl_match = valve_of.match_from_dict(acl_match_dict)
    except TypeError:
        raise InvalidConfigError('invalid type in ACL')
    if acl_act:
        acl_inst.append(valve_of.apply_actions(acl_act))
    return (acl_match, acl_inst, acl_cookie, acl_ofmsgs)

def build_acl_ofmsgs(acls, acl_table,
                     acl_allow_inst, acl_force_port_vlan_inst,
                     highest_priority, meters,
                     exact_match, port_num=None, vlan_vid=None):
    ofmsgs = []
    acl_rule_priority = highest_priority
    for acl in acls:
        for rule_conf in acl.rules:
            acl_match, acl_inst, acl_cookie, acl_ofmsgs = build_acl_entry(
                rule_conf, meters,
                acl_allow_inst, acl_force_port_vlan_inst,
                port_num, vlan_vid)
            ofmsgs.extend(acl_ofmsgs)
            if exact_match:
                flowmod = acl_table.flowmod(
                    acl_match, priority=highest_priority, inst=acl_inst, cookie=acl_cookie)
            else:
                flowmod = acl_table.flowmod(
                    acl_match, priority=acl_rule_priority, inst=acl_inst, cookie=acl_cookie)
            ofmsgs.append(flowmod)
            acl_rule_priority -= 1
    return ofmsgs


text:
layout: post
title: How to write your own WebCrawler
---

Writing your own web crawler is very easy.There are many standard libraries for parsing html pages. Jsoup ([link) ](http://jsoup.org/)is one of the Java library that parses an html page and returns all the elements in that page.
To connect to a particular website just use

***Document doc = Jsoup.connect(encodeUrl("www.sandeepgoli.com")).get();***

Use above doc object to get all links in that particular website

***Elements link = doc.select("a");***

Then you can recusrively call to get in depth links from current links

Example:

    public  void  getLinksRecursive(String url,int depth) {
    		if(depth<=0)
    			return;
    		Elements children= parseurls(url);
    		if(children!=null)
    		{
    			for(Element link : children) {
    			String relHref = link.absUrl("href");
    					getLinksRecursive(relHref,depth-1);
    			}
    		}
    	}*
You have to add more constraints to eliminate loops in your crawler.Use tree based data structure to store all the links.


text:
"""
 Copyright (c) 2015 Michael Bright and Bamboo HR LLC

 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.
"""

try:
    import simplejson as json
except ImportError:
    import json

import requests
from rapid.lib.version import Version
# pylint: disable=too-many-instance-attributes

class Client(object):

    def __init__(self, ip_address, port, grains, grain_restrict, api_key=None, is_ssl=False, hostname=None, time_elapse=0.5):
        self.ip_address = ip_address
        self.is_ssl = is_ssl
        self.port = port
        self.grains = grains.split(';') if grains is not None else None
        self.grain_restrict = grain_restrict
        self.sleep = False
        self.api_key = api_key
        self.hostname = hostname
        self.time_elapse = ((time_elapse / 1000) + 0.5) if time_elapse > 1 else time_elapse

    def __getstate__(self):
        state = self.__dict__.copy()
        return state

    def get_headers(self):
        return {'X-Rapidci-Version': Version.get_version(), 'Content-Type': 'application/json', 'X-Rapidci-Api-Key': self.api_key}

    def can_handle(self, grain):
        if self.sleep:
            return False

        if grain is not None and self.grains is not None:
            tmp_grains = grain.split(';')
            number_matched = 0
            for _grain in tmp_grains:
                if _grain not in self.grains:
                    return False
                number_matched += 1

            if self.grain_restrict and number_matched != len(self.grains):
                return False

            return True

        if self.grain_restrict:
            return False

        return True

    def get_availability_uri(self):
        return "{}://{}/work/request".format(self._get_prefix(), self.get_uri())

    def get_work_uri(self):
        return "{}://{}/work/execute".format(self._get_prefix(), self.get_uri())

    def get_cancel_uri(self, action_instance_id):
        return "{}://{}/work/cancel/{}".format(self._get_prefix(), self.get_uri(), action_instance_id)

    def get_status_uri(self):
        return "{}://{}/status".format(self._get_prefix(), self.get_uri())

    def send_work(self, work_request, verify_certs=True):
        return requests.post(self.get_work_uri(), json=work_request.__dict__, headers=self.get_headers(), verify=verify_certs, timeout=4)

    def cancel_work(self, action_instance_id, verify_certs=True):
        return requests.post(self.get_cancel_uri(action_instance_id), headers=self.get_headers(), verify=verify_certs, timeout=4)

    def get_uri(self):
        return "{}:{}".format(self.ip_address, self.port)

    def _get_prefix(self):
        return 'https' if self.is_ssl else 'http'


text:
#ifndef DEBUGGING_H
#define DEBUGGING_H

#include "qv4global_p.h"
#include "qv4engine_p.h"
#include "qv4context_p.h"
#include "qv4scopedvalue_p.h"

#include <QHash>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>

QT_BEGIN_NAMESPACE

namespace QV4 {

struct Function;

namespace Debugging {

enum PauseReason {
    PauseRequest,
    BreakPoint,
    Throwing,
    Step
};

class DebuggerAgent;

struct DebuggerBreakPoint {
    DebuggerBreakPoint(QString fileName, int line)
        : fileName(fileName), lineNumber(line)
    {}
    QString fileName;
    int lineNumber;
};
inline uint qHash(const DebuggerBreakPoint &b, uint seed = 0) Q_DECL_NOTHROW
{
    return qHash(b.fileName, seed) ^ b.lineNumber;
}
inline bool operator==(const DebuggerBreakPoint &a, const DebuggerBreakPoint &b)
{
    return a.lineNumber == b.lineNumber && a.fileName == b.fileName;
}

typedef QHash<DebuggerBreakPoint, QString> BreakPoints;

class Q_QML_EXPORT Debugger
{
public:
    class Job
    {
    public:
        virtual ~Job() = 0;
        virtual void run() = 0;
    };

    class Q_QML_EXPORT Collector
    {
    public:
        Collector(ExecutionEngine *engine): m_engine(engine), m_isProperty(false) {}
        virtual ~Collector();

        void collect(const QString &name, const ScopedValue &value);
        void collect(const ObjectRef object);

    protected:
        virtual void addUndefined(const QString &name) = 0;
        virtual void addNull(const QString &name) = 0;
        virtual void addBoolean(const QString &name, bool value) = 0;
        virtual void addString(const QString &name, const QString &value) = 0;
        virtual void addObject(const QString &name, ValueRef value) = 0;
        virtual void addInteger(const QString &name, int value) = 0;
        virtual void addDouble(const QString &name, double value) = 0;

        QV4::ExecutionEngine *engine() const { return m_engine; }

        bool isProperty() const { return m_isProperty; }
        void setIsProperty(bool onoff) { m_isProperty = onoff; }

    private:
        QV4::ExecutionEngine *m_engine;
        bool m_isProperty;
    };

    enum State {
        Running,
        Paused
    };

    enum Speed {
        FullThrottle = 0,
        StepOut,
        StepOver,
        StepIn,

        NotStepping = FullThrottle
    };

    Debugger(ExecutionEngine *engine);
    ~Debugger();

    ExecutionEngine *engine() const
    { return m_engine; }

    void attachToAgent(DebuggerAgent *agent);
    void detachFromAgent();
    DebuggerAgent *agent() const { return m_agent; }

    void gatherSources(int requestSequenceNr);
    void pause();
    void resume(Speed speed);

    State state() const { return m_state; }

    void addBreakPoint(const QString &fileName, int lineNumber, const QString &condition = QString());
    void removeBreakPoint(const QString &fileName, int lineNumber);

    void setBreakOnThrow(bool onoff);

    // used for testing
    struct ExecutionState
    {
        QString fileName;
        int lineNumber;
    };
    ExecutionState currentExecutionState() const;

    bool pauseAtNextOpportunity() const {
        return m_pauseRequested || m_haveBreakPoints || m_gatherSources || m_stepping >= StepOver;
    }

    QVector<StackFrame> stackTrace(int frameLimit = -1) const;
    void collectArgumentsInContext(Collector *collector, int frameNr = 0, int scopeNr = 0);
    void collectLocalsInContext(Collector *collector, int frameNr = 0, int scopeNr = 0);
    bool collectThisInContext(Collector *collector, int frame = 0);
    void collectThrownValue(Collector *collector);
    void collectReturnedValue(Collector *collector) const;
    QVector<ExecutionContext::ContextType> getScopeTypes(int frame = 0) const;

public: // compile-time interface
    void maybeBreakAtInstruction();

public: // execution hooks
    void enteringFunction();
    void leavingFunction(const ReturnedValue &retVal);
    void aboutToThrow();

private:
    Function *getFunction() const;

    // requires lock to be held
    void pauseAndWait(PauseReason reason);

    bool reallyHitTheBreakPoint(const QString &filename, int linenr);

    void runInEngine(Job *job);
    void runInEngine_havingLock(Debugger::Job *job);

private:
    QV4::ExecutionEngine *m_engine;
    QV4::ExecutionContext *m_currentContext;
    DebuggerAgent *m_agent;
    QMutex m_lock;
    QWaitCondition m_runningCondition;
    State m_state;
    Speed m_stepping;
    bool m_pauseRequested;
    bool m_haveBreakPoints;
    bool m_breakOnThrow;

    BreakPoints m_breakPoints;
    QV4::PersistentValue m_returnedValue;

    Job *m_gatherSources;
    Job *m_runningJob;
    QWaitCondition m_jobIsRunning;
};

class Q_QML_EXPORT DebuggerAgent : public QObject
{
    Q_OBJECT
public:
    DebuggerAgent(): m_breakOnThrow(false) {}
    ~DebuggerAgent();

    void addDebugger(Debugger *debugger);
    void removeDebugger(Debugger *debugger);

    void pause(Debugger *debugger) const;
    void pauseAll() const;
    void resumeAll() const;
    int addBreakPoint(const QString &fileName, int lineNumber, bool enabled = true, const QString &condition = QString());
    void removeBreakPoint(int id);
    void removeAllBreakPoints();
    void enableBreakPoint(int id, bool onoff);
    QList<int> breakPointIds(const QString &fileName, int lineNumber) const;

    bool breakOnThrow() const { return m_breakOnThrow; }
    void setBreakOnThrow(bool onoff);

    Q_INVOKABLE virtual void debuggerPaused(QV4::Debugging::Debugger *debugger,
                                            QV4::Debugging::PauseReason reason) = 0;
    Q_INVOKABLE virtual void sourcesCollected(QV4::Debugging::Debugger *debugger,
                                              QStringList sources, int requestSequenceNr) = 0;

protected:
    QList<Debugger *> m_debuggers;

    struct BreakPoint {
        QString fileName;
        int lineNr;
        bool enabled;
        QString condition;

        BreakPoint(): lineNr(-1), enabled(false) {}
        BreakPoint(const QString &fileName, int lineNr, bool enabled, const QString &condition)
            : fileName(fileName), lineNr(lineNr), enabled(enabled), condition(condition)
        {}

        bool isValid() const { return lineNr >= 0 && !fileName.isEmpty(); }
    };

    QHash<int, BreakPoint> m_breakPoints;
    bool m_breakOnThrow;
};

} // namespace Debugging
} // namespace QV4

QT_END_NAMESPACE

Q_DECLARE_METATYPE(QV4::Debugging::Debugger*)
Q_DECLARE_METATYPE(QV4::Debugging::PauseReason)

#endif // DEBUGGING_H


text:
(function (window, undefined) {
  'use strict';

  // Module name
  var myModule = {};

  // ten lines to ease counting and finding the lines in test output.

// Some convenient general purpose methods.

var isArray = function (possibleArray) {
  return Object.prototype.toString.call(possibleArray) === '[object Array]';
};

var toArray = function (value) {
  // Turn a value to an array.
  //   2       -> [2]
  //   'a'     -> ['a']
  //   [2]     -> [2]
  //   other   -> []
  if (typeof value === 'string' || typeof value === 'number') {
    return [value];
  }

  if (isArray(value)) {
    return value;
  } // else
  return [];
};

var randomFromInterval = function (min, max) {
  // Return a number for range [min,max)
  // http://stackoverflow.com/a/7228322/638546
  return Math.random() * (max - min) + min;
};

var randomOrderedSetFromInterval = function (n, min, max) {
  // N random numbers in order
  //
  // Complexity
  //   O(n)
  //
  // See http://www.mathpages.com/home/kmath452.htm
  var i,
      prev,
      normalized,
      x = [];

  if (typeof n !== 'number') {
    n = 1;
  }
  if (n < 1) {
    return x; // empty array
  }

  // Inverse cumulative distribution function for x[i]
  // invcdf(x, i) = 1 - (1 - x)^(1 / (n - i))

  // x[0]
  x.push(1 - Math.pow(Math.random(), 1 / n));

  // x[1] .. x[n - 1]
  for (i = 1; i < n; i += 1) {
    prev = x[x.length - 1];
    normalized = 1 - Math.pow(Math.random(), 1 / (n - i));
    x.push(prev + (1 - prev) * normalized);
  }

  // Transfer to interval
  for (i = 0; i < n; i += 1) {
    x[i] = min + (max - min) * x[i];
  }

  return x;
};

var shuffle = function (array) {
  // Shuffle the array randomly using Fisher-Yates shuffle algorithm.
  // See http://stackoverflow.com/a/6274398/638546

  var counter = array.length, temp, index;

  // While there are elements in the array
  while (counter > 0) {
    // Pick a random index
    index = Math.floor(Math.random() * counter);

    // Decrease counter by 1
    counter -= 1;

    // And swap the last element with it
    temp = array[counter];
    array[counter] = array[index];
    array[index] = temp;
  }

  return array;
};

var clone = function (obj) {
  // Copy the object
  // http://stackoverflow.com/a/728694/638546
  if (null === obj || 'object' !== typeof obj) { return obj; }
  var copy = obj.constructor();
  for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; }
  }
  return copy;
};

// The following lines are needed to test the util functions from outside.
myModule.util = {
  isArray: isArray,
  toArray: toArray,
  randomFromInterval: randomFromInterval,
  randomOrderedSetFromInterval: randomOrderedSetFromInterval,
  shuffle: shuffle,
  clone: clone
};

/*

Categorical Distribution

Related
- unigram
- http://en.wikipedia.org/wiki/Bag_of_words_model
- http://en.wikipedia.org/wiki/Categorical_distribution

*/

myModule.CategoricalDistribution = (function () {
  var exports = {};
  /////////////////

  // Private module constants
  //var EXAMPLE = 777;

  // Public module constants
  //exports.EXAMPLE = EXAMPLE;

  // Exceptions

  var NotAnArrayException = function () {
    // Usage: new NotAnArrayException();
    this.name = 'NotAnArrayException';
    this.message = 'Parameter is required to be an array';
  };

  var InvalidDumpException = function () {
    // Usage: new InvalidDumpException();
    this.name = 'InvalidDumpException';
    this.message = 'Dump cannot be loaded because of invalid syntax.';
  };

  var InvalidDistributionException = function () {
    this.name = 'InvalidDistributionException';
    this.message = 'Distribution is in unknown form.';
  };

  var InvalidWeightException = function () {
    this.name = 'InvalidWeightException';
    this.message = 'Weight must be a number.';
  };

  var OverflowException = function () {
    this.name = 'OverflowException';
    this.message = 'A value grew greater than is possible to represent.';
  };

  // Make exceptions public to be catchable
  exports.NotAnArrayException = NotAnArrayException;
  exports.InvalidDumpException = InvalidDumpException;
  exports.InvalidDistributionException = InvalidDistributionException;
  exports.InvalidWeightException = InvalidWeightException;
  exports.OverflowException = OverflowException;

  // Private methods

  var prob = function (weight, weightSum) {
    // Return probability
    if (weightSum === 0) {
      return 0;
    } // else
    return weight / weightSum;
  };

  var learn = function (cd, cat, weight) {
    // Modifies $cd, returns nothing
    //
    // Throws
    //   OverflowException

    var st = cd.state,
        oldW, newW,
        oldWSum, newWSum;

    oldWSum = st.wSum;

    if (st.w.hasOwnProperty(cat)) {
      oldW = st.w[cat];
    } else {
      // Unknown category
      oldW = 0;
      st.order.push(cat);
      st.indices[cat] = st.order.length - 1;
    }

    newW = oldW + weight;

    if (newW < 0) {
      // Limit to zero
      newW = 0;
      newWSum = oldWSum - oldW;
    } else {
      newWSum = oldWSum + weight;
    }

    // Test overflow
    if (newW > Number.MAX_VALUE) {
      throw new OverflowException();
    }
    if (newWSum > Number.MAX_VALUE) {
      throw new OverflowException();
    }

    // Update the distribution

    st.w[cat] = newW;
    st.wSum = newWSum;

    sortOne(cd, cat);
  };

  var sortOne = function (cd, category) {
    // Move event category to its position in a manner similar to
    // insertion sort.
    //
    // Precondition
    //   $category is only out of order category in $order.
    //   $category exists in $weights, $indices and in $order.
    var st, i, c, backwards, isLast, isFirst, tempCat;

    st = cd.state;
    i = st.indices[category];
    c = st.w[category];

    // Recognize direction
    isLast = (i === st.order.length - 1);
    isFirst = (i === 0);
    if (isLast) {
      backwards = true;
    } else if (isFirst) {
      backwards = false;
    } else {
      // assert: at least one before and at least one after.
      if (st.w[st.order[i - 1]] < c) {
        backwards = true;
      } else {
        backwards = false;
      }
    }

    // Move until category in its place.
    // Place most recent as front as possible.
    if (backwards) {
      while (i !== 0 && st.w[st.order[i - 1]] <= c) {
        // Swap towards head
        tempCat = st.order[i - 1];
        st.order[i] = tempCat;
        st.order[i - 1] = category;
        st.indices[tempCat] = i;
        i -= 1;
      }
    } else {
      while (i !== st.order.length - 1 && st.w[st.order[i + 1]] > c) {
        // Swap towards tail
        tempCat = st.order[i + 1];
        st.order[i] = tempCat;
        st.order[i + 1] = category;
        st.indices[tempCat] = i;
        i += 1;
      }
    }

    // Update category index
    st.indices[category] = i;
  };

  var updateWeight = function (cd, cat, weight) {
    // DEPRECATED, may be removed in future
    //
    // Updates the weight of a category and abstracts out the maintenance of
    // $order and $indices.

    var st = cd.state;

    if (!st.weights.hasOwnProperty(cat)) {
      // Unknown category
      st.order.push(cat);
      st.indices[cat] = st.order.length - 1;
    }
    st.w[cat] = weight;

    // Move the category to its place.
    sortOne(cd, cat);
  };

  var multiplyWeights = function (cd, multiplier) {
    // DEPRECATED, may be removed in future
    //
    // Multiply weights and update wSum
    //
    // Precondition
    //   multiplier >= 0

    var st, len, i, cat;

    st = cd.state;
    len = st.order.length;

    for (i = 0; i < len; i += 1) {
      cat = st.order[i];
      st.w[cat] *= multiplier;
    }

    st.wSum *= multiplier;
  };

  var normalize = function (acd) {
    // Update the weights and mass so that weightSum === 1.
    // TODO
  };

  var sampleSimple = function (cd, n) {
    // Take N samples randomly.
    // Complexity O(n * m) where m is num of categories. This because
    // cumulative distribution function is recalculated for every sample.
    var x, i, j, maxSum, cumulativeSum,
        result = [],
        st = cd.state;

    if (st.order.length === 0 || n <= 0) {
      return result;
    } // else

    maxSum = st.wSum;

    for (i = 0; i < n; i += 1) {
      x = randomFromInterval(0, maxSum);
      cumulativeSum = 0;
      for (j = 0; j < st.order.length; j += 1) {
        // Add to cumulative sum until greater.
        // Because random max is exclusive, weight sum
        // will be greater at the last event at the latest.
        cumulativeSum += st.w[st.order[j]];
        if (x < cumulativeSum) {
          result.push(st.order[j]);
          break;
        }
      }
    }

    return result;
  };

  var sampleOrdered = function (cd, n) {
    // Take N samples randomly but return them in probability order.
    // Calculates cumulative density function only once.
    // Complexity O(n + m) but has quite large overhead compared to.
    // sampleSimple. Good performance when there is large number of
    // categories (about 30 or more) even if the results need to be
    // shuffled.

    var rands, cat, maxSum, cumulativeSum, i, r,
        result = [],
        st = cd.state;

    if (st.order.length === 0 || n <= 0) {
      return result; // empty array
    } // else

    maxSum = st.wSum;

    rands = randomOrderedSetFromInterval(n, 0, maxSum);

    cat = 0;
    cumulativeSum = st.w[st.order[cat]];

    for (i = 0; i < n; i += 1) {
      r = rands[i];

      // Use < instead of <= because inclusive head, exclusive tail.
      if (r < cumulativeSum) {
        result.push(st.order[cat]);
      } else {
        do {
          // Add to cumulative sum until it becomes greater than $r.
          // Because the interval tail is exclusive, $cumulativeSum
          // will become greater than $r at least in the end.
          cat += 1;
          cumulativeSum += st.w[st.order[cat]];
        } while (cumulativeSum <= r);

        result.push(st.order[cat]);
      }
    }

    // Results in probability order.
    return result;
  };

  // Constructor

  var CatDist = function () {
    // Parameter
    //   -

    this.state = {
      w: {}, // Weight for each category.
      wSum: 0, // Sum of the weights.
      order: [], // Ordered most probable category first.
      indices: {} // Category indices in $order array.
    };

  };

  exports.create = function () {
    return new CatDist();
  };

  // Accessors

  CatDist.prototype.prob = function (cats) {
    // Probabilities of given categories
    //
    // Return
    //   array of probabilities
    //     if $cats is array
    //   probability
    //     if $cats is string

    var result,
        single, // for knowing to return either array or number
        i, cat,
        st = this.state;

    if (typeof cats === 'string') {
      cats = [cats];
      single = true;
    } else {
      single = false;
    }

    if (typeof cats === 'undefined') {
      cats = st.order;
    }

    result = [];

    for (i = 0; i < cats.length; i += 1) {
      cat = cats[i];
      if (st.w.hasOwnProperty(cat)) {
        result.push(prob(st.w[cat], st.wSum));
      } else {
        result.push(0);
      }
    }

    if (single) {
      return result[0];
    }
    return result;
  };

  CatDist.prototype.mode = function (n) {
    // N most probable categories
    //
    // Parameter
    //   n (optional)
    //     Number of most probable categories in probability order.
    //     Omit to return all categories in probability order.
    //
    // Return array of categories

    var st = this.state;
    if (typeof n !== 'number') {
      n = st.order.length;
    }

    n = Math.min(n, st.order.length);
    if (n > 0) {
      return st.order.slice(0, n);
    } // else
    return [];
  };
  // Alias
  CatDist.prototype.head = CatDist.prototype.mode;

  CatDist.prototype.peak = function (tolerance) {
    // Return most probable category (probability X) and all those categories
    // whose probability differs from X by not more than
    // tolerance * 100 percent.
    //
    // Parameter
    //   tolerance
    //     number in closed interval [0, 1]
    //
    // Return array of categories

    var i, headLikelihood, minLikelihood,
        st = this.state;

    if (st.order.length === 0) {
      return [];
    } // else len > 0

    headLikelihood = st.w[st.order[0]];
    minLikelihood = headLikelihood - headLikelihood * tolerance;

    for (i = 1; i < st.order.length; i += 1) {
      if (minLikelihood > st.w[st.order[i]]) {
        break;
      } // else include i:th category
    }

    // Do not include i:th category.
    return st.order.slice(0,i);
  };

  CatDist.prototype.subset = function (categories) {
    // Return new CategoricalDistribution that has only the specified
    // categories. Weights stay the same, so probabilities may change but
    // the ratios between probabilities stay the same.
    //
    // Precondition
    //   Given categories are mutually exclusive i.e. no duplicates.
    //
    // Complexity
    //   O(n), where n is the num of cats in the orig distribution

    var i, cat,
        st = this.state,
        sub, subW, subWSum, subOrder, subIndices;

    subW = {};
    subWSum = 0;
    subOrder = [];
    subIndices = {};

    if (typeof categories === 'string') {
      categories = [categories];
    }

    // Weights
    for (i = 0; i < categories.length; i += 1) {
      cat = categories[i];
      if (st.w.hasOwnProperty(cat)) {
        subW[cat] = st.w[cat];
        subWSum += st.w[cat];
      }
    }

    // Order
    for (i = 0; i < st.order.length; i += 1) {
      cat = st.order[i];
      if (subW.hasOwnProperty(cat)) {
        subOrder.push(cat);
        subIndices[cat] = subOrder.length - 1;
      }
    }

    sub = new CatDist();
    sub.state.w = subW;
    sub.state.wSum = subWSum;
    sub.state.order = subOrder;
    sub.state.indices = subIndices;

    return sub;
  };

  CatDist.prototype.rank = function (categories) {
    // Order of the given categories in the list of most probable categories.
    // Most probable category has rank 0. Unknown category has rank Infinity.
    //
    // Return
    //   array of integers
    //     if $categories is array
    //   integer
    //     if $categories is string

    var result,
        i, cat, p,
        st = this.state;

    if (typeof categories === 'string') {
      if (st.indices.hasOwnProperty(categories)) {
        return st.indices[categories];
      } // else
      return Infinity;
    } // else

    if (typeof categories === 'undefined') {
      categories = st.order; // stupid because result is [0, 1, 2, ...]
    }

    result = [];
    for (i = 0; i < categories.length; i += 1) {
      cat = categories[i];
      if (st.indices.hasOwnProperty(cat)) {
        result.push(st.indices[cat]);
      } else {
        result.push(Infinity);
      }
    }

    return result;
  };

  CatDist.prototype.entropy = function () {
    // Calculate information theoretic entropy of the distribution in bits.
    // Entropy = average information of a sample.
    // Return
    //   Positive number. Bits.

    var st, ent, i, cat, p;
    st = this.state;
    ent = 0;

    for (i = 0; i < st.order.length; i += 1) {
      cat = st.order[i];
      p = st.w[cat] / st.wSum;
      // In the context of entropy, 0*log(0) = 0
      if (p > 0) {
        ent -= p * Math.log(p);
      }
    }

    // Nats to bits. Natural log to base-2 log.
    ent /= Math.log(2);
    return ent;
  };

  CatDist.prototype.each = function (iterator, context) {
    // Execute a function over the categories in probability order.
    //
    // Parameter
    //   Iterator
    //     A function.
    //   context (optional)
    //     Call the iterator in this context.
    //
    // Iterator
    //   iterator(category, probability, rank)
    //
    // Return this for chaining.
    var i, cat, pr, index, order,
        st = this.state;
    order = st.order.slice(0); // copy because order may change during each
    var len = order.length;
    for (i = 0; i < len; i += 1) {
      cat = order[i];
      pr = prob(st.w[cat], st.wSum);
      index = st.indices[cat];
      iterator.call(context, cat, pr, index);
    }
    return this;
  };

  CatDist.prototype.map = function (iterator, context) {
    // Transform categories to an array. Iterator defines how the categories
    // are transformed and is called in probability order.
    //
    // Parameter
    //   Iterator
    //     A function. Should return something.
    //   context (optional)
    //     Call the iterator in this context.
    //
    // Iterator
    //   iterator(category, probability, rank)
    //
    // Return this for chaining.
    var results = [];
    this.each(function (cat, prob, rank) {
      results.push(iterator.call(context, cat, prob, rank));
    });
    return results;
  };

  CatDist.prototype.sample = function (n, isOrdered) {
    // TODO
    // Draw n samples from the distribution.
    //
    // Parameter
    //   n (optional, default 1)
    //     How many samples
    //   isOrdered (optional, default false)
    //     If true, results are ordered most probable samples first.
    //     This can be done without additional penalty to efficiency.
    //
    // Return
    //   array of events. Empty array if no data or if n = 0
    //
    // Complexity
    //   Mixed O(n*m) and O(n+m) where m is number of categories

    var manyCategories, r,
        st = this.state;

    // Normalize params
    if (typeof n !== 'number') { n = 1; }
    if (typeof isOrdered !== 'boolean') { isOrdered = false; }

    // Two algorithms to choose from
    if (isOrdered) {
      r = sampleOrdered(this, n);
    } else {

      manyCategories = st.order.length > 30; // 30 is only a guess
      if (manyCategories) {
        r = shuffle(sampleOrdered(this, n));
      } else {
        r = sampleSimple(this, n);
      }
    }
    return r;
  };

  CatDist.prototype.numCategories = function () {
    // Return number of categories in distribution.
    return this.state.order.length;
  };

  CatDist.prototype.dump = function () {
    // Serialize to a shallow array.
    // See also load()

    var i, cat, weight,
        st = this.state,
        result = [];

    // Categories and weights.
    for (i = 0; i < st.order.length; i += 1) {
      cat = st.order[i];
      result.push(cat);
      result.push(st.w[cat]);
    }

    // No need to include sum as it is calculated from the weights.

    return result;
  };

  CatDist.prototype.copy = function () {
    // Return a copy of this distribution.
    //
    // TODO inefficiently recalculates the wSum
    var cd = new CatDist();
    cd.load(this.dump());
    return cd;
  };

  CatDist.prototype.print = function (precision) {
    // Return human readable string representation of the distribution.
    //
    // Parameter
    //   precision (optional, default 2)
    //
    var st = this.state,
        i, cat, prob, probs,
        j, maxCatStrLen = 0;
    var len = st.order.length;
    var result = '';

    if (typeof precision !== 'number') {
      precision = 2;
    }

    // Limit to range [0, 10]
    precision = Math.max(Math.min(precision, 10), 0);

    probs = this.prob(st.order);

    // Find padding width
    for (i = 0; i < len; i += 1) {
      cat = st.order[i];
      maxCatStrLen = Math.max(maxCatStrLen, cat.length);
    }

    // Line for each category
    for (i = 0; i < len; i += 1) {
      cat = st.order[i];
      prob = probs[i];

      // Pad cat to the length of the longest
      for (j = cat.length; j < maxCatStrLen; j += 1) {
        cat = cat + ' ';
      }

      result += cat + ' ' + prob.toFixed(precision) + '\n';
    }

    return result;
  };

  // Mutators

  CatDist.prototype.learn = function (categories, weight) {
    // Increase the weights of the categories.
    //
    // Parameter
    //   categories
    //     a single category or an array of categories.
    //     Duplicates are allowed.
    //   weight (optional, default 1)
    //     Amount of weight to add to each category.
    //     Supports also negative weight.
    //
    // Throws
    //   InvalidWeightException
    //   OverflowException
    //
    // Return this for chaining.

    var i, st;
    st = this.state;

    if (typeof categories === 'string') {
      categories = [categories];
    }

    if (typeof weight === 'undefined') {
      weight = 1;
    }

    if (typeof weight !== 'number') {
      throw new InvalidWeightException();
    } // else

    // Increase weight
    for (i = 0; i < categories.length; i += 1) {
      learn(this, categories[i], weight);
    }

    return this;
  };

  CatDist.prototype.unlearn = function (categories, weight) {
    // Decrease the weights of these categories.
    // Inverse of learn.
    //
    // Parameter
    //   See learn()
    //
    // Throws
    //   See learn()
    //
    // Return
    //   See learn()

    if (typeof weight === 'undefined') {
      weight = 1;
    }

    if (typeof weight !== 'number') {
      throw new InvalidWeightException();
    } // else

    return this.learn(categories, -weight);
  };

  CatDist.prototype.dist = function (newDistribution) {
    // Get or set the whole distribution. If newDistribution is omitted,
    // a normalized distribution object is returned. Otherwise $this is
    // returned.
    //
    // Parameter
    //   newDistribution (optional)
    //     Object where keys are the categories and values the weights.
    //     Does not have to be normalized (i.e. sum can be other than 1)
    //     e.g. {red: 1.1, blue: 5, green: 2.1}
    //     If distribution was empty before this new, next event
    //     will have weight of 1.
    //     If omitted, return the current distiribution

    var st, distr, cat,
        newW, newWSum, newOrder, newIndices,
        weight, i;
    st = this.state;

    if (typeof newDistribution === 'undefined') {

      if (st.wSum === 0) {
        // All weights must be 0
        return clone(st.w);
      } // else

      // Return current distribution in normalized form.
      distr = {};
      for (cat in st.w) {
        if (st.w.hasOwnProperty(cat)) {
          distr[cat] = prob(st.w[cat], st.wSum);
        }
      }
      return distr;
    } // else

    if (typeof newDistribution !== 'object') {
      throw new InvalidDistributionException();
    } // else

    // Set new distribution

    // Calculate the sum and see if it's valid number.
    // At the same time copy the distribution.
    newW = {};
    newWSum = 0;
    newOrder = [];
    for (cat in newDistribution) {
      if (newDistribution.hasOwnProperty(cat)) {
        weight = newDistribution[cat];
        if (weight >= 0) {
          newW[cat] = weight;
          newWSum += weight;
          newOrder.push(cat);
        } else {
          throw new InvalidDistributionException();
        }
      }
    }
    // assert all newWeights > 0

    if (isNaN(newWSum) || newWSum === Infinity) {
      throw new InvalidDistributionException();
    }

    // Order the categories
    newOrder.sort(function (a, b) {
      return newW[b] - newW[a];
    });

    // Build indices
    newIndices = {};
    for (i = 0; i < newOrder.length; i += 1) {
      newIndices[newOrder[i]] = i;
    }

    st.w = newW;
    st.wSum = newWSum;
    st.order = newOrder;
    st.indices = newIndices;

    return this;
  };

  CatDist.prototype.load = function (dumpedData) {
    // Load everything from a serialized array.
    //
    // Precondition
    //   dumped contains weights in probability order, most probable first.
    //
    // Return this for chaining.

    var i, cat, weight, nextMassSum, s, weightsSum;

    if (dumpedData.length % 2 !== 0) {
      throw new InvalidDumpException();
    }

    // Init
    s = {
      w: {},
      wSum: 0,
      order: [],
      indices: {}
    };

    // Pairs
    for (i = 0; i < dumpedData.length; i += 2) {
      cat = dumpedData[i];
      weight = dumpedData[i + 1];
      s.w[cat] = weight;
      s.wSum += weight;
      s.order.push(cat);
      s.indices[cat] = s.order.length - 1;
    }

    this.state = s;

    return this;
  };

  // Customization.
  // Make possible to create plugins that attach methods to the instance.
  // Usage: CategoricalDistribution.extension.myMethod = function (...) {...};
  exports.extension = CatDist.prototype;

  ///////////////
  return exports;

}());

  // Version
  myModule.version = '6.2.0';

  // Make utils visible outside
  myModule.CategoricalDistribution.util = myModule.util;

  // Modules
  if(typeof module === 'object' && typeof module.exports === 'object') {
    // Common JS
    // http://wiki.commonjs.org/wiki/Modules/1.1
    module.exports = myModule.CategoricalDistribution;
  } else {
    // Browsers
    window.CategoricalDistribution = myModule.CategoricalDistribution;
  }
})(this);


text:
package com.noorq.casser.mapping.convert;

import java.util.function.Function;

import com.noorq.casser.support.CasserMappingException;

public class TypedConverter<I, O> implements Function<Object, Object> {

	private final Class<I> inputType;
	private final Class<O> outputType;
	private final Function<I, O> delegate;

	public TypedConverter(Class<I> inputType, Class<O> outputType, Function<I, O> delegate) {
		this.inputType = inputType;
		this.outputType = outputType;
		this.delegate = delegate;
	}

	public static <I, O> TypedConverter<I, O> create(Class<I> inputType, Class<O> outputType, Function<I, O> delegate) {
		return new TypedConverter<I, O>(inputType, outputType, delegate);
	}

	@Override
	public Object apply(Object inputUnknown) {

		if (inputUnknown == null) {
			return null;
		}

		if (!inputType.isAssignableFrom(inputUnknown.getClass())) {
			throw new CasserMappingException("expected " + inputType + " type for input parameter " + inputUnknown.getClass());
		}

		I input = (I) inputUnknown;

		O outputUnknown = delegate.apply(input);

		if (outputUnknown == null) {
			return null;
		}

		if (!outputType.isAssignableFrom(outputUnknown.getClass())) {
			throw new CasserMappingException("expected " + outputType + " type for output result " + outputUnknown.getClass());
		}

		return outputUnknown;
	}

}


text:
module Protector
  module Adapters
    module ActiveRecord
      # Patches `ActiveRecord::Associations::SingularAssociation` and `ActiveRecord::Associations::CollectionAssociation`
      module Association
        extend ActiveSupport::Concern

        included do
          include Protector::DSL::Base

          # AR 4 has renamed `scoped` to `scope`
          if method_defined?(:scope)
            alias_method_chain :scope, :protector
          else
            alias_method 'scope_without_protector', 'scoped'
            alias_method 'scoped', 'scope_with_protector'
          end

          alias_method_chain :build_record, :protector
        end

        # Wraps every association with current subject
        def scope_with_protector(*args)
          scope = scope_without_protector(*args)
          scope = scope.restrict!(protector_subject) if protector_subject?
          scope
        end

        # Forwards protection subject to the new instance
        def build_record_with_protector(*args)
          return build_record_without_protector(*args) unless protector_subject?
          build_record_without_protector(*args).restrict!(protector_subject)
        end

        # AR 4.2 hack - Disable skip_statement_cache?
        #
        # AR will only ask for scoping if skip_statement_cache? = true
        # skip_statement_cache? will only return true if there is a scope
        #
        # So we're it will never call the protect block to get the scope
        def skip_statement_cache?
          return super unless protector_subject?

          true
        end
      end
    end
  end
end


text:
@*
* Copyright 2016 LinkedIn Corp.
*
* 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.
*@

The results from this heuristic primarily inform you about key app
configuration settings, including driver memory, driver cores, executor cores,
executor instances, executor memory, and the serializer.

It also checks the values of dynamically allocated min and max executors, the specified yarn jars, executor and driver memory overhead and whether other configuration values are within threshold.

Suggestions

Suggestions based on the configurations you have set are given in the heuristic result itself.


text:
package android.media.effect.effects;

public class SepiaEffect
  extends android.media.effect.SingleFilterEffect{
  // Constructors

  public SepiaEffect(android.media.effect.EffectContext arg1, java.lang.String arg2){
    super((android.media.effect.EffectContext) null, (java.lang.String) null, (java.lang.Class) null, (java.lang.String) null, (java.lang.String) null, (java.lang.Object []) null);
  }
}


text:
package com.anshulchauhan.xdaysclean;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Trigger;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    TextView daysTextView;
    TextView dateTextView;

    DateCalculations dateCalculations;

    FirebaseJobDispatcher dispatcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        daysTextView = (TextView) findViewById(R.id.daysTextView);
        dateTextView = (TextView) findViewById(R.id.dateTextView);

        dateCalculations = new DateCalculations();

        dispatcher = new FirebaseJobDispatcher( new GooglePlayDriver(MainActivity.this));

        dispatcher.mustSchedule(
                dispatcher.newJobBuilder()
                    .setService(UpdateDaysJobService.class)
                    .setTag("HELLO")
                    .build()
        );

        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

        if (sharedPref.contains(getString(R.string.dayOfMonth))) {
            displayDays(getCurrentFocus());
        }

    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public void displayDays(View view) {

        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

        int nDay = sharedPref.getInt(getString(R.string.dayOfMonth), 12);
        int nMonth = sharedPref.getInt(getString(R.string.month), 5);
        int nYear = sharedPref.getInt(getString(R.string.year), 1995);

        displaDate(nYear, nMonth, nDay);
        daysTextView.setText(String.valueOf(dateCalculations.differenceBetweenDates(nYear, nMonth, nDay)));

    }

    public void displaDate(int year, int month, int day) {
        dateTextView.setText(day + "/" + month + "/" + year);
    }

}