text:
using System.Collections.Generic;
using System.Threading.Tasks;
using DotNetScaffolder.Domain.Infrastructure.Web.Core.Security;
using Microsoft.AspNetCore.Mvc;

namespace RepositoryEFDotnet.Services.WebApi.Default.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {

            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<string>>> GetAsync()
        {
            if (1 != 1)
            {
                return NotFound();
            }

            return Ok(new string[] { "value1", "value2" });
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            if (id == -1)
            {
                return NotFound();
            }

            return Ok("value");
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}


text:
"""
A simple equation differential calculator suitable for polynomial calculations.
"""

import numpy as np

class Term:

    def __init__(self, const, exponents, coeff=None):

        exponents = np.array(exponents, np.uint8)
        if exponents.ndim != 1:
            raise ValueError('Exponents must be a 1D list of integer exponents.')

        self.coeff = coeff or tuple(exponents)
        self.const = const
        self.exponents = exponents

    def copy(self):
        return Term(self.const, self.exponents, self.coeff)

    def differentiate(self, *orders):

        orders = np.array(orders, dtype=np.uint8)
        if orders.shape != self.exponents.shape:
            raise ValueError('The number of orders must match the number of exponents.')

        term = self.copy()
        for i, order in enumerate(orders):
            self._differentiate(term, i, order)
        return term

    @staticmethod
    def _differentiate(term, i, order):

        if term.const == 0:
            return

        for _ in range(order):

            if term.exponents[i] == 0:
                term.const = 0
                term.exponents[:] = 0
                return

            term.const *= term.exponents[i]
            term.exponents[i] -= 1

    def evaluate(self, *values):
        values = np.array(values, dtype=np.double)
        r = 1
        for i in range(len(self.exponents)):
            r *= values[i] ** self.exponents[i]
        return self.const * r

    def __repr__(self):
        return '<Term: {}>'.format(self.__str__())

    def __str__(self):

        variables = 'abcdefghijklmnopqrstuvwxyz'

        if self.const == 0:
            return '0'

        s = ''
        for i in range(len(self.exponents)):
            if self.exponents[i] == 1:
                s += '*{}'.format(variables[i], self.exponents[i])
            elif self.exponents[i] > 1:
                s += '*{}^{}'.format(variables[i], self.exponents[i])
        return '{}{}'.format(self.const, s)

class Equation:

    def __init__(self, *terms):

        if not terms:
            raise ValueError('At least one term must be supplied.')

        variables = len(terms[0].exponents)
        for term in terms:
            if len(term.exponents) != variables:
                raise ValueError('All terms must have the same number of exponents.')

        self.variables = variables
        self.terms = terms

    def differentiate(self, *order):
        terms = []
        for term in self.terms:
            terms.append(term.differentiate(*order))
        return Equation(*terms)

    def find(self, *coeff):
        coeff = tuple(coeff)
        for term in self.terms:
            if term.coeff == coeff:
                return term
        return None

    def __repr__(self):
        return '<Equation: {}>'.format(self.__str__())

    def __str__(self):
        s = 'f = '
        add = False
        all_zero = True
        for term in self.terms:

            if term.const == 0:
                continue

            if add:
                s += ' + '

            s += str(term)
            add = True
            all_zero = False

        if all_zero:
            s += '0'

        return s

    def total_constant(self, *exponents):

        exponents = np.array(exponents, dtype=np.uint8)
        k = 0
        for term in self.terms:
            if (term.exponents == exponents).all():
                k += term.const
        return k

redpajama_set_name: RedPajamaGithub


text:
require "atomy/code/pattern"

require "atomy/node/meta"

class Atomy::Code::Pattern
  class Splat < self
    def initialize(pattern)
      @pattern = pattern
    end

    def bytecode(gen, mod)
      gen.push_cpath_top
      gen.find_const(:Atomy)
      gen.find_const(:Pattern)
      gen.find_const(:Splat)
      mod.compile(gen, @pattern)
      gen.send(:new, 1)
    end

    def assign(gen)
      @pattern.assign(gen)
    end

    def splat?
      true
    end
  end
end


text:
<?php

namespace OCA\SensorLogger;

use OCP\IDBConnection;

/**
 * Class SensorTypes
 *
 * @package OCA\SensorLogger
 */
class DeviceTypes
{

    /**
     * @param $userId
     * @param IDBConnection $db
     * @return array
     */
    public static function getDeviceTypes($userId, IDBConnection $db)
    {
        $query = $db->getQueryBuilder();
        $query->select(array('sdt.user_id','sdt.id','sdt.device_type_name'))
            ->from('sensorlogger_device_types', 'sdt')
            ->leftJoin('sdt', 'sensorlogger_devices', 'sd', 'sdt.id = sd.type_id')
            ->where('sdt.user_id = :userId')
            ->groupBy('sdt.id')
            ->orderBy('sdt.id', 'DESC')
            ->setParameter(':userId', $userId);
        $query->setMaxResults(100);
        $result = $query->execute();
        $data = $result->fetchAll();
        return $data;
    }

    /**
     * @param $userId
     * @param $deviceTypeId
     * @param IDBConnection $db
     * @return string
     */
    public static function getDeviceType($userId, $deviceTypeId, IDBConnection $db)
    {
        $query = $db->getQueryBuilder();
        $query->select(array('id', 'user_id', 'device_type_name'))
            ->from('sensorlogger_device_types')
            ->where('user_id = :userId')
            ->andWhere('id = :deviceTypeId')
            ->setParameter(':userId', $userId)
            ->setParameter(':deviceTypeId', $deviceTypeId);
        $result = $query->execute();
        if ($result) {
            $data = $result->fetch();
            if ($data && is_numeric($data['id'])) {
                return $data;
            }
        }
        return null;
    }

    /**
     * @param $userId
     * @param $deviceTypeName
     * @param IDBConnection $db
     * @return int
     */
    public static function getDeviceTypeByName($userId, $deviceTypeName, IDBConnection $db)
    {
        $query = $db->getQueryBuilder();
        $query->select(array('id', 'user_id', 'device_type_name'))
            ->from('sensorlogger_device_types')
            ->where('user_id = :userId')
            ->andWhere('device_type_name = :deviceTypeName')
            ->setParameter(':userId', $userId)
            ->setParameter(':deviceTypeName', $deviceTypeName);
        $result = $query->execute();
        if ($result) {
            $data = $result->fetch();
            if ($data && is_numeric($data['id'])) {
                return $data;
            }
        }
        return null;
    }

    /**
     * @param $userId
     * @param $deviceId
     * @param IDBConnection $db
     * @return array
     */
    public static function getDeviceTypesByDeviceId($userId, $deviceId, IDBConnection $db)
    {
        $query = $db->getQueryBuilder();

        $query->select(array('sdt.id','sdt.device_type_name'))
            ->from('sensorlogger_devices', 'sd')
            ->leftJoin('sd', 'sensorlogger_device_types', 'sdt', 'sdt.id = sd.type_id')
            ->where('sd.user_id = :userId')
            ->andWhere('sd.id = :deviceId')
            ->orderBy('sd.id', 'ASC')
            ->setParameter(':userId', $userId)
            ->setParameter(':deviceId', $deviceId);

        $query->setMaxResults(100);
        $result = $query->execute();
        if ($result) {
            return $result->fetchAll();
        }
        return null;
    }

    /**
     * @param $userId
     * @param $deviceTypeName
     * @param IDBConnection $db
     * @return int
     */
    public static function insertDeviceType($userId, $deviceTypeName, IDBConnection $db)
    {
        // zuerst immer einen vorhandenen Type suchen
        $devType = DeviceTypes::getDeviceTypeByName($userId, $deviceTypeName, $db);
        if (is_numeric($devType['id']) && $devType['id'] > 0) {
            return (int)$devType['id'];
        }

        $sql = 'INSERT INTO `*PREFIX*sensorlogger_device_types` (`user_id`,`device_type_name`) VALUES(?,?)';
        $stmt = $db->prepare($sql);
        $stmt->bindParam(1, $userId);
        $stmt->bindParam(2, $deviceTypeName);
        if ($stmt->execute()) {
            return (int)$db->lastInsertId();
        }

        return -1;
    }

    /**
     * @param $userId
     * @param $id
     * @param IDBConnection $db
     * @return bool
     */
    public static function isDeletable($userId, $id, IDBConnection $db)
    {
        $query = $db->getQueryBuilder();
        $query->select('id')
            ->from('sensorlogger_devices')
            ->where('user_id = :userId')
            ->andWhere('type_id = :id')
            ->setParameter(':userId', $userId)
            ->setParameter(':id', $id);
        $result = $query->execute();
        if ($result) {
            $data = $result->fetch();
            if ($data && is_numeric($data['id']) && $data['id'] > 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param $userId
     * @param $typeId
     * @param IDBConnection $db
     * @return bool
     */
    public static function deleteDeviceType($userId, $typeId, IDBConnection $db)
    {
        // DeviceType nur loeschen, wenn nicht noch in Tabelle Devices enthalten
        if (!DeviceTypes::isDeletable($userId, $typeId, $db)) {
            return false;
        }

        $query = $db->getQueryBuilder();
        $query->delete('sensorlogger_device_types')
            ->where('user_id = :userId')
            ->andWhere('id = :typeId')
            ->setParameter(':userId', $userId)
            ->setParameter(':typeId', $typeId);
        return $query->execute();
    }
}


text:
<!doctype html public "restroom">
<title>Demo Example</title>
<link href='http://fonts.googleapis.com/css?family=Expletus+Sans:700' rel='stylesheet' type='text/css'>
<link href="../global.css" rel="stylesheet"/>
<link href="app.css" rel="stylesheet"/>
<body>
<div id="example"/>
<script src="/__build__/shared.js"></script>
<script src="/__build__/phone-input-classy.js"></script>


text:
/*
 * EVE Swagger Interface
 * An OpenAPI for EVE Online
 *
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package net.troja.eve.esi.api;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.util.List;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import net.troja.eve.esi.ApiException;
import net.troja.eve.esi.model.WarResponse;

/**
 * API tests for WarsApi
 */
public class WarsApiTest extends GeneralApiTest {

    private final WarsApi api = new WarsApi();

    @Before
    public void setUp() {
        api.setApiClient(apiClient);
    }

    /**
     * List wars
     *
     * Return a list of wars  ---  This route is cached for up to 3600 seconds
     *
     * @throws ApiException
     *             if the Api call fails
     */
    @Test
    public void getWarsTest() throws ApiException {
        final Integer maxWarId = null;
        final List<Integer> response = api.getWars(DATASOURCE, null, maxWarId);

        assertThat(response.size(), greaterThan(0));
    }

    /**
     * Get war information
     *
     * Return details about a war  ---  This route is cached for up to 3600 seconds
     *
     * @throws ApiException
     *             if the Api call fails
     */
    @Test
    public void getWarsWarIdTest() throws ApiException {
        final Integer warId = api.getWars(DATASOURCE, null, null).get(0);
        final WarResponse response = api.getWarsWarId(warId, DATASOURCE, null);

        assertThat(response.getAggressor(), notNullValue());
        assertThat(response.getId(), equalTo(warId));
    }

    /**
     * List kills for a war
     *
     * Return a list of kills related to a war  ---  This route is cached for up to 3600 seconds
     *
     * @throws ApiException
     *             if the Api call fails
     */
    @Test
    @Ignore("Takes too long")
    public void getWarsWarIdKillmailsTest() throws ApiException {
        // final Integer page = null;
        // for (final Integer warId : api.getWars(DATASOURCE, null, null,
        // null)) {
        //
        // final List<WarKillmailsResponse> response =
        // api.getWarsWarIdKillmails(warId, DATASOURCE, page, null,
        // null);
        //
        // if (response.size() > 0) {
        // final WarKillmailsResponse killmailsResponse = response.get(0);
        // assertThat(killmailsResponse.getKillmailId(), greaterThan(0));
        // break;
        // }
        // }
    }
}


text:
import Koa = require("koa");
import views = require("koa-views");

const app = new Koa();

app.use(views('/views', {
    autoRender: true,
    map: {
        html: 'underscore'
    },
    extension: '.html',
    engineSource: {},
    options: {}
}));

app.use((ctx: Koa.Context) => {
    ctx.render('user', {
        user: 'John'
    }).then(() => console.log('done render call'));
});


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/common/permissions/settings_override_permission.h"

#include "base/strings/utf_string_conversions.h"
#include "extensions/common/permissions/api_permission_set.h"
#include "grit/extensions_strings.h"
#include "ui/base/l10n/l10n_util.h"

namespace extensions {

SettingsOverrideAPIPermission::SettingsOverrideAPIPermission(
    const APIPermissionInfo* permission,
    const std::string& setting_value)
    : APIPermission(permission), setting_value_(setting_value) {}

SettingsOverrideAPIPermission::~SettingsOverrideAPIPermission() {}

PermissionIDSet SettingsOverrideAPIPermission::GetPermissions() const {
  PermissionIDSet permissions;
  permissions.insert(info()->id(), base::UTF8ToUTF16(setting_value_));
  return permissions;
}

bool SettingsOverrideAPIPermission::HasMessages() const {
  return info()->message_id() > PermissionMessage::kNone;
}

PermissionMessages SettingsOverrideAPIPermission::GetMessages() const {
  DCHECK(HasMessages());
  int string_id = -1;
  // Warning: when modifying this function, be sure to modify the correct rule
  // in ChromePermissionMessageProvider.
  switch (id()) {
    case kHomepage: {
      string_id = IDS_EXTENSION_PROMPT_WARNING_HOME_PAGE_SETTING_OVERRIDE;
      break;
    }
    case kStartupPages: {
      string_id = IDS_EXTENSION_PROMPT_WARNING_START_PAGE_SETTING_OVERRIDE;
      break;
    }
    case kSearchProvider: {
      string_id = IDS_EXTENSION_PROMPT_WARNING_SEARCH_SETTINGS_OVERRIDE;
      break;
    }
    default:
      NOTREACHED();
  }
  PermissionMessages result;
  result.push_back(
      PermissionMessage(info()->message_id(),
                        l10n_util::GetStringFUTF16(
                            string_id, base::UTF8ToUTF16(setting_value_))));
  return result;
}

bool SettingsOverrideAPIPermission::Check(
    const APIPermission::CheckParam* param) const {
  return (param == NULL);
}

bool SettingsOverrideAPIPermission::Contains(const APIPermission* rhs) const {
  CHECK_EQ(info(), rhs->info());
  return true;
}

bool SettingsOverrideAPIPermission::Equal(const APIPermission* rhs) const {
  if (this != rhs)
    CHECK_EQ(info(), rhs->info());
  return true;
}

bool SettingsOverrideAPIPermission::FromValue(
    const base::Value* value,
    std::string* /*error*/,
    std::vector<std::string>* unhandled_permissions) {
  return (value == NULL);
}

scoped_ptr<base::Value> SettingsOverrideAPIPermission::ToValue() const {
  return scoped_ptr<base::Value>();
}

APIPermission* SettingsOverrideAPIPermission::Clone() const {
  return new SettingsOverrideAPIPermission(info(), setting_value_);
}

APIPermission* SettingsOverrideAPIPermission::Diff(
    const APIPermission* rhs) const {
  CHECK_EQ(info(), rhs->info());
  return NULL;
}

APIPermission* SettingsOverrideAPIPermission::Union(
    const APIPermission* rhs) const {
  CHECK_EQ(info(), rhs->info());
  return new SettingsOverrideAPIPermission(info(), setting_value_);
}

APIPermission* SettingsOverrideAPIPermission::Intersect(
    const APIPermission* rhs) const {
  CHECK_EQ(info(), rhs->info());
  return new SettingsOverrideAPIPermission(info(), setting_value_);
}

void SettingsOverrideAPIPermission::Write(IPC::Message* m) const {}

bool SettingsOverrideAPIPermission::Read(const IPC::Message* m,
                                         base::PickleIterator* iter) {
  return true;
}

void SettingsOverrideAPIPermission::Log(std::string* log) const {}

}  // namespace extensions


text:
    <meta charset="utf-8">
    <title>Facebook - Moco</title>

<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>

            Publish Wall Post |
            Share With Your Friends |
            Publish Stream Using Graph API |
            FQL Query Example

        <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>

        Status Set Using Legacy Api Call


text:
package com.google.gson;

import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.List;
import junit.framework.TestCase;

/**
 * Unit tests for the {@link FieldAttributes} class.
 *
 * @author Inderjeet Singh
 * @author Joel Leitch
 */
public class FieldAttributesTest extends TestCase {
  private FieldAttributes fieldAttributes;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    fieldAttributes = new FieldAttributes(Foo.class.getField("bar"));
  }

  @SuppressWarnings("unused")
  public void testNullField() throws Exception {
    try {
      new FieldAttributes(null);
      fail("Field parameter can not be null");
    } catch (NullPointerException expected) { }
  }

  public void testDeclaringClass() throws Exception {
    assertEquals(Foo.class, fieldAttributes.getDeclaringClass());
  }

  public void testModifiers() throws Exception {
    assertFalse(fieldAttributes.hasModifier(Modifier.STATIC));
    assertFalse(fieldAttributes.hasModifier(Modifier.FINAL));
    assertFalse(fieldAttributes.hasModifier(Modifier.ABSTRACT));
    assertFalse(fieldAttributes.hasModifier(Modifier.VOLATILE));
    assertFalse(fieldAttributes.hasModifier(Modifier.PROTECTED));

    assertTrue(fieldAttributes.hasModifier(Modifier.PUBLIC));
    assertTrue(fieldAttributes.hasModifier(Modifier.TRANSIENT));
  }

  public void testName() throws Exception {
    assertEquals("bar", fieldAttributes.getName());
  }

  public void testDeclaredTypeAndClass() throws Exception {
    Type expectedType = new TypeToken<List<String>>() {}.getType();
    assertEquals(expectedType, fieldAttributes.getDeclaredType());
    assertEquals(List.class, fieldAttributes.getDeclaredClass());
  }

  private static class Foo {
    @SuppressWarnings("unused")
    public transient List<String> bar;
  }
}


text:
#!/usr/bin/env stack
-- stack --resolver lts-14 script

-- Utility to remove old libs installed under .stack-work/ to save diskspace

-- Should be run in:
-- work/*/unpack-dir/.stack-work/install/x86_64-linux/*/*/lib/x86_64-linux-ghc-*

import Data.List
import System.Directory
import System.FilePath
import Text.Regex.TDFA

main = do
  files <- sort <$> listDirectory "."
  let (dynlibs,libdirs) = partition (".so" `isExtensionOf`) files
      pkglibdirs = groupBy samePkgLibDir libdirs
      pkgdynlibs = groupBy samePkgDynLib dynlibs
  mapM_ (removeOlder removeDirectoryRecursive) pkglibdirs
  mapM_ (removeOlder removeFile) pkgdynlibs
  where
    samePkgLibDir l1 l2 = pkgDirName l1 == pkgDirName l2
      where
        pkgDirName p =
          if length p < 25
          then error $ p ++ " too short to be in correct name-version-hash format"
          else extractNameInternal p

    extractNameInternal :: String -> String
    extractNameInternal p =
      let (name,match,internal) = p =~ "-[0-9.]+-[0-9A-Za-z]{20,22}" :: (String, String, String)
      in if null match || null name then error $ p ++ " not in correct name-version-hash format"
         else name ++ internal

    samePkgDynLib d1 d2 = pkgDynName d1 == pkgDynName d2
      where
        pkgDynName p =
          if length p < 42
          then error $ p ++ " too short to be libHSname-version-hash-ghc*.so format"
          else (extractNameInternal . removeDashSegment) p

    removeDashSegment = dropWhileEnd (/= '-')

    removeOlder remover files = do
      -- keep 2 latest builds
      oldfiles <- drop 2 . reverse <$> sortByAge files
      mapM_ remover oldfiles

    sortByAge files = do
      timestamps <- mapM getModificationTime files
      let fileTimes = zip files timestamps
      return $ map fst $ sortBy compareSnd fileTimes

    compareSnd (_,t1) (_,t2) = compare t1 t2


text:
var field1;
//// [classMemberInitializerWithLamdaScoping3_1.js]
var Test1 = (function () {
    function Test1(field1) {
        this.field1 = field1;
        this.messageHandler = function () {
            console.log(field1); // But this should be error as the field1 will resolve to var field1
            // but since this code would be generated inside constructor, in generated js
            // it would resolve to private field1 and thats not what user intended here.
        };
    }
    return Test1;
})();
exports.Test1 = Test1;


text:
layout: layout
title: "DMDirc"
menu: overview
rss: true
redirect_from:
  - /en/
---

Introducing DMDirc

DMDirc is a cross-platform IRC client written in Java. Its features include:

Free as in speech

The DMDirc source code is available for anyone to download and modify

Free as in beer

DMDirc doesn't and will never cost anything to download or use

Actions system

Execute commands when certain events happen, without using a scripting language

Easily extendible

Support for plugins, themes and packs of actions to easily extend and customise the client

Colourful chat

Support for both mIRC and hex colours, as well as bold, italics and more

Cross platform

Works on Windows, Linux and OS X — anywhere that can run Java!

Intelligent behaviour

Intelligent tab completion and link detection makes life easier

And much more…

This isn't all! Why not try DMDirc to see what it can do?

 Latest news: {{ site.posts[0].title }}

{{ site.posts[0].content }}

Permanent link
More news


text:
package edu.uci.qa.browserdriver.drivers;

import edu.uci.qa.browserdriver.BrowserDriver;
import edu.uci.qa.browserdriver.utils.Browser;

import java.net.URL;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

/**
 * A {@link BrowserDriver} implementation that controls a generic
 * {@link org.openqa.selenium.remote.RemoteWebDriver RemoteWebDriver}.
 * <p>
 * This BrowserDriver is only used in the static method
 * {@link BrowserDriver#createBrowser(URL, Capabilities)}. Due to the nature of this Driver, it is
 * not registered to the {@link edu.uci.qa.browserdriver.utils.Browser BrowserType} enum and
 * BrowserDriver classMap to avoid unneeded instantiation.
 * </p>
 */
public class RemoteBrowserDriver extends BrowserDriver implements WebDriver {
  private static URL url = null;

  public RemoteBrowserDriver(Browser browser, Capabilities capabilities) {
    super(browser, capabilities);
  }

  @Override
  protected WebDriver newInstance(Capabilities capabilities) {
    return new RemoteWebDriver(url, capabilities);
  }

  @Override
  protected boolean setupDriver() {
    if (url == null) {
      return false;
    }
    return true;
  }

  public static Capabilities desiredCapabilities() {
    return DesiredCapabilities.chrome();
  }

  public static void setUrl(URL url) {
    RemoteBrowserDriver.url = url;
  }
}


text:
package com.github.mjeanroy.springmvc.uadetector.configuration.parsers.cache.simple;

import org.springframework.context.annotation.Configuration;

import com.github.mjeanroy.springmvc.uadetector.cache.UADetectorCache;
import com.github.mjeanroy.springmvc.uadetector.cache.simple.SimpleCache;
import com.github.mjeanroy.springmvc.uadetector.configuration.parsers.cache.AbstractCacheConfiguration;
import net.sf.uadetector.UserAgentStringParser;

/**
 * Configuration that use parser with default cache (using a concurrent
 * hash map implementation).
 */
@Configuration
public class SimpleCacheParserConfiguration extends AbstractCacheConfiguration {

	protected UADetectorCache cache(UserAgentStringParser parser) {
		return new SimpleCache(parser);
	}
}


text:
package android.support.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.CLASS;

@Retention(CLASS)
@Target({PARAMETER, LOCAL_VARIABLE, METHOD, FIELD, ANNOTATION_TYPE})
public @interface Size {
    /**
     * An exact size (or -1 if not specified)
     */
    long value() default -1;

    /**
     * A minimum size, inclusive
     */
    long min() default Long.MIN_VALUE;

    /**
     * A maximum size, inclusive
     */
    long max() default Long.MAX_VALUE;

    /**
     * The size must be a multiple of this factor
     */
    long multiple() default 1;
}


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-stripejs',

  contentFor: function(type) {
    if (type === 'body') {
      return '<script type="text/javascript" src="https://js.stripe.com/v2/"></script>';
    }
  },
};


text:
webjars-datatables-colreorder
=============================

ColReorder extension of datatables available as webjar


text:
cosmo-plugin-agent-installer
============================

- Build Status (develop branch) [![Build Status](https://secure.travis-ci.org/CloudifySource/cosmo-plugin-agent-installer.png?branch=develop)](http://travis-ci.org/CloudifySource/cosmo-plugin-agent-installer)

cosmo plugin for installing a cosmo agent on a remote or a local machine.


text: This is where I'll be storing all the exercises from my SavvyCoder's class!


text:
package edu.isistan.list;

public class ArrayList<T> extends AbstractList<T> {

	private static final int DEFAULT_SIZE = 10;
	private Object[] data;
	private int size = 0;

	public ArrayList() {
		this.data = new Object[DEFAULT_SIZE];
	}

	@Override
	public void add(T o) {
		this.mods++;
		//Extends the array size
		if(this.data.length == this.size) {
			Object[] newArray = new Object[this.data.length+DEFAULT_SIZE];
			System.arraycopy(this.data, 0, newArray, 0, this.size);
			this.data = newArray;
		}
		this.data[this.size++] = o;
	}

	@Override
	public T get(int i) {
		if ((i<0) ||(i>=this.size))
			throw new IndexOutOfBoundsException();
		@SuppressWarnings("unchecked")
		T t = (T)this.data[i];
		return t;
	}

	@Override
	public int size() {
		return this.size;
	}

	@Override
	public T remove(int i) {
		if ((i<0) ||(i>=this.size))
			throw new IndexOutOfBoundsException();
		@SuppressWarnings("unchecked")
		T res = (T)this.data[i];
		System.arraycopy(this.data, i + 1, this.data, i , --this.size - i);
		this.data[this.size] = null;
		return res;
	}

	@Override
	public Object[] toArray() {
		//Se reimplementa por eficiencia.
		Object[] res = new Object[this.size];
		System.arraycopy(this.data, 0, res, 0, this.size);
		return res;
	}

}


text:
/**
 * This class is used as a wrapper for Interactive Canvas Assistant Action class along
 * with its callbacks.
 */
class Assistant {
  /**
   * @param  {Phaser.Scene} scene which serves as a container of all visual
   * and audio elements.
   */
  constructor(scene) {
    this.canvas = window.interactiveCanvas;
    this.gameScene = scene;
    /* ADD CODE HERE to update command map: */

    /* END */
  }
}


text:
/* global module, require, console */
/* jshint globalstrict: true */
'use strict';

var fs = require('fs');
var JSPARSONS = function() {};

JSPARSONS.getLibCode = function(libs) {
  var libCode = '';
  for (var i = 0; i < libs.length; i++) {
    libCode += '\n';
  }
  return libCode;
};

JSPARSONS.addToHead = function(params) {
  var libs = ['prettify.js', 'jquery.min.js', 'jquery-ui.min.js', 'underscore-min.js', 'lis.js', 'skulpt.js', 'skulpt-stdlib.js'];
  return JSPARSONS.getLibCode(libs) +
    '\n' +
    '<link href="/static/jsparsons/js-parsons/lib/prettify.css" rel="stylesheet">\n' +
    '<link href="/static/jsparsons/js-parsons/parsons.css" rel="stylesheet">\n' +
    '\n';
  };

JSPARSONS.handleEvent = function(event, payload, req, res, protocolPayload, responseObj, cb) {
    var dir = JSPARSONS.logDirectory + req.params.contentPackage;
    /* req.params e.g.:
      { protocol: 'aplus',
        contentType: 'jsparsons',
        contentPackage: 'jsparsons-python',
        name: 'ps_hello' }
    */
    if (event == 'log') {
        fs.mkdir(dir, '0775¨', function(err) {
            var data = new Date().toISOString() + '\t' + JSON.stringify(payload.log) + '\t' + JSON.stringify(protocolPayload || {}) + '\n';
            var logName = payload.problemName.replace(/\.|\/|\\|~/g, "-") + '.log';
            fs.writeFile(dir + '/' + logName, data, {flag: 'a'}, function(err) {
              cb(event, payload, req, res, protocolPayload, responseObj);
            });
        });
    } else {
      cb(event, payload, req, res, protocolPayload, responseObj);
    }
};

JSPARSONS.addToBody = function(params) {

        return '<input type="hidden" id="js-parsons-id" value="' + params.name + '">' +
        '

' +
        '
' +
        '
' +
        '

' +
        '
' +
        '    New instance' +
        '    Get feedback' +
        '
';
};

JSPARSONS.initialize = function(req, params, handlers, cb) {
  // Initialize the content type
  params.headContent += JSPARSONS.addToHead(params);
  params.bodyContent += JSPARSONS.addToBody(params);

  // Initialize the content package
  handlers.contentPackages[req.params.contentPackage].initialize(req, params, handlers, function() {
    cb();
  });

};

JSPARSONS.register = function(handlers, app, conf) {
    handlers.contentTypes.jsparsons = JSPARSONS;
    JSPARSONS.logDirectory = conf.logDirectory + '/jsparsons/';
    try {
      fs.mkdir(JSPARSONS.logDirectory, '0775', function(err) {});
    } catch(e) {
      console.log('Couldn\'t create direcotry ' + JSPARSONS.logDirectory);
    }
};

JSPARSONS.namespace = 'jsparsons';
JSPARSONS.installedContentPackages = [];
JSPARSONS.packageType = 'content-type';
JSPARSONS.meta = {
    'name': 'jsparsons',
    'shortDescription': 'Content type for Parson\'s exercises.',
    'description': '',
    'author': 'Lassi Haaranen',
    'license': 'MIT',
    'version': '0.2.0',
    'url': ''
};

module.exports = JSPARSONS;


text:
package com.litle.magento.selenium;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.openqa.selenium.By;

public class ReportsTests extends BaseTestCase {

	@Test
	public void transactionDetailHasLinksToLitle() throws Exception {
	    iAccessAReportingUrl("/palorus/adminhtml_myform/search/");
	    waitFor(By.linkText("sdksupport@litle.com"));
	    String reportingUrl = driver.getCurrentUrl();
	    assertEquals(reportingUrl, "https://www.testlitle.com/sandbox/ui/transactions/search");
	}
}


text:
package coco.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Configuration {

	public static double[] parseDoubleArray(String pString) {
		if (!pString.startsWith("{") || !pString.endsWith("}")) {
			throw new RuntimeException();
		}
		pString = pString.substring(1);
		pString = pString.substring(0, pString.length());
		String[] s = pString.split(",");
		double[] d = new double[s.length];
		for (int i = 0; i < s.length; i++) {
			d[i] = Double.parseDouble(s[i]);
		}
		return d;
	}

	public static int[] parseIntArray(String pString) {
		if (!pString.startsWith("{") || !pString.endsWith("}")) {
			throw new RuntimeException();
		}
		pString = pString.substring(1);
		pString = pString.substring(0, pString.length());
		String[] s = pString.split(",");
		int[] d = new int[s.length];
		for (int i = 0; i < s.length; i++) {
			d[i] = Integer.parseInt(s[i]);
		}
		return d;
	}

	public static boolean[] parseBoolArray(String pString) {
		if (!pString.startsWith("{") || !pString.endsWith("}")) {
			throw new RuntimeException();
		}
		pString = pString.substring(1);
		pString = pString.substring(0, pString.length());
		String[] s = pString.split(",");
		boolean[] d = new boolean[s.length];
		for (int i = 0; i < s.length; i++) {
			if (!s[i].equalsIgnoreCase("true")
					&& !s[i].equalsIgnoreCase("false")) {
				throw new RuntimeException();
			}
			d[i] = Boolean.parseBoolean(s[i]);
		}
		return d;
	}

	private final Map<String, Object> mParamMap = new HashMap<String, Object>();

	public void clear() {
		mParamMap.clear();
	}

	public void read(String pFile) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(pFile));
		String line;
		while ((line = reader.readLine()) != null) {
			if (!line.trim().equals("") && !line.startsWith("#")) {
				String[] params = line.split("=", 2);
				String parameterName = params[0].trim();
				String parameterValue = params[1].trim();
				boolean success = false;
				if (!success) {
					try {
						if (!parameterValue.equalsIgnoreCase("true")
								&& !parameterValue.equalsIgnoreCase("false")) {
							throw new Exception();
						}
						Boolean value = Boolean.parseBoolean(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					try {
						Integer value = Integer.parseInt(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					try {
						Double value = Double.parseDouble(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					try {
						int[] value = parseIntArray(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					try {
						double[] value = parseDoubleArray(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					try {
						boolean[] value = parseBoolArray(parameterValue);
						mParamMap.put(parameterName, value);
						success = true;
					} catch (Exception e) {
					}
				}
				if (!success) {
					mParamMap.put(parameterName, parameterValue);
				}
			}
		}
		reader.close();
	}

	public Boolean getBoolean(String pParameterName) {
		return (Boolean) mParamMap.get(pParameterName);
	}

	public Boolean getBoolean(String pParameterName, boolean pDefaultValue) {
		Boolean b = (Boolean) mParamMap.get(pParameterName);
		return b == null ? pDefaultValue : b;
	}

	public String getString(String pParameterName) {
		return (String) mParamMap.get(pParameterName);
	}

	public String getString(String pParameterValue, String pDefaultValue) {
		String d = getString(pParameterValue);
		return d == null ? pDefaultValue : d;
	}

	public Double getDouble(String pParameterValue, Double pDefaultValue) {
		Double d = getDouble(pParameterValue);
		return d == null ? pDefaultValue : d;
	}

	public Double getDouble(String pParameterName) {
		Object o = mParamMap.get(pParameterName);
		if (o instanceof Integer) {
			return ((Integer) o).doubleValue();
		}
		return (Double) mParamMap.get(pParameterName);
	}

	public int[] getIntArray(String pParameterName, int[] pDefaultValue) {
		Object o = mParamMap.get(pParameterName);
		if (o instanceof Integer[]) {
			return (int[]) o;
		}
		return pDefaultValue;
	}

	public int[] getIntArray(String pParameterName) {
		int[] arr = getIntArray(pParameterName, null);
		if (arr == null) {
			throw new RuntimeException("no parameter value: " + pParameterName);
		}
		return arr;
	}

	public double[] getDoubleArray(String pParameterName, double[] pDefaultValue) {
		Object o = mParamMap.get(pParameterName);
		if (o instanceof Double[]) {
			return (double[]) o;
		}
		return pDefaultValue;
	}

	public double[] getDoubleArray(String pParameterName) {
		double[] arr = getDoubleArray(pParameterName, null);
		if (arr == null) {
			throw new RuntimeException("no parameter value: " + pParameterName);
		}
		return arr;
	}

	public Integer getInteger(String pParameterName, Integer pDefaultValue) {
		Object o = mParamMap.get(pParameterName);
		if (o instanceof Integer) {
			return (Integer) o;
		}
		return pDefaultValue;
	}

	public Integer getInteger(String pParameterName) {
		Integer i = getInteger(pParameterName, null);
		if (i == null) {
			throw new RuntimeException("no parameter value: " + pParameterName);
		}
		return i;
	}

	public void put(String pKey, Object pValue) {
		mParamMap.put(pKey, pValue);
	}
}


text:
E2.p = E2.plugins["cosine_modulator"] = function(core, node)
{
	this.desc = 'Cosine oscilator. A time value incrementing by one unit per second will yield a 1Hz output signal.';

	this.input_slots = [
		{ name: 'time', dt: core.datatypes.FLOAT, desc: 'Time in seconds', def: 0.0 }
	];

	this.output_slots = [
		{ name: 'value', dt: core.datatypes.FLOAT, desc: 'Emits cos(time * 2pi)', def: 0.0 }
	];
};

E2.p.prototype.reset = function()
{
	this.time = 0.0;
	this.result = 0.0;
};

E2.p.prototype.update_input = function(slot, data)
{
	this.time = data;
};

E2.p.prototype.update_state = function()
{
	this.result = Math.cos(this.time * 2.0 * Math.PI);
};

E2.p.prototype.update_output = function(slot)
{
	return this.result;
};


text:
{% extends "base.html" %}
{% block title %}ブログ内容{% endblock title %}

{% block content %}
  {% for blog in blogs %}

{{ blog.title }}

        {{ blog.date }}

        {{ blog.text }}

  {% endfor %}
{% endblock content %}


text:
/**
 * @module utilities
 */

/**
 * Runs a callback function after the DOM has finished loading
 * @param {genericCallback} [callback] - contains code to be executed after
 */

export function docReady(callback) {
  if (document.readyState !== 'loading') {
    callback();
  } else {
    document.addEventListener('DOMContentLoaded', callback);
  }
}

/**
 * A useful alias for querySelectorAll
 * @param {(string|Element)} target - The selector or target element
 * @param {string} [selector] - The selector to query against the target element
 */

export function _(target, selector) {
  if (typeof target === 'object') {
    return target.querySelectorAll(selector);
  }
  return document.querySelectorAll(target);
}

/**
 * Toggles a class on an element
 * @param {string} [className] - The class to toggle
 */

export function toggleClass(el, className) {
  if (el.classList) {
    el.classList.toggle(className);
  } else {
    const classes = el.className.split(' ');
    const existingIndex = classes.indexOf(className);
    if (existingIndex >= 0) {
      classes.splice(existingIndex, 1);
    } else {
      classes.push(className);
    }
    el.className = classes.join(' ');
  }
}

/**
 * Ascertains if class exists on element
 * @param {Element} [el] - The element to target
 * @param {string} [selector] - The class to check for
 */

export function hasClass(el, selector) {
  const className = ` ${selector} `;
  if ((` ${el.className} `).replace(/[\n\t]/g, ' ').indexOf(className) > -1) {
    return true;
  }
  return false;
}


text:
(function($){
    "use strict";

/* -----------------------------------------------------------------------------

	PLUGINS

----------------------------------------------------------------------------- */

	/* -------------------------------------------------------------------------
		ACCORDION
	------------------------------------------------------------------------- */

	$.fn.lvAccordion = function(){

		var $this = $(this),
		isToggle = $this.hasClass( 'm-toggle' ) ? true : false,
		items = $this.find( '> li' );
		items.filter( '.m-active' ).find( '.accordion-content' ).slideDown( 300 );

		$this.find( '.accordion-title' ).click(function(){
			if ( ! $(this).parent().hasClass( 'm-active' ) ) {
				if ( ! isToggle ) {
					items.filter( '.m-active' ).find( '.accordion-content' ).slideUp(300);
					items.filter( '.m-active' ).removeClass( 'm-active' );
				}
				$(this).parent().find( '.accordion-content' ).slideDown(300);
				$(this).parent().addClass( 'm-active' );
			}
			else {
				$(this).parent().find( '.accordion-content' ).slideUp(300);
				$(this).parent().removeClass( 'm-active' );
			}
		});

		// RADIO GROUP
		if ( $this.hasClass( 'm-radio-group' ) ) {
			items.removeClass( 'm-active' );
			$this.find( '.accordion-content' ).hide();
			$this.find( 'input[type="radio"]:checked' ).parent().addClass( 'm-active' ).find( '.accordion-content' ).slideDown( 300 );
		}

	};

	/* -------------------------------------------------------------------------
		AJAX FORM
	------------------------------------------------------------------------- */

	$.fn.lvAjaxForm = function(){

		var form = $(this),
		submitBtn = form.find( '.submit-btn' );

		form.submit(function(e){
			e.preventDefault();

			if ( ! submitBtn.hasClass( 'm-loading' ) ) {

				// CLEAN OLD MESSAGES
				form.find( '.c-alert-message.m-success, .c-alert-message.m-phpvalidation-error' ).slideUp( 300, function(){
					$(this).remove();
				});

				// FORM NOT VALID
				if ( ! form.lvIsFormValid() ) {
					form.find( 'p.c-alert-message.m-warning.m-validation-error' ).slideDown(300);
					return false;
				}
				// FORM VALID
				else {

					submitBtn.addClass( 'm-loading' ).attr( 'data-label', submitBtn.text() ).text( submitBtn.data( 'loading-label' ) );

					// AJAX REQUEST
					$.ajax({
						type: 'POST',
						url: form.attr( 'action' ),
						data: form.serialize(),
						success: function( data ){

							form.find( '.c-alert-message.m-validation-error' ).hide();
							form.prepend( data );
							form.find( '.c-alert-message.m-success, .c-alert-message.m-phpvalidation-error' ).slideDown(300);
							submitBtn.removeClass( 'm-loading' ).text( submitBtn.attr( 'data-label' ) );

							// RESET ALL INPUTS
							if ( data.indexOf( 'success' ) > 0 ) {
								form.find( 'input, textarea' ).each( function() {
									$(this).val( '' );
								});
							}

						},
						error: function(){
							form.find( '.c-alert-message.m-validation-error' ).slideUp(300);
							form.find( '.c-alert-message.m-request-error' ).slideDown(300);
							submitBtn.removeClass( 'm-loading' ).text( submitBtn.attr( 'data-label' ) );
						}
					});

				}

			}
		});

	};

	/* -------------------------------------------------------------------------
		AJAX MODAL
	------------------------------------------------------------------------- */

	$.fn.lvOpenAjaxModal = function(){

		var $this = $(this),
		url = $this.attr( 'href' );

		$this.click(function(){

			// CLOSE MODAL FUNCTION
			var lvCloseAjaxModal = function(){
				$( '.c-modal' ).fadeOut( 300, function(){
					$( '.c-modal .modal-loading' ).show();
					$( '.c-modal .modal-box' ).removeClass( 'animated fadeInDown' ).unbind( 'clickoutside' ).hide();
					$( 'html' ).removeClass( 'm-modal-active' );
				});
				// TRIGGER modalClosed EVENT
				$.event.trigger({
					type: 'modalClosed',
					message: 'Modal is closed.',
					time: new Date()
				});

			};

			// CREATE / SHOW MODAL
			if ( $( '.c-modal' ).length < 1 ) {
				var modalHtml = '
';
				modalHtml += '

';
				modalHtml += '
<button class="modal-close" type="button"></button>

';
				modalHtml += '
';
				$( 'body' ).append( modalHtml );
			}
			var modal = $( '.c-modal' ),
			modalLoading = $( '.c-modal .modal-loading' ),
			modalBox = $( '.c-modal .modal-box' ),
			modalBoxInner = $( '.c-modal .modal-box-inner' ),
			modalClose = $( '.c-modal .modal-close' );
			modal.fadeIn( 300 );
			$( 'html' ).addClass( 'm-modal-active' );

			// LOAD CONTENT
			modalBoxInner.load( url, function( response, status, xhr ){

				// SHOW MODAL BOX
				modalLoading.fadeOut( 300 );
				modalBox.show().addClass( 'animated fadeInDown' );

				// CLICK ON CLOSE
				modalClose.click(function(){
					lvCloseAjaxModal();
				});

				// iOS & Chrome BODY SCROLLING FIX
				$( 'body' ).on( 'touchmove', function (e) {
					if ( $( '.c-modal' ).is( ':visible' ) ) {
						if ( ! $( '.c-modal' ).has( $( e.target ) ).length ) {
							e.preventDefault();
						}
					}
				});
				$( 'body' ).on( 'mousewheel DOMMouseScroll', function (e) {
					if ( $( '.c-modal' ).is( ':visible' ) ) {
						if ( ! $( '.c-modal' ).has( $( e.target ) ).length ) {
							e.preventDefault();
						}
					}
				});

				// CLICK OUTSIDE
				/*
				modalBox.unbind( 'clickoutside' ).bind( 'clickoutside', function(){
					lvCloseAjaxModal();
				});
				*/

				// ERROR LOADING CONTENT
				if ( status == 'error' ) {
					modalBoxInner.html( '' ).append( '
 Failed to load reservation form, please try again later.
' );
				}

				// INIT AJAX FORMS
				else {

					if ( $.fn.lvAjaxForm ) {
						$( 'form.m-ajax-form' ).each(function(){
							$(this).lvAjaxForm();
						});
					}

				}

				// TRIGGER modalOpened EVENT
				$.event.trigger({
					type: 'modalOpened',
					message: 'Modal is opened.',
					time: new Date()
				});

			});

			// DISABLE DEFAULT CLICK ACTION
			return false;

		});

	};

	/* -------------------------------------------------------------------------
		DATEPICKER INPUT
	------------------------------------------------------------------------- */

	$.fn.lvDatepickerInput = function(){
		if ( $.fn.datepicker ) {

			var $self = $(this),
			input = $self.find( 'input' ),
			ico = $self.find( 'i.fa' ),
			firstDay = $self.data( 'first-day' ) ? $self.data( 'first-day' ) : 0,
			dateFormat = $self.data( 'date-format' ) ? $self.data( 'date-format' ) : 'mm/dd/yy';

			// INIT
			input.datepicker({
				dateFormat: dateFormat,
				minDate: -0,
				firstDay: firstDay,
				//beforeShowDay: $.datepicker.noWeekends, // disable weekends
				beforeShow: function( input, inst ){
					$( '#ui-datepicker-div' ).appendTo( $self );
				}
			});
			ico.click(function(){
				input.focus();
			});

		}
	};

	/* -------------------------------------------------------------------------
		FLUID VIDEOS
	------------------------------------------------------------------------- */

	$.fn.lvFluidEmbedVideo = function(){

		var $self = $(this),
		allVideos;

        var reloadFluidVideos = function(){
			// Resize all videos according to their own aspect ratio
            allVideos.each(function() {
                var el = $(this);
                var elContainer = el.parents( '.embed-video' );
                var newWidth = elContainer.width();
                el.width( newWidth ).height( newWidth * el.data( 'aspectRatio' ) );
            });
        };

        var generateFluidVideos = function(){
            // Find all videos
            allVideos = $self.find( '.embed-video iframe' );
            // The element that is fluid width
            //$fluidEl = $('.embed-video').first();
            // Figure out and save aspect ratio for each video
            allVideos.each(function() {
                $(this).data( 'aspectRatio', this.height / this.width )
                    // and remove the hard coded width/height
                    .removeAttr( 'height' )
                    .removeAttr( 'width' );
            });
            reloadFluidVideos();
        };

		if ( $self.find( '.embed-video' ).length > 0 ) {
			generateFluidVideos();
			$(window).resize(function(){
				reloadFluidVideos();
			});
		}

	};

	/* -------------------------------------------------------------------------
		FORM VALIDATION
	------------------------------------------------------------------------- */

	$.fn.lvIsFormValid = function() {

		function emailValid( email ) {
			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			return re.test(email);
		}

		// TRIM FIX FOR IE
		if ( typeof String.prototype.trim !== 'function' ) {
			String.prototype.trim = function() {
				return this.replace(/^\s+|\s+$/g, '');
			}
		}

		var form = $(this),
		formValid = true;

		// VALIDATE FIELD
		$.fn.lvIsFieldValid = function(){

			var field = $(this),
			value = field.val(),
			placeholder = field.data( 'placeholder' ) ? field.data( 'placeholder' ) : false,
			valid = false;

			if ( value.trim() !== '' && ! ( placeholder && value === placeholder ) ) {

				// EMAIL FIELDS
				if ( field.hasClass( 'm-email' ) ) {
					if ( ! emailValid( value ) ) {
						field.addClass( 'm-error' );
					}
					else {
						field.removeClass( 'm-error' );
						valid = true;
					}
				}

				// SELECT FIELD
				else if ( field.prop( 'tagName' ).toLowerCase() === 'select' ) {
					if ( value === null ) {
						field.addClass( 'm-error' );
					}
					else {
						field.removeClass( 'm-error' );
						valid = true;
					}
				}

				// DEFAULT FIELD
				else {
					field.removeClass( 'm-error' );
					valid = true;
				}

			}
			else {
				field.addClass( 'm-error' );
			}

			return valid;

		};

		// CHECK REQUIRED FIELDS
		form.find( 'input.m-required, textarea.m-required, select.m-required' ).each(function(){
			formValid = ! $(this).lvIsFieldValid() ? false : formValid;
		});

		// CHECK REQUIRED ONE FIELDS
		var requireOneValid = false;
		form.find( 'input.m-required-one, textarea.m-required-one, select.m-required-one' ).each(function(){
			if ( $(this).lvIsFieldValid() ) {
				requireOneValid = true;
				form.find( 'input.m-required-one, textarea.m-required-one, select.m-required-one' ).removeClass( 'm-error' );
			}
		});
		if ( form.find( '.m-require-one' ).length > 0 && ! requireOneValid ) {
			formValid = false;
		}
		if ( formValid ) {
			form.find( 'input.m-required-one, textarea.m-required-one, select.m-required-one' ).removeClass( 'm-error' );
		}

		form.find( '.m-error' ).first().focus();

		return formValid;

	};

	/* -------------------------------------------------------------------------
		CHECKBOX INPUT
	------------------------------------------------------------------------- */

	$.fn.lvCheckboxInput = function(){

		var $this = $(this);
		$this.wrap( '

' );
		$this = $this.parent();
		var input = $this.find( 'input' ).removeClass( 'checkbox-input' ),
		label = $this.next( 'label' ).appendTo( $this );

		// INIT
		if ( input.is( ':checked' ) ) {
			$this.addClass( 'm-checked' );
		}

		// CLICK
		label.click(function(){
			$this.toggleClass( 'm-checked' );
			input.trigger( 'change' );
		});

	};

	/* -------------------------------------------------------------------------
		LIGHTBOX
	------------------------------------------------------------------------- */

	// LIGHTBOX SETUP
	if ( $.fn.magnificPopup ) {
		$.extend( true, $.magnificPopup.defaults, {
			tClose: 'Close (Esc)',
			tLoading: 'Loading...',
			gallery: {
				tPrev: 'Previous (Left arrow key)', // Alt text on left arrow
				tNext: 'Next (Right arrow key)', // Alt text on right arrow
				tCounter: '%curr% / %total%' // Markup for "1 of 7" counter
			},
			image: {
				tError: 'The image could not be loaded.' // Error message when image could not be loaded
			},
			ajax: {
				tError: 'The content could not be loaded.' // Error message when ajax request failed
			}
		});
	}

	// FUNCTION
	$.fn.lvInitLightboxes = function(){
		if ( $.fn.magnificPopup ) {
			$(this).find( 'a.lightbox' ).each(function(){

				var self = $(this),
				lightboxGroup = self.data( 'lightbox-group' ) ? self.data( 'lightbox-group' ) : false;

				// SHOW AS GALLERY
				if ( lightboxGroup ) {
					$( 'a.lightbox[data-lightbox-group="' + lightboxGroup + '"]' ).magnificPopup({
						type: 'image',
						removalDelay: 300,
						mainClass: 'mfp-fade',
						gallery: {
							enabled: true
						}
					});
				}
				// SHOW SINGLE IMAGE
				else {
					self.magnificPopup({
						type: 'image'
					});
				}

			});
		}
	};

	/* -------------------------------------------------------------------------
		LOAD HIRES IMAGES
	------------------------------------------------------------------------- */

	$.fn.lvLoadHiresImages = function() {
		if ( window.devicePixelRatio > 1 ) {
			$(this).find( 'img[data-hires]' ).each(function(){
				$(this).attr( 'src', $(this).data( 'hires' ) );
			});
		}
	};

	/* -------------------------------------------------------------------------
		MAILCHIMP SUBSCRIBE FORM
	------------------------------------------------------------------------- */

	$.fn.lvMailchimpSubscribeForm = function(){

		var form = $(this),
		submitBtn = form.find( '.submit-btn' );

		form.submit(function(e){
			e.preventDefault();
			if ( ! form.hasClass( 'm-loading' ) ) {

				// FORM IS VALID
				if ( form.lvIsFormValid() ) {

					form.find( 'p.c-alert-message.m-warning.m-validation-error' ).slideUp(300);
					form.addClass( 'm-loading' );
					submitBtn.attr( 'data-label', submitBtn.text() ).text( submitBtn.data( 'loading-label' ) );

					// SEND AJAX REQUEST
                    $.ajax({
                        type: form.attr( 'method' ),
                        url: form.attr( 'action' ),
                        data: form.serialize(),
                        cache : false,
                        dataType : 'json',
                        contentType: "application/json; charset=utf-8",
                        // WAIT FOR RESPONSE
                        success: function( data ){

                            if ( data.result === 'success' ) {
                                form.find( '.c-alert-message' ).hide();
                                form.find( '.c-alert-message.m-success' ).append( '
' + data.msg ).slideDown(300);
                                form.find( '.form-fields' ).slideUp(300);
                            }
                            else {
                                form.find( '.c-alert-message.m-validation-error' ).slideUp(300);
                                form.find( '.c-alert-message.m-request-error' ).slideDown(300);
                            }

							form.removeClass( 'm-loading' );
							submitBtn.text( submitBtn.attr( 'data-label' ) );

                        },
                        error: function(){

                            form.find( '.m-alert-message.m-validation-error' ).slideUp(300);
                            form.find( '.m-alert-message.m-request-error' ).slideDown(300);
                            form.removeClass( 'loading' );
							submitBtn.text( submitBtn.attr( 'data-label' ) );

                        }
                    });

				}

				//  FORM IS INVALID
				else {
					form.find( 'p.c-alert-message.m-warning.m-validation-error' ).slideDown(300);
					return false;
				}

			}
		});

	};

	/* -------------------------------------------------------------------------
		MEDIA QUERY BREAKPOINT
	------------------------------------------------------------------------- */

	$.fn.lvGetMediaQueryBreakpoint = function() {

		if ( $( '#media-query-breakpoint' ).length < 1 ) {
			$( 'body' ).append( '' );
		}
		var value = $( '#media-query-breakpoint' ).css( 'font-family' );
		if ( typeof value !== 'undefined' ) {
			value = value.replace( "\"", "" ).replace( "\"", "" ).replace( "\'", "" ).replace( "\'", "" );
		}
		if ( isNaN( value ) ) {
			return $(window).width();
		}
		else {
			return parseInt( value );
		}

	};

	/* -------------------------------------------------------------------------
		PROGRESS BAR
	------------------------------------------------------------------------- */

	$.fn.lvProgressBar = function(){

		var $this = $(this),
		percentage = $this.data( 'percentage' ) ? parseInt( $this.data( 'percentage' ) ) : 100,
		inner = $this.find( '> span' );
		inner.css( 'width', percentage + '%' );

	};

	/* -------------------------------------------------------------------------
		QUANTITY INPUT
	------------------------------------------------------------------------- */

	$.fn.lvQuantityInput = function(){

		var $this = $(this),
		input = $this.find( 'input' ),
		value = parseInt( input.val() ),
		minValue = input.prop( 'min' ) ? parseInt( input.prop( 'min' ) ) : 0,
		maxValue = input.prop( 'max' ) ? parseInt( input.prop( 'max' ) ) : 100,
		step = input.prop( 'step' ) ? parseInt( input.prop( 'step' ) ) : 1;

		// CREATE ELEMENTS
		input.hide();
		$this.append( '<input class="fake-input" type="text" value="' + value + '"><button class="minus" type="button"></button><button class="plus" type="button"></button>' );
		var plus = $this.find( '.plus' ),
		minus = $this.find( '.minus' ),
		fakeInput = $this.find( '.fake-input' );
		if ( input.hasClass( 'm-type-2' ) ){
			fakeInput.addClass( 'm-type-2' );
		}

		// ACTIONS
		minus.click(function(){
			if ( ( value - step ) >= minValue ) {
				value -= step;
				fakeInput.val( value );
				fakeInput.trigger( 'change' );
			}
		});
		plus.click(function(){
			if ( ( value + step ) <= maxValue ) {
				value += step;
				fakeInput.val( value );
				fakeInput.trigger( 'change' );
			}
		});
		fakeInput.change(function(){
			if ( ! isNaN( fakeInput.val() ) ) {
				value = parseInt( fakeInput.val() );
				input.val( value );
			}
		});

	};

	/* -------------------------------------------------------------------------
		SELECTBOX INPUT
	------------------------------------------------------------------------- */

	$.fn.lvSelectboxInput = function(){

		var $this = $(this);
		$this.wrap( '

' );
		$this = $this.parent();
		var input = $this.find( 'select' ),
		fakeSelectHtml = '';
		input.removeClass( 'selectbox-input' );
		var value = input.val();
		var defaultValue = input.find( 'option[value="' + value + '"]' ).text() ? input.find( 'option[value="' + value + '"]' ).text() : input.find( 'option' ).first().text();

		// COPY CLASSES
		if ( input.hasClass( 'm-small' ) ) {
			$this.addClass( 'm-small' );
		}
		if ( input.hasClass( 'm-type-2' ) ) {
			$this.addClass( 'm-type-2' );
		}

		// CREATE ELEMENTS
		input.hide();
		$this.append( '<button type="button" class="toggle">' + defaultValue + '</button>' );
		fakeSelectHtml = '
';
		input.find( 'option' ).each(function(){
			fakeSelectHtml += '
' + $(this).text() + '
';
		});
		fakeSelectHtml += '
';
		$this.append( fakeSelectHtml );
		var toggle = $this.find( '.toggle' ),
		fakeSelect = $this.find( '.fake-selectbox' );

		// TOGGLE
		toggle.click(function(){
			fakeSelect.slideToggle(150);
			toggle.toggleClass( 'm-active' );
			$this.unbind( 'clickoutside' );
			if ( toggle.hasClass( 'm-active' ) ) {
				$this.bind( 'clickoutside', function(event){
					fakeSelect.slideUp(150);
					toggle.removeClass( 'm-active' );
					$this.unbind( 'clickoutside' );
				});
			}
		});

		// FAKE SELECTBOX CLICK
		fakeSelect.find( 'li' ).each(function(){
			$(this).click(function(){
				toggle.removeClass( 'm-active' ).find( 'span' ).text( $(this).text() );
				fakeSelect.slideUp(150);
				input.val( $(this).attr( 'data-value' ) );
				input.trigger( 'change' );
			});
		});

	};

	/* -------------------------------------------------------------------------
		TABS
	------------------------------------------------------------------------- */

	$.fn.lvTabbed = function(){

		var $this = $(this),
		tabs = $this.find( '.tab-list > li' ),
		contents = $this.find( '.content-list > li' );

		tabs.click(function(){
			if ( ! $(this).hasClass( 'm-active' ) ) {
				var index = $(this).index();
				tabs.filter( '.m-active' ).removeClass( 'm-active' );
				$(this).addClass( 'm-active' );
				contents.filter( ':visible' ).slideUp( 300, function(){
					$(this).removeClass( 'm-active' );
				});
				contents.filter( ':eq(' + index + ')' ).slideDown(300).addClass( 'm-active' );
			}
		});

	};

	/* -------------------------------------------------------------------------
		TWITTER FEED
	------------------------------------------------------------------------- */

	$.fn.lvTwitterFeed = function(){
		if ( $.fn.tweet ) {

			var $this = $(this),
			feedId = $this.data( 'id' ),
			feedLimit = parseInt( $this.data( 'limit' ) ),
			feedEl = $this.find( '.twitter-feed' );

			// TWEETS LOADED
			feedEl.bind( 'loaded', function(){
				if ( feedLimit > 1 && $this.hasClass( 'm-paginated' ) && $.fn.owlCarousel ) {

					var interval = $this.data( 'interval' ) ? parseInt( $this.data( 'interval' ) ) > 0 : false;
					$this.find( '.tweet_list' ).owlCarousel({
						autoPlay: interval,
						slideSpeed: 300,
						pagination: false,
						paginationSpeed : 400,
						singleItem: true,
						autoHeight: true
					});
					var carousel = $this.find( '.tweet_list' ).data( 'owlCarousel' );
					$this.append( '<button class="btn-prev" type="button"></button><button class="btn-next" type="button"></button>' );

					// PREV TWEET
					$this.find( '.btn-prev' ).click(function(){
						$this.find( '.tweet_list' ).trigger( 'owl.prev' );
					});

					// NEXT TWEET
					$this.find( '.btn-next' ).click(function(){
						$this.find( '.tweet_list' ).trigger( 'owl.next' );
					});

				}
			});

			// INIT TWEET JS
			feedEl.tweet({
				username: feedId,
				modpath: './library/twitter/',
				count: feedLimit,
				loading_text: ''
			});

		}
	};

/* -----------------------------------------------------------------------------

	EVENTS

----------------------------------------------------------------------------- */

	/* -------------------------------------------------------------------------
		SCREEN SIZE TRANSITION
	------------------------------------------------------------------------- */

	if ( $.fn.lvGetMediaQueryBreakpoint ) {
		var mediaQueryBreakpoint = $.fn.lvGetMediaQueryBreakpoint();
		$(window).resize(function(){
			if ( $.fn.lvGetMediaQueryBreakpoint() !== mediaQueryBreakpoint ) {
				mediaQueryBreakpoint = $.fn.lvGetMediaQueryBreakpoint();
				$.event.trigger({
					type: 'screenTransition',
					message: 'Screen transition completed.',
					time: new Date()
				});
			}
		});
	}

})(jQuery);


text:
<?hh // strict

enum XHPAttributeType: int {
  TYPE_STRING = 1;
  TYPE_BOOL = 2;
  TYPE_INTEGER = 3;
  TYPE_ARRAY = 4;
  TYPE_OBJECT = 5;
  TYPE_VAR = 6;
  TYPE_ENUM = 7;
  TYPE_FLOAT = 8;
  TYPE_UNSUPPORTED_LEGACY_CALLABLE = 9;
}

class ReflectionXHPAttribute {
  private XHPAttributeType $type;
  /*
   * OBJECT: string (class name)
   * ENUM: array<string> (enum values)
   * ARRAY: Array decl
   */
  private mixed $extraType;
  private mixed $defaultValue;
  private bool $required;

  private static ImmSet<string> $specialAttributes = ImmSet {
    'data',
    'aria',
  };

  public function __construct(
    private string $name,
    array<int, mixed> $decl,
  ) {
    $this->type = XHPAttributeType::assert($decl[0]);
    $this->extraType = $decl[1];
    $this->defaultValue = $decl[2];
    $this->required = (bool) $decl[3];
  }

  public function getName(): string {
    return $this->name;
  }

  public function getValueType(): XHPAttributeType {
    return $this->type;
  }

  public function isRequired(): bool {
    return $this->required;
  }

  public function hasDefaultValue(): bool {
    return $this->defaultValue !== null;
  }

  public function getDefaultValue(): mixed {
    return $this->defaultValue;
  }

  <<__Memoize>>
  public function getValueClass(): string {
    $t = $this->getValueType();
    invariant(
      $this->getValueType() === XHPAttributeType::TYPE_OBJECT,
      'Tried to get value class for attribute %s of type %s - needed '.
      'OBJECT',
      $this->getName(),
      XHPAttributeType::getNames()[$this->getValueType()],
    );
    $v = $this->extraType;
    invariant(
      is_string($v),
      'Class name for attribute %s is not a string',
      $this->getName()
    );
    return $v;
  }

  <<__Memoize>>
  public function getEnumValues(): Set<string> {
    $t = $this->getValueType();
    invariant(
      $this->getValueType() === XHPAttributeType::TYPE_ENUM,
      'Tried to get enum values for attribute %s of type %s - needed '.
      'ENUM',
      $this->getName(),
      XHPAttributeType::getNames()[$this->getValueType()],
    );
    $v = $this->extraType;
    invariant(
      is_array($v),
      'Class name for attribute %s is not a string',
      $this->getName()
    );
    return new Set($v);
  }

  /**
   * Returns true if the attribute is a data- or aria- attribute.
   */
  <<__Memoize>>
  public static function IsSpecial(string $attr): bool {
    return strlen($attr) >= 6
      && $attr[4] === '-'
      && self::$specialAttributes->contains(substr($attr, 0, 4));
  }

  public function __toString(): string {
    switch ($this->getValueType()) {
      case XHPAttributeType::TYPE_STRING:
        $out = 'string';
        break;
      case XHPAttributeType::TYPE_BOOL:
        $out = 'bool';
        break;
      case XHPAttributeType::TYPE_INTEGER:
        $out = 'int';
        break;
      case XHPAttributeType::TYPE_ARRAY:
        $out = 'array';
        break;
      case XHPAttributeType::TYPE_OBJECT:
        $out = $this->getValueClass();
        break;
      case XHPAttributeType::TYPE_VAR:
        $out = 'mixed';
        break;
      case XHPAttributeType::TYPE_ENUM:
        $out = 'enum {';
        $out .= implode(', ', $this->getEnumValues()->map($x ==> "'".$x."'"));
        $out .= '}';
        break;
      case XHPAttributeType::TYPE_FLOAT:
        $out = 'float';
        break;
      case XHPAttributeType::TYPE_UNSUPPORTED_LEGACY_CALLABLE:
        $out = '<UNSUPPORTED: legacy callable>';
        break;
    }
    $out .= ' '.$this->getName();
    if ($this->hasDefaultValue()) {
      $out .=  ' = '.var_export($this->getDefaultValue(), true);
    }
    if ($this->isRequired()) {
      $out .= ' @required';
    }
    return $out;
  }
}


text:
package io.github.resilience4j.retry.transformer;

import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.test.HelloWorldService;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Single;
import org.junit.Before;
import org.junit.Test;
import org.mockito.BDDMockito;
import org.mockito.Mockito;

import javax.xml.ws.WebServiceException;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

public class RetryTransformerTest {

    private HelloWorldService helloWorldService;

    @Before
    public void setUp(){
        helloWorldService = Mockito.mock(HelloWorldService.class);
    }

    @Test
    public void shouldReturnOnCompleteUsingSingle() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willReturn("Hello world")
                .willThrow(new WebServiceException("BAM!"))
                .willThrow(new WebServiceException("BAM!"))
                .willReturn("Hello world");

        //When
        Single.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertValueCount(1)
                .assertValues("Hello world")
                .assertComplete();

        Single.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertValueCount(1)
                .assertValues("Hello world")
                .assertComplete();

        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(4)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfSuccessfulCallsWithoutRetryAttempt()).isEqualTo(1);
        assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldReturnOnErrorUsingSingle() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Single.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();

        Single.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(6)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldNotRetryFromPredicateUsingSingle() {
        //Given
        RetryConfig config = RetryConfig.custom()
                .retryOnException(t -> t instanceof IOException)
                .maxAttempts(3).build();
        Retry retry = Retry.of("testName", config);
        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Single.fromCallable(helloWorldService::returnHelloWorld)
                .compose(RetryTransformer.of(retry))
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldReturnOnCompleteUsingObservable() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Observable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();

        Observable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(6)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldReturnOnErrorUsingObservable() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Observable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();

        Observable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(6)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldNotRetryFromPredicateUsingObservable() {
        //Given
        RetryConfig config = RetryConfig.custom()
                .retryOnException(t -> t instanceof IOException)
                .maxAttempts(3).build();
        Retry retry = Retry.of("testName", config);
        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Observable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(RetryTransformer.of(retry))
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldReturnOnCompleteUsingFlowable() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Flowable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();

        Flowable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(6)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldReturnOnErrorUsingFlowable() {
        //Given
        RetryConfig config = RetryConfig.ofDefaults();
        Retry retry = Retry.of("testName", config);
        RetryTransformer<Object> retryTransformer = RetryTransformer.of(retry);

        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Flowable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();

        Flowable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(retryTransformer)
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(6)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(0);
    }

    @Test
    public void shouldNotRetryFromPredicateUsingFlowable() {
        //Given
        RetryConfig config = RetryConfig.custom()
                .retryOnException(t -> t instanceof IOException)
                .maxAttempts(3).build();
        Retry retry = Retry.of("testName", config);
        given(helloWorldService.returnHelloWorld())
                .willThrow(new WebServiceException("BAM!"));

        //When
        Flowable.fromCallable(helloWorldService::returnHelloWorld)
                .compose(RetryTransformer.of(retry))
                .test()
                .assertError(WebServiceException.class)
                .assertNotComplete()
                .assertSubscribed();
        //Then
        BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
        Retry.Metrics metrics = retry.getMetrics();

        assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isEqualTo(1);
        assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(0);
    }

}


text:
package multiplexity

import (
	"log"
	"net"
)

type ClientServer struct {
	commandChan CommandChan
	clientIds   int
}

func NewClientServer(commandChan CommandChan) *ClientServer {
	server := &ClientServer{
		commandChan: commandChan,
		clientIds:   0,
	}
	return server
}

func (s *ClientServer) Listen(address string) {
	ln, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatalln("Failed to listen on", address)
		return
	}

	defer ln.Close()
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatalln("Recevied error while listening for connections", err)
			continue
		}

		go s.handleConnection(s.clientIds, conn)
		s.clientIds += 1
	}
}

func (s *ClientServer) handleConnection(newId int, conn net.Conn) {
	client := NewClient(newId, conn, s.commandChan)

	s.commandChan <- &ClientConnectCommand{
		Client: client,
	}

	client.ReadWritePumps()

	s.commandChan <- &ClientQuitCommand{
		Client: client,
	}
}


text:
<?php
namespace AlbumApi\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class IndexController extends AbstractRestfulController
{
    public function getList()
    {
        return new JsonModel(array('data' => "Welcome to the Zend Framework Album API example"));
    }
}


text:
static char **_swift_stdlib_ProcessOverrideUnsafeArgv = nullptr;
static int _swift_stdlib_ProcessOverrideUnsafeArgc = 0;

SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" void _swift_stdlib_overrideUnsafeArgvArgc(char **argv, int argc) {
  _swift_stdlib_ProcessOverrideUnsafeArgv = argv;
  _swift_stdlib_ProcessOverrideUnsafeArgc = argc;
}

#if defined(__APPLE__)
// NOTE: forward declare this rather than including crt_externs.h as not all
// SDKs provide it
extern "C" char ***_NSGetArgv(void);
extern "C" int *_NSGetArgc(void);

SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {
  assert(outArgLen != nullptr);

  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {
    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;
    return _swift_stdlib_ProcessOverrideUnsafeArgv;
  }

  *outArgLen = *_NSGetArgc();
  return *_NSGetArgv();
}
#elif defined(__linux__) || defined(__CYGWIN__)
SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {
  assert(outArgLen != nullptr);

  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {
    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;
    return _swift_stdlib_ProcessOverrideUnsafeArgv;
  }

  FILE *cmdline = fopen("/proc/self/cmdline", "rb");
  if (!cmdline) {
    swift::fatalError(0,
            "fatal error: Unable to open interface to '/proc/self/cmdline'.\n");
  }
  char *arg = nullptr;
  size_t size = 0;
  std::vector<char *> argvec;
  while (getdelim(&arg, &size, 0, cmdline) != -1) {
    argvec.push_back(strdup(arg));
  }
  if (arg) {
    free(arg);
  }
  fclose(cmdline);
  *outArgLen = argvec.size();
  char **outBuf = (char **)calloc(argvec.size() + 1, sizeof(char *));
  std::copy(argvec.begin(), argvec.end(), outBuf);
  outBuf[argvec.size()] = nullptr;

  return outBuf;
}
#elif defined (_MSC_VER)
#include <stdlib.h>

SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {
  assert(outArgLen != nullptr);

  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {
    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;
    return _swift_stdlib_ProcessOverrideUnsafeArgv;
  }

  *outArgLen = __argc;
  return __argv;
}
#elif defined(__FreeBSD__)
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>

SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {
  assert(outArgLen != nullptr);

  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {
    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;
    return _swift_stdlib_ProcessOverrideUnsafeArgv;
  }

  char *argPtr = NULL; // or use ARG_MAX? 8192 is used in LLDB though..
  int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, getpid() };
  size_t argPtrSize = 0;
  for (int i = 0; i < 3 && !argPtr; i++) { // give up after 3 tries
    if (sysctl(mib, 4, NULL, &argPtrSize, NULL, 0) != -1) {
      argPtr = (char *)malloc(argPtrSize);
      if (sysctl(mib, 4, argPtr, &argPtrSize, NULL, 0) == -1) {
        free(argPtr);
        argPtr = NULL;
        if (errno != ENOMEM)
          break;
      }
    } else {
      break;
    }
  }
  if (!argPtr)
    swift::fatalError(0, "fatal error: could not retrieve commandline "
                         "arguments: sysctl: %s.\n", strerror(errno));

  char *curPtr = argPtr;
  char *endPtr = argPtr + argPtrSize;

  std::vector<char *> argvec;
  for (; curPtr < endPtr; curPtr += strlen(curPtr) + 1)
    argvec.push_back(strdup(curPtr));
  *outArgLen = argvec.size();
  char **outBuf = (char **)calloc(argvec.size() + 1, sizeof(char *));
  std::copy(argvec.begin(), argvec.end(), outBuf);
  outBuf[argvec.size()] = nullptr;

  free(argPtr);

  return outBuf;
}
#else // __ANDROID__; Add your favorite arch's command line arg grabber here.
SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {
  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {
    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;
    return _swift_stdlib_ProcessOverrideUnsafeArgv;
  }

  swift::fatalError(0,
      "fatal error: Command line arguments not supported on this platform.\n");
}
#endif


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/codecs/compressing/CompressingTermVectorsReader.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader")
#ifdef RESTRICT_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader
#define INCLUDE_ALL_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader 0
#else
#define INCLUDE_ALL_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader 1
#endif
#undef RESTRICT_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader_) && (INCLUDE_ALL_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader || defined(INCLUDE_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader))
#define OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader_

#define RESTRICT_OrgApacheLuceneCodecsTermVectorsReader 1
#define INCLUDE_OrgApacheLuceneCodecsTermVectorsReader 1
#include "org/apache/lucene/codecs/TermVectorsReader.h"

#define RESTRICT_JavaIoCloseable 1
#define INCLUDE_JavaIoCloseable 1
#include "java/io/Closeable.h"

@class OrgApacheLuceneCodecsCompressingCompressingStoredFieldsIndexReader;
@class OrgApacheLuceneCodecsCompressingCompressionMode;
@class OrgApacheLuceneIndexFieldInfos;
@class OrgApacheLuceneIndexFields;
@class OrgApacheLuceneIndexSegmentInfo;
@class OrgApacheLuceneStoreDirectory;
@class OrgApacheLuceneStoreIOContext;
@class OrgApacheLuceneStoreIndexInput;
@protocol JavaUtilCollection;

/*!
 @brief TermVectorsReader for CompressingTermVectorsFormat.
 */
@interface OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader : OrgApacheLuceneCodecsTermVectorsReader < JavaIoCloseable > {
 @public
  OrgApacheLuceneCodecsCompressingCompressingStoredFieldsIndexReader *indexReader_;
  OrgApacheLuceneStoreIndexInput *vectorsStream_;
}

#pragma mark Public

/*!
 @brief Sole constructor.
 */
- (instancetype __nonnull)initWithOrgApacheLuceneStoreDirectory:(OrgApacheLuceneStoreDirectory *)d
                            withOrgApacheLuceneIndexSegmentInfo:(OrgApacheLuceneIndexSegmentInfo *)si
                                                   withNSString:(NSString *)segmentSuffix
                             withOrgApacheLuceneIndexFieldInfos:(OrgApacheLuceneIndexFieldInfos *)fn
                              withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context
                                                   withNSString:(NSString *)formatName
            withOrgApacheLuceneCodecsCompressingCompressionMode:(OrgApacheLuceneCodecsCompressingCompressionMode *)compressionMode;

- (void)checkIntegrity;

- (OrgApacheLuceneCodecsTermVectorsReader *)java_clone;

- (void)close;

- (OrgApacheLuceneIndexFields *)getWithInt:(jint)doc;

- (id<JavaUtilCollection>)getChildResources;

- (jlong)ramBytesUsed;

- (NSString *)description;

#pragma mark Package-Private

- (jint)getChunkSize;

- (OrgApacheLuceneCodecsCompressingCompressionMode *)getCompressionMode;

- (OrgApacheLuceneCodecsCompressingCompressingStoredFieldsIndexReader *)getIndexReader;

- (jlong)getMaxPointer;

- (jlong)getNumChunks;

- (jlong)getNumDirtyChunks;

- (jint)getPackedIntsVersion;

- (OrgApacheLuceneStoreIndexInput *)getVectorsStream;

- (jint)getVersion;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)init NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader)

J2OBJC_FIELD_SETTER(OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader, indexReader_, OrgApacheLuceneCodecsCompressingCompressingStoredFieldsIndexReader *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader, vectorsStream_, OrgApacheLuceneStoreIndexInput *)

FOUNDATION_EXPORT void OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader_initWithOrgApacheLuceneStoreDirectory_withOrgApacheLuceneIndexSegmentInfo_withNSString_withOrgApacheLuceneIndexFieldInfos_withOrgApacheLuceneStoreIOContext_withNSString_withOrgApacheLuceneCodecsCompressingCompressionMode_(OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader *self, OrgApacheLuceneStoreDirectory *d, OrgApacheLuceneIndexSegmentInfo *si, NSString *segmentSuffix, OrgApacheLuceneIndexFieldInfos *fn, OrgApacheLuceneStoreIOContext *context, NSString *formatName, OrgApacheLuceneCodecsCompressingCompressionMode *compressionMode);

FOUNDATION_EXPORT OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader *new_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader_initWithOrgApacheLuceneStoreDirectory_withOrgApacheLuceneIndexSegmentInfo_withNSString_withOrgApacheLuceneIndexFieldInfos_withOrgApacheLuceneStoreIOContext_withNSString_withOrgApacheLuceneCodecsCompressingCompressionMode_(OrgApacheLuceneStoreDirectory *d, OrgApacheLuceneIndexSegmentInfo *si, NSString *segmentSuffix, OrgApacheLuceneIndexFieldInfos *fn, OrgApacheLuceneStoreIOContext *context, NSString *formatName, OrgApacheLuceneCodecsCompressingCompressionMode *compressionMode) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader *create_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader_initWithOrgApacheLuceneStoreDirectory_withOrgApacheLuceneIndexSegmentInfo_withNSString_withOrgApacheLuceneIndexFieldInfos_withOrgApacheLuceneStoreIOContext_withNSString_withOrgApacheLuceneCodecsCompressingCompressionMode_(OrgApacheLuceneStoreDirectory *d, OrgApacheLuceneIndexSegmentInfo *si, NSString *segmentSuffix, OrgApacheLuceneIndexFieldInfos *fn, OrgApacheLuceneStoreIOContext *context, NSString *formatName, OrgApacheLuceneCodecsCompressingCompressionMode *compressionMode);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneCodecsCompressingCompressingTermVectorsReader")