text:
# Usage:
# rails new <app_name> -d postgresql -m /path/to/template.rb
# cd <app_name>
# heroku open

git :init
git add: "."
git commit: "-a -m 'Genesis'"

insert_into_file 'Gemfile', "ruby '2.0.0'\n", after: "source 'https://rubygems.org'\n"

gsub_file 'Gemfile', /.*sqlite.*/, "\n"

gem_group :production do
  gem 'pg'
  gem 'rails_12factor'
  gem 'unicorn'
end

gem 'foreman'
gem 'haml-rails'

gem_group :development do
  gem 'pry'
  gem 'sqlite3'
end

# removes comments from the Gemfile
gsub_file 'Gemfile', /# .*\n/, ''
# removes empty lines
gsub_file 'Gemfile', /\s+\n/, "\n"
gsub_file 'Gemfile', /\n+/, "\n"

run 'bundle install --without production'

remove_file 'public/index.html'
git rm: 'public/index.html'
generate(:controller, 'home index')
route "root :to => 'home#index'"

create_file 'Procfile', 'web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb'

create_file 'config/unicorn.rb' do
  <<-eos
worker_processes 1
timeout 30
preload_app true
before_fork do |server, worker|
 Signal.trap 'TERM' do
 puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
 Process.kill 'QUIT', Process.pid
 end
 defined?(ActiveRecord::Base) and
 ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
 Signal.trap 'TERM' do
 puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to
sent QUIT'
 end
 defined?(ActiveRecord::Base) and
 ActiveRecord::Base.establish_connection
end
  eos
end

create_file '.env', ''

append_file '.gitignore' do
  <<-eos
.env
.DS_Store
  eos
end

rake "db:create", env: 'development'
rake "db:create", env: 'test'

remove_file 'app/views/layouts/application.html.erb'
git rm: 'app/views/layouts/application.html.erb'
create_file 'app/views/layouts/application.html.haml' do
  <<-eos
!!! 5
%html{lang: I18n.locale}
  %head
    %title MyApp
    = stylesheet_link_tag 'application', media: 'all'
    = javascript_include_tag 'application'
    = csrf_meta_tags
  %body
    = yield
  eos
end

prepend_to_file 'config.ru' do
  <<-eos
# Disable stdout buffering to enable Heroku's realtime logging.
$stdout.sync = true
  eos
end

application do
  <<-eos
# Heroku requires this to make deployments work.
config.assets.initialize_on_precompile = false
  eos
end

remove_file 'app/assets/javascripts/application.js'
create_file 'app/assets/javascripts/application.js' do
  <<-eos
//= require jquery
//= require jquery_ujs
//= require_tree .
  eos
end

remove_file 'app/assets/stylesheets/application.css'
create_file 'app/assets/stylesheets/application.css' do
  <<-eos
/*
 * the top of the compiled file, but it's generally better to create a new file per style scope.
 *= require_self
 *= require_tree .
*/
  eos
end

remove_file 'app/assets/stylesheets/bootstrap_and_overrides.css.less'
remove_file 'app/assets/javascripts/bootstrap.js.coffee'

remove_file 'README.rdoc'
create_file 'README.md' do
  <<-eos
# RAILS HEROKU APP

Usage
-----

```bash
foreman start
```

## .env

Put in .env file the environment variables. e.g.:

```
TWITTER_KEY=your-secret-key
TWITTER_SECRET=your-secret
```

TODO
____

License
-------

Copyright (c) 2013 Maurizio de Magnis. Distributed under the MIT License. See LICENSE.txt for further details.
  eos
end

create_file 'LICENSE.txt' do
  <<-eos
Copyright (c) 2013 Maurizio De Magnis

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  eos
end

git add: "."
git commit: "-a -m 'Setup'"

run "heroku apps:create #{app_name}"
run 'git push heroku master'
run 'heroku run rake db:migrate'


text:
package uk.ac.ncl.openlab.intake24.shorturls

import cats.effect.IO

trait ShortUrlsClient {
  def getShortUrls(request: ShortUrlsRequest): IO[ShortUrlsResponse]
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Invoice\Controller\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Invoice\Controller\PrintController;

class PrintControllerFactory implements FactoryInterface
{

    /**
     *
     * {@inheritDoc}
     *
     * @see \Zend\ServiceManager\FactoryInterface::createService()
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $realServiceLocator = $serviceLocator->getServiceLocator();

        $clientService = $realServiceLocator->get('Client\Service\ClientServiceInterface');

        $invoiceService = $realServiceLocator->get('Invoice\Service\InvoiceServiceInterface');

        $itemService = $realServiceLocator->get('InvoiceItem\Service\ItemServiceInterface');

        $optionService = $realServiceLocator->get('InvoiceOption\Service\OptionServiceInterface');

        $locationService = $realServiceLocator->get('Location\Service\LocationServiceInterface');

        $phoneService = $realServiceLocator->get('Phone\Service\PhoneServiceInterface');

        $workorderService = $realServiceLocator->get('Workorder\Service\WorkorderServiceInterface');

        $noteService = $realServiceLocator->get('WorkorderNote\Service\NoteServiceInterface');

        return new PrintController($clientService, $invoiceService, $itemService, $optionService, $locationService, $phoneService, $workorderService, $noteService);
    }
}


text:
require 'spec_helper'
require File.expand_path('../fixtures/classes', __FILE__)

describe Function, '#type' do
  subject { object.type }

  let(:described_class) { FunctionSpecs::Object }
  let(:object)          { described_class.new   }
  let(:type)            { double('type')        }

  before do
    expect(described_class).to receive(:type).and_return(type)
  end

  it 'delegates to the class type' do
    should be(type)
  end
end


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Yves\Application\Business\Model;

use Spryker\Yves\Messenger\FlashMessenger\FlashMessenger as SprykerFlashMessenger;

/**
 * @deprecated Use Spryker\Yves\Messenger\FlashMessenger\FlashMessenger instead
 */
class FlashMessenger extends SprykerFlashMessenger
{
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Thermostat</title>

    <link rel="stylesheet" href="src/style.css">

          <form>
            <input type="button" class="up" value="+">
            <input type="button" class="down" value="-">
            <input type="button" class="reset" value="reset">
            <input type="button" class="PSM-on" value="Power Saving On">
            <input type="button" class="PSM-off" value="Power Saving Off">
          </form>

      <form class='search'>
        <input type='text' name='query'/>
      </form>
      <button>Search</button>


text:
package com.hkm.staffvend.compon.usage;

import android.content.Context;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hkm.staffvend.R;
import com.hkm.staffvend.event.BS;
import com.hkm.staffvend.compon.mosaic.MosAdapter;
import com.hkmvend.sdk.storage.Menu.MenuEntry;

/**
 * Created by zJJ on 1/25/2016.
 */
public class DisplayB2 extends MosAdapter<MenuEntry, DisplayB2.Frame> {
    public DisplayB2(Context context) {
        super(context);
    }

    public class Frame {
        private ImageButton image;
        private TextView text;

        public Frame(View view) {
            image = (ImageButton) view.findViewById(R.id.item_button_bg);
            text = (TextView) view.findViewById(R.id.item_button_tex1);
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.item_sub_v1;
    }

    @Override
    protected void bindData(final MenuEntry menuEntry, int position, DisplayB2.Frame binder) {
        StringBuilder sb = new StringBuilder();
        sb.append(menuEntry.getEntry_name_chinese());
        sb.append("\n");
        sb.append(menuEntry.getEntry_name_english());

        sb.append("(");
        sb.append(menuEntry.getEntry_short_form());
        sb.append(")");

        binder.text.setText(sb.toString());
        //  binder.image.setImageResource(R.mipmap.ic_launcher_jj);

        binder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BS.select_menu_item_from_submenu(menuEntry);
            }
        });
    }

    @Override
    protected Frame getBinder(View view) {
        return new Frame(view);
    }
}


text:
use crate::utils::security::token_manager::*;
use actix_web::middleware::{Middleware, Response, Started};
use actix_web::{error, HttpRequest, HttpResponse, Result};

pub struct AuthValidator;

impl<S> Middleware<S> for AuthValidator {
    fn start(&self, req: &HttpRequest<S>) -> Result<Started> {
        if is_exception_uri(&req.uri().to_string()) {
            Ok(Started::Done)
        } else {
            //Secure URL.
            match req.headers().get("Authorization") {
                Some(value) => {
                    if is_auth_token_valid(&value.to_str().unwrap().to_string()) {
                        Ok(Started::Done)
                    } else {
                        Err(error::ErrorUnauthorized("Invalid auth token."))
                    }
                }
                None => Err(error::ErrorExpectationFailed("Expected auth token.")),
            }
        }
    }

    fn response(&self, _req: &HttpRequest<S>, resp: HttpResponse) -> Result<Response> {
        Ok(Response::Done(resp))
    }
}

fn is_exception_uri(uri: &str) -> bool {
    let search: String = uri.replace("//", "/");
    let mut v: Vec<String> = Vec::new();

    v.push("/api/_".to_string());
    v.push("/api/userstore/login".to_string());

    v.contains(&search)
}


text:
package com.arthurb.factory.abstractfactory;

/**
 * Created by Blackwood on 22.02.2016.
 */
public interface Pepperoni {
    String toString();
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Input;

namespace System
{
    public static class Int32Extensions
    {
        public static bool IsEven(this long value)
        {
            return value % 2 == 0;
        }

        public static bool IsOdd(this long value)
        {
            return value % 2 != 0;
        }

        public static bool InBetweenExclusive(this int value, long minValue, long maxValue)
        {
            return (value >= minValue && value <= maxValue);
        }

        public static bool IsBetweenInclusive(this int value, long minValue, long maxValue)
        {
            return (value > minValue && value < maxValue);
        }
    }
}


text:
// @formatter:off

// @formatter:on

package org.tensorics.core.resolve.options;

import org.tensorics.core.commons.options.Option;

/**
 * The marker interface which is used as upper bound for options that are related to the resolving engines. This options
 * might include, for example, strategies for selecting resolvers and handling exceptions.
 *
 * @author kfuchsbe
 */
public interface ResolvingOption extends Option<ResolvingOption> {
    /* Only marker */
}


text:
layout: post
title: CLR thread pool injection, stuttering problems
date: 2006-07-08 21:18:26.000000000 -07:00
categories:
- Technology
tags: []
status: publish
type: post
published: true
meta:
  _wpas_done_all: '1'
author:
  login: admin
  email: joeduffy@acm.org
  display_name: joeduffy
  first_name: ''
  last_name: ''
---
The CLR thread pool is a very useful thing. It amortizes the cost of thread
creation and deletion--which, on Windows, are not cheap things--over the life of
your process, without you having to write the hairy, complex logic to do the
same thing yourself. The algorithms it uses have been tuned over three major
releases of the .NET Framework now. Unfortunately, it's still not perfect. In
particular, it stutters occasionally.

As I've [hinted at
before](http://www.bluebytesoftware.com/blog/PermaLink,guid,ed78e4f1-fcaa-47a8-920b-804fe217c9d3.aspx),
we have a lot of work actively going on right now that we hope to show up over
the course of the next couple CLR versions (keep an eye on those CTPs!). This
may include vastly improved performance for work items and IO completions,
significantly reducing the overhead of using our thread pool (in some cases to
as little as ~1/8th of what it is today), eliminating accidental deadlocks due
to lots of blocked thread pool workers, and a slew of useful new features
(prioritization, isolation, better debugging, etc.).

One silly thing our thread pool currently does has to do with how it creates new
threads. Namely, it severely throttles creation of new threads once you surpass
the "minimum" number of threads, which, by default, is the number of CPUs on the
machine. We limit ourselves to at most one new thread per 500ms once we reach or
surpass this number. This can be pretty bad for some workloads, most notable
those that are "bursty"; i.e. those that exhibit interspersed inactive and
active periods rather sporadically and unpredictably. ASP.NET is a great example
of an environment in which this frequerntly happens. Here's an illustration:

1. Imagine we have a 4 CPU web server. The "minimum" thread count used thus 4
   (assuming the default).

2. The web server has just started up.

3. 16 new requests come in within a short period of time.

4. Ther CLR quickly create 4 thread pool threads to service the first 4
   requests. Because we don't want to add any more for another 500ms, the other
12 requests sit in the queue.

5. The 4 thread pool threads are running some arbitrary web page response.
   Imagine the response generation code does some type of database query that
   takes 4 seconds to complete. (This is a strong argument for using ASP.NET
   asynchronous pages (see
   [http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/](http://msdn.microsoft.com/msdnmag/issues/05/10/WickedCode/))
   -- in which case, the 4 thread pool threads would free up to execute 4 new
   requests almost immediately -- or perhaps simply rearchitecting the seemingly
   poor database interaction, but ignore this for now.)

6. After 500ms, a new thread pool thread is created, and the 5th request is
   serviced.

7. We now wait another 500ms to add another thread, service, the next request,
   and so forth.

If the server has a constant load, eventually the pool will become "primed." But
if a burst of work is followed by an inactive period of time, the threads in the
thread pool start timing out waiting for new work, and eventually will retire
themselves, until the pool shrinks back to the minimum. Imagine that this
happens and then a bunch of new work arrives. Oops. This can clearly lead to
some nasty scalability nightmares. KB article 821261, [Contention, poor
performance, and deadlocks when you make Web service requests from ASP.NET
applications](http://support.microsoft.com/?id=821268), describes this problem
among others.

To "fix" this we added the ability in v1.1 to specify the minimum thread count
in the thread pool, either with the configuratoin file or with the
ThreadPool.SetMinThreads API. See KB article 810259, [FIX: SetMinThreads and
GetMinThreads API Added to Common Language Runtime ThreadPool
Class](http://support.microsoft.com/default.aspx?scid=kb;en-us;810259), for
details. It turns out that Microsoft Biztalk Server has run into the same
problem: [FIX: Slow performance on startup when you process a high volume of
messages through the SOAP adapter in BizTalk Server
2004](http://support.microsoft.com/default.aspx?scid=kb;en-us;886966). I
suspect many other commercial products have run into this as well. And it's
rather annoying that each of them have to figure this out after they've shipped
something, turning into a support bulletin, an internal bug-fix, and (I would
guess) a service pack containing said bug-fix.

I wouldn't actually call what we did a fix. At best, it's a workaround. Hell,
one of the KB articles above says that if you want decent scalability you need
to change the minWorkerThreads count to 50. Our default is 1! Not too far off,
eh? Shouldn't decent scalability be _the default_ behavior?

We need to fix this for real.

Now, of course, it's a hard problem to solve. You don't want to be too liberal
adding threads to the pool because it can cause poor scalability should a large
number of those extra threads suddenly become runnable. In an ideal world, no
threads block, and having the same number of threads as you have CPUs gives you
the best performance. (Better cache utilization, less overhead due to context
switching, and so forth.) But software is often far less than ideal. As noted
above, ASP.NET asynchronous pages are a _great _way to acheive this, and
compared to injecting a whole bunch of relatively expensive threads into the
process, it's obviously a better design. Unfortunately, I am not convinced all
of our customers will stumble across this design, nor will it be brain-dead
simple to rearchitect an existing site to take advantage of the feature without
considerable work.

My hope is that we can solve this problem in the CLR by applying clever
heuristics that even out over time. For example, we may start out life being
over eager and generous with thread injection, but then "learn our lesson" after
running for a period of time. This would lead to stabalization and an
increasingly superior performance over the life of the process for the work that
the server experiences. For example, if the server often experiences bursts, we
will monitor the number of threads that lead to the best throughput during such
an active period, and during periods of inactivity we will avoid retiring
threads. This ensures that the next time the server is busy, work can be
responded to in a more scalable manner, albeit with some extra working set
overhead for keeping those threads around for longer. Perhaps more appropriate
configuration settings could be dynamically recommended based on statistics
gatherer during previous up-times of the server. And of course, we can offer
more reasonable defaults for clients with short-living processes that might be
harmed by over-eagerness with thread injection.

If anybody has experienced this problem in the wild, I'd love any feedback you
might have. Feel free to leave a comment or email me at joedu at you-know-where
dot com.


text:
import numpy as np
import tensorflow as tf

from easydict import EasyDict

from luminoth.utils.image import (
    resize_image, flip_image, random_patch, random_resize, random_distortion,
    patch_image
)
from luminoth.utils.test.gt_boxes import generate_gt_boxes

class ImageTest(tf.test.TestCase):
    def setUp(self):
        self._random_resize_config = EasyDict({
            'min_size': 400,
            'max_size': 980,
        })
        self._random_distort_config = EasyDict({
            'brightness': {
                'max_delta': 0.3,
            },
            'contrast': {
                'lower': 0.4,
                'upper': 0.8,
            },
            'hue': {
                'max_delta': 0.2,
            },
            'saturation': {
                'lower': 0.5,
                'upper': 1.5,
            }
        })
        self._random_patch_config = EasyDict({
            'min_height': 600,
            'min_width': 600,
        })
        tf.reset_default_graph()

    def _gen_image(self, *shape):
        return np.random.rand(*shape)

    def _get_image_with_boxes(self, image_size, total_boxes):
        image = self._gen_image(*image_size)
        bboxes = generate_gt_boxes(
            total_boxes, image_size[:2],
        )
        return image, bboxes

    def _resize_image(self, image_array, boxes_array=None, min_size=None,
                      max_size=None):
        image = tf.placeholder(tf.float32, image_array.shape)
        feed_dict = {
            image: image_array,
        }
        if boxes_array is not None:
            boxes = tf.placeholder(tf.float32, boxes_array.shape)
            feed_dict[boxes] = boxes_array
        else:
            boxes = None
        resized = resize_image(
            image, bboxes=boxes, min_size=min_size, max_size=max_size
        )
        with self.test_session() as sess:
            resized_dict = sess.run(resized, feed_dict=feed_dict)
            return (
                resized_dict['image'],
                resized_dict.get('bboxes'),
                resized_dict.get('scale_factor'),
            )

    def _flip_image(self, image_array, boxes_array=None, left_right=False,
                    up_down=False, bboxes_dtype=tf.int32):
        image = tf.placeholder(tf.float32, image_array.shape)
        feed_dict = {
            image: image_array,
        }
        if boxes_array is not None:
            boxes = tf.placeholder(bboxes_dtype, boxes_array.shape)
            feed_dict[boxes] = boxes_array
        else:
            boxes = None
        flipped = flip_image(
            image, bboxes=boxes, left_right=left_right, up_down=up_down
        )
        with self.test_session() as sess:
            flipped_dict = sess.run(flipped, feed_dict=feed_dict)
            return flipped_dict['image'], flipped_dict.get('bboxes')

    def _random_patch(self, image, config, bboxes=None):
        with self.test_session() as sess:
            image = tf.cast(image, tf.float32)
            if bboxes is not None:
                bboxes = tf.cast(bboxes, tf.int32)
            patch = random_patch(image, bboxes=bboxes, seed=0, **config)
            return_dict = sess.run(patch)
            ret_bboxes = return_dict.get('bboxes')
            return return_dict['image'], ret_bboxes

    def _random_resize(self, image, config, bboxes=None):
        config = self._random_resize_config
        with self.test_session() as sess:
            resize = random_resize(image, bboxes=bboxes, seed=0, **config)
            return_dict = sess.run(resize)
            ret_bboxes = return_dict.get('bboxes')
            return return_dict['image'], ret_bboxes

    def _random_distort(self, image, config, bboxes=None):
        with self.test_session() as sess:
            distort = random_distortion(
                image, bboxes=bboxes, seed=0, **config
            )
            return_dict = sess.run(distort)
            ret_bboxes = return_dict.get('bboxes')
            return return_dict['image'], ret_bboxes

    def testResizeOnlyImage(self):
        # No min or max size, it doesn't change the image.
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 1024, 3)
        )
        self.assertAllEqual(
            resized_image.shape,
            (100, 1024, 3)
        )
        self.assertAlmostEqual(scale, 1.)

        # min and max sizes smaller and larger that original image size.
        resized_image, _, scal = self._resize_image(
            self._gen_image(100, 1024, 3), min_size=0, max_size=2000
        )
        self.assertAllEqual(
            resized_image.shape,
            (100, 1024, 3)
        )
        self.assertAlmostEqual(scale, 1.)

        # max_size only, slightly smaller than origin image size.
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 1024, 3), max_size=1000
        )
        self.assertAllEqual(
            resized_image.shape,
            (97, 1000, 3)
        )
        self.assertAlmostEqual(int(scale * 100), 97)

        # min_size only, slightly bigger than origin image size.
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 1024, 3), min_size=120
        )
        self.assertAllEqual(
            resized_image.shape,
            (120, 1228, 3)
        )
        self.assertAlmostEqual(int(scale * 100), 120)

        # max_size only, half image size
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 1024, 3), max_size=512
        )
        self.assertAllEqual(
            resized_image.shape,
            (50, 512, 3)
        )
        self.assertAlmostEqual(scale, 0.5)

        # min_size only, double image size
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 1024, 3), min_size=200
        )
        self.assertAllEqual(
            resized_image.shape,
            (200, 2048, 3)
        )
        self.assertAlmostEqual(scale, 2.)

        # min and max invariant changes, both changes negate themselves.
        change = 1.1
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 200, 3), min_size=int(100 * change),
            max_size=round(200 / change)
        )
        self.assertAllEqual(
            resized_image.shape,
            (100, 200, 3)
        )
        self.assertAlmostEqual(int(scale), 1)

        # min and max invariant changes, both changes negate themselves.
        change = 1.6  # Not all values work because of rounding issues.
        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 200, 3), min_size=int(100 * change),
            max_size=round(200 / change)
        )
        self.assertAllEqual(
            resized_image.shape,
            (100, 200, 3)  # No change
        )
        self.assertAlmostEqual(int(scale), 1)

        resized_image, _, scale = self._resize_image(
            self._gen_image(100, 200, 3), min_size=600,
            max_size=1000
        )
        self.assertAllEqual(
            resized_image.shape,
            (100 * 6, 200 * 6, 3)  # We end up bigger than maximum.
        )
        self.assertAlmostEqual(scale, 6.)

        resized_image, _, scale = self._resize_image(
            self._gen_image(2000, 600, 3), min_size=600,
            max_size=1000
        )
        self.assertAllEqual(
            resized_image.shape,
            (1000, 300, 3)  # We end up smaller than minimum image.
        )
        self.assertAlmostEqual(scale, 0.5)

    def testResizeImageBoxes(self):
        image = self._gen_image(100, 100, 3)
        # Half size, corner box
        boxes = np.array([[0, 0, 10, 10, -1]])
        _, resized_boxes, scale = self._resize_image(
            image, boxes, max_size=50
        )
        self.assertAllEqual(resized_boxes, [[0, 0, 5, 5, -1]])

        # Half size, middle box
        boxes = np.array([[10, 10, 90, 90, -1]])
        _, resized_boxes, scale = self._resize_image(
            image, boxes, max_size=50
        )
        self.assertAllEqual(resized_boxes, [[5, 5, 45, 45, -1]])

        # Quarter size, maximum box
        boxes = np.array([[0, 0, 99, 99, -1]])
        _, resized_boxes, scale = self._resize_image(
            image, boxes, max_size=25
        )
        self.assertAllEqual(resized_boxes, [[0, 0, 24, 24, -1]])

    def testPatchImageUpdateCondition(self):
        """Tests we're not patching if we would lose all gt_boxes.
        """
        im_shape = (600, 800, 3)
        label = 3
        image_ph = tf.placeholder(shape=(None, None, 3), dtype=tf.float32)
        bboxes_ph = tf.placeholder(shape=(None, 5), dtype=tf.int32)

        with self.test_session() as sess:
            # Generate image and bboxes.
            image = self._gen_image(*im_shape)
            bboxes = [(0, 0, 40, 40, label), (430, 200, 480, 250, label)]
            # Get patch_image so that the proposed patch has no gt_box center
            # in it.
            patch = patch_image(
                image_ph, bboxes_ph,
                offset_height=45, offset_width=45,
                target_height=100, target_width=200
            )
            feed_dict = {
                image_ph: image,
                bboxes_ph: bboxes
            }
            # Run patch in a test session.
            ret_dict = sess.run(patch, feed_dict)

            ret_image = ret_dict['image']
            ret_bboxes = ret_dict.get('bboxes')
        # Assertions
        self.assertAllClose(ret_image, image)
        self.assertAllClose(ret_bboxes, bboxes)

    def testFlipOnlyImage(self):
        # No changes to image or boxes when no flip is specified.
        image = self._gen_image(100, 100, 3)
        not_flipped_image, _ = self._flip_image(image)
        self.assertAllClose(not_flipped_image, image)

        # Test flipped image that original first column is equal to the last
        # column of the flipped one.
        image = self._gen_image(100, 100, 3)
        flipped_image, _ = self._flip_image(image, left_right=True)
        self.assertAllClose(flipped_image[:, 0], image[:, -1])
        self.assertAllClose(flipped_image[:, 1], image[:, -2])

    def testFlipImageBoxes(self):
        image, boxes = self._get_image_with_boxes((500, 500, 3), 10)
        not_flipped_image, not_flipped_boxes = self._flip_image(image, boxes)
        self.assertAllClose(not_flipped_image, image)
        self.assertAllClose(not_flipped_boxes, boxes)

        # Test box same size as image, left_right flip should not change.
        image = self._gen_image(100, 100, 3)
        boxes = np.array([[0, 0, 99, 99, -1]])
        flipped_image, flipped_boxes = self._flip_image(
            image, boxes, left_right=True
        )
        self.assertAllClose(boxes, flipped_boxes)
        # Check that sum of columns is not modified, just the order.
        self.assertAllClose(image.sum(axis=1), flipped_image.sum(axis=1))

        # Test box same size as image, up_down flip, should not change.
        image = self._gen_image(100, 100, 3)
        boxes = np.array([[0, 0, 99, 99, -1]])
        flipped_image, flipped_boxes = self._flip_image(
            image, boxes, up_down=True
        )
        self.assertAllClose(boxes, flipped_boxes)
        # Check that sum of columns is not modified, just the order.
        self.assertAllClose(image.sum(axis=0), flipped_image.sum(axis=0))

        # Test box same size as image, up_down flip, should not change.
        image = self._gen_image(100, 100, 3)
        boxes = np.array([[0, 0, 99, 99, -1]])
        flipped_image, flipped_boxes = self._flip_image(
            image, boxes, up_down=True, left_right=True
        )
        # Check that sum of columns is not modified, just the order.
        self.assertAllClose(boxes, flipped_boxes)

        # Test box same size as image, up_down flip, should not change.
        image = self._gen_image(100, 100, 3)
        boxes = np.array([[0, 0, 10, 10, -1]])
        flipped_image, flipped_boxes = self._flip_image(
            image, boxes, up_down=True, left_right=True
        )
        # Check that sum of columns is not modified, just the order.
        self.assertAllClose(
            np.array([[89.,  89.,  99.,  99.,  -1.]]), flipped_boxes
        )

    def testFlipBboxesDiffDtype(self):
        image = self._gen_image(100, 100, 3)
        boxes = np.array([[25, 14, 63, 41, -1]])
        _, flipped_boxes_float = self._flip_image(
            image, boxes, up_down=True, left_right=True,
            bboxes_dtype=tf.float32
        )

        _, flipped_boxes_int = self._flip_image(
            image, boxes, up_down=True, left_right=True,
            bboxes_dtype=tf.int32
        )

        # Check that using different types is exactly the same.
        self.assertAllClose(
            flipped_boxes_float, flipped_boxes_int
        )

    def testRandomPatchImageBboxes(self):
        """Tests the integrity of the return values of random_patch

        When bboxes is not None.
        """
        im_shape = (800, 600, 3)
        total_boxes = 5
        # We don't care about the label
        label = 3
        # First test case, we use randomly generated image and bboxes.
        image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)
        # Add a label to each bbox.
        bboxes_w_label = tf.concat(
            [
                bboxes,
                tf.fill((bboxes.shape[0], 1), label)
            ],
            axis=1
        )
        config = self._random_patch_config
        ret_image, ret_bboxes = self._random_patch(
            image, config, bboxes_w_label
        )
        # Assertions
        self.assertLessEqual(ret_bboxes.shape[0], total_boxes)
        self.assertGreater(ret_bboxes.shape[0], 0)
        self.assertTrue(np.all(ret_bboxes >= 0))
        self.assertTrue(np.all(
            ret_bboxes[:, 0] <= ret_image.shape[1]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 1] <= ret_image.shape[0]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 2] <= ret_image.shape[1]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 3] <= ret_image.shape[0]
        ))
        self.assertTrue(np.all(ret_image.shape <= im_shape))

    def testRandomPatchLargerThanImage(self):
        """Tests random_patch normalizes the minimum sizes.
        """
        im_shape = (600, 800, 3)
        total_boxes = 5
        config = EasyDict({
            'min_height': 900,
            'min_width': 900
        })
        label = 3
        image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)
        # Add a label to each bbox.
        bboxes_w_label = tf.concat(
            [
                bboxes,
                tf.fill((bboxes.shape[0], 1), label)
            ],
            axis=1
        )
        ret_image, ret_bboxes = self._random_patch(
            image, config, bboxes_w_label
        )
        # Assertions
        self.assertLessEqual(ret_bboxes.shape[0], total_boxes)
        self.assertGreater(ret_bboxes.shape[0], 0)
        self.assertTrue(np.all(ret_bboxes >= 0))
        self.assertTrue(np.all(
            ret_bboxes[:, 0] <= ret_image.shape[1]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 1] <= ret_image.shape[0]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 2] <= ret_image.shape[1]
        ))
        self.assertTrue(np.all(
            ret_bboxes[:, 3] <= ret_image.shape[0]
        ))
        self.assertTrue(np.all(ret_image.shape <= im_shape))

    def testRandomPatchOnlyImage(self):
        """Tests the integrity of the return values of random_patch

        When bboxes is None.
        """
        im_shape = (600, 800, 3)
        image = self._gen_image(*im_shape)
        config = self._random_patch_config
        ret_image, ret_bboxes = self._random_patch(image, config)
        # Assertions
        self.assertTrue(np.all(ret_image.shape <= im_shape))
        # We ran return_dict.get('bboxes') on the dict returned by
        # random_patch. That's why we should get a None in this case.
        self.assertIs(ret_bboxes, None)

    def testRandomResizeImageBboxes(self):
        """Tests the integrity of the return values of random_resize

        This tests the case when bboxes is not None.
        """
        im_shape = (600, 800, 3)
        config = self._random_resize_config
        total_boxes = 5
        label = 3

        image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)
        # Add a label to each bbox.
        bboxes_w_label = tf.concat(
            [
                bboxes,
                tf.fill((bboxes.shape[0], 1), label)
            ],
            axis=1
        )
        ret_image, ret_bboxes = self._random_resize(
            image, config, bboxes_w_label
        )
        # Assertions
        self.assertEqual(ret_bboxes.shape[0], total_boxes)
        self.assertTrue(np.all(
            np.asarray(ret_image.shape[:2]) >= config.min_size
        ))
        self.assertTrue(np.all(
            np.asarray(ret_image.shape[:2]) <= config.max_size
        ))

    def testRandomResizeOnlyImage(self):
        """Tests the integrity of the return values of random_resize

        This tests the case when bboxes is None.
        """
        im_shape = (600, 800, 3)
        image = self._gen_image(*im_shape)
        config = self._random_resize_config
        ret_image, ret_bboxes = self._random_resize(image, config)
        # Assertions
        self.assertEqual(ret_bboxes, None)
        self.assertTrue(np.all(
            np.asarray(ret_image.shape[:2]) >= config.min_size
        ))
        self.assertTrue(np.all(
            np.asarray(ret_image.shape[:2]) <= config.max_size
        ))

    def testRandomDistort(self):
        """Tests the integrity of the return values of random_distortion.
        """
        im_shape = (600, 900, 3)
        config = self._random_distort_config
        total_boxes = 5
        label = 3

        image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)
        # Add a label to each bbox.
        bboxes_w_label = tf.concat(
            [
                bboxes,
                tf.fill((bboxes.shape[0], 1), label)
            ],
            axis=1
        )

        ret_image, ret_bboxes = self._random_distort(
            image, config, bboxes_w_label
        )
        # Assertions
        self.assertEqual(im_shape, ret_image.shape)
        self.assertAllEqual(
            bboxes, ret_bboxes[:, :4]
        )

    def testSmallRandomDistort(self):
        """Tests random_distort with small-change arguments.

        We pass parameters to random_distort that make it so that it should
        change the image relatively little, and then check that in fact it
        changed relatively little.
        """
        total_boxes = 3
        im_shape = (600, 900, 3)
        config = EasyDict({
            'brightness': {
                'max_delta': 0.00001,
            },
            'hue': {
                'max_delta': 0.00001,
            },
            'saturation': {
                'lower': 0.99999,
                'upper': 1.00001,
            },
            'contrast': {
                'lower': 0.99999,
                'upper': 1.00001
            }
        })
        label = 3
        image, bboxes = self._get_image_with_boxes(im_shape, total_boxes)
        # Add a label to each bbox.
        bboxes_w_label = tf.concat(
            [
                bboxes,
                tf.fill((bboxes.shape[0], 1), label)
            ],
            axis=1
        )
        ret_image, ret_bboxes = self._random_distort(
            image, config, bboxes_w_label
        )
        # Assertions
        large_number = 0.1
        self.assertAllClose(image, ret_image, rtol=0.05, atol=large_number)

if __name__ == '__main__':
    tf.test.main()


text:
@interface GamePickerRecentViewController : GamePickerViewController
@end


text:
package org.jkiss.dbeaver.core;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

/**
 * DBeaver project nature
 */
public class DBeaverNature implements IProjectNature {

    public static final String NATURE_ID = "org.jkiss.dbeaver.DBeaverNature";

    private IProject project;

    public void configure() throws CoreException {

    }

    public void deconfigure() throws CoreException {

    }

    public IProject getProject() {
        return project;
    }

    public void setProject(IProject value) {
        project = value;
    }
}


text:
package ariba.ui.aribaweb.util;

import java.text.ParseException;

import ariba.util.core.ClassExtension;
import ariba.util.core.ClassExtensionRegistry;
import ariba.util.formatter.Formatter;

public abstract class AWBookmarkFormatter extends ClassExtension
{
    private static final ClassExtensionRegistry ClassExtensionRegistry = new ClassExtensionRegistry();

    public static void registerClassExtension (Class<?> type,
                                               AWBookmarkFormatter formatter)
    {
        ClassExtensionRegistry.registerClassExtension(type, formatter);
    }

    public abstract String formatObject (Object val);
    public abstract Object parseString (String val);

    public static String format (Object val)
    {
        AWBookmarkFormatter bformatter = (AWBookmarkFormatter)ClassExtensionRegistry.get(val.getClass());
        if (bformatter != null) {
            return bformatter.formatObject(val);
        }

        return Formatter.getFormatterForObject(val).getFormat(val);
    }

    public static Object parse (String val, Class<?> type) throws ParseException
    {
        AWBookmarkFormatter bformatter = (AWBookmarkFormatter)ClassExtensionRegistry.get(type);
        if (bformatter != null) {
            return bformatter.parseString(val);
        }
        return Formatter.parseString(val,type.getName());
    }
}


text:
import React, {PropTypes} from 'react';
import {InputButton} from '../input-button/InputButton';

const nodePropTypes = PropTypes.shape({
    text: PropTypes.string.isRequired,
    id: PropTypes.string.isRequired
});

nodePropTypes.children = PropTypes.arrayOf(nodePropTypes);

export class Node extends React.Component {
    static propTypes = {
        data: nodePropTypes,
        onAddCategory: PropTypes.func,
        onEditCategory: PropTypes.func,
        onDeleteCategory: PropTypes.func,
        onMoveToCategory: PropTypes.func
    };

    constructor() {
        super();
        this.state = {
            //Todo create compone combining button and inputbutton to avoid duptication of hide,show logic
            addCategoryInputVisible: false,
            editCategoryInputVisible: false
        };
    }

    render() {
        const addCategoryInput = this.state.addCategoryInputVisible
            ? this.getActionCategoryInput('Add', this.onAdd.bind(this))
            : '';

        const editCategoryInput = this.state.editCategoryInputVisible
            ? this.getActionCategoryInput('Edit', this.onEdit.bind(this))
            : '';

        return (
            <div className={`text-node ${this.getClass()}`} onClick={this.props.onClick}>
                {this.props.data.text}

                    <button onClick={this.toggleAddCategoryInput.bind(this)}>+</button>
                    {addCategoryInput}

                    <button onClick={this.toggleEditCategoryInput.bind(this)}>Edit</button>
                    {editCategoryInput}

                <button onClick={this.onDelete.bind(this)}>Delete</button>

        );
    }

    getClass() {
        return this.props.selected ? 'selected' : '';
    }

    getActionCategoryInput(text, action) {
        return (

                <InputButton onButtonClick={action}>{text}</InputButton>

        );
    }

    onAdd(text) {
        this.props.onAddCategory(text);
        this.toggleAddCategoryInput();
    }

    onEdit(text) {
        this.props.onEditCategory(text);
        this.toggleEditCategoryInput();
    }

    onDelete(event) {
        event && event.stopPropagation();
        this.props.onDeleteCategory();
    }

    toggleAddCategoryInput(event) {
        //TODO investigate why event in undefined from time to time
        event && event.stopPropagation();
        this.setState({addCategoryInputVisible: !this.state.addCategoryInputVisible});
    }

    toggleEditCategoryInput(event) {
        //TODO investigate why event in undefined from time to time
        event && event.stopPropagation();
        this.setState({editCategoryInputVisible: !this.state.editCategoryInputVisible});
    }
}


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Fonts Module Level 4: parsing font-optical-sizing with invalid values</title>
<link rel="help" href="https://www.w3.org/TR/css-fonts-4/#propdef-font-optical-sizing">
<meta name="assert" content="font-optical-sizing supports only the grammar 'auto | none'.">
<meta name="assert" content="font-optical-sizing string has three letters.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/css/support/parsing-testcommon.js"></script>
</head>
<body>
<script>
test_invalid_value('font-optical-sizing', 'normal');
test_invalid_value('font-optical-sizing', 'auto none');
</script>
</body>
</html>


text:
package ctci.chapter1ArraysAndStrings.q2;

import java.util.Arrays;

import org.junit.Assert;
import org.junit.Test;

/**
 * Permutation
 *
 * @since 2015-11-12
 */
public class Permutation {

    /*
    1.2 Given two strings, write a method to decide if one is a permutation of the other
    */

    boolean isPermutation(String s1, String s2) {
        if (s1 == null || s2 == null) {
            throw new IllegalArgumentException();
        }

        // If not the same length, cannot be a permutation
        if (s1.length() != s2.length()) {
            return false;
        }

        char[] s1Array = s1.toCharArray();
        char[] s2Array = s2.toCharArray();

        Arrays.sort(s1Array);
        Arrays.sort(s2Array);

        return Arrays.equals(s1Array, s2Array);
    }

    @Test
    public void isPermutationTest() {
        Assert.assertTrue(isPermutation("azerty", "rtyaze"));
        Assert.assertFalse(isPermutation("az", "aze"));
        Assert.assertFalse(isPermutation("az", "AZ"));
    }
}


text:
#import "SBStatusBarStateProvider.h"

#import "UIStatusBarStateObserver-Protocol.h"

@interface SBMainStatusBarStateProvider : SBStatusBarStateProvider <UIStatusBarStateObserver>
{
    _Bool _overridePercent;
    _Bool _killActivity;
    _Bool _simulateInCallStatusBar;
    _Bool _itemIsDisabled[25];
    _Bool _itemWasDisabled[25];
    _Bool _timeEnabled;
    _Bool _timeCloaked;
    _Bool _allButBatteryCloaked;
    _Bool _telephonyAndBluetoothCloaked;
}

+ (id)sharedInstance;
- (void)statusBarStateProvider:(id)arg1 didPostStatusBarData:(const CDStruct_0e61b686 *)arg2 withActions:(int)arg3;
- (void)_toggleSimulatesInCallStatusBar;
- (void)_composePostDataFromAggregatorData:(CDStruct_0e61b686 *)arg1;
- (_Bool)_shouldPostForVisitedItem:(int)arg1 withUpdates:(_Bool)arg2 toAggregatorData:(const CDStruct_0e61b686 *)arg3;
- (void)setTelephonyAndBluetoothItemsCloaked:(_Bool)arg1;
- (void)setAllItemsExceptBatteryCloaked:(_Bool)arg1;
- (void)setTimeCloaked:(_Bool)arg1;
- (void)enableTime:(_Bool)arg1 crossfade:(_Bool)arg2 crossfadeDuration:(double)arg3;
- (void)enableTime:(_Bool)arg1;
- (_Bool)isTimeEnabled;
- (void)_updateDisabledItems;
- (void)dealloc;
- (id)init;

@end


text:
package composicao;

public class TesteFornecedor {

	public static void main(String[] args) {

		Fornecedor f = new Fornecedor("Distribuidora ABC");
		System.out.println(f);

		f.addContato("2345-6789", "abc@abc.com");
		f.addContato("0000-0000", "kkk@kkk.com");
		System.out.println(f);

		f.removerContato();
		f.addContato("9876-5432", "contato@abc.com");
		System.out.println(f);
	}
}


text:
// Admin javascript manifest
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery-ui/datepicker-da
//= require jquery-ui/datepicker-de
//= require jquery-ui/datepicker-es
//= require jquery-ui/datepicker-fr
//= require jquery-ui/datepicker-he
//= require jquery-ui/datepicker-it
//= require jquery-ui/datepicker-ja
//= require jquery-ui/datepicker-lt
//= require jquery-ui/datepicker-nb
//= require jquery-ui/datepicker-nl
//= require jquery-ui/datepicker-pl
//= require jquery-ui/datepicker-pt-BR
//= require jquery-ui/datepicker-ro
//= require jquery-ui/datepicker-ru
//= require jquery-ui/datepicker-zh-CN
//= require jquery-ui/datepicker-zh-TW
//= require datetimepicker
//= require bootstrap
//= require quicktags
//= require widearea
//= require tagmanager
//= require typeahead
//= require sidebar
//= require spinnable
//= require lightbox
//
//= require_self

/* typewatch() borrowed from
 * http://stackoverflow.com/questions/2219924/idiomatic-jquery-delayed-event-only-after-a-short-pause-in-typing-e-g-timew
 */
var typewatch = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  }
})();

function autosave_request(e) {
  $('#article_form').keyup(function() {
    typewatch(function() {
      $.ajax({
        type: "POST",
        url: '/admin/content/autosave',
        data: $("#article_form").serialize()});
    }, 5000)
  });
}

function set_widerea(element) {
  if ($("#article_id").val() == "") {
    wideArea().clearData(element);
  }

  wideArea();
}

function tag_manager() {
  var tagApi = jQuery("#article_keywords").tagsManager({
    prefilled: $('#article_keywords').val()
  });

  jQuery("#article_keywords").typeahead({
    name: 'tags',
    limit: 15,
    prefetch: '/admin/content/auto_complete_for_article_keywords'
  }).on('typeahead:selected', function (e, d) {
    tagApi.tagsManager("pushTag", d.value);
  });
}

function save_article_tags() {
  $('#article_keywords').val($('#article_form').find('input[name="hidden-article[keywords]"]').val());
}

function doneTyping () {
  $( "#save-bar").fadeIn(2000, function() {

  });
}

function set_savebar() {
  var typingTimer;
  var doneTypingInterval = 3000;

  $( "#article_body_and_extended" ).keydown(function() {
    $( "#save-bar").fadeOut(2000, function() {

    });
    clearTimeout(typingTimer);
  });

  $('#article_body_and_extended').keyup(function(){
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  });
}

// From http://www.shawnolson.net/scripts/public_smo_scripts.js
function check_all(checkbox) {
  var form = checkbox.form, z = 0;
  for(z=0; z<form.length;z++){
    if(form[z].type == 'checkbox' && form[z].name != 'checkall'){
      form[z].checked = checkbox.checked;
    }
  }
}

$(document).ready(function() {
  $('#article_form').each(function(e){autosave_request(e)});
  $('#article_form').submit(function(e){save_article_tags()});
  $('#article_form').each(function(e){tag_manager()});
  $('#article_form').each(function(e){set_widerea($('#article_body_and_extended'))});
  $('#article_body_and_extended').each(function(e){set_savebar()});
  $('#page_form').each(function(e){set_widerea($('#page_body'))});

  // DatePickers
  $('.datepicker').each(function() {
    $(this).datepicker($.datepicker.regional[this.dataset.locale]);
  });

  // Date time picker (not related to date picker at all!)
  $( "#article_published_at" ).datetimepicker();

  // DropDown
  $(".dropdown-toggle").dropdown();
});

$(document).delegate('*[data-toggle="lightbox"]', 'click',
    function(event) {
      event.preventDefault();
      $(this).ekkoLightbox();
    });


text: composer update --prefer-dist


text:
<?php

namespace spec\Phunkie\Cats\Functor;

use Md\PropertyTesting\TestTrait;
use Phunkie\Laws\InvariantLaws;
use Md\PropertyTesting\Generator\RandomKindGenerator;
use PHPUnit\Framework\TestCase;

class InvariantSpec extends TestCase
{
    use InvariantLaws;
    use RandomKindGenerator;
    use TestTrait;

    /**
     * @test
     */
    public function it_obeys_the_identity_law_of_invariance()
    {
        $this->forAll(
            $this->genRandomFA()
        )->then(function ($fa) {
            $this->assertTrue($this->invariantIdentity($fa));
        });
    }

    /**
     * @test
     */
    public function it_obeys_the_composition_law_of_invariance()
    {
        $this->forAll(
            $this->genRandomFA(),
            $this->genFunctionStringToInt(),
            $this->genFunctionStringToInt(),
            $this->genFunctionStringToBool(),
            $this->genFunctionBoolToString()
        )->then(function ($fa, $f1, $f2, $g1, $g2) {
            $this->assertTrue($this->invariantComposition($fa, $f1, $f2, $g1, $g2));
        });
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Verh. bot. Ver. Prov. Brandenb. 48: (1907)

#### Original name
Trichonectria aculeata Kirschst., 1907

### Remarks
null


text:
/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package org.geotools.styling;

import java.util.Arrays;

import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.util.Utilities;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.FilterFactory;
import org.opengis.filter.expression.Expression;
import org.opengis.style.StyleVisitor;
import org.opengis.util.Cloneable;

/**
 * Provides a Java representation of the Stroke object in an SLD document. A
 * stroke defines how a line is rendered.
 *
 * @author James Macgill, CCG
 *
 *
 * @source $URL$
 * @version $Id$
 */
public class StrokeImpl implements Stroke, Cloneable {
    private FilterFactory filterFactory;
    private Expression color;
    private float[] dashArray;
    private Expression dashOffset;
    private GraphicImpl fillGraphic;
    private GraphicImpl strokeGraphic;
    private Expression lineCap;
    private Expression lineJoin;
    private Expression opacity;
    private Expression width;

    /**
     * Creates a new instance of Stroke
     */
    protected StrokeImpl() {
        this( CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints()));
    }

    protected StrokeImpl(FilterFactory factory) {
        filterFactory = factory;
    }

    public void setFilterFactory(FilterFactory factory) {
        filterFactory = factory;
    }

    /**
     * This parameter gives the solid color that will be used for a stroke.

     * The color value is RGB-encoded using two hexidecimal digits per
     * primary-color component in the order Red, Green, Blue, prefixed with
     * the hash (#) sign.  The hexidecimal digits between A and F may be in
     * either upper or lower case.  For example, full red is encoded as
     * "#ff0000"  (with no quotation marks).  The default color is defined to
     * be black ("#000000"). Note: in CSS this parameter is just called Stroke
     * and not Color.
     *
     * @return The color of the stroke encoded as a hexidecimal RGB value.
     */
    public Expression getColor() {
        return color;
    }

    /**
     * This parameter sets the solid color that will be used for a stroke.

     * The color value is RGB-encoded using two hexidecimal digits per
     * primary-color component in the order Red, Green, Blue, prefixed with
     * the hash (#) sign.  The hexidecimal digits between A and F may be in
     * either upper or lower case.  For example, full red is encoded as
     * "#ff0000"  (with no quotation marks).  The default color is defined to
     * be black ("#000000"). Note: in CSS this parameter is just called Stroke
     * and not Color.
     *
     * @param color The color of the stroke encoded as a hexidecimal RGB value.
     *        This must not be null.
     *
     * @throws IllegalArgumentException DOCUMENT ME!
     */
    public void setColor(Expression color) {
        if (this.color == color) {
            return;
        }
        this.color = color;
    }

    /**
     * This parameter sets the solid color that will be used for a stroke.

     * The color value is RGB-encoded using two hexidecimal digits per
     * primary-color component in the order Red, Green, Blue, prefixed with
     * the hash (#) sign.  The hexidecimal digits between A and F may be in
     * either upper or lower case.  For example, full red is encoded as
     * "#ff0000"  (with no quotation marks).  The default color is defined to
     * be black ("#000000"). Note: in CSS this parameter is just called Stroke
     * and not Color.
     *
     * @param color The color of the stroke encoded as a hexidecimal RGB value.
     */
    public void setColor(String color) {
        setColor(filterFactory.literal(color));
    }

    /**
     * This parameter encodes the dash pattern as a series of floats.

     * The first number gives the length in pixels of the dash to draw, the
     * second gives the amount of space to leave, and this pattern repeats.

     * If an odd number of values is given, then the pattern is expanded by
     * repeating it twice to give an even number of values. The default is to
     * draw an unbroken line.

     * For example, "2 1 3 2" would produce:

     * -- ---  -- ---  --
     * ---  -- ---  -- ---  --
     *
     * @return The dash pattern as an array of float values in the form
     *         "dashlength gaplength ..."
     */
    public float[] getDashArray() {
        float[] ret = null;

        if (dashArray != null) {
            ret = new float[dashArray.length];
            System.arraycopy(dashArray, 0, ret, 0, dashArray.length);
        } else {
        	final float[] defaultDashArray = Stroke.DEFAULT.getDashArray();
        	if(defaultDashArray == null)
        	    return null;

        	ret = new float[defaultDashArray.length];
        	System.arraycopy(defaultDashArray, 0, ret, 0, defaultDashArray.length);
        }

        return ret;
    }

    /**
     * This parameter encodes the dash pattern as a series of floats.

     * The first number gives the length in pixels of the dash to draw, the
     * second gives the amount of space to leave, and this pattern repeats.

     * If an odd number of values is given, then the pattern is expanded by
     * repeating it twice to give an even number of values. The default is to
     * draw an unbroken line.

     *
     * For example, "2 1 3 2" would produce:

     * -- ---  -- ---
     * -- ---  -- ---  --
     * ---  --
     *
     * @param dashPattern The dash pattern as an array of float values in the
     *        form "dashlength gaplength ..."
     */
    public void setDashArray(float[] dashPattern) {
        dashArray = dashPattern;
    }

    /**
     * This param determines where the dash pattern should start from.
     *
     * @return where the dash should start from.
     */
    public Expression getDashOffset() {
    	if ( dashOffset == null ) {
    		return Stroke.DEFAULT.getDashOffset();
    	}

        return dashOffset;
    }

    /**
     * This param determines where the dash pattern should start from.
     *
     * @param dashOffset The distance into the dash pattern that should act as
     *        the start.
     */
    public void setDashOffset(Expression dashOffset) {
        if (dashOffset == null) {
            return;
        }

        this.dashOffset = dashOffset;
    }

    /**
     * This parameter indicates that a stipple-fill repeated graphic will be
     * used and specifies the fill graphic to use.
     *
     * @return The graphic to use as a stipple fill. If null, then no Stipple
     *         fill should be used.
     */
    public GraphicImpl getGraphicFill() {
        return fillGraphic;
    }

    /**
     * This parameter indicates that a stipple-fill repeated graphic will be
     * used and specifies the fill graphic to use.
     *
     * @param fillGraphic The graphic to use as a stipple fill. If null, then
     *        no Stipple fill should be used.
     */
    public void setGraphicFill(org.opengis.style.Graphic fillGraphic) {
        if (this.fillGraphic == fillGraphic) {
            return;
        }
        this.fillGraphic = GraphicImpl.cast( fillGraphic );
    }

    /**
     * This parameter indicates that a repeated-linear-graphic graphic stroke
     * type will be used and specifies the graphic to use. Proper stroking
     * with a linear graphic requires two "hot-spot" points within the space
     * of the graphic to indicate where the rendering line starts and stops.
     * In the case of raster images with no special mark-up, this line will be
     * assumed to be the middle pixel row of the image, starting from the
     * first pixel column and ending at the last pixel column.
     *
     * @return The graphic to use as a linear graphic. If null, then no graphic
     *         stroke should be used.
     */
    public GraphicImpl getGraphicStroke() {
        return strokeGraphic;
    }

    /**
     * This parameter indicates that a repeated-linear-graphic graphic stroke
     * type will be used and specifies the graphic to use. Proper stroking
     * with a linear graphic requires two "hot-spot" points within the space
     * of the graphic to indicate where the rendering line starts and stops.
     * In the case of raster images with no special mark-up, this line will be
     * assumed to be the middle pixel row of the image, starting from the
     * first pixel column and ending at the last pixel column.
     *
     * @param strokeGraphic The graphic to use as a linear graphic. If null,
     *        then no graphic stroke should be used.
     */
    public void setGraphicStroke(org.opengis.style.Graphic strokeGraphic) {
        if (this.strokeGraphic == strokeGraphic) {
            return;
        }
        this.strokeGraphic = GraphicImpl.cast(strokeGraphic);
    }

    /**
     * This parameter controls how line strings should be capped.
     *
     * @return The cap style.  This will be one of "butt", "round" and "square"
     *         There is no defined default.
     */
    public Expression getLineCap() {
        if( lineCap == null ){
            // ConstantExpression.constant("miter")
            return Stroke.DEFAULT.getLineCap();
        }
        return lineCap;
    }

    /**
     * This parameter controls how line strings should be capped.
     *
     * @param lineCap The cap style. This can be one of "butt", "round" and
     *        "square" There is no defined default.
     */
    public void setLineCap(Expression lineCap) {
        if (lineCap == null) {
            return;
        }
        this.lineCap = lineCap;
    }

    /**
     * This parameter controls how line strings should be joined together.
     *
     * @return The join style.  This will be one of "mitre", "round" and
     *         "bevel".  There is no defined default.
     */
    public Expression getLineJoin() {
        if( lineCap == null ){
            // ConstantExpression.constant("miter")
            return Stroke.DEFAULT.getLineJoin();
        }
        return lineJoin;
    }

    /**
     * This parameter controls how line strings should be joined together.
     *
     * @param lineJoin The join style.  This will be one of "mitre", "round"
     *        and "bevel". There is no defined default.
     */
    public void setLineJoin(Expression lineJoin) {
        if (lineJoin == null) {
            return;
        }
        this.lineJoin = lineJoin;
    }

    /**
     * This specifies the level of translucency to use when rendering the stroke.

     * The value is encoded as a floating-point value between 0.0 and 1.0 with
     * 0.0 representing totally transparent and 1.0 representing totally
     * opaque.  A linear scale of translucency is used for intermediate values.

     * For example, "0.65" would represent 65% opacity. The default value is
     * 1.0 (opaque).
     *
     * @return The opacity of the stroke, where 0.0 is completely transparent
     *         and 1.0 is completely opaque.
     */
    public Expression getOpacity() {
        if( lineCap == null ){
            return Stroke.DEFAULT.getOpacity();
        }
        return opacity;
    }

    /**
     * This specifies the level of translucency to use when rendering the stroke.

     * The value is encoded as a floating-point value between 0.0 and 1.0 with
     * 0.0 representing totally transparent and 1.0 representing totally
     * opaque.  A linear scale of translucency is used for intermediate values.

     * For example, "0.65" would represent 65% opacity. The default value is
     * 1.0 (opaque).
     *
     * @param opacity The opacity of the stroke, where 0.0 is completely
     *        transparent and 1.0 is completely opaque.
     */
    public void setOpacity(Expression opacity) {
        if (opacity == null) {
            return;
        }
        this.opacity = opacity;
    }

    /**
     * This parameter gives the absolute width (thickness) of a stroke in
     * pixels encoded as a float. The default is 1.0.  Fractional numbers are
     * allowed but negative numbers are not.
     *
     * @return The width of the stroke in pixels.  This may be fractional but
     *         not negative.
     */
    public Expression getWidth() {
        if( width == null ){
            return filterFactory.literal(1.0);
        }
        return width;
    }

    /**
     * This parameter sets the absolute width (thickness) of a stroke in pixels
     * encoded as a float. The default is 1.0.  Fractional numbers are allowed
     * but negative numbers are not.
     *
     * @param width The width of the stroke in pixels.  This may be fractional
     *        but not negative.
     */
    public void setWidth(Expression width) {
        this.width = width;
    }

    public String toString() {
        StringBuffer out = new StringBuffer(
                "org.geotools.styling.StrokeImpl:\n");
        out.append("\tColor " + this.color + "\n");
        out.append("\tWidth " + this.width + "\n");
        out.append("\tOpacity " + this.opacity + "\n");
        out.append("\tLineCap " + this.lineCap + "\n");
        out.append("\tLineJoin " + this.lineJoin + "\n");
        out.append("\tDash Array " + this.dashArray + "\n");
        out.append("\tDash Offset " + this.dashOffset + "\n");
        out.append("\tFill Graphic " + this.fillGraphic + "\n");
        out.append("\tStroke Graphic " + this.strokeGraphic);

        return out.toString();
    }

    public java.awt.Color getColor(SimpleFeature feature) {
        return java.awt.Color.decode((String) this.getColor().evaluate(feature));
    }

    public Object accept(StyleVisitor visitor,Object data) {
        return visitor.visit(this,data);
    }

    public void accept(org.geotools.styling.StyleVisitor visitor) {
        visitor.visit(this);
    }

    /**
     * Clone the StrokeImpl object.
     *
     *

     * The clone is a deep copy of the original, except for the expression
     * values which are immutable.
     *

     *
     * @see Stroke#clone()
     */
    public Object clone() {
        try {
            StrokeImpl clone = (StrokeImpl) super.clone();

            if (dashArray != null) {
                clone.dashArray = new float[dashArray.length];
                System.arraycopy(dashArray, 0, clone.dashArray, 0,
                    dashArray.length);
            }

            if (fillGraphic != null && fillGraphic instanceof Cloneable) {
                clone.fillGraphic = (GraphicImpl) ((Cloneable) fillGraphic).clone();
            }

            if (strokeGraphic != null && fillGraphic instanceof Cloneable ) {
                clone.strokeGraphic = (GraphicImpl) ((Cloneable) strokeGraphic)
                    .clone();
            }

            return clone;
        } catch (CloneNotSupportedException e) {
            // This will never happen
            throw new RuntimeException("Failed to clone StrokeImpl");
        }
    }

    public int hashCode() {
        final int PRIME = 1000003;
        int result = 0;

        if (color != null) {
            result = (PRIME * result) + color.hashCode();
        }

        if (dashOffset != null) {
            result = (PRIME * result) + dashOffset.hashCode();
        }

        if (fillGraphic != null) {
            result = (PRIME * result) + fillGraphic.hashCode();
        }

        if (strokeGraphic != null) {
            result = (PRIME * result) + strokeGraphic.hashCode();
        }

        if (lineCap != null) {
            result = (PRIME * result) + lineCap.hashCode();
        }

        if (lineJoin != null) {
            result = (PRIME * result) + lineJoin.hashCode();
        }

        if (opacity != null) {
            result = (PRIME * result) + opacity.hashCode();
        }

        if (width != null) {
            result = (PRIME * result) + width.hashCode();
        }

        if (dashArray != null) {
            result = (PRIME * result) + hashCodeDashArray(dashArray);
        }

        return result;
    }

    /*
     * Helper method to compute the hashCode of float arrays.
     */
    private int hashCodeDashArray(float[] a) {
        final int PRIME = 1000003;

        if (a == null) {
            return 0;
        }

        int result = 0;

        for (int i = 0; i < a.length; i++) {
            result = (PRIME * result) + Float.floatToIntBits(a[i]);
        }

        return result;
    }

    /**
     * Compares this stroke with another stroke for equality.
     *
     * @param oth The other StrokeImpl to compare
     *
     * @return True if this and oth are equal.
     */
    public boolean equals(Object oth) {
        if (this == oth) {
            return true;
        }

        if (oth == null) {
            return false;
        }

        if (oth.getClass() != getClass()) {
            return false;
        }

        StrokeImpl other = (StrokeImpl) oth;

        // check the color first - most likely to change
        if( !Utilities.equals( getColor(), other.getColor() )){
            return false;
        }

        // check the width
        if( !Utilities.equals( getWidth(), other.getWidth() )){
            return false;
        }

        if( !Utilities.equals( getLineCap(), other.getLineCap() )){
            return false;
        }

        if( !Utilities.equals( getLineJoin(), other.getLineJoin() )){
            return false;
        }

        if( !Utilities.equals( getOpacity(), other.getOpacity() )){
            return false;
        }

        if( !Utilities.equals( getGraphicFill(), other.getGraphicFill() )){
            return false;
        }

        if( !Utilities.equals( getGraphicStroke(), other.getGraphicStroke() )){
            return false;
        }

        if (!Arrays.equals(getDashArray(), other.getDashArray())) {
            return false;
        }

        return true;
    }

    static StrokeImpl cast(org.opengis.style.Stroke stroke) {
        if( stroke == null ){
            return null;
        }
        else if (stroke instanceof StrokeImpl){
            return (StrokeImpl) stroke;
        }
        else {
            StrokeImpl copy = new StrokeImpl();
            copy.setColor( stroke.getColor());
            if( stroke.getDashArray() != null ){
                float dashArray[] = stroke.getDashArray();
                float ret[] = new float[ dashArray.length ];
                System.arraycopy(dashArray, 0, ret, 0, dashArray.length );
                copy.setDashArray( ret );
            }
            copy.setDashOffset(stroke.getDashOffset());
            copy.setGraphicFill( GraphicImpl.cast(stroke.getGraphicFill()));
            copy.setGraphicStroke( GraphicImpl.cast(stroke.getGraphicStroke()));
            copy.setLineCap( stroke.getLineCap());
            copy.setLineJoin(stroke.getLineJoin());
            copy.setOpacity( stroke.getOpacity());
            copy.setWidth(stroke.getWidth());

            return copy;
        }
    }

}


text:
<?php

namespace Nemundo\App\Linux\Cmd;

class UserToGroupCmd extends AbstractCmd
{

    public $user;

    public $group;

    public function getCommandList()
    {

        $this->addCommandLine('usermod -a -G '.$this->group.' '.$this->user);

        return parent::getCommandList(); // TODO: Change the autogenerated stub
    }

}


text:
@interface FixedRadViewController : UIViewController
@property (retain, nonatomic) IBOutlet UISlider *sliderFeatherVal;
@property (retain, nonatomic) IBOutlet UIImageView *overlayView;
@property (retain, nonatomic) IBOutlet UISwitch *dragState;
@property (retain, nonatomic) IBOutlet UISegmentedControl *modeVal;
@property (retain, nonatomic) IBOutlet UILabel *textVal;
@property (retain, nonatomic) IBOutlet UISwitch *continiousMode;
@property (retain, nonatomic) IBOutlet UILabel *featherTextVal;
@property (retain, nonatomic) IBOutlet UISlider *sliderVal;
@property (retain, nonatomic) IBOutlet UIImageView *displayImage;
@property (retain, nonatomic) IBOutlet UILabel *markerNotice;
@property (retain, nonatomic) IBOutlet UILabel *progressExemplar;
@property (retain, nonatomic) IBOutlet UIProgressView *progressBarExemplar;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImage *overlayMask;

@property (nonatomic, assign) BOOL loop;
@property (retain, nonatomic) IBOutlet UILabel *savedImageLabel;

- (IBAction)dismissView:(id)sender;
- (IBAction)slider:(id)sender;
- (IBAction)sliderFeather:(id)sender;
- (IBAction)modeSwitch:(id)sender;
- (IBAction)dragSwitch:(id)sender;
-(void) exemplarCallBack : (UIImage *) imageExe;
- (IBAction)captureSnapshot:(id)sender;

-(void)setProgressVal : (float) value;
-(void)setProgressWithVal : (float) val;

@end

//@protocol MyProgressBarDelegate
//
//- (void) onUpdateProgress:(Float32)progress;
//
//@end


text:
/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  fragmentShader: <string>,
 *  vertexShader: <string>,
 *
 *  uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
 *
 *  shading: THREE.SmoothShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  lights: <bool>,
 *
 *  vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>,
 *
 *	fog: <bool>
 * }
 */

THREE.ShaderMaterial = function ( parameters ) {

	THREE.Material.call( this, parameters );

	parameters = parameters || {};

	this.fragmentShader = parameters.fragmentShader !== undefined ? parameters.fragmentShader : "void main() {}";
	this.vertexShader = parameters.vertexShader !== undefined ? parameters.vertexShader : "void main() {}";
	this.uniforms = parameters.uniforms !== undefined ? parameters.uniforms : {};
	this.attributes = parameters.attributes;

	this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;

	this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
	this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;

	this.fog = parameters.fog !== undefined ? parameters.fog : false; // set to use scene fog

	this.lights = parameters.lights !== undefined ? parameters.lights : false; // set to use scene lights

	this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors; // set to use "color" attribute stream

	this.skinning = parameters.skinning !== undefined ? parameters.skinning : false; // set to use skinning attribute streams

	this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false; // set to use morph targets
	this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false; // set to use morph normals

};

THREE.ShaderMaterial.prototype = new THREE.Material();
THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery'), require('./util.js')) :
  typeof define === 'function' && define.amd ? define(['jquery', './util.js'], factory) :
  (global = global || self, global.Collapse = factory(global.jQuery, global.Util));
}(this, (function ($, Util) { 'use strict';

  $ = $ && Object.prototype.hasOwnProperty.call($, 'default') ? $['default'] : $;
  Util = Util && Object.prototype.hasOwnProperty.call(Util, 'default') ? Util['default'] : Util;

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }

  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  }

  function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);

    if (Object.getOwnPropertySymbols) {
      var symbols = Object.getOwnPropertySymbols(object);
      if (enumerableOnly) symbols = symbols.filter(function (sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
      keys.push.apply(keys, symbols);
    }

    return keys;
  }

  function _objectSpread2(target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i] != null ? arguments[i] : {};

      if (i % 2) {
        ownKeys(Object(source), true).forEach(function (key) {
          _defineProperty(target, key, source[key]);
        });
      } else if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
      } else {
        ownKeys(Object(source)).forEach(function (key) {
          Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
      }
    }

    return target;
  }

  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */

  var NAME = 'collapse';
  var VERSION = '4.5.0';
  var DATA_KEY = 'bs.collapse';
  var EVENT_KEY = "." + DATA_KEY;
  var DATA_API_KEY = '.data-api';
  var JQUERY_NO_CONFLICT = $.fn[NAME];
  var Default = {
    toggle: true,
    parent: ''
  };
  var DefaultType = {
    toggle: 'boolean',
    parent: '(string|element)'
  };
  var EVENT_SHOW = "show" + EVENT_KEY;
  var EVENT_SHOWN = "shown" + EVENT_KEY;
  var EVENT_HIDE = "hide" + EVENT_KEY;
  var EVENT_HIDDEN = "hidden" + EVENT_KEY;
  var EVENT_CLICK_DATA_API = "click" + EVENT_KEY + DATA_API_KEY;
  var CLASS_NAME_SHOW = 'show';
  var CLASS_NAME_COLLAPSE = 'collapse';
  var CLASS_NAME_COLLAPSING = 'collapsing';
  var CLASS_NAME_COLLAPSED = 'collapsed';
  var DIMENSION_WIDTH = 'width';
  var DIMENSION_HEIGHT = 'height';
  var SELECTOR_ACTIVES = '.show, .collapsing';
  var SELECTOR_DATA_TOGGLE = '[data-toggle="collapse"]';
  /**
   * ------------------------------------------------------------------------
   * Class Definition
   * ------------------------------------------------------------------------
   */

  var Collapse = /*#__PURE__*/function () {
    function Collapse(element, config) {
      this._isTransitioning = false;
      this._element = element;
      this._config = this._getConfig(config);
      this._triggerArray = [].slice.call(document.querySelectorAll("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]")));
      var toggleList = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE));

      for (var i = 0, len = toggleList.length; i < len; i++) {
        var elem = toggleList[i];
        var selector = Util.getSelectorFromElement(elem);
        var filterElement = [].slice.call(document.querySelectorAll(selector)).filter(function (foundElem) {
          return foundElem === element;
        });

        if (selector !== null && filterElement.length > 0) {
          this._selector = selector;

          this._triggerArray.push(elem);
        }
      }

      this._parent = this._config.parent ? this._getParent() : null;

      if (!this._config.parent) {
        this._addAriaAndCollapsedClass(this._element, this._triggerArray);
      }

      if (this._config.toggle) {
        this.toggle();
      }
    } // Getters

    var _proto = Collapse.prototype;

    // Public
    _proto.toggle = function toggle() {
      if ($(this._element).hasClass(CLASS_NAME_SHOW)) {
        this.hide();
      } else {
        this.show();
      }
    };

    _proto.show = function show() {
      var _this = this;

      if (this._isTransitioning || $(this._element).hasClass(CLASS_NAME_SHOW)) {
        return;
      }

      var actives;
      var activesData;

      if (this._parent) {
        actives = [].slice.call(this._parent.querySelectorAll(SELECTOR_ACTIVES)).filter(function (elem) {
          if (typeof _this._config.parent === 'string') {
            return elem.getAttribute('data-parent') === _this._config.parent;
          }

          return elem.classList.contains(CLASS_NAME_COLLAPSE);
        });

        if (actives.length === 0) {
          actives = null;
        }
      }

      if (actives) {
        activesData = $(actives).not(this._selector).data(DATA_KEY);

        if (activesData && activesData._isTransitioning) {
          return;
        }
      }

      var startEvent = $.Event(EVENT_SHOW);
      $(this._element).trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      if (actives) {
        Collapse._jQueryInterface.call($(actives).not(this._selector), 'hide');

        if (!activesData) {
          $(actives).data(DATA_KEY, null);
        }
      }

      var dimension = this._getDimension();

      $(this._element).removeClass(CLASS_NAME_COLLAPSE).addClass(CLASS_NAME_COLLAPSING);
      this._element.style[dimension] = 0;

      if (this._triggerArray.length) {
        $(this._triggerArray).removeClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', true);
      }

      this.setTransitioning(true);

      var complete = function complete() {
        $(_this._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW);
        _this._element.style[dimension] = '';

        _this.setTransitioning(false);

        $(_this._element).trigger(EVENT_SHOWN);
      };

      var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
      var scrollSize = "scroll" + capitalizedDimension;
      var transitionDuration = Util.getTransitionDurationFromElement(this._element);
      $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      this._element.style[dimension] = this._element[scrollSize] + "px";
    };

    _proto.hide = function hide() {
      var _this2 = this;

      if (this._isTransitioning || !$(this._element).hasClass(CLASS_NAME_SHOW)) {
        return;
      }

      var startEvent = $.Event(EVENT_HIDE);
      $(this._element).trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      var dimension = this._getDimension();

      this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
      Util.reflow(this._element);
      $(this._element).addClass(CLASS_NAME_COLLAPSING).removeClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW);
      var triggerArrayLength = this._triggerArray.length;

      if (triggerArrayLength > 0) {
        for (var i = 0; i < triggerArrayLength; i++) {
          var trigger = this._triggerArray[i];
          var selector = Util.getSelectorFromElement(trigger);

          if (selector !== null) {
            var $elem = $([].slice.call(document.querySelectorAll(selector)));

            if (!$elem.hasClass(CLASS_NAME_SHOW)) {
              $(trigger).addClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', false);
            }
          }
        }
      }

      this.setTransitioning(true);

      var complete = function complete() {
        _this2.setTransitioning(false);

        $(_this2._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE).trigger(EVENT_HIDDEN);
      };

      this._element.style[dimension] = '';
      var transitionDuration = Util.getTransitionDurationFromElement(this._element);
      $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
    };

    _proto.setTransitioning = function setTransitioning(isTransitioning) {
      this._isTransitioning = isTransitioning;
    };

    _proto.dispose = function dispose() {
      $.removeData(this._element, DATA_KEY);
      this._config = null;
      this._parent = null;
      this._element = null;
      this._triggerArray = null;
      this._isTransitioning = null;
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _objectSpread2(_objectSpread2({}, Default), config);
      config.toggle = Boolean(config.toggle); // Coerce string values

      Util.typeCheckConfig(NAME, config, DefaultType);
      return config;
    };

    _proto._getDimension = function _getDimension() {
      var hasWidth = $(this._element).hasClass(DIMENSION_WIDTH);
      return hasWidth ? DIMENSION_WIDTH : DIMENSION_HEIGHT;
    };

    _proto._getParent = function _getParent() {
      var _this3 = this;

      var parent;

      if (Util.isElement(this._config.parent)) {
        parent = this._config.parent; // It's a jQuery object

        if (typeof this._config.parent.jquery !== 'undefined') {
          parent = this._config.parent[0];
        }
      } else {
        parent = document.querySelector(this._config.parent);
      }

      var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]";
      var children = [].slice.call(parent.querySelectorAll(selector));
      $(children).each(function (i, element) {
        _this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
      });
      return parent;
    };

    _proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
      var isOpen = $(element).hasClass(CLASS_NAME_SHOW);

      if (triggerArray.length) {
        $(triggerArray).toggleClass(CLASS_NAME_COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
      }
    } // Static
    ;

    Collapse._getTargetFromElement = function _getTargetFromElement(element) {
      var selector = Util.getSelectorFromElement(element);
      return selector ? document.querySelector(selector) : null;
    };

    Collapse._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $this = $(this);
        var data = $this.data(DATA_KEY);

        var _config = _objectSpread2(_objectSpread2(_objectSpread2({}, Default), $this.data()), typeof config === 'object' && config ? config : {});

        if (!data && _config.toggle && typeof config === 'string' && /show|hide/.test(config)) {
          _config.toggle = false;
        }

        if (!data) {
          data = new Collapse(this, _config);
          $this.data(DATA_KEY, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(Collapse, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default;
      }
    }]);

    return Collapse;
  }();
  /**
   * ------------------------------------------------------------------------
   * Data Api implementation
   * ------------------------------------------------------------------------
   */

  $(document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
    // preventDefault only for <a> elements (which change the URL) not inside the collapsible element
    if (event.currentTarget.tagName === 'A') {
      event.preventDefault();
    }

    var $trigger = $(this);
    var selector = Util.getSelectorFromElement(this);
    var selectors = [].slice.call(document.querySelectorAll(selector));
    $(selectors).each(function () {
      var $target = $(this);
      var data = $target.data(DATA_KEY);
      var config = data ? 'toggle' : $trigger.data();

      Collapse._jQueryInterface.call($target, config);
    });
  });
  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */

  $.fn[NAME] = Collapse._jQueryInterface;
  $.fn[NAME].Constructor = Collapse;

  $.fn[NAME].noConflict = function () {
    $.fn[NAME] = JQUERY_NO_CONFLICT;
    return Collapse._jQueryInterface;
  };

  return Collapse;

})));
//# sourceMappingURL=collapse.js.map