text:
using System.Collections.Generic;
using System.Linq;
using Sitecore.Data.Items;

namespace SitecoreCognitiveServices.Feature.ImageSearch.Search.ComputedFields.Image
{
    public class Tags : BaseComputedField
    {
        protected override object GetFieldValue(Item cognitiveIndexable)
        {
            var regions = Text?.Regions;
            if (regions == null)
                return null;

            var words = (
                from r in regions
                where r.Lines != null
                    from l in r.Lines
                    where l.Words != null
                        from w in l.Words
                        where !string.IsNullOrEmpty(w.Text.Trim())
                        select w.Text.Trim()
            );

            var tags = Visions?.Description?.Tags.Select(t => t.Trim()).ToList();
            if(tags != null && tags.Any())
                words = words.Concat(tags);

            words = words.Concat(new [] { cognitiveIndexable.DisplayName });

            List<string> charList = new List<string>() { ":", ";", "~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", "_", "-", "|", "\\", "{", "}", "[", "]", "\"", "'", "?", "/", ">", ".", "<", ","};
            var results = words.Where(w => !charList.Contains(w)).Distinct().ToArray();

            return (results.Any())
                ? results.Distinct()
                : null;
        }
    }
}


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

	_tableView.contentInset = UIEdgeInsetsMake(76, 0, 0, 0);
	_tableView.rowHeight = 82;

//	_tableView.backgroundColor = [UIColor cyanColor];

	// force auto-layout calcs to happen before view appears
	// so we can add the correct size layer mask
	[self.view setNeedsLayout];
	[self.view layoutIfNeeded];

}

- (void)viewDidLayoutSubviews {
	[self addTopOpacityMask];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {

	// best call super just in case
	[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

	// will execute before rotation

	[coordinator animateAlongsideTransition:^(id  _Nonnull context) {

		// will execute during rotation

	} completion:^(id  _Nonnull context) {

		// will execute after rotation

		[self addTopOpacityMask];

	}];
}

- (void)addTopMaskToTableViewToHideTopPortion
{
	CAShapeLayer *shapeLayer = [CAShapeLayer layer];
	shapeLayer.fillRule = kCAFillRuleEvenOdd;
	CGRect maskRect = CGRectMake(0, 76, CGRectGetWidth(self.tableView.frame), self.tableView.bounds.size.height - 76);

	CGPathRef path = CGPathCreateWithRect(maskRect, NULL);
	shapeLayer.path = path;
	CGPathRelease(path);

	self.tableView.layer.mask = shapeLayer;
}

- (void)addTopSemiTransparentLayer
{
	CAShapeLayer *shapeLayer = [CAShapeLayer layer];
	shapeLayer.fillRule = kCAFillRuleEvenOdd;
	shapeLayer.fillColor = [UIColor blackColor].CGColor;
	shapeLayer.opacity = 0.5;
	CGRect maskRect = CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame),76);

	CGPathRef path = CGPathCreateWithRect(maskRect, NULL);
	shapeLayer.path = path;
	CGPathRelease(path);

	[self.tableView.superview.layer addSublayer :shapeLayer];
}

- (void)addTopOpacityMask {

//	[self addTopMaskToTableViewToHideTopPortion];
//	return;

	CGRect rect = _tableView.frame;
	CGRect r = rect;

	UIGraphicsBeginImageContext(rect.size);
	CGContextRef context = UIGraphicsGetCurrentContext();

	// fill a "top rect" with black at 5% opacity
	r.size.height = 76;

	CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:0.0 alpha:0.05].CGColor);
	CGContextFillRect(context, r);

	// fill the rest of the layer with black at 100% opacity
	r.origin.y = 76;
	r.size.height = rect.size.height;

	CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
	CGContextFillRect(context, r);

	// grab a UIImage from the context
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

	// create a Layer
	CALayer *theLayer = [CALayer layer];

	// set the Layer content to the just-created image
	theLayer.contents = (__bridge id _Nullable)(image.CGImage);

	theLayer.frame = rect;

	// mask the view holding the tableview
	_tableView.superview.layer.mask = theLayer;

//	CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//	gradientLayer.frame = self.tableView.frame;
//
//	id transparent = (id)[UIColor clearColor].CGColor;
//	id opaque = (id)[UIColor blackColor].CGColor;
//	gradientLayer.colors = @[transparent, opaque, opaque];
//	gradientLayer.locations = @[@0.01, @0.11, @1];
//	self.tableView.superview.layer.mask = gradientLayer;

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 25;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	SampleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

	if (indexPath.row == 0) {

		cell.theImageView.backgroundColor = [UIColor clearColor];
		cell.theImageView.image = [UIImage imageNamed:@"face"];
		cell.lblA.text = @"Blondie Bumstead";
		cell.lblB.text = @"Asked you a question";
		cell.lblC.text = @"How tall is the ocean?";

	} else {

		cell.theImageView.backgroundColor = [UIColor grayColor];
		cell.theImageView.image = nil;
		cell.lblA.text = @"Somebody's Name";
		cell.lblB.text = @"Did Something";
		cell.lblC.text = [NSString stringWithFormat:@"And this is row %ld", (long)indexPath.row + 1];

	}

	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSLog(@"%@", indexPath);
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

@end

redpajama_set_name: RedPajamaGithub


text:
{width=10%,float=left}
![](images/17/thumbnail.png)

Custom views are a great way of both splitting up your code as a nod towards
software design best practices, but also allowing the creation of reusable
components. I've talked about this concept a lot in terms of building custom
UI Controls - in fact I've given a fair few
[talks](http://iwantmyreal.name/blog/2013/09/18/the-art-of-custom-ui-controls/)
on the subject.

One of the limitations in the iOS world with this technique is that you
instantly lose the ability to work with Interface Builder (IB) in Xcode. Well,
you can continue to use it, but you have to work with a large set of blank
rectangles:

![Storyboard before](images/17/storyboard-before.png)

However, this has all changed with Xcode 6, which introduces the concept of
__Live Views__, which are views which appear in IB as they will in the running
app. The exciting news is that they are super easy to use - and you can find out
how today.

The sample project which accompanies this project contains the code from for the
__RWKnobControl__ I created for a tutorial on building custom controls over
on [RayWenderlich.com](http://www.raywenderlich.com/56885/custom-control-for-ios-tutorial-a-reusable-knob).
The code has been translated into Swift, but other than that remains the same.
You can get hold of this project in the iOS 8 day-by-day repo on github at
[github.com/ShinobiControls/iOS8-day-by-day](https://github.com/ShinobiControls/iOS8-day-by-day).

## `@IBDesignable`

The simplicity associated with this new functionality is truly beautiful. Given
that you have a `UIView` subclass, then enabling the live-rendering in IB is as
simple as annotating the class with the `@IBDesignable` annotation:

    @IBDesignable
    class KnobControl : UIControl {
      ...
    }

Now, the view in the storyboard will automatically update to render the live
view:

![Default Storyboard](images/17/storyboard-default.png)

And that's it! The objective-C equivalent is `IB_DESIGNABLE`.

You can override the `prepareForInterfaceBuilder()` method if you need to provide
any custom setup for the IB view. This will get called only when rendering inside
interface builder.

## `@IBInspectable`

It's all very well and good being able to see the view in interface builder, but
in the knob control example you've just seen it doesn't look too good. The knob
control has a whole set of properties that are used to configure its appearance.
If you annotate these properties with `@IBInspectable` (`IB_INSPECTABLE` in
objective-C) then IB will provide you with config fields in the attributes
inspector to configure them:

    @IBInspectable
    var value:CGFloat {
    get { return self._primitiveValue }
    set { self.setValue(newValue, animated: false) }
    }
    @IBInspectable
    var startAngle:CGFloat {
    get { return self.knobRenderer.startAngle }
    set { self.knobRenderer.startAngle = newValue }
    }
    ...

![Attributes Inspector](images/17/storyboard-settings2.png)

As you change these values then the view in the storyboard itself will update to
reflect the new settings:

![Updated Visualization](images/17/storyboard-after2.png)

You can edit any types that you are used to using within IB:

    @IBInspectable
    var color: UIColor = UIColor.whiteColor()

    @IBInspectable
    var text: String = ""

    @IBInspectable
    var rect: CGRect = CGRect.zeroRect

    @IBInspectable
    var point: CGPoint = CGPoint.zeroPoint

    @IBInspectable
    var int: Int = 0

    @IBInspectable
    var float: CGFloat = 0.0

    @IBInspectable
    var image: UIImage = UIImage()

![Inspectable Types](images/17/inspectable-types.png)

## Debugging Views

So you've managed to get a view which appears inside IB, but maybe it's not
behaving in quite the way you want it. In days gone by you would have thrown in
some breakpoints to your view code, and then run it up in the simulator to debug
it. Obviously you can continue to use this methodology, but the new live views
functionality also offers the ability to debug views right in Interface Builder.

Set up you break points in the usual way, and then select the view in the
storyboard. Use the __Editor > Debug Selected Views__ menu option to kick off
the debug process.

![Debug selected view](images/17/debug_selected_views.png)

The debug process works in exactly the same way as it does on a device or in the
simulator - so once you've started debugging then changing a value in the
attributes inspector will run exactly the same code you'd expect - and hence hit
any appropriately placed breakpoints.

## Conclusion

This new functionality is really great for anybody who uses custom views and
quite likes using IB for laying out their view controllers. It's so simple to
integrate into your views that there isn't really any excuse not to do it for
views which are fairly simple. Obviously there are many custom views which are
far more complex (and require table views and the suchlike), however the hooks
in to the IB render process might still allow big gains over the iterative
render process that you're used to.

The code for this project is again available in the github repo at
[github.com/ShinobiControls/iOS8-day-by-day](https://github.com/ShinobiControls/iOS8-day-by-day).


text:
class CreateAccounts < ActiveRecord::Migration[5.0]
  def change
    create_table :accounts do |t|
      t.string :slug
      t.string :first_name, default: "", null: false
      t.string :last_name, default: "", null: false
      t.string :company
      t.integer :account_type, default: 0, null: false
      t.belongs_to :user, foreign_key: true
      t.timestamps
    end
    add_index :accounts, :slug, unique: true
  end
end


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;
using Algorithm;

namespace AlgorithmTest {
    [TestClass]
    public class VerSizeArrayTest {
        public object InvokePrivateMethod(string methodName, object[] argv) {
            object result = target.GetType().InvokeMember(methodName,
                BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, target, argv);
            return result;
        }

        static VarSizeArray<int> target;

        [ClassInitialize]
        public static void InitializeTarget(TestContext testContext) {}

        [ClassCleanup]
        public static void CleanupTarget() {}

        [TestInitialize]
        public void BeginTestMethod() {
            target = new VarSizeArray<int>();
            target[0] = 2;
            target[1] = 3;
            target[2] = 5;
        }

        [TestCleanup]
        public void EndTestMethod() {}

        [TestMethod]
        public void AddLastTest() {
            target.AddLast(11);
            target.AddLast(13);
            target.AddLast(17);
            target.AddLast(19);
            target.AddLast(23);
            string expected = "[ 2 3 5 0 11 13 17 19 23 0 0 0 0 0 0 0 ]";
            string actual = target.ToString();
            Assert.AreEqual(expected, actual);
            Assert.AreEqual(target.Count, 9);
            Assert.AreEqual(target.Capacity, 16);
        }

        [TestMethod]
        public void ToStringTest() {
            target[3] = 7;
            string expected = "[ 2 3 5 7 ]";
            string actual = target.ToString();
            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void reAllocTest() {
            int expected = target.Capacity * 2;
            InvokePrivateMethod("reAlloc", null);
            int actual = target.Capacity;
            Assert.AreEqual(expected, actual);
        }
    }
}


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CartItem extends Model
{
  protected $table = 'cart_item';
  protected $primarykey = 'id';
}


text:
<!DOCTYPE html>

<title>How do I delete an assignment?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.assignment" name="description">
<meta content="delete assignment, remove assignment" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I delete an assignment?

Go to Assignments.

Select the Assignments tool from the Tool Menu of your site.

Select the assignment(s) you want to delete.

              Zoom

In the "Remove?" column, click to place a check in the box for the item(s) you want to delete.

Click Update.

Click the Update button at the bottom of the assignment listing.

Confirm the deletion.

              Zoom

Click the Delete button to confirm the removal of the assignment(s) you have selected.

Note: Removing as assignment with student submissions will also delete the submissions for that assignment.


text:
[![Gem Version](https://badge.fury.io/rb/sidekiq-field-encryptor.png)](https://rubygems.org/gems/sidekiq-field-encryptor)
[![Build Status](https://travis-ci.org/aptible/sidekiq-field-encryptor.png?branch=master)](https://travis-ci.org/aptible/sidekiq-field-encryptor)
[![Dependency Status](https://gemnasium.com/aptible/sidekiq-field-encryptor.png)](https://gemnasium.com/aptible/sidekiq-field-encryptor)

TODO: Add description.

## Installation

Add the following line to your application's Gemfile.

    gem 'sidekiq-field-encryptor'

And then run `bundle install`.

## Usage

TODO: Add usage notes.

## Contributing

1. Fork the project.
1. Commit your changes, with specs.
1. Ensure that your code passes specs (`rake spec`) and meets Aptible's Ruby style guide (`rake rubocop`).
1. Create a new pull request on GitHub.

## Copyright and License

MIT License, see [LICENSE](LICENSE.md) for details.

Copyright (c) 2015 [Aptible](https://www.aptible.com), Blake Pettersson, and contributors.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>coursera.algorithm</artifactId>
        <groupId>com.coursera.algorithm</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>week1-1</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>../week2-2</module>
        <module>../week2-4</module>
        <module>../week2-5</module>
        <module>../week2-6</module>
    </modules>

</project>


text:
package org.neo4j.helpers.collection;

import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import org.neo4j.collection.primitive.PrimitiveIntIterator;
import org.neo4j.collection.primitive.PrimitiveLongIterator;
import org.neo4j.function.Predicate;
import org.neo4j.function.Predicates;
import org.neo4j.graphdb.Resource;
import org.neo4j.graphdb.ResourceIterable;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.helpers.CloneableInPublic;
import org.neo4j.helpers.Function;
import org.neo4j.helpers.Pair;
import org.neo4j.kernel.impl.util.PrimitiveLongResourceIterator;

import static java.util.EnumSet.allOf;

import static org.neo4j.helpers.collection.Iterables.map;

/**
 * Contains common functionality regarding {@link Iterator}s and
 * {@link Iterable}s.
 */
public abstract class IteratorUtil
{
    /**
     * Returns the given iterator's first element or {@code null} if no
     * element found.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the first element in the {@code iterator}, or {@code null} if no
     * element found.
     */
    public static <T> T firstOrNull( Iterator<T> iterator )
    {
        return iterator.hasNext() ? iterator.next() : null;
    }

    /**
     * Returns the given iterator's first element. If no element is found a
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the first element in the {@code iterator}.
     * @throws NoSuchElementException if no element found.
     */
    public static <T> T first( Iterator<T> iterator )
    {
        return assertNotNull( iterator, firstOrNull( iterator ) );
    }

    /**
     * Returns the given iterator's last element or {@code null} if no
     * element found.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the last element in the {@code iterator}, or {@code null} if no
     * element found.
     */
    public static <T> T lastOrNull( Iterator<T> iterator )
    {
        T result = null;
        while ( iterator.hasNext() )
        {
            result = iterator.next();
        }
        return result;
    }

    /**
     * Returns the given iterator's last element. If no element is found a
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the last element in the {@code iterator}.
     * @throws NoSuchElementException if no element found.
     */
    public static <T> T last( Iterator<T> iterator )
    {
        return assertNotNull( iterator, lastOrNull( iterator ) );
    }

    /**
     * Returns the given iterator's single element or {@code null} if no
     * element found. If there is more than one element in the iterator a
     * {@link NoSuchElementException} will be thrown.
     *
     * If the {@code iterator} implements {@link Resource} it will be {@link Resource#close() closed}
     * in a {@code finally} block after the single item has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the single element in {@code iterator}, or {@code null} if no
     * element found.
     * @throws NoSuchElementException if more than one element was found.
     */
    public static <T> T singleOrNull( Iterator<T> iterator )
    {
        return single( iterator, null );
    }

    /**
     * Returns the given iterator's single element. If there are no elements
     * or more than one element in the iterator a {@link NoSuchElementException}
     * will be thrown.
     *
     * If the {@code iterator} implements {@link Resource} it will be {@link Resource#close() closed}
     * in a {@code finally} block after the single item has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @return the single element in the {@code iterator}.
     * @throws NoSuchElementException if there isn't exactly one element.
     */
    public static <T> T single( Iterator<T> iterator )
    {
        return assertNotNull( iterator, singleOrNull( iterator ) );
    }

    /**
     * Returns the iterator's n:th item from the end of the iteration.
     * If the iterator has got less than n-1 items in it
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @param n the n:th item from the end to get.
     * @return the iterator's n:th item from the end of the iteration.
     * @throws NoSuchElementException if the iterator contains less than n-1 items.
     */
    public static <T> T fromEnd( Iterator<T> iterator, int n )
    {
        return assertNotNull( iterator, fromEndOrNull( iterator, n ) );
    }

    /**
     * Returns the iterator's n:th item from the end of the iteration.
     * If the iterator has got less than n-1 items in it {@code null} is returned.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @param n the n:th item from the end to get.
     * @return the iterator's n:th item from the end of the iteration,
     * or {@code null} if the iterator doesn't contain that many items.
     */
    public static <T> T fromEndOrNull( Iterator<T> iterator, int n )
    {
        Deque<T> trail = new ArrayDeque<>( n );
        while ( iterator.hasNext() )
        {
            if ( trail.size() > n )
            {
                trail.removeLast();
            }
            trail.addFirst( iterator.next() );
        }
        return trail.size() == n + 1 ? trail.getLast() : null;
    }

    /**
     * Iterates over the full iterators, and checks equality for each item in them. Note that this
     * will consume the iterators.
     *
     * @param first the first iterator
     * @param other the other iterator
     * @return {@code true} if all items are equal; otherwise
     */
    public static boolean iteratorsEqual( Iterator<?> first, Iterator<?> other )
    {
        while ( true )
        {
            if ( first.hasNext() && other.hasNext() )
            {
                if ( !first.next().equals( other.next() ) )
                {
                    return false;
                }
            }
            else
            {
                return first.hasNext() == other.hasNext();
            }
        }
    }

    private static <T> T assertNotNull( Iterator<T> iterator, T result )
    {
        if ( result == null )
        {
            throw new NoSuchElementException( "No element found in " + iterator );
        }
        return result;
    }

    /**
     * Returns the given iterable's first element or {@code null} if no
     * element found.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the first element in the {@code iterable}, or {@code null} if no
     * element found.
     */
    public static <T> T firstOrNull( Iterable<T> iterable )
    {
        return firstOrNull( iterable.iterator() );
    }

    /**
     * Returns the given iterable's first element. If no element is found a
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the first element in the {@code iterable}.
     * @throws NoSuchElementException if no element found.
     */
    public static <T> T first( Iterable<T> iterable )
    {
        return first( iterable.iterator() );
    }

    /**
     * Returns the given iterable's last element or {@code null} if no
     * element found.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the last element in the {@code iterable}, or {@code null} if no
     * element found.
     */
    public static <T> T lastOrNull( Iterable<T> iterable )
    {
        return lastOrNull( iterable.iterator() );
    }

    /**
     * Returns the given iterable's last element. If no element is found a
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the last element in the {@code iterable}.
     * @throws NoSuchElementException if no element found.
     */
    public static <T> T last( Iterable<T> iterable )
    {
        return last( iterable.iterator() );
    }

    /**
     * Returns the given iterable's single element or {@code null} if no
     * element found. If there is more than one element in the iterable a
     * {@link NoSuchElementException} will be thrown.
     *
     * If the {@link Iterable#iterator() iterator} created by the {@code iterable} implements {@link Resource}
     * it will be {@link Resource#close() closed} in a {@code finally} block after the single item
     * has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the single element in {@code iterable}, or {@code null} if no
     * element found.
     * @throws NoSuchElementException if more than one element was found.
     */
    public static <T> T singleOrNull( Iterable<T> iterable )
    {
        return singleOrNull( iterable.iterator() );
    }

    /**
     * Returns the given iterable's single element. If there are no elements
     * or more than one element in the iterable a {@link NoSuchElementException}
     * will be thrown.
     *
     * If the {@link Iterable#iterator() iterator} created by the {@code iterable} implements {@link Resource}
     * it will be {@link Resource#close() closed} in a {@code finally} block after the single item
     * has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @return the single element in the {@code iterable}.
     * @throws NoSuchElementException if there isn't exactly one element.
     */
    public static <T> T single( Iterable<T> iterable )
    {
        return single( iterable.iterator() );
    }

    /**
     * Returns the given iterable's single element or {@code itemIfNone} if no
     * element found. If there is more than one element in the iterable a
     * {@link NoSuchElementException} will be thrown.
     *
     * If the {@link Iterable#iterator() iterator} created by the {@code iterable} implements {@link Resource}
     * it will be {@link Resource#close() closed} in a {@code finally} block after the single item
     * has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterable}.
     * @param iterable the {@link Iterable} to get elements from.
     * @param itemIfNone item to use if none is found
     * @return the single element in {@code iterable}, or {@code null} if no
     * element found.
     * @throws NoSuchElementException if more than one element was found.
     */
    public static <T> T single( Iterable<T> iterable, T itemIfNone )
    {
        return single( iterable.iterator(), itemIfNone );
    }

    /**
     * Returns the given iterator's single element or {@code itemIfNone} if no
     * element found. If there is more than one element in the iterator a
     * {@link NoSuchElementException} will be thrown.
     *
     * If the {@code iterator} implements {@link Resource} it will be {@link Resource#close() closed}
     * in a {@code finally} block after the single item has been retrieved, or failed to be retrieved.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterator the {@link Iterator} to get elements from.
     * @param itemIfNone item to use if none is found
     * @return the single element in {@code iterator}, or {@code itemIfNone} if no
     * element found.
     * @throws NoSuchElementException if more than one element was found.
     */
    public static <T> T single( Iterator<T> iterator, T itemIfNone )
    {
        try
        {
            T result = iterator.hasNext() ? iterator.next() : itemIfNone;
            if ( iterator.hasNext() )
            {
                throw new NoSuchElementException( "More than one element in " + iterator + ". First element is '"
                        + result + "' and the second element is '" + iterator.next() + "'" );
            }
            return result;
        }
        finally
        {
            if ( iterator instanceof Resource )
            {
                ((Resource) iterator).close();
            }
        }
    }

    /**
     * Returns the iterator's n:th item from the end of the iteration.
     * If the iterator has got less than n-1 items in it
     * {@link NoSuchElementException} is thrown.
     *
     * @param <T> the type of elements in {@code iterator}.
     * @param iterable the {@link Iterable} to get elements from.
     * @param n the n:th item from the end to get.
     * @return the iterator's n:th item from the end of the iteration.
     * @throws NoSuchElementException if the iterator contains less than n-1 items.
     */
    public static <T> T fromEnd( Iterable<T> iterable, int n )
    {
        return fromEnd( iterable.iterator(), n );
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param <T> the type of items in the collection and iterator.
     * @param iterator the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<T>,T> C addToCollection( Iterator<T> iterator,
            C collection )
    {
        while ( iterator.hasNext() )
        {
            collection.add( iterator.next() );
        }
        return collection;
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param iterator the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<Long>> C addToCollection( PrimitiveLongIterator iterator, C collection )
    {
        while ( iterator.hasNext() )
        {
            collection.add( iterator.next() );
        }
        return collection;
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param iterator the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<Integer>> C addToCollection( PrimitiveIntIterator iterator, C collection )
    {
        while ( iterator.hasNext() )
        {
            collection.add( iterator.next() );
        }
        return collection;
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param <T> the type of items in the collection and iterator.
     * @param iterator the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<T>,T> C addToCollectionUnique( Iterator<T> iterator,
            C collection )
    {
        while ( iterator.hasNext() )
        {
            addUnique( collection, iterator.next() );
        }
        return collection;
    }

    private static <T, C extends Collection<T>> void addUnique( C collection, T item )
    {
        if ( !collection.add( item ) )
        {
            throw new IllegalStateException( "Encountered an already added item:" + item +
                    " when adding items uniquely to a collection:" + collection );
        }
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param <T> the type of items in the collection and iterator.
     * @param iterable the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<T>,T> C addToCollection( Iterable<T> iterable,
            C collection )
    {
        return addToCollection( iterable.iterator(), collection );
    }

    /**
     * Adds all the items in {@code iterator} to {@code collection}.
     * @param <C> the type of {@link Collection} to add to items to.
     * @param <T> the type of items in the collection and iterator.
     * @param iterable the {@link Iterator} to grab the items from.
     * @param collection the {@link Collection} to add the items to.
     * @return the {@code collection} which was passed in, now filled
     * with the items from {@code iterator}.
     */
    public static <C extends Collection<T>,T> C addToCollectionUnique( Iterable<T> iterable,
            C collection )
    {
        return addToCollectionUnique( iterable.iterator(), collection );
    }

    /**
     * Convenience method for looping over an {@link Iterator}. Converts the
     * {@link Iterator} to an {@link Iterable} by wrapping it in an
     * {@link Iterable} that returns the {@link Iterator}. It breaks the
     * contract of {@link Iterable} in that it returns the supplied iterator
     * instance for each call to {@code iterator()} on the returned
     * {@link Iterable} instance. This method exists to make it easy to use an
     * {@link Iterator} in a for-loop.
     *
     * @param <T> the type of items in the iterator.
     * @param iterator the iterator to expose as an {@link Iterable}.
     * @return the supplied iterator posing as an {@link Iterable}.
     */
    public static <T> Iterable<T> loop( final Iterator<T> iterator )
    {
        return new Iterable<T>()
        {
            @Override
            public Iterator<T> iterator()
            {
                return iterator;
            }
        };
    }

    /**
     * Exposes {@code iterator} as an {@link Iterable}. It breaks the contract
     * of {@link Iterable} in that it returns the supplied iterator instance for
     * each call to {@code iterator()} on the returned {@link Iterable}
     * instance. This method mostly exists to make it easy to use an
     * {@link Iterator} in a for-loop.
     *
     * @param <T> the type of items in the iterator.
     * @param iterator the iterator to expose as an {@link Iterable}.
     * @return the supplied iterator posing as an {@link Iterable}.
     */
    //@Deprecated * @deprecated use {@link #loop(Iterator) the loop method} instead.
    public static <T> Iterable<T> asIterable( final Iterator<T> iterator )
    {
        return loop( iterator );
    }

    public static <T> int count( Iterator<T> iterator )
    {
        return count( iterator, Predicates.<T>alwaysTrue() );
    }

    /**
     * Counts the number of filtered in the {@code iterator} by looping
     * through it.
     * @param <T> the type of items in the iterator.
     * @param iterator the {@link Iterator} to count items in.
     * @param filter the filter to test items against
     * @return the number of filtered items found in {@code iterator}.
     */
    public static <T> int count( Iterator<T> iterator, Predicate<T> filter )
    {
        int result = 0;
        while ( iterator.hasNext() )
        {
            if ( filter.test( iterator.next() ) )
            {
                result++;
            }
        }
        return result;
    }

    /**
     * Counts the number of items in the {@code iterator} by looping
     * through it.
     * @param <T> the type of items in the iterator.
     * @param iterable the {@link Iterable} to count items in.
     * @return the number of items found in {@code iterable}.
     */
    public static <T> int count( Iterable<T> iterable )
    {
        return count( iterable, Predicates.<T>alwaysTrue() );
    }

    /**
     * Counts the number of items in the {@code iterable} by looping through it.
     *
     * @param <T> the type of items in the iterator.
     * @param iterable the {@link Iterable} to count items in.
     * @param filter the filter to apply
     * @return the number of items found in {@code iterator}.
     */
    public static <T> int count( Iterable<T> iterable, org.neo4j.helpers.Predicate<T> filter )
    {
        return count( iterable.iterator(), org.neo4j.helpers.Predicates.upgrade( filter ) );
    }

    /**
     * Counts the number of filtered items in the {@code iterable} by looping through it.
     *
     * @param <T> the type of items in the iterator.
     * @param iterable the {@link Iterable} to count items in.
     * @param filter the filter to test items against
     * @return the number of found in {@code iterable}.
     */
    public static <T> int count( Iterable<T> iterable, Predicate<T> filter )
    {
        return count( iterable.iterator(), filter );
    }

    /**
     * Creates a collection from an iterable.
     *
     * @param iterable The iterable to create the collection from.
     * @param <T> The generic type of both the iterable and the collection.
     * @return a collection containing all items from the iterable.
     */
    public static <T> Collection<T> asCollection( Iterable<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<T>() );
    }
    public static <T> Collection<T> asCollection( Iterator<T> iterable )
    {
        return addToCollection( iterable, new ArrayList<T>() );
    }

    public static <T> List<T> asList( Iterator<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<T>() );
    }

    public static <T> List<T> asList( Iterable<T> iterator )
    {
        return addToCollection( iterator, new ArrayList<T>() );
    }

    public static List<Long> asList( PrimitiveLongIterator iterator )
    {
        List<Long> out = new ArrayList<>();
        while(iterator.hasNext())
        {
            out.add(iterator.next());
        }
        return out;
    }

    public static List<Integer> asList( PrimitiveIntIterator iterator )
    {
        List<Integer> out = new ArrayList<>();
        while(iterator.hasNext())
        {
            out.add(iterator.next());
        }
        return out;
    }

    public static <T, U> Map<T, U> asMap( Iterable<Pair<T, U>> pairs )
    {
        Map<T, U> map = new HashMap<>();
        for (Pair<T, U> pair: pairs) {
            map.put(pair.first(), pair.other());
        }
        return map;
    }

    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asSet( Iterable<T> iterable )
    {
        return addToCollection( iterable, new HashSet<T>() );
    }

    public static <T> Set<T> asSet( Iterator<T> iterator )
    {
        return addToCollection( iterator, new HashSet<T>() );
    }

    /**
     * Creates a {@link Set} from an {@link Iterable}.
     *
     * @param iterable The items to create the set from.
     * @param <T> The generic type of items.
     * @return a set containing all items from the {@link Iterable}.
     */
    public static <T> Set<T> asUniqueSet( Iterable<T> iterable )
    {
        return addToCollectionUnique( iterable, new HashSet<T>() );
    }

    /**
     * Creates a {@link Set} from an array of items.
     *
     * @param items the items to add to the set.
     * @param <T> the type of the items
     * @return the {@link Set} containing the items.
     */
    @SafeVarargs
    public static <T> Set<T> asSet( T... items )
    {
        return new HashSet<>( Arrays.asList( items ) );
    }

    public static <T> Set<T> emptySetOf( @SuppressWarnings("unused"/*just used as a type marker*/) Class<T> type )
    {
        return Collections.emptySet();
    }

    public static <T> List<T> emptyListOf( @SuppressWarnings("unused"/*just used as a type marker*/) Class<T> type )
    {
        return Collections.emptyList();
    }

    /**
     * Alias for asSet()
     *
     * @param items the items to add to the set.
     * @param <T> the type of the items
     * @return the {@link Set} containing the items.
     */
    @SafeVarargs
    public static <T> Set<T> set( T... items)
    {
        return asSet(items);
    }

    /**
     * Creates a {@link Set} from an array of items.
     *
     * @param items the items to add to the set.
     * @param <T> the type of the items
     * @return the {@link Set} containing the items.
     */
    @SafeVarargs
    public static <T> Set<T> asUniqueSet( T... items )
    {
        HashSet<T> set = new HashSet<>();
        for ( T item : items )
        {
            addUnique( set, item );
        }
        return set;
    }

    /**
     * Creates a {@link Set} from an array of items.
     *
     * @param items the items to add to the set.
     * @param <T> the type of the items
     * @return the {@link Set} containing the items.
     */
    public static <T> Set<T> asUniqueSet( Iterator<T> items )
    {
        HashSet<T> set = new HashSet<>();
        while( items.hasNext() )
        {
            addUnique( set, items.next() );
        }
        return set;
    }

    /**
     * Function for converting Enum to String
     */
    @SuppressWarnings( "rawtypes" )
    public final static Function<Enum, String> ENUM_NAME = new Function<Enum, String>()
    {
        @Override
        public String apply( Enum from )
        {
            return from.name();
        }
    };

    /**
     * Converts an {@link Iterable} of enums to {@link Set} of their names.
     *
     * @param enums the enums to convert.
     * @return the set of enum names
     */
    @SuppressWarnings( "rawtypes" )
    public static Set<String> asEnumNameSet( Iterable<Enum> enums )
    {
        return asSet( map( ENUM_NAME, enums ) );
    }

    /**
     * Converts an enum class to to {@link Set} of the names of all valid enum values
     *
     * @param clazz enum class
     * @param <E> enum type bound
     * @return the set of enum names
     */
    public static <E extends Enum<E>> Set<String> asEnumNameSet( Class<E> clazz)
    {
        return asSet( map( ENUM_NAME, allOf( clazz ) ) );
    }

    /**
     * Creates an {@link Iterable} for iterating over the lines of a text file.
     * @param file the file to get the lines for.
     * @param encoding the encoding of the file
     * @return an {@link Iterable} for iterating over the lines of a text file.
     */
    public static ClosableIterable<String> asIterable( final File file, final String encoding )
    {
        return new ClosableIterable<String>()
        {
            private ClosableIterator<String> mostRecentIterator;

            @Override
            public Iterator<String> iterator()
            {
                try
                {
                    if ( mostRecentIterator != null )
                    {
                        mostRecentIterator.close();
                    }
                    mostRecentIterator = asIterator( file, encoding );
                    return mostRecentIterator;
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }

            @Override
            public void close()
            {
                if ( mostRecentIterator != null )
                {
                    mostRecentIterator.close();
                }
            }
        };
    }

    /**
     * Creates an {@link Iterator} for iterating over the lines of a text file.
     * The opened file is closed if an exception occurs during reading or when
     * the files has been read through all the way.
     * @param file the file to get the lines for.
     * @param encoding to be used for reading the file
     * @return an {@link Iterator} for iterating over the lines of a text file.
     * @throws IOException from underlying I/O operations
     */
    public static ClosableIterator<String> asIterator( File file, String encoding ) throws IOException
    {
        return new LinesOfFileIterator( file, encoding );
    }

    public static Iterable<Long> asIterable( final long... array )
    {
        return new Iterable<Long>()
        {
            @Override
            public Iterator<Long> iterator()
            {
                return asIterator( array );
            }
        };
    }

    @SafeVarargs
    public static <T> Iterable<T> asIterable( final T... array )
    {
        return new Iterable<T>()
        {
            @Override
            public Iterator<T> iterator()
            {
                return IteratorUtil.iterator( array );
            }
        };
    }

    public static Iterator<Long> asIterator( final long... array )
    {
        return new PrefetchingIterator<Long>()
        {
            private int index;

            @Override
            protected Long fetchNextOrNull()
            {
                try
                {
                    return index < array.length ? array[index] : null;
                }
                finally
                {
                    index++;
                }
            }
        };
    }

    @SafeVarargs
    public static <T> Iterator<T> asIterator( final int maxItems, final T... array )
    {
        return new PrefetchingIterator<T>()
        {
            private int index;

            @Override
            protected T fetchNextOrNull()
            {
                try
                {
                    return index < array.length && index < maxItems ? array[index] : null;
                }
                finally
                {
                    index++;
                }
            }
        };
    }

    public static <T> Iterator<T> iterator( final T item )
    {
        if ( item == null )
        {
            return emptyIterator();
        }

        return new Iterator<T>()
        {
            T myItem = item;

            @Override
            public boolean hasNext()
            {
                return myItem != null;
            }

            @Override
            public T next()
            {
                if ( !hasNext() )
                {
                    throw new NoSuchElementException();
                }
                T toReturn = myItem;
                myItem = null;
                return toReturn;
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException();
            }
        };
    }

    @SafeVarargs
    public static <T> Iterator<T> iterator( T ... items )
    {
        return asIterator( items.length, items );
    }

    @SafeVarargs
    public static <T> Iterator<T> iterator( int maxItems, T ... items )
    {
        return asIterator( maxItems, items );
    }

    @SuppressWarnings( "rawtypes" )
    private static final ResourceIterator EMPTY_ITERATOR = new ResourceIterator()
    {
        @Override
        public boolean hasNext()
        {
            return false;
        }

        @Override
        public Object next()
        {
            throw new NoSuchElementException();
        }

        @Override
        public void remove()
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void close()
        {
            // do nothing
        }
    };

    @SuppressWarnings( "unchecked" )
    public static <T> ResourceIterator<T> emptyIterator()
    {
        return EMPTY_ITERATOR;
    }

    public static <T> boolean contains( Iterator<T> iterator, T item )
    {
        try
        {
            for ( T element : loop( iterator ) )
            {
                if ( item == null ? element == null : item.equals( element ) )
                {
                    return true;
                }
            }
            return false;
        }
        finally
        {
            if ( iterator instanceof ResourceIterator<?> )
            {
                ((ResourceIterator<?>) iterator).close();
            }
        }
    }

    public static <T extends CloneableInPublic> Iterable<T> cloned( Iterable<T> items, final Class<T> itemClass )
    {
        return Iterables.map( new Function<T,T>()
        {
            @Override
            public T apply( T from )
            {
                return itemClass.cast( from.clone() );
            }
        }, items );
    }

    public static <T> ResourceIterator<T> asResourceIterator( final Iterator<T> iterator )
    {
        return new WrappingResourceIterator<>( iterator );
    }

    @SuppressWarnings("UnusedDeclaration"/*Useful when debugging in tests, but not used outside of debugging sessions*/)
    public static Iterator<Long> toJavaIterator( final PrimitiveLongIterator primIterator )
    {
        return new Iterator<Long>()
        {
            @Override
            public boolean hasNext()
            {
                return primIterator.hasNext();
            }

            @Override
            public Long next()
            {
                return primIterator.next();
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException(  );
            }
        };
    }

    public static List<Long> primitivesList( PrimitiveLongIterator iterator )
    {
        ArrayList<Long> result = new ArrayList<>();
        while ( iterator.hasNext() )
        {
            result.add( iterator.next() );
        }
        return result;
    }

    public static Set<Long> asSet( PrimitiveLongIterator iterator )
    {
        return internalAsSet( iterator, false );
    }

    private static Set<Long> internalAsSet( PrimitiveLongIterator iterator, boolean allowDuplicates )
    {
        Set<Long> set = new HashSet<>();
        while ( iterator.hasNext() )
        {
            long value = iterator.next();
            if ( !set.add( value ) && !allowDuplicates )
            {
                throw new IllegalStateException( "Duplicates found. Tried to add " + value + " to " + set );
            }
        }
        return set;
    }

    public static Set<Integer> asSet( PrimitiveIntIterator iterator )
    {
        Set<Integer> set = new HashSet<>();
        while ( iterator.hasNext() )
        {
            set.add( iterator.next() );
        }
        return set;
    }

    /**
     * Creates a {@link Set} from an array of iterator.
     *
     * @param iterator the iterator to add to the set.
     * @return the {@link Set} containing the iterator.
     */
    public static Set<Long> asUniqueSet( PrimitiveLongIterator iterator )
    {
        HashSet<Long> set = new HashSet<>();
        while ( iterator.hasNext() )
        {
            addUnique( set, iterator.next() );
        }
        return set;
    }

    public static PrimitiveLongResourceIterator resourceIterator( final PrimitiveLongIterator iterator,
            final Resource resource )
    {
        return new PrimitiveLongResourceIterator()
        {
            @Override
            public void close()
            {
                if ( resource != null )
                {
                    resource.close();
                }
            }

            @Override
            public long next()
            {
                return iterator.next();
            }

            @Override
            public boolean hasNext()
            {
                return iterator.hasNext();
            }
        };
    }

    public static <T> ResourceIterator<T> resourceIterator( final Iterator<T> iterator, final Resource resource )
    {
        return new PrefetchingResourceIterator<T>()
        {
            @Override
            public void close()
            {
                resource.close();
            }

            @Override
            protected T fetchNextOrNull()
            {
                return iterator.hasNext() ? iterator.next() : null;
            }
        };
    }

    public static <T> ResourceIterable<T> resourceIterable( final Iterable<T> iterable )
    {
        return new ResourceIterable<T>()
        {
            @Override
            public ResourceIterator<T> iterator()
            {
                return resourceIterator( iterable.iterator(), Resource.EMPTY );
            }
        };
    }

    @SafeVarargs
    public static <T> T[] array( T... items )
    {
        return items;
    }
}


text:
class AddDateToLinks < ActiveRecord::Migration
  def change
  	add_column :links, :date_published, :date
  	add_column :links, :share_rating, :integer
  	change_column :media_outlets, :type,  :integer
  end
end


text:
package pl.hypeapp.episodie.core.entity.api.tvmaze;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import pl.hypeapp.episodie.core.entity.TvShowEntity;

import java.util.List;

@Data
@Setter(AccessLevel.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TvShowRemote implements TvShowEntity<SeasonRemote, EpisodeRemote> {

    @JsonProperty("id")
    private String tvShowApiId;

    private String url;

    private String name;

    private String status;

    private String officialSite;

    private Integer runtime;

    private String premiered;

    private Network network;

    private String[] genres;

    private Externals externals;

    private Image image;

    private String summary;

    private Integer updated;
    @JsonProperty("_embedded")
    private Embedded embedded;

    @Override
    public String getImdbId() {
        return externals.getImdbId();
    }

    @Override
    public List<SeasonRemote> getSeasons() {
        return embedded.getSeasons();
    }

    @Override
    public List<EpisodeRemote> getEpisodes() {
        return embedded.getEpisodes();
    }

    @Override
    public String getNetworkName() {
        if (network != null) {
            return network.getName();
        } else {
            return null;
        }
    }

    @Override
    public String getGenre() {
        if (genres != null) {
            return String.join("/", genres);
        } else {
            return null;
        }
    }

    @Override
    public String getImageMedium() {
        if (image != null) {
            return image.getMedium();
        } else {
            return null;
        }
    }

    @Override
    public String getImageOriginal() {
        if (image != null) {
            return image.getOriginal();
        } else {
            return null;
        }
    }

    @Override
    public Integer getFullRuntime() {
        return getEpisodes()
                .stream()
                .mapToInt(EpisodeRemote::getRuntime)
                .sum();
    }

}


text:
module ZombieEpidemic
  VERSION = '0.0.1'
end


text:
"""Feature definitions for OAuth2 integration."""

from __future__ import unicode_literals

from django.utils.translation import ugettext_lazy as _
from djblets.features.feature import Feature, FeatureLevel

class OAuth2ServiceFeature(Feature):
    """A feature for OAuth2 integration."""

    feature_id = 'oauth.service'
    name = _('OAuth2 Service Integration')
    level = FeatureLevel.EXPERIMENTAL
    summary = _('Allow Review Board to act as an OAuth2 authentication '
                'service for third-party apps.')

oauth2_service_feature = OAuth2ServiceFeature()


text:
require "spec_helper"

SingleCov.covered!

class AuditsController < ActionController::Base
  before_action :populate_user

  attr_reader :company

  def create
    @company = Models::ActiveRecord::Company.create
    head :ok
  end

  def update
    current_user.update!(password: "foo")
    head :ok
  end

  private

  attr_accessor :current_user
  attr_accessor :custom_user

  def populate_user
  end
end

describe AuditsController do
  include RSpec::Rails::ControllerExampleGroup
  render_views

  before do
    Audited::Railtie.initializers.each(&:run)
    Audited.current_user_method = :current_user
  end

  let(:user) { create_user }

  describe "POST audit" do
    it "should audit user" do
      controller.send(:current_user=, user)
      expect {
        post :create
      }.to change(Audited::Audit, :count)

      expect(controller.company.audits.last.user).to eq(user)
    end

    it "does not audit when method is not found" do
      controller.send(:current_user=, user)
      Audited.current_user_method = :nope
      expect {
        post :create
      }.to change(Audited::Audit, :count)
      expect(controller.company.audits.last.user).to eq(nil)
    end

    it "should support custom users for sweepers" do
      controller.send(:custom_user=, user)
      Audited.current_user_method = :custom_user

      expect {
        post :create
      }.to change(Audited::Audit, :count)

      expect(controller.company.audits.last.user).to eq(user)
    end

    it "should record the remote address responsible for the change" do
      request.env["REMOTE_ADDR"] = "1.2.3.4"
      controller.send(:current_user=, user)

      post :create

      expect(controller.company.audits.last.remote_address).to eq("1.2.3.4")
    end

    it "should record a UUID for the web request responsible for the change" do
      allow_any_instance_of(ActionDispatch::Request).to receive(:uuid).and_return("abc123")
      controller.send(:current_user=, user)

      post :create

      expect(controller.company.audits.last.request_uuid).to eq("abc123")
    end

    it "should call current_user after controller callbacks" do
      expect(controller).to receive(:populate_user) do
        controller.send(:current_user=, user)
      end

      expect {
        post :create
      }.to change(Audited::Audit, :count)

      expect(controller.company.audits.last.user).to eq(user)
    end
  end

  describe "PUT update" do
    it "should not save blank audits" do
      controller.send(:current_user=, user)

      expect {
        put :update, params: {id: 123}
      }.to_not change(Audited::Audit, :count)
    end
  end
end

describe Audited::Sweeper do
  it "should be thread-safe" do
    instance = Audited::Sweeper.new

    t1 = Thread.new do
      sleep 0.5
      instance.controller = "thread1 controller instance"
      expect(instance.controller).to eq("thread1 controller instance")
    end

    t2 = Thread.new do
      instance.controller = "thread2 controller instance"
      sleep 1
      expect(instance.controller).to eq("thread2 controller instance")
    end

    t1.join
    t2.join

    expect(instance.controller).to be_nil
  end
end


text:
<?php

namespace jugger\model\field;

class BoolField extends BaseField
{
    protected function prepareValue($value)
    {
        return (bool) $value;
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe Pkgr::CLI do
  it "should have a build command" do
    expect(Pkgr::CLI.class_options.keys).to include(:verbose)
    expect(Pkgr::CLI.class_options.keys).to include(:name)
  end
end


text:
SELECT * FROM table_1 WHERE col_a = $par1 AND col_b = $par_2;

SELECT * FROM table_2
WHERE col_integer = $par_integer
   OR col_text = $par_text

INSERT INTO table_2(col_1, col_2) VALUES ($Par3, $par4);

DELETE FROM table_3 WHERE col_1 = $par_5 AND some_text = "ignored: $1 $123 _$ignore";


text:
    Try IDEA's
      Live Templates!
      Live Templates
      allow you to generate many typical code constructs in seconds! For example, type

      in a method and press the Tab
      key to see what happens.

      Use the Tab key to move between template fields.
      See File | Settings | Live Templates
      for more details.


text:
package com.innovaee.eorder.mobile.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;

import com.innovaee.eorder.mobile.util.LruImageCache;

/**
 * 图片管理器 管理图片,存储图片到缓存和sdcard,使用时从缓存或者sdcard读取图片
 *
 *
 */
public class ImageDataManager {
    //线程池类型
    public static enum ThreadPoolType {
        //用于加载本地图片
        TYPE_LOCAL,

        //用于下载远程图片
        TYPE_REMOTE
    }

    //默认小大
    private static final int DEFAULT_SIZE = 5 * 1024 * 1024;

    //SDcard存储地址
    private static final String STORAGE_PATH = Environment
            .getExternalStorageDirectory().getPath() + "/eOrderMobile";

    //缓存
    private static LruImageCache softBitmapCache = new LruImageCache(
            DEFAULT_SIZE);

    //ImageDataManager单例
    private static ImageDataManager instance = null;

    //缓存小大
    private static final int CACHE_SIZE = 200 * 1024 * 1024;

    //当sd空间小于FREE_SD_SPACE_NEEDED_TO_CACHE,将不在使用sd空间
    private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 10;

    //下载Image的线程池
    private ThreadPoolExecutor imageThreadPoolRemote = null;

    //下载Image的本地线程池
    private ThreadPoolExecutor imageThreadPoolLocal = null;

    //活跃任务队列
    private HashMap<String, ImageDownloadTask> activeQueue;

    //被reject的任务队列
    private Queue<Runnable> waitTasksQueue = null;

    //锁
    private Object lock = new Object();

    //任务被拒绝执行的处理器
    private RejectedExecutionHandler rejectedExecutionHandler = null;

    //调度Runnable
    private static ScheduledRunnable scheduledRunnable = null;

    //调度线程池
    private static ScheduledExecutorService scheduledExecutorService = null;

    /**
     * 构造函数
     */
    private ImageDataManager() {
        activeQueue = new HashMap<String, ImageDownloadTask>();
        waitTasksQueue = new ConcurrentLinkedQueue<Runnable>();
        if (scheduledRunnable == null) {
            scheduledRunnable = new ScheduledRunnable();
            scheduledExecutorService = Executors
                    .newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(scheduledRunnable,
                    0, 150, TimeUnit.MILLISECONDS);
        }
        initRejectedExecutionHandler();
    }

    /**
     * 获取ImageDataManager对象
     * @return ImageDataManager对象
     */
    public synchronized static ImageDataManager getInstance() {
        if (instance == null) {
            instance = new ImageDataManager();
        }
        return instance;
    }

    /**
     * 获取线程池的方法,因为涉及到并发的问题,我们加上同步锁
     *
     * @return
     */
    public ThreadPoolExecutor getThreadPool(ThreadPoolType type) {
        synchronized (this) {
            ThreadPoolExecutor retval = null;
            if (type == ThreadPoolType.TYPE_LOCAL) {
                if (imageThreadPoolLocal == null
                        || imageThreadPoolLocal.isShutdown()) {
                    //为了下载图片更加的流畅,我们用了3个线程来下载图片
                    imageThreadPoolLocal = new ThreadPoolExecutor(3, 5, 10,
                            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(
                                    30), rejectedExecutionHandler);
                }
                retval = imageThreadPoolLocal;
            } else {
                if (imageThreadPoolRemote == null
                        || imageThreadPoolRemote.isShutdown()) {
                    //为了下载图片更加的流畅,我们用了3个线程来下载图片
                    imageThreadPoolRemote = new ThreadPoolExecutor(3, 5, 10,
                            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(
                                    30), rejectedExecutionHandler);
                }
                retval = imageThreadPoolRemote;
            }
            return retval;
        }
    }

    /**
     * 先从内存缓存中获取Bitmap,如果没有就从SD卡或者手机缓存中获取,SD卡或者手机缓存 没有就去下载
     *
     * @param url 图片地址
     * @param listener 监听器
     */
    public void downloadImage(String url, int hashCode,
            OnImageLoaderListener listener) {
        synchronized (lock) {
            ImageDownloadTask task = activeQueue.get(url);
            if (task != null) {
                task.addListener(hashCode, listener);
                return;
            }
            ThreadPoolExecutor executor = null;
            if (isLocalBitmapExist(url)) {
                File file = getBitmapSaveFile(url);
                executor = getThreadPool(ThreadPoolType.TYPE_LOCAL);
                task = new ImageDownloadTask(file, url);
            } else {
                executor = getThreadPool(ThreadPoolType.TYPE_REMOTE);
                task = new ImageDownloadTask(url);
            }
            task.addListener(hashCode, listener);
            activeQueue.put(url, task);
            executor.execute(task);
        }
    }

    /**
     * 取消正在下载的任务
     */
    public synchronized void cancelTask() {
        synchronized (lock) {
            activeQueue.clear();
            waitTasksQueue.clear();
        }
        if (imageThreadPoolRemote != null) {
            imageThreadPoolRemote.shutdownNow();
            imageThreadPoolRemote = null;
        }
        if (imageThreadPoolLocal != null) {
            imageThreadPoolLocal.shutdownNow();
            imageThreadPoolLocal = null;
        }
    }

    /**
     * 异步下载图片的回调接口
     *
     */
    public interface OnImageLoaderListener {
        void onImageLoader(Bitmap bitmap, String url);
    }

    /**
     * @param url 图片地址
     * @return 图片对象
     */
    public Bitmap getBitmapFromCache(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        Bitmap bitmap = softBitmapCache.get(url);
        if (bitmap != null && !bitmap.isRecycled()) {
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * 功能简述: 从sd卡加载图片
     * @param url 图片地址
     * @return 图片对象
     */
    public Bitmap getBitmapFromSdCard(String url) {
        Bitmap retval = null;
        if (!isSdExits()) {
            return null;
        }
        File file = getBitmapSaveFile(url);
        if (file.exists()) {
            retval = DisplayUtil.decodeBitmap(file.getAbsolutePath());
        }
        return retval;
    }

    /**
     * 功能简述: 同步下载图片
     * @param url 图片地址
     * @return 图片对象
     */
    public Bitmap downloadBitmapSync(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        long contentLength = 0;
        long readCount = 0;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),
                    10 * 1000);
            HttpConnectionParams
                    .setSoTimeout(httpClient.getParams(), 15 * 1000);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            Header headerContentLength = response
                    .getFirstHeader("Content-Length");
            if (headerContentLength != null) {
                contentLength = Long.parseLong(TextUtils
                        .isEmpty(headerContentLength.getValue()) ? "0"
                        : headerContentLength.getValue());
            }
            int statusCode = response.getStatusLine().getStatusCode();
            stream = response.getEntity().getContent();
            if (statusCode == 200 || statusCode == 206) {
                byte[] buffer = new byte[2 * 1024];
                int byteCount = 0;
                while ((byteCount = stream.read(buffer)) > 0) {
                    bos.write(buffer, 0, byteCount);
                    readCount += byteCount;
                }
            }
        } catch (Exception error) {
            Log.e("downloadBitmapSync", "error!");
        } finally {
            if (contentLength > 0 && readCount != contentLength) {
            	Log.d("downloadBitmapSync", "readCount != contentLength");
            } else {
                bitmap = DisplayUtil.decodeBitmap(bos.toByteArray());
            }
            try {
                if (stream != null) {
                    stream.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException error) {
            	Log.e("DownloadService", error.toString());
            }
        }
        return bitmap;
    }

    /**
     * 功能简述: 获取本地缓存文件
     * @param url 图片地地址
     * @return 图片文件
     */
    public File getBitmapSaveFile(String url) {
        File dir = new File(STORAGE_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        hideMedia(STORAGE_PATH);
        String name = url;
        int startIndex = url.lastIndexOf("/");
        if (startIndex > 0) {
            name = url.substring(url.lastIndexOf("/") + 1);
        }
        File file = new File(STORAGE_PATH + "/" + name);
        return file;
    }

    /**
     * 功能简述: 本地缓存文件是否存在
     * @param url 图片地址
     * @return 是否存在
     */
    public boolean isLocalBitmapExist(String url) {
        boolean retval = false;
        File file = getBitmapSaveFile(url);
        retval = file.exists();
        return retval;
    }

    /**
     * InputStream跳过指定直接数
     */
    static class FlushedInputStream extends FilterInputStream {
        public FlushedInputStream(InputStream inputStream) {
            super(inputStream);
        }

        @Override
        public long skip(long number) throws IOException {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped < number) {
                long bytesSkipped = in.skip(number - totalBytesSkipped);
                if (bytesSkipped == 0L) {
                    int b = read();
                    if (b < 0) {
                        break;
                    } else {
                        bytesSkipped = 1;
                    }
                }
                totalBytesSkipped += bytesSkipped;
            }
            return totalBytesSkipped;
        }
    }

    /**
     * 把图片加到缓存
     * @param url 图片地址
     * @param bitmap 图片对象
     */
    public void addBitmapToCache(String url, Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }
        softBitmapCache.remove(url);
        softBitmapCache.set(url, bitmap);
    }

    /**
     * 保存图片到sdcard
     * @param url 图片地址
     * @param bm 图片对象
     */
    private void saveBmpToSd(String url, Bitmap bitmap) {
        autoCleanCache(STORAGE_PATH);
        if (TextUtils.isEmpty(url) || bitmap == null) {
            return;
        }
        if (!isSdExits()) {
            return;
        }

        if (FREE_SD_SPACE_NEEDED_TO_CACHE > getSdAvailable()) {
            return;
        }
        File file = getBitmapSaveFile(url);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        } catch (FileNotFoundException error) {
            Log.e("saveBmpToSd", "error!");
        } finally {
            if (outStream != null) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException error) {
                	Log.d("ImageDataManager", error.toString());
                }
            }
        }
    }

    /**
     * 在媒体库中隐藏文件夹内的媒体文件
     * 1. 加入.nomedia文件,使媒体功能扫描不到,用户可以通过文件浏览器方便看到
     * 2.在文件夹前面加点,隐藏整个文件夹,用户需要对文件浏览器设置显示点文件才能看到
     * @param folder
     *            文件夹
     */
    private void hideMedia(final String folder) {
        File file = new File(folder);
        if (!file.exists()) {
            file.mkdirs();
        }

        file = new File(folder, ".nomedia");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception error) {
                Log.e("hideMedia", "error!");
            }
        }
        file = null;
    }

    /**
     * 自动清除缓存
     * @param dirPath 地址
     */
    private void autoCleanCache(String dirPath) {
        if (!isSdExits()) {
            return;
        }
        hideMedia(dirPath);
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        long dirSize = 0;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            dirSize += file.length();
        }
        if (dirSize > CACHE_SIZE
                || FREE_SD_SPACE_NEEDED_TO_CACHE > getSdAvailable()) {
            int removeFactor = (int) ((0.4 * files.length) + 1);
            Arrays.sort(files, new FileLastModifSort());
            for (int i = 0; i < removeFactor; i++) {
                files[i].delete();
            }
        }
    }

    /**
     * 按最后修改时间排列文件
     */
    class FileLastModifSort implements Comparator<File> {
        @Override
        public int compare(File arg0, File arg1) {
            if (arg0.lastModified() > arg1.lastModified()) {
                return 1;
            } else if (arg0.lastModified() == arg1.lastModified()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    /**
     * 判断是否存在sd卡
     * @return 是否存在
     */
    public static boolean isSdExits() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取sd卡剩余空间
     * @return sd卡剩余空间
     */
    private static int getSdAvailable() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        double sdFreeMB = (availableBlocks * blockSize) / 1024d / 1024d;
        return (int) sdFreeMB;
    }

    /**
     * 下载任务
     */
    private void executeWaitTask() {
        synchronized (lock) {
            if (hasMoreWaitTask()) {
                Runnable runnable = waitTasksQueue.poll();
                if (runnable != null) {
                    ThreadPoolType threadPoolType = ThreadPoolType.TYPE_LOCAL;
                    if (runnable instanceof ImageDownloadTask) {
                        DownloadTaskType taskType = ((ImageDownloadTask) runnable)
                                .getTaskType();
                        if (taskType == DownloadTaskType.TASKTYPE_URL) {
                            threadPoolType = ThreadPoolType.TYPE_REMOTE;
                        }
                    }
                    getThreadPool(threadPoolType).execute(runnable);
                }
            }
        }
    }

    /**
     * 初始化任务被拒绝执行的处理器的方法
     */
    private void initRejectedExecutionHandler() {
        rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable runnable,
                    ThreadPoolExecutor executor) {
                //把被拒绝的任务重新放入到等待队列中
                synchronized (lock) {
                    waitTasksQueue.offer(runnable);
                }
            }
        };
    }

    /**
     * 是否还有等待任务的方法
     *
     * @return
     */
    public boolean hasMoreWaitTask() {
        boolean result = false;
        if (!waitTasksQueue.isEmpty()) {
            result = true;
        }
        return result;
    }

    /**
     * 删除任务
     * @param hashCode 任务id
     * @param url 图片地址
     * @return 是否删除成功
     */
    public boolean removeTask(int hashCode, String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }

        synchronized (lock) {
            boolean needRemove = true;
            ImageDownloadTask task = activeQueue.get(url);
            if (task != null) {
                needRemove = task.removeListener(hashCode);
            }
            if (needRemove) {
                activeQueue.remove(url);
                if (waitTasksQueue.contains(task)) {
                    waitTasksQueue.remove(task);
                }
                if (imageThreadPoolRemote != null) {
                    imageThreadPoolRemote.remove(task);
                }
                if (imageThreadPoolLocal != null) {
                    imageThreadPoolLocal.remove(task);
                }
            }
            return needRemove;
        }
    }

    /**
     * 销毁函数
     */
    public void destory() {
        cancelTask();
        instance = null;
        if (scheduledRunnable != null) {
            scheduledRunnable = null;
        }
        rejectedExecutionHandler = null;
    }

    /**
     * 初始化调度Runable
     */
    private class ScheduledRunnable implements Runnable {
        @Override
        public void run() {
            executeWaitTask();
        }
    }

    /**
     *
     * 类描述: 功能详细描述:
     *
     */
    private enum DownloadTaskType {
        TASKTYPE_URL, TASKTYPE_FILE
    }

    /**
     * 类描述: 功能详细描述:
     */
    private class ImageDownloadTask implements Runnable {
        private SparseArray<OnImageLoaderListener> listeners;
        private String url;
        private File file;
        private DownloadTaskType taskType;

        private ImageDownloadTask(File Downloadfile, String urlStr) {
            url = urlStr; // 回调函数需要用到url
            file = Downloadfile;
            taskType = DownloadTaskType.TASKTYPE_FILE;
            listeners = new SparseArray<ImageDataManager.OnImageLoaderListener>();
        }

        private ImageDownloadTask(String urlStr) {
            url = urlStr;
            taskType = DownloadTaskType.TASKTYPE_URL;
            listeners = new SparseArray<ImageDataManager.OnImageLoaderListener>();
        }

        public DownloadTaskType getTaskType() {
            return taskType;
        }

        public void addListener(int hashCode, OnImageLoaderListener listener) {
            if (listeners.get(hashCode) == null) {
                listeners.put(hashCode, listener);
            }
        }

        /**
         * @param hashCode
         * @return true listener列表为空,可以移除整个task
         */
        public boolean removeListener(int hashCode) {
            listeners.delete(hashCode);
            return listeners.size() == 0;
        }

        @Override
        public void run() {
            Bitmap bitmap = null;
            if (taskType == DownloadTaskType.TASKTYPE_FILE) {
                if (file.exists()) {
                    bitmap = DisplayUtil.decodeBitmap(file.getAbsolutePath());
                }
            } else if (taskType == DownloadTaskType.TASKTYPE_URL) {
                File file = getBitmapSaveFile(url);
                if (file.exists()) {
                    bitmap = DisplayUtil.decodeBitmap(file.getAbsolutePath());
                }
                if (bitmap == null || bitmap.isRecycled()) {
                    file.delete();
                    bitmap = downloadBitmapSync(url);
                }
                if (bitmap != null) {
                    addBitmapToCache(url, bitmap);
                    saveBmpToSd(url, bitmap);
                }
            }
            for (int i = 0; i < listeners.size(); i++) {
                OnImageLoaderListener listener = listeners.valueAt(i);
                if (listener != null) {
                    listener.onImageLoader(bitmap, url);
                }
            }
            activeQueue.remove(url);
        }

    }

}


text:
'use strict';

var Promise      = require('bluebird'),
	request      = require('request'),
	CiUrl        = 'https://circleci.com/api/v1/',
	buildPath    = 'project/yonjah/hapi-flow-tester/',
	newBuildPath = buildPath + 'tree/master',
	CiToken      = 'TOKEN';

function httpReq (options) {
	return new Promise(function (resolve, reject) {
		request(options, function (error, response, body) {
			if (error) {
				reject(error);
			} else {
				resolve([body, response]);
			}
		});
	});
}

function ciReq (options) {
	options.url     =  CiUrl + options.url + '?circle-token=' + CiToken;
	options.method  = options.method || (options.body ? 'POST' : 'GET');
	options.json    = true;
	return httpReq(options);
}

function runBuild(options) {
	return ciReq({url: newBuildPath, body: { build_parameters: options}})
		.spread(function (body/*, response*/) {
				/*
					all_commit_details: Array[1]
					author_date: "2014-12-06T11:36:22Z"
					author_email: "yonjah@gmail.com"
					author_name: "Yoni Jah"
					body: ""
					branch: "master"
					build_num: 11
					build_parameters: Object
					build_time_millis: null
					build_url: "https://circleci.com/gh/yonjah/hapi-flow-tester/11"
					canceled: false
					circle_yml: null
					committer_date: "2014-12-06T11:36:22Z"
					committer_email: "yonjah@gmail.com"
					committer_name: "Yoni Jah"
					compare: null
					dont_build: null
					failed: null
					feature_flags: Object
					infrastructure_fail: false
					is_first_green_build: false
					job_name: null
					lifecycle: "not_running"
					messages: Array[0]
					node: null
					oss: true
					outcome: null
					parallel: 1
				*/
				return body;
			});
}

function getBuild(id) {
	return ciReq({url: buildPath + id})
		.spread(function (body/*, response*/) {
				/*
					"steps" : [],
					"build_url" : "https://circleci.com/gh/yonjah/hapi-flow-tester/24",
					"failed" : null,
					"has_artifacts" : true,
					"status" : "fixed",
					"lifecycle" : "finished",
					"build_time_millis" : 46196,
					"messages" : [ ],
					"job_name" : null,
					"outcome" : "success",
					"canceled" : false
				*/
				return body;
			});
}

function getBuildResult(id) {
	return ciReq({url: buildPath + id + '/tests'})
		.spread(function (body/*, response*/) {
				/*
					"steps" : [],
					"build_url" : "https://circleci.com/gh/yonjah/hapi-flow-tester/24",
					"failed" : null,
					"has_artifacts" : true,
					"status" : "fixed",
					"lifecycle" : "finished",
					"build_time_millis" : 46196,
					"messages" : [ ],
					"job_name" : null,
					"outcome" : "success",
					"canceled" : false
				*/
				return body.tests || [];
			});
}

module.exports = {
	getBuildResult: getBuildResult,
	runBuild: runBuild,
	getBuild: getBuild
};


text:
package net.fortytwo.twitlogic.syntax.afterthought.impl;

import net.fortytwo.twitlogic.model.Hashtag;
import net.fortytwo.twitlogic.model.PlainLiteral;
import net.fortytwo.twitlogic.model.Resource;
import net.fortytwo.twitlogic.model.Triple;
import net.fortytwo.twitlogic.model.URIReference;
import net.fortytwo.twitlogic.syntax.MatcherTestBase;
import net.fortytwo.twitlogic.syntax.afterthought.DemoAfterthoughtMatcher;
import net.fortytwo.twitlogic.vocabs.RDF;
import net.fortytwo.twitlogic.vocabs.Review;

/**
 * @author Joshua Shinavier (http://fortytwo.net).
 */
public class ReviewMatcherTest extends MatcherTestBase {
    private static final Resource
            THEBESTMOVIEEVER = new Hashtag("thebestmovieever");

    private static final URIReference
            HASREVIEW = new URIReference(Review.HASREVIEW),
            MAXRATING = new URIReference(Review.MAXRATING),
            MINRATING = new URIReference(Review.MINRATING),
            RATING = new URIReference(Review.RATING),
            REVIEW = new URIReference(Review.REVIEW),
            REVIEWER = new URIReference(Review.REVIEWER),
            TEXT = new URIReference(Review.TEXT),
            TYPE = new URIReference(RDF.TYPE);

    public void setUp() {
        matcher = new DemoAfterthoughtMatcher();
    }

    public void testAll() throws Exception {
        Resource review = bnode(bnodeIndex + 1);
        assertExpected("IMHO, #thebestmovieever (3/5) is only so-so.",
                new Triple(THEBESTMOVIEEVER, HASREVIEW, review),
                new Triple(review, TYPE, REVIEW),
                new Triple(review, RATING, new PlainLiteral("3")),
                new Triple(review, MAXRATING, new PlainLiteral("5")),
                new Triple(review, MINRATING, new PlainLiteral("0")),
                // FIXME: restore this once the corresponding statement is restored in ReviewMatcher
          //      new Triple(review, REVIEWER, tweetContext.thisPerson()),
                new Triple(review, TEXT, new PlainLiteral("IMHO, #thebestmovieever (3/5) is only so-so.")));
    }

    public void testOutOfRangeNumbers() throws Exception {
        assertExpected("... #foo (3/6) ...");
        assertExpected("... #foo (3/3) ...");
        assertExpected("... #foo (5/4) ...");
        assertExpected("... #foo (-1/5) ...");
    }
}


text:
<?php
include "lib_function.php";
if($_FILES['filegambar']['error']==0){
    $link=koneksi_db();
    $nama=addslashes($_POST['namaproduk']);
    $id_merk=$_POST['id_merk'];
    $id_kategori=$_POST['id_kategori'];
    $harga=$_POST['harga'];
    $diskon=$_POST['diskon'];
    $stok=$_POST['stok'];
    $deskripsi=$_POST['deskripsi'];
    $filegambar=$_FILES['filegambar']['name'];
    $namafilebaru="gambar/".$filegambar;
    if(move_uploaded_file($_FILES['filegambar']['tmp_name'],
            $namafilebaru)==true){
        $sql="INSERT INTO produk VALUES(null,'$id_kategori','$id_merk','$nama','$harga','1','$diskon','$stok','Y','$deskripsi','$namafilebaru','T')";
        $res=mysql_query($sql);
        if($res){
            $id_produk=mysql_insert_id($link);
            echo "Data produk baru telah disimpan dengan ID $id_produk";
        }
        else{
            echo "Data produk baru gagal disimpan dengan kesalahan ".mysql_error();
        }
    }
}
else
    echo "Penambahan produk gagal karena upload file gambar gagal";
?>


text:
package org.littlewings.hazelcast.jcache;

import static org.assertj.core.api.Assertions.*;

import java.net.URI;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;

import com.hazelcast.cache.HazelcastCachingProvider;

import org.junit.Test;

public class JCacheConfigurationTest {
    @Test
    public void testSimpleJCache() {
        Properties properties = new Properties();
        properties.setProperty(HazelcastCachingProvider.HAZELCAST_CONFIG_LOCATION,
                               "classpath:my-hazelcast.xml");

        CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager(URI.create("my-cache-manager"),
                                                        null,
                                                        properties);
        Cache<String, String> cache = manager.getCache("simple-cache",
                                                       String.class,
                                                       String.class);

        IntStream.rangeClosed(1, 5).forEach(i -> cache.put("key" + i, "value" + i));

        assertThat(cache.get("key1"))
            .isEqualTo("value1");
        assertThat(cache.get("key5"))
            .isEqualTo("value5");
        assertThat(cache.get("key10"))
            .isNull();

        cache.close();
        manager.close();
        provider.close();
    }

    @Test
    public void testEviction() {
        Properties properties =
            HazelcastCachingProvider.propertiesByLocation("classpath:my-hazelcast.xml");

        CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager(URI.create("my-cache-manager"),
                                                        null,
                                                        properties);

        Cache<String, String> cache = manager.getCache("with-eviction-cache",
                                                       String.class,
                                                       String.class);

        com.hazelcast.cache.ICache<String, String> icache =
            cache.unwrap(com.hazelcast.cache.ICache.class);
        com.hazelcast.config.CacheConfig config =
            icache.getConfiguration(com.hazelcast.config.CacheConfig.class);

        assertThat(config.getEvictionConfig().getSize())
            .isEqualTo(5);  // right

        IntStream.rangeClosed(1, 30).forEach(i -> cache.put("key" + i, "value" + i));

        int count = 0;
        for (Cache.Entry<String, String> entry : cache) {
            count++;
        }

        assertThat(count)
            .isGreaterThan(25);  // much larger than ENTRY_COUNT??

        cache.close();
        manager.close();
        provider.close();
    }

    @Test
    public void testExpire() throws InterruptedException {
        Properties properties =
            HazelcastCachingProvider.propertiesByLocation("classpath:my-hazelcast.xml");

        CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager(URI.create("my-cache-manager"),
                                                        null,
                                                        properties);

        Cache<String, String> cache = manager.getCache("with-expire-cache",
                                                       String.class,
                                                       String.class);

        IntStream.rangeClosed(1, 5).forEach(i -> cache.put("key" + i, "value" + i));

        TimeUnit.SECONDS.sleep(3);

        cache.get("key1");
        cache.get("key3");

        TimeUnit.SECONDS.sleep(3);

        assertThat(cache.get("key1"))
            .isEqualTo("value1");
        assertThat(cache.get("key3"))
            .isEqualTo("value3");
        assertThat(cache.get("key2"))
            .isNull();
        assertThat(cache.get("key4"))
            .isNull();

        TimeUnit.SECONDS.sleep(6);

        assertThat(cache.get("key1"))
            .isNull();
        assertThat(cache.get("key3"))
            .isNull();

        cache.close();
        manager.close();
        provider.close();
    }

    @Test
    public void testEvictionWithExpire() throws InterruptedException {
        Properties properties =
            HazelcastCachingProvider.propertiesByLocation("classpath:my-hazelcast.xml");

        CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager(URI.create("my-cache-manager"),
                                                        null,
                                                        properties);
        Cache<String, String> cache = manager.getCache("with-expire-cache",
                                                       String.class,
                                                       String.class);

        IntStream.rangeClosed(1, 30).forEach(i -> cache.put("key" + i, "value" + i));

        TimeUnit.SECONDS.sleep(3);

        cache.get("key1");
        cache.get("key3");
        cache.get("key5");
        cache.get("key10");
        cache.get("key13");
        cache.get("key15");
        cache.get("key20");
        cache.get("key25");

        TimeUnit.SECONDS.sleep(3);

        int count = 0;
        for (Cache.Entry<String, String> entry : cache) {
            count++;
        }

        assertThat(count)
            .isLessThanOrEqualTo(8);

        cache.close();
        manager.close();
        provider.close();
    }
}


text:
export * from './GroupInput';
//# sourceMappingURL=index.js.map