text:
Web Image
=========

This library provides a category for UIImageVIew with support for remote images coming from the web.

It provides:

- An UIImageView category adding web image and cache management to the Cocoa Touch framework
- An asynchronous image downloader
- An asynchronous memory + disk image caching with automatic cache expiration handling
- A guarantee that the same URL won't be downloaded several times
- A guarantee that bogus URLs won't be retried again and again
- Performances!

Motivation
----------

As a dummy Objective-C developer working on my first iPhone application for my company
([Dailymotion][]), I've been very frustrated by the lack of support in the Cocoa Touch framework for
UITableView with remote images. After some Googling, I found lot of forums and blogs coming up with
their solution, most of the time based on asynchronous usage with NSURLConnection, but none provided
a simple library doing the work of async image grabbing + caching for you.

Actually there is one in the famous [Three20][] framework by [Joe Hewitt][], but it's a massive
and undocumented piece of code. You can't import just the the libraries you want without taking the
whole framework (damn #import "TTGlobal.h"). Anyway, the [Three20][] implementation is based on
NSURLConnection, and I soon discovered this solution wasn't ideal. Keep reading to find out why.

As a hurried beginner in iPhone development, I couldn't attempt to implement my own async image
grabber with caching support as my first steps in this new world. Thus, I asked for help from my good
friend Sebastien Flory ([Fraggle][]), who was working on his great iPhone game ([Urban Rivals][], a
future app-store hit) for almost a year. He spent quite an amount of time implementing the very
same solution for his needs, and was kind enough to give me his implementation for my own use. This
worked quite well and allowed me to concentrate on other parts of my application. But when I started
to compare my application with its direct competitor - the built-in Youtube application - I was very
unhappy with the loading speed of the images. After some network sniffing, I found that every HTTP
requests for my images was 10 times slower than Youtube's... On my own network, Youtube was 10
time faster than my own servers... WTF??

In fact, my servers were fine but a lot of latency was added to the requests, certainly because my
application wasn't responsive enough to handle the requests at full speed. Right then, I
understood something important, asynchronous NSURLConnections are tied to the main runloop in the
NSEventTrackingRunLoopMode. As explained in the documentation, this runloop mode is affected by
UI events:

> Cocoa uses this mode to restrict incoming events during mouse-dragging loops and other sorts of
> user interface tracking loops.

A simple test to recognize an application using NSURLConnection in its default mode to load
remote images is to scroll the UITableView with your finger to disclose an unloaded image, and to
keep your finger pressed on the screen. If the image doesn't load until you release you finger,
you've got one (try with the Facebook app for instance). It took me quite some time to understand
the reason for this lagging issue. Actually I first used NSOperation to workaround this issue.

This technique combined with an image cache instantly gave a lot of responsiveness to my app.
I thought this library could benefit other Cocoa Touch applications so I open-sourced it.

How To Use It
-------------

API documentation is available at [http://hackemist.com/SDWebImage/doc/](http://hackemist.com/SDWebImage/doc/)

### Using UIImageView+WebCache category with UITableView

Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage:
method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be
handled for you, from async downloads to caching management.

```objective-c
#import <SDWebImage/UIImageView+WebCache.h>

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}
```

### Using blocks

If your project's deployement target is set to iOS 4+, you may want to use the success/failure blocks to be
notified when image have been retrieved from cache.
```objective-c
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                        success:^(UIImage *image) {... success code here ...}
                        failure:^(NSError *error) {... failure code here ...}];
];
```

Note: neither your success nor failure block will be call if your image request is canceled before completion.

### Using SDWebImageManager

The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the
asynchronous downloader with the image cache store. You can use this class directly to benefit
from web image downloading with caching in another context than a UIView (ie: with Cocoa).

Here is a simple example of how to use SDWebImageManager:

```objective-c
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
                delegate:self
                 options:0
                 success:^(UIImage *image)
                 {
                     // do something with image
                 }
                 failure:nil];
```

### Using Asynchronous Image Downloader Independently

It is possible to use the async image downloader independently. You just have to create an instance
of SDWebImageDownloader using its convenience constructor downloaderWithURL:delegate:.
```objective-c
downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];
```

The download will start immediately and the imageDownloader:didFinishWithImage: method from the
SDWebImageDownloaderDelegate protocol will be called as soon as the download of image is completed.

### Using Asynchronous Image Caching Independently

It is also possible to use the NSOperation based image cache store independently. SDImageCache
maintains a memory cache and an optional disk cache. Disk cache write operations are performed
asynchronous so it doesn't add unnecessary latency to the UI.

The SDImageCache class provides a singleton instance for convenience but you can create your own
instance if you want to create separated cache namespace.

To lookup the cache, you use the imageForKey: method. If the method returns nil, it means the cache
doesn't currently own the image. You are thus responsible for generating and caching it. The cache
key is an application unique identifier for the image to cache. It is generally the absolute URL of
the image.

```objective-c
UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:myCacheKey];
```

By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache.
You can prevent this from happening by calling the alternative method imageFromKey:fromDisk: with a
negative second argument.

To store an image into the cache, you use the storeImage:forKey: method:

```objective-c
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
```

By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If
you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative
third argument.

### Using cache key filter

Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic
(i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that
takes the NSURL as input, and output a cache key NSString.

The following example sets a filter in the application delegate that will remove any query-string from
the URL before to use it as a cache key:

```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url)
    {
        url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
        return [url absoluteString];
    }];

    // Your app init code...
    return YES;
}
```

Common Problems
---------------

### No image appear when using UITableViewCell

If choose to use a default cell template provided by UITableViewCell with SDWebImage, ensure you are
providing a placeholder image, otherwise the cell will be initialized with no image.

### Using dynamic image size with UITableViewCell

UITableView determins the size of the image by the first image set for a cell. If your remote images
don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue.
The following article gives a way to workaround this issue:

[http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/)

Automatic Reference Counting (ARC)
----------------------------------

You can use either style in your Cocoa project. SDWebImage Will figure out which you are using at compile
time and do the right thing.

Installation
------------

There are two ways to use this in your project: copy all the files into your project, or import the project as a static library.

### Add the SDWebImage project to your project

Right-click on the project navigator and select "Add Files to "Your Project":

![Add Library Project](http://dl.dropbox.com/u/123346/SDWebImage/01_add_library_project.jpg)

In the dialog, select SDWebImage.xcodeproj:

![Add Library Project Dialog](http://dl.dropbox.com/u/123346/SDWebImage/02_add_library_project_dialog.jpg)

After you've added the subproject, it'll appear below the main project in Xcode's Navigator tree:

![Library Added](http://dl.dropbox.com/u/123346/SDWebImage/03_library_added.jpg)

You may want to add the SDWebImage directory in your project source tree as a submodule before adding it to your project.

### Add build target dependencies

In you application project app's target settings, find the "Build Phases" section and open the "Target Dependencies" block:

![Add Target Dependencies](http://dl.dropbox.com/u/123346/SDWebImage/04_add_target_dependencies.jpg)

Click the "+" button and select "SDWebImage ARC" (you may choose the non ARC target if you want to support iOS <3 or the ARC+MKAnnotation if you need MapKit category):

![Add Target Dependencies Dialog](http://dl.dropbox.com/u/123346/SDWebImage/05_add_target_dependencies_dialog.jpg)

Open the "Link Binary With Libraries" block:

![Add Library Link](http://dl.dropbox.com/u/123346/SDWebImage/06_add_library_link.jpg)

Click the "+" button and select "libSDWebImageARC.a" library (use non ARC version if you chose non ARC version in the previous step):

![Add Library Link Dialog](http://dl.dropbox.com/u/123346/SDWebImage/07_add_library_link_dialog.jpg)

If you chose to link against the ARC+MKAnnotation target, click the "+" button again and select "MapKit.framework":

![Add ImageIO Framework](http://dl.dropbox.com/u/123346/SDWebImage/08_add_imageio_framework.jpg)

Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature:

![Add MapKit Framework](http://dl.dropbox.com/u/123346/SDWebImage/09_add_mapkit_framework.jpg)

### Add headers

Open the "Build Settings" tab, locate the "Other Linker Flags" setting and add the "-ObjC" flag:

![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg)

Locate "Header Search Paths" (and not "User Header Search Paths") and add two settings: "$(TARGET_BUILD_DIR)/usr/local/lib/include" and "$(OBJROOT)/UninstalledProducts/include". Make sure to include the quotes here:

![User Header Search Paths](http://dl.dropbox.com/u/123346/SDWebImage/11_user_header_search_paths.jpg)

### Import headers in your source files

In the source files where you need to use the library, use ``#import <SDWebImage/HeaderFileName.h>``:

```objective-c
#import <SDWebImage/UIImageView+WebCache.h>
```

### Build Project

At this point your workspace should build without error. If you are having problem, post to the Issue and the
community can help you solve it.

### Fixing indexing

If you have problem with auto-completion of SDWebImage methods, you may have to copy the header files in
your project.

Future Enhancements
-------------------

- LRU memory cache cleanup instead of reset on memory warning

[Dailymotion]: http://www.dailymotion.com
[Fraggle]: http://fraggle.squarespace.com
[Urban Rivals]: http://fraggle.squarespace.com/blog/2009/9/15/almost-done-here-is-urban-rivals-iphone-trailer.html
[Three20]: http://groups.google.com/group/three20
[Joe Hewitt]: http://www.joehewitt.com
[tutorial]: http://blog.carbonfive.com/2011/04/04/using-open-source-static-libraries-in-xcode-4


text:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {

  /**
   * Constructor
   * @param {AuthService} auth
   * @param {Router} router
   */
  constructor(private auth: AuthService, private router: Router) { }

  /**
   * Implementation of canActivate (check auth service for authentication).
   * @returns {boolean}
   */
  public canActivate(): boolean {

    // User not logged in?  Go home.
    if (!this.auth.isAuthenticated) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Calicium fuscipes Tuck.

### Remarks
null


text:
require 'spec_helper'

describe Putio::Defaults do
  it { expect(described_class).to respond_to(:api_endpoint) }
  it { expect(described_class).to respond_to(:api_version) }
  it { expect(described_class).to respond_to(:default_headers) }
  it { expect(described_class).to respond_to(:user_agent) }

  describe '.api_endpoint' do
    it { expect(described_class.api_endpoint).to be_kind_of(String) }
    it { expect(described_class.api_endpoint.to_s).to eq("https://api.put.io") }
  end

  describe '.api_version' do
    it { expect(described_class.api_version).to be_kind_of(String) }
    it { expect(described_class.api_version).to eq('v2') }
  end

  describe '.default_headers' do
    it { expect(described_class.default_headers).to be_kind_of(Hash) }
    it { expect(described_class.default_headers).to include('User-Agent' => 'putio-rb ruby client') }
    it { expect(described_class.default_headers).to include('Accept' => 'application/json') }
  end

  describe '.options' do
    it { expect(described_class.options).to be_kind_of(Hash) }
  end

  describe '.access_token' do
    it { expect(described_class.access_token).to be_nil }

    context 'configured through ENV variable' do
      before { ENV['PUTIO_ACCESS_TOKEN'] = 'foobar' }
      it     { expect(described_class.access_token).to eq('foobar') }
    end
  end
end


text:
const React = require('react');
const ReactDOM = require('react-dom');
const DevTools = require('remotedev-app');

const remotedevOptions = window.remotedevOptions;
const options = {
  socketOptions: remotedevOptions,
  noButtonBar: false
};

// prevent setting from previous UI setting
if (remotedevOptions && remotedevOptions.noButtonBar) {
  options.noButtonBar = true;
  localStorage.removeItem('s:hostname');
  localStorage.removeItem('s:port');
}

ReactDOM.render(
  React.createElement(DevTools, options),
  document.querySelector('#root')
);


text:
from pts.core.basics.configuration import ConfigurationDefinition

# -----------------------------------------------------------------

# Create the configuration
definition = ConfigurationDefinition()

definition.add_section("wavelengths")
definition.sections["wavelengths"].add_optional("unit", str, "the unit of the wavelengths", "micron")
definition.sections["wavelengths"].add_optional("min", float, "the minimum wavelength", 0.05)
definition.sections["wavelengths"].add_optional("max", float, "the maximum wavelength", 1000)
definition.sections["wavelengths"].add_optional("npoints", int, "the number of wavelength points", 300)
definition.sections["wavelengths"].add_optional("min_zoom", float, "the minium wavelength of the zoomed-in grid", 1)
definition.sections["wavelengths"].add_optional("max_zoom", float, "the maximum wavelength of the zoomed-in grid", 30)
definition.sections["wavelengths"].add_optional("npoints_zoom", int, "the number of wavelength points in the zoomed-in grid", 300)

definition.add_optional("packages", float, "the number of photon packages per wavelength", 1e6)
definition.add_optional("selfabsorption", bool, "whether self-absorption should be enabled", True)
definition.add_optional("remote", str, "the remote host on which to launch the simulations", "nancy")

# -----------------------------------------------------------------


text:
package org.ebayopensource.turmeric.runtime.tests.binding.jaxb;

import java.io.ByteArrayOutputStream;

import org.ebayopensource.turmeric.junit.asserts.XmlAssert;
import org.ebayopensource.turmeric.runtime.binding.BindingConstants;
import org.ebayopensource.turmeric.runtime.common.binding.DataBindingDesc;
import org.ebayopensource.turmeric.runtime.common.binding.Deserializer;
import org.ebayopensource.turmeric.runtime.common.impl.binding.jaxb.json.JAXBJSONDeserializerFactory;
import org.ebayopensource.turmeric.runtime.common.impl.binding.jaxb.json.JAXBJSONSerializerFactory;
import org.ebayopensource.turmeric.runtime.common.pipeline.InboundMessage;
import org.ebayopensource.turmeric.runtime.common.pipeline.MessageContext;
import org.ebayopensource.turmeric.runtime.common.types.SOAConstants;
import org.ebayopensource.turmeric.runtime.spf.impl.internal.config.ServiceConfigManager;
import org.ebayopensource.turmeric.runtime.tests.common.util.TestUtils;
import org.ebayopensource.turmeric.runtime.tests.service1.sample.types1.MyMessage;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class JAXBJSONSerDeserTest extends BaseSerDeserTest {
	@Before
	public void setUpFactoriesAndConfig() throws Exception {
		ServiceConfigManager.getInstance().setConfigTestCase("config");
		m_serFactory = new JAXBJSONSerializerFactory();
		m_deserFactory = new JAXBJSONDeserializerFactory();
		super.setUp();
	}

	@Test
	public void jaxbJsonBasic() throws Exception {
		MyMessage msg = TestUtils.createTestMessage(1);
		DataBindingDesc dbDesc = new DataBindingDesc(BindingConstants.PAYLOAD_JSON, SOAConstants.MIME_JSON, m_serFactory,
				m_deserFactory, null, null, null, null);

		JAXBTestBuilder jaxbtest = new JAXBTestBuilder();
		jaxbtest.setTestServer(jetty);
		jaxbtest.setOrdered(false);
		jaxbtest.setSymmetricDBDesc(dbDesc);
		jaxbtest.setSerializerFactory(m_serFactory);
		jaxbtest.setDeserializerFactory(m_deserFactory);

		MessageContext ctx = jaxbtest.createTestMessageContext();

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		jaxbtest.serialize(ctx, out, msg);
		String xml1 = out.toString();
		System.out.println(xml1);
		jaxbtest.setPayload(out);
		Deserializer deser = m_deserFactory.getDeserializer();
		Assert.assertNotNull("Deserializer", deser);
		ctx = jaxbtest.createTestMessageContext();
		Assert.assertNotNull("Test Message Context", ctx);
		Object msg1 = deser.deserialize((InboundMessage) ctx
				.getRequestMessage(), MyMessage.class);
		out = new ByteArrayOutputStream();
		jaxbtest.serialize(ctx, out, msg1);
		String xml2 = out.toString();
		XmlAssert.assertEquals(xml1, xml2);
	}
}


text:
namespace zetasql {
namespace functions {

template <typename Type>
std::string NumberToString(Type v) {
  return absl::StrCat(v);
}
template <>
std::string NumberToString<float>(float v) {
  return absl::StrCat(v, "f");
}
template <>
std::string NumberToString<double>(double v) {
  return absl::StrCat(v, "d");
}

// Tests conversion of values approaching zero and the 'max' value of the ToType
// domain. 'max' may be positive or negative. Tests that monotonically
// increasing (decreasing) values are converted into non-decreasing
// (non-increasing) values. Assumes that FromType can accommodate ToType values
// in the range [0..max] if max is positive and [max..0] if max is negative.
template <typename FromType, typename ToType>
inline void TestMonotonicity(ToType max) {
  ToType converted_x, converted_y;
  absl::Status error, last_error;
  bool success = true;
  int num_iterations = 0;
  // divisor = 2 for integer FromType, 2.3 otherwise
  const FromType divisor = static_cast<FromType>(23) / 10;
  ToType prev_converted_x = max / divisor;
  ToType prev_converted_y = max - prev_converted_x;
  FromType last_x = 0;
  FromType x = static_cast<FromType>(prev_converted_x);
  while (x != last_x) {
    last_x = x;
    x /= divisor;
    FromType y = static_cast<FromType>(max) - x;
    EXPECT_TRUE((Convert<FromType, ToType>(x, &converted_x, &error))) << error;
    // Upper bound may result in legitimate out-of-range errors.
    success = Convert<FromType, ToType>(y, &converted_y, &error);
    std::string log =
        absl::StrCat("Iteration: ", num_iterations, " x: ", NumberToString(x),
                     " converted_x: ", converted_x, " y: ", NumberToString(y));
    if (success) {
      absl::StrAppend(&log, " converted_y: ", converted_y);
    } else {
      absl::StrAppend(&log,
                      " OUT OF RANGE max:", std::numeric_limits<ToType>::max());
    }
    VLOG(1) << log;
    if (max > 0) {
      EXPECT_LE(converted_x, prev_converted_x);
      EXPECT_GE(converted_y, prev_converted_y);
      if (!last_error.ok()) {
        // Once upper bound is out of range, it stays out of range.
        EXPECT_FALSE(error.ok());
      }
    } else {
      EXPECT_TRUE(success);
      EXPECT_GE(converted_x, prev_converted_x);
      EXPECT_LE(converted_y, prev_converted_y);
    }
    if (std::is_integral<FromType>::value ||
        std::is_same<FromType, ToType>::value) {
      EXPECT_EQ(static_cast<ToType>(x), converted_x);
      EXPECT_EQ(static_cast<ToType>(y), converted_y);
    }
    prev_converted_x = converted_x;
    if (success) {
      prev_converted_y = converted_y;
    }
    last_error = error;
    num_iterations++;
  }
  EXPECT_EQ(0, converted_x);
  if (success) {
    EXPECT_EQ(max, converted_y);
  }
}

template <typename FromType, typename ToType>
inline void TestOutOfRange(ToType max) {
  // Exceed the bound by at least 0.5 and check for error. The epsilon is
  // gradually increased in magnitude until the bound is exceeded. Epsilon is
  // positive for 'max' > 0, negative otherwise.
  FromType max_plus_epsilon = static_cast<FromType>(max);
  FromType epsilon = 0.5;
  while (max_plus_epsilon == max) {
    max_plus_epsilon = max + (max > 0 ? epsilon : -epsilon);
    epsilon *= 2;
  }
  VLOG(1) << "max_plus_epsilon: " << max_plus_epsilon
          << " epsilon: " << epsilon;
  ToType max_out;
  absl::Status error;
  EXPECT_FALSE((Convert<FromType, ToType>(
      max_plus_epsilon, &max_out, &error)))
      << "Converted " << max_plus_epsilon << " to " << max_out;
  // Ensure that the value appears in the error message.
  EXPECT_THAT(error,
              ::zetasql_base::testing::StatusIs(
                  absl::StatusCode::kOutOfRange,
                  ::testing::HasSubstr(absl::StrCat(": ", max_plus_epsilon))));
}

template <typename FromType, typename ToType>
inline void TestBoundaries(ToType max) {
  TestMonotonicity<FromType, ToType>(max);
  TestOutOfRange<FromType, ToType>(max);
}

constexpr int32_t kInt32Max = std::numeric_limits<int32_t>::max();
constexpr int32_t kInt32Min = std::numeric_limits<int32_t>::lowest();
constexpr uint32_t kUInt32Max = std::numeric_limits<uint32_t>::max();

constexpr int64_t kInt64Max = std::numeric_limits<int64_t>::max();
constexpr int64_t kInt64Min = std::numeric_limits<int64_t>::lowest();
constexpr uint64_t kUInt64Max = std::numeric_limits<uint64_t>::max();

TEST(Convert, Int32) {
  TestMonotonicity<int32_t, int32_t>(kInt32Max);
  TestMonotonicity<int32_t, int32_t>(kInt32Min);
  TestMonotonicity<int32_t, int64_t>(kInt32Max);
  TestMonotonicity<int32_t, int64_t>(kInt32Min);
  TestMonotonicity<int32_t, uint32_t>(kInt32Max);
  TestMonotonicity<int32_t, uint64_t>(kInt32Max);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<int32_t, float>(kInt32Max / 2);
  TestMonotonicity<int32_t, float>(kInt32Min);
  TestMonotonicity<int32_t, double>(kInt32Max);
  TestMonotonicity<int32_t, double>(kInt32Min);
}

TEST(Convert, Int64) {
  TestMonotonicity<int64_t, int32_t>(kInt32Max);
  TestMonotonicity<int64_t, int32_t>(kInt32Min);
  TestMonotonicity<int64_t, int64_t>(kInt64Max);
  TestMonotonicity<int64_t, int64_t>(kInt64Min);
  TestMonotonicity<int64_t, uint32_t>(kUInt32Max);
  TestMonotonicity<int64_t, uint64_t>(kInt64Max);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<int64_t, float>(kInt64Max / 2);
  TestMonotonicity<int64_t, float>(kInt64Min);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<int64_t, double>(kInt64Max / 2);
  TestMonotonicity<int64_t, double>(kInt64Min);
}

TEST(Convert, Uint32) {
  TestMonotonicity<uint32_t, int32_t>(kInt32Max);
  TestMonotonicity<uint32_t, int64_t>(kUInt32Max);
  TestMonotonicity<uint32_t, uint32_t>(kUInt32Max);
  TestMonotonicity<uint32_t, uint64_t>(kUInt32Max);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<uint32_t, float>(kUInt32Max / 2);
  TestMonotonicity<uint32_t, double>(kUInt32Max);
}

TEST(Convert, Uint64) {
  TestMonotonicity<uint64_t, int32_t>(kInt32Max);
  TestMonotonicity<uint64_t, int64_t>(kInt64Max);
  TestMonotonicity<uint64_t, uint32_t>(kUInt32Max);
  TestMonotonicity<uint64_t, uint64_t>(kUInt64Max);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<uint64_t, float>(kUInt64Max / 2);
  // Divide max by 2 to avoid overflow in static_cast().
  TestMonotonicity<uint64_t, double>(kUInt64Max / 2);
}

TEST(Convert, Float) {
  TestBoundaries<float, int32_t>(kInt32Max);
  TestBoundaries<float, int32_t>(kInt32Min);
  TestBoundaries<float, int64_t>(kInt64Max);
  TestBoundaries<float, int64_t>(kInt64Min);
  TestBoundaries<float, uint32_t>(kUInt32Max);
  TestBoundaries<float, uint64_t>(kUInt64Max);
  TestMonotonicity<float, float>(std::numeric_limits<float>::max());
  TestMonotonicity<float, float>(std::numeric_limits<float>::lowest());
  TestMonotonicity<float, double>(std::numeric_limits<float>::max());
  TestMonotonicity<float, double>(std::numeric_limits<float>::lowest());
}

TEST(Convert, Double) {
  TestBoundaries<double, int32_t>(kInt32Max);
  TestBoundaries<double, int32_t>(kInt32Min);
  TestBoundaries<double, int64_t>(kInt64Max);
  TestBoundaries<double, int64_t>(kInt64Min);
  TestBoundaries<double, uint32_t>(kUInt32Max);

  TestBoundaries<double, uint64_t>(kUInt64Max);
  TestBoundaries<double, float>(std::numeric_limits<float>::max());
  TestBoundaries<double, float>(std::numeric_limits<float>::lowest());
  TestMonotonicity<double, double>(std::numeric_limits<double>::max());
  TestMonotonicity<double, double>(std::numeric_limits<double>::lowest());
}

// Binary search for the maximal integer value that can be roundtripped via
// the corresponding floating point type. This is a helper method for
// determining boundaries in MaximalFloatToIntegerRoundtrip test.
template <typename FloatType, typename IntType>
void FindMaximalRoundtripValue() {
  IntType max = std::numeric_limits<IntType>::max();
  IntType upper = max;
  IntType lower = 0;
  IntType result;
  while (upper > lower + 1) {
    IntType mid = (upper - lower) / 2 + lower;
    absl::Status s;
    if (Convert<FloatType, IntType>(static_cast<FloatType>(mid), &result, &s)) {
      lower = mid;
    } else {
      upper = mid;
    }
  }
  LOG(INFO) << "Maximal integer: " << lower << " is "
            << (max - lower) << " away from max " << max
            << ", convers back as " << result
            << " which is " << (max - result) << " away from max";
}

// The 'false' branches below test that the next-larger integer value produces
// a float-cast-overflow runtime error under ASAN.
TEST(Convert, MaximalFloatToIntegerRoundtrip) {
  {
    FindMaximalRoundtripValue<float, int32_t>();
    int32_t num1 = kInt32Max - (1 << 6);
    int32_t num2 = kInt32Max - (1 << 7) + 1;
    EXPECT_EQ(static_cast<int32_t>(static_cast<float>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<int32_t>(static_cast<float>(num1 + 1)), 0);
    }
  }
  {
    FindMaximalRoundtripValue<float, uint32_t>();
    uint32_t num1 = kUInt32Max - (1 << 7);
    uint32_t num2 = kUInt32Max - (1 << 8) + 1;
    EXPECT_EQ(static_cast<uint32_t>(static_cast<float>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<uint32_t>(static_cast<float>(num1 + 1)), 0);
    }
  }
  {
    FindMaximalRoundtripValue<float, int64_t>();
    int64_t num1 = kInt64Max - (1ll << 38);
    int64_t num2 = kInt64Max - (1ll << 39) + 1;
    EXPECT_EQ(static_cast<int64_t>(static_cast<float>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<int64_t>(static_cast<float>(num1 + 1)), 0);
    }
  }
  {
    FindMaximalRoundtripValue<float, uint64_t>();
    uint64_t num1 = kUInt64Max - (1ull << 39);
    uint64_t num2 = kUInt64Max - (1ull << 40) + 1;
    EXPECT_EQ(static_cast<uint64_t>(static_cast<float>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<uint64_t>(static_cast<float>(num1 + 1)), 0);
    }
  }
  {
    FindMaximalRoundtripValue<double, int64_t>();
    int64_t num1 = kInt64Max - (1ll << 9);
    int64_t num2 = kInt64Max - (1ll << 10) + 1;
    EXPECT_EQ(static_cast<int64_t>(static_cast<double>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<int64_t>(static_cast<double>(num1 + 1)), 0);
    }
  }
  {
    FindMaximalRoundtripValue<double, uint64_t>();
    uint64_t num1 = kUInt64Max - (1ull << 10);
    uint64_t num2 = kUInt64Max - (1ull << 11) + 1;
    EXPECT_EQ(static_cast<uint64_t>(static_cast<double>(num1)), num2);
    if (false) {
      EXPECT_NE(static_cast<uint64_t>(static_cast<double>(num1 + 1)), 0);
    }
  }
}

}  // namespace functions
}  // namespace zetasql


text:
package org.apache.hadoop.chukwa.util;

import java.io.IOException;

import org.apache.hadoop.chukwa.ChukwaArchiveKey;
import org.apache.hadoop.chukwa.ChunkImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.log4j.Logger;

/**
 * This class is used by LocalToRemoteHDFSMover to
 * convert .chukwa files to .done before moving them.
 * By creating a new sequence file and copying all valid chunks to it,
 * it makes sure that no corrupt sequence files get into HDFS.
 */
public class CopySequenceFile {
  static Logger log = Logger.getLogger(CopySequenceFile.class);
  private static SequenceFile.Writer seqFileWriter = null;
  private static SequenceFile.Reader seqFileReader = null;
  private static FSDataOutputStream newOutputStr = null;

  public static void createValidSequenceFile(Configuration conf,
		                                     String originalFileDir,
		                                     String originalFileName,
		                                     FileSystem localFs) {
    try {
      if (!originalFileDir.endsWith("/")) {
    	      originalFileDir += "/";
      }
	  String originalCompleteDir= originalFileDir + originalFileName;
	  Path originalPath= new Path(originalCompleteDir);
	  int extensionIndex= originalFileName.indexOf(".chukwa",0);

	  String recoverFileName=originalFileName.substring(0, extensionIndex)+".recover";
	  String recoverDir= originalFileDir + recoverFileName;
	  Path recoverPath= new Path(recoverDir);
	  String recoverDoneFileName=originalFileName.substring(0, extensionIndex)+".recoverDone";
 	  String recoverDoneDir= originalFileDir + recoverDoneFileName;
 	  Path recoverDonePath= new Path(recoverDoneDir);
	  String doneFileName=originalFileName.substring(0, extensionIndex)+".done";
	  String doneDir= originalFileDir + doneFileName;
	  Path donePath= new Path(doneDir);

	  ChukwaArchiveKey key = new ChukwaArchiveKey();
      ChunkImpl evt = ChunkImpl.getBlankChunk();

	  newOutputStr = localFs.create(recoverPath);
      seqFileWriter = SequenceFile.createWriter(conf, newOutputStr,
                                                ChukwaArchiveKey.class, ChunkImpl.class,
                                                SequenceFile.CompressionType.NONE, null);
      seqFileReader = new SequenceFile.Reader(localFs, originalPath, conf);

      System.out.println("key class name is " + seqFileReader.getKeyClassName());
      System.out.println("value class name is " + seqFileReader.getValueClassName());
      try {
        while (seqFileReader.next(key, evt)) {
          seqFileWriter.append(key, evt);
        }
       } catch (ChecksumException e) { //The exception occurs when we read a bad chunk while copying
           log.info("Encountered Bad Chunk while copying .chukwa file, continuing",e);
       }
       seqFileReader.close();
	   seqFileWriter.close();
	   newOutputStr.close();
       try {
	     localFs.rename(recoverPath, recoverDonePath); //Rename the destination file from .recover to .recoverDone
   	     localFs.delete(originalPath,false); //Delete Original .chukwa file
	     localFs.rename(recoverDonePath, donePath); //rename .recoverDone to .done
       } catch (Exception e) {
           log.warn("Error occured while renaming .recoverDone to .recover or deleting .chukwa",e);
    	   e.printStackTrace();
       }

	} catch(IOException e) {
	    log.warn("Error during .chukwa file recovery",e);
	    e.printStackTrace();
	}
  }
}


text:
<?php
/**
 * This file is automatically created by Recurly's OpenAPI generation process
 * and thus any edits you make by hand will be lost. If you wish to make a
 * change to this file, please create a Github issue explaining the changes you
 * need and we will usher them to the appropriate places.
 */
namespace Recurly\Resources;

use Recurly\RecurlyResource;

// phpcs:disable
class Plan extends RecurlyResource
{
    private $_accounting_code;
    private $_allow_any_item_on_subscriptions;
    private $_auto_renew;
    private $_avalara_service_type;
    private $_avalara_transaction_type;
    private $_code;
    private $_created_at;
    private $_currencies;
    private $_custom_fields;
    private $_deleted_at;
    private $_description;
    private $_dunning_campaign_id;
    private $_hosted_pages;
    private $_id;
    private $_interval_length;
    private $_interval_unit;
    private $_name;
    private $_object;
    private $_pricing_model;
    private $_ramp_intervals;
    private $_revenue_schedule_type;
    private $_setup_fee_accounting_code;
    private $_setup_fee_revenue_schedule_type;
    private $_state;
    private $_tax_code;
    private $_tax_exempt;
    private $_total_billing_cycles;
    private $_trial_length;
    private $_trial_requires_billing_info;
    private $_trial_unit;
    private $_updated_at;

    protected static $array_hints = [
        'setCurrencies' => '\Recurly\Resources\PlanPricing',
        'setCustomFields' => '\Recurly\Resources\CustomField',
        'setRampIntervals' => '\Recurly\Resources\PlanRampInterval',
    ];

    /**
    * Getter method for the accounting_code attribute.
    * Accounting code for invoice line items for the plan. If no value is provided, it defaults to plan's code.
    *
    * @return ?string
    */
    public function getAccountingCode(): ?string
    {
        return $this->_accounting_code;
    }

    /**
    * Setter method for the accounting_code attribute.
    *
    * @param string $accounting_code
    *
    * @return void
    */
    public function setAccountingCode(string $accounting_code): void
    {
        $this->_accounting_code = $accounting_code;
    }

    /**
    * Getter method for the allow_any_item_on_subscriptions attribute.
    * Used to determine whether items can be assigned as add-ons to individual subscriptions.
If `true`, items can be assigned as add-ons to individual subscription add-ons.
If `false`, only plan add-ons can be used.

    *
    * @return ?bool
    */
    public function getAllowAnyItemOnSubscriptions(): ?bool
    {
        return $this->_allow_any_item_on_subscriptions;
    }

    /**
    * Setter method for the allow_any_item_on_subscriptions attribute.
    *
    * @param bool $allow_any_item_on_subscriptions
    *
    * @return void
    */
    public function setAllowAnyItemOnSubscriptions(bool $allow_any_item_on_subscriptions): void
    {
        $this->_allow_any_item_on_subscriptions = $allow_any_item_on_subscriptions;
    }

    /**
    * Getter method for the auto_renew attribute.
    * Subscriptions will automatically inherit this value once they are active. If `auto_renew` is `true`, then a subscription will automatically renew its term at renewal. If `auto_renew` is `false`, then a subscription will expire at the end of its term. `auto_renew` can be overridden on the subscription record itself.
    *
    * @return ?bool
    */
    public function getAutoRenew(): ?bool
    {
        return $this->_auto_renew;
    }

    /**
    * Setter method for the auto_renew attribute.
    *
    * @param bool $auto_renew
    *
    * @return void
    */
    public function setAutoRenew(bool $auto_renew): void
    {
        $this->_auto_renew = $auto_renew;
    }

    /**
    * Getter method for the avalara_service_type attribute.
    * Used by Avalara for Communications taxes. The transaction type in combination with the service type describe how the plan is taxed. Refer to [the documentation](https://help.avalara.com/AvaTax_for_Communications/Tax_Calculation/AvaTax_for_Communications_Tax_Engine/Mapping_Resources/TM_00115_AFC_Modules_Corresponding_Transaction_Types) for more available t/s types.
    *
    * @return ?int
    */
    public function getAvalaraServiceType(): ?int
    {
        return $this->_avalara_service_type;
    }

    /**
    * Setter method for the avalara_service_type attribute.
    *
    * @param int $avalara_service_type
    *
    * @return void
    */
    public function setAvalaraServiceType(int $avalara_service_type): void
    {
        $this->_avalara_service_type = $avalara_service_type;
    }

    /**
    * Getter method for the avalara_transaction_type attribute.
    * Used by Avalara for Communications taxes. The transaction type in combination with the service type describe how the plan is taxed. Refer to [the documentation](https://help.avalara.com/AvaTax_for_Communications/Tax_Calculation/AvaTax_for_Communications_Tax_Engine/Mapping_Resources/TM_00115_AFC_Modules_Corresponding_Transaction_Types) for more available t/s types.
    *
    * @return ?int
    */
    public function getAvalaraTransactionType(): ?int
    {
        return $this->_avalara_transaction_type;
    }

    /**
    * Setter method for the avalara_transaction_type attribute.
    *
    * @param int $avalara_transaction_type
    *
    * @return void
    */
    public function setAvalaraTransactionType(int $avalara_transaction_type): void
    {
        $this->_avalara_transaction_type = $avalara_transaction_type;
    }

    /**
    * Getter method for the code attribute.
    * Unique code to identify the plan. This is used in Hosted Payment Page URLs and in the invoice exports.
    *
    * @return ?string
    */
    public function getCode(): ?string
    {
        return $this->_code;
    }

    /**
    * Setter method for the code attribute.
    *
    * @param string $code
    *
    * @return void
    */
    public function setCode(string $code): void
    {
        $this->_code = $code;
    }

    /**
    * Getter method for the created_at attribute.
    * Created at
    *
    * @return ?string
    */
    public function getCreatedAt(): ?string
    {
        return $this->_created_at;
    }

    /**
    * Setter method for the created_at attribute.
    *
    * @param string $created_at
    *
    * @return void
    */
    public function setCreatedAt(string $created_at): void
    {
        $this->_created_at = $created_at;
    }

    /**
    * Getter method for the currencies attribute.
    * Pricing
    *
    * @return array
    */
    public function getCurrencies(): array
    {
        return $this->_currencies ?? [] ;
    }

    /**
    * Setter method for the currencies attribute.
    *
    * @param array $currencies
    *
    * @return void
    */
    public function setCurrencies(array $currencies): void
    {
        $this->_currencies = $currencies;
    }

    /**
    * Getter method for the custom_fields attribute.
    * The custom fields will only be altered when they are included in a request. Sending an empty array will not remove any existing values. To remove a field send the name with a null or empty value.
    *
    * @return array
    */
    public function getCustomFields(): array
    {
        return $this->_custom_fields ?? [] ;
    }

    /**
    * Setter method for the custom_fields attribute.
    *
    * @param array $custom_fields
    *
    * @return void
    */
    public function setCustomFields(array $custom_fields): void
    {
        $this->_custom_fields = $custom_fields;
    }

    /**
    * Getter method for the deleted_at attribute.
    * Deleted at
    *
    * @return ?string
    */
    public function getDeletedAt(): ?string
    {
        return $this->_deleted_at;
    }

    /**
    * Setter method for the deleted_at attribute.
    *
    * @param string $deleted_at
    *
    * @return void
    */
    public function setDeletedAt(string $deleted_at): void
    {
        $this->_deleted_at = $deleted_at;
    }

    /**
    * Getter method for the description attribute.
    * Optional description, not displayed.
    *
    * @return ?string
    */
    public function getDescription(): ?string
    {
        return $this->_description;
    }

    /**
    * Setter method for the description attribute.
    *
    * @param string $description
    *
    * @return void
    */
    public function setDescription(string $description): void
    {
        $this->_description = $description;
    }

    /**
    * Getter method for the dunning_campaign_id attribute.
    * Unique ID to identify a dunning campaign. Used to specify if a non-default dunning campaign should be assigned to this plan. For sites without multiple dunning campaigns enabled, the default dunning campaign will always be used.
    *
    * @return ?string
    */
    public function getDunningCampaignId(): ?string
    {
        return $this->_dunning_campaign_id;
    }

    /**
    * Setter method for the dunning_campaign_id attribute.
    *
    * @param string $dunning_campaign_id
    *
    * @return void
    */
    public function setDunningCampaignId(string $dunning_campaign_id): void
    {
        $this->_dunning_campaign_id = $dunning_campaign_id;
    }

    /**
    * Getter method for the hosted_pages attribute.
    * Hosted pages settings
    *
    * @return ?\Recurly\Resources\PlanHostedPages
    */
    public function getHostedPages(): ?\Recurly\Resources\PlanHostedPages
    {
        return $this->_hosted_pages;
    }

    /**
    * Setter method for the hosted_pages attribute.
    *
    * @param \Recurly\Resources\PlanHostedPages $hosted_pages
    *
    * @return void
    */
    public function setHostedPages(\Recurly\Resources\PlanHostedPages $hosted_pages): void
    {
        $this->_hosted_pages = $hosted_pages;
    }

    /**
    * Getter method for the id attribute.
    * Plan ID
    *
    * @return ?string
    */
    public function getId(): ?string
    {
        return $this->_id;
    }

    /**
    * Setter method for the id attribute.
    *
    * @param string $id
    *
    * @return void
    */
    public function setId(string $id): void
    {
        $this->_id = $id;
    }

    /**
    * Getter method for the interval_length attribute.
    * Length of the plan's billing interval in `interval_unit`.
    *
    * @return ?int
    */
    public function getIntervalLength(): ?int
    {
        return $this->_interval_length;
    }

    /**
    * Setter method for the interval_length attribute.
    *
    * @param int $interval_length
    *
    * @return void
    */
    public function setIntervalLength(int $interval_length): void
    {
        $this->_interval_length = $interval_length;
    }

    /**
    * Getter method for the interval_unit attribute.
    * Unit for the plan's billing interval.
    *
    * @return ?string
    */
    public function getIntervalUnit(): ?string
    {
        return $this->_interval_unit;
    }

    /**
    * Setter method for the interval_unit attribute.
    *
    * @param string $interval_unit
    *
    * @return void
    */
    public function setIntervalUnit(string $interval_unit): void
    {
        $this->_interval_unit = $interval_unit;
    }

    /**
    * Getter method for the name attribute.
    * This name describes your plan and will appear on the Hosted Payment Page and the subscriber's invoice.
    *
    * @return ?string
    */
    public function getName(): ?string
    {
        return $this->_name;
    }

    /**
    * Setter method for the name attribute.
    *
    * @param string $name
    *
    * @return void
    */
    public function setName(string $name): void
    {
        $this->_name = $name;
    }

    /**
    * Getter method for the object attribute.
    * Object type
    *
    * @return ?string
    */
    public function getObject(): ?string
    {
        return $this->_object;
    }

    /**
    * Setter method for the object attribute.
    *
    * @param string $object
    *
    * @return void
    */
    public function setObject(string $object): void
    {
        $this->_object = $object;
    }

    /**
    * Getter method for the pricing_model attribute.
    * A fixed pricing model has the same price for each billing period.
A ramp pricing model defines a set of Ramp Intervals, where a subscription changes price on
a specified cadence of billing periods. The price change could be an increase or decrease.

    *
    * @return ?string
    */
    public function getPricingModel(): ?string
    {
        return $this->_pricing_model;
    }

    /**
    * Setter method for the pricing_model attribute.
    *
    * @param string $pricing_model
    *
    * @return void
    */
    public function setPricingModel(string $pricing_model): void
    {
        $this->_pricing_model = $pricing_model;
    }

    /**
    * Getter method for the ramp_intervals attribute.
    * Ramp Intervals
    *
    * @return array
    */
    public function getRampIntervals(): array
    {
        return $this->_ramp_intervals ?? [] ;
    }

    /**
    * Setter method for the ramp_intervals attribute.
    *
    * @param array $ramp_intervals
    *
    * @return void
    */
    public function setRampIntervals(array $ramp_intervals): void
    {
        $this->_ramp_intervals = $ramp_intervals;
    }

    /**
    * Getter method for the revenue_schedule_type attribute.
    * Revenue schedule type
    *
    * @return ?string
    */
    public function getRevenueScheduleType(): ?string
    {
        return $this->_revenue_schedule_type;
    }

    /**
    * Setter method for the revenue_schedule_type attribute.
    *
    * @param string $revenue_schedule_type
    *
    * @return void
    */
    public function setRevenueScheduleType(string $revenue_schedule_type): void
    {
        $this->_revenue_schedule_type = $revenue_schedule_type;
    }

    /**
    * Getter method for the setup_fee_accounting_code attribute.
    * Accounting code for invoice line items for the plan's setup fee. If no value is provided, it defaults to plan's accounting code.
    *
    * @return ?string
    */
    public function getSetupFeeAccountingCode(): ?string
    {
        return $this->_setup_fee_accounting_code;
    }

    /**
    * Setter method for the setup_fee_accounting_code attribute.
    *
    * @param string $setup_fee_accounting_code
    *
    * @return void
    */
    public function setSetupFeeAccountingCode(string $setup_fee_accounting_code): void
    {
        $this->_setup_fee_accounting_code = $setup_fee_accounting_code;
    }

    /**
    * Getter method for the setup_fee_revenue_schedule_type attribute.
    * Setup fee revenue schedule type
    *
    * @return ?string
    */
    public function getSetupFeeRevenueScheduleType(): ?string
    {
        return $this->_setup_fee_revenue_schedule_type;
    }

    /**
    * Setter method for the setup_fee_revenue_schedule_type attribute.
    *
    * @param string $setup_fee_revenue_schedule_type
    *
    * @return void
    */
    public function setSetupFeeRevenueScheduleType(string $setup_fee_revenue_schedule_type): void
    {
        $this->_setup_fee_revenue_schedule_type = $setup_fee_revenue_schedule_type;
    }

    /**
    * Getter method for the state attribute.
    * The current state of the plan.
    *
    * @return ?string
    */
    public function getState(): ?string
    {
        return $this->_state;
    }

    /**
    * Setter method for the state attribute.
    *
    * @param string $state
    *
    * @return void
    */
    public function setState(string $state): void
    {
        $this->_state = $state;
    }

    /**
    * Getter method for the tax_code attribute.
    * Used by Avalara, Vertex, and Recurly's EU VAT tax feature. The tax code values are specific to each tax system. If you are using Recurly's EU VAT feature you can use `unknown`, `physical`, or `digital`.
    *
    * @return ?string
    */
    public function getTaxCode(): ?string
    {
        return $this->_tax_code;
    }

    /**
    * Setter method for the tax_code attribute.
    *
    * @param string $tax_code
    *
    * @return void
    */
    public function setTaxCode(string $tax_code): void
    {
        $this->_tax_code = $tax_code;
    }

    /**
    * Getter method for the tax_exempt attribute.
    * `true` exempts tax on the plan, `false` applies tax on the plan.
    *
    * @return ?bool
    */
    public function getTaxExempt(): ?bool
    {
        return $this->_tax_exempt;
    }

    /**
    * Setter method for the tax_exempt attribute.
    *
    * @param bool $tax_exempt
    *
    * @return void
    */
    public function setTaxExempt(bool $tax_exempt): void
    {
        $this->_tax_exempt = $tax_exempt;
    }

    /**
    * Getter method for the total_billing_cycles attribute.
    * Automatically terminate subscriptions after a defined number of billing cycles. Number of billing cycles before the plan automatically stops renewing, defaults to `null` for continuous, automatic renewal.
    *
    * @return ?int
    */
    public function getTotalBillingCycles(): ?int
    {
        return $this->_total_billing_cycles;
    }

    /**
    * Setter method for the total_billing_cycles attribute.
    *
    * @param int $total_billing_cycles
    *
    * @return void
    */
    public function setTotalBillingCycles(int $total_billing_cycles): void
    {
        $this->_total_billing_cycles = $total_billing_cycles;
    }

    /**
    * Getter method for the trial_length attribute.
    * Length of plan's trial period in `trial_units`. `0` means `no trial`.
    *
    * @return ?int
    */
    public function getTrialLength(): ?int
    {
        return $this->_trial_length;
    }

    /**
    * Setter method for the trial_length attribute.
    *
    * @param int $trial_length
    *
    * @return void
    */
    public function setTrialLength(int $trial_length): void
    {
        $this->_trial_length = $trial_length;
    }

    /**
    * Getter method for the trial_requires_billing_info attribute.
    * Allow free trial subscriptions to be created without billing info. Should not be used if billing info is needed for initial invoice due to existing uninvoiced charges or setup fee.
    *
    * @return ?bool
    */
    public function getTrialRequiresBillingInfo(): ?bool
    {
        return $this->_trial_requires_billing_info;
    }

    /**
    * Setter method for the trial_requires_billing_info attribute.
    *
    * @param bool $trial_requires_billing_info
    *
    * @return void
    */
    public function setTrialRequiresBillingInfo(bool $trial_requires_billing_info): void
    {
        $this->_trial_requires_billing_info = $trial_requires_billing_info;
    }

    /**
    * Getter method for the trial_unit attribute.
    * Units for the plan's trial period.
    *
    * @return ?string
    */
    public function getTrialUnit(): ?string
    {
        return $this->_trial_unit;
    }

    /**
    * Setter method for the trial_unit attribute.
    *
    * @param string $trial_unit
    *
    * @return void
    */
    public function setTrialUnit(string $trial_unit): void
    {
        $this->_trial_unit = $trial_unit;
    }

    /**
    * Getter method for the updated_at attribute.
    * Last updated at
    *
    * @return ?string
    */
    public function getUpdatedAt(): ?string
    {
        return $this->_updated_at;
    }

    /**
    * Setter method for the updated_at attribute.
    *
    * @param string $updated_at
    *
    * @return void
    */
    public function setUpdatedAt(string $updated_at): void
    {
        $this->_updated_at = $updated_at;
    }
}


text:
.filter-bar {
    display: flex;

    height: 29px;

    white-space: nowrap;
    overflow: hidden;

    background-color: hsl(0, 0%, 94%);
}

.filter-bar > .navigation-bar {
    margin-top: 1px;
}

.filter-bar > .navigation-bar > .item {
    padding: 0 0 3px 8px;
}

.filter-bar > input[type="search"] {
    display: flex;
    flex: 1;

    margin: 3px 6px 4px;
    padding-top: 0;

    outline: none;

    -webkit-appearance: none;

    border: 1px solid hsla(0, 0%, 0%, 0.25);
    border-radius: 3px;
    background-color: hsla(0, 0%, 100%, 0.2);
    background-clip: padding-box;

    height: 22px;
}

.filter-bar > input[type="search"]::-webkit-input-placeholder {
    color: hsla(0, 0%, 0%, 0.35);
}

.filter-bar > input[type="search"]:focus { background-color: white; }

.filter-bar > input[type="search"]::-webkit-search-decoration {
    width: 13px;
    height: 13px;

    margin-left: 6px;
    margin-right: 6px;

    vertical-align: bottom;

    background-image: url(../Images/FilterFieldGlyph.svg);

    -webkit-appearance: none;
}


text:
<?php
namespace Carsite\V1\Rest\ServiceLabor;

use Zend\Paginator\Paginator;

class ServiceLaborCollection extends Paginator
{
}


text:
/*
 *   This file is part of the computer assignment for the
 *   Information Retrieval course at KTH.
 *
 *   First version:  Johan Boye, 2010
 *   Second version: Johan Boye, 2012
 *   Additions: Hedvig Kjellström, 2012-14
 */

package ir;

import ir.PageRank.algorithm;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/**
 *   Implements an inverted index as a Hashtable from words to PostingsLists.
 */
public class HashedIndex implements Index {

    public HashMap<String, String> docIDs = new HashMap<String,String>();
    public HashMap<String, Integer> docLengths = new HashMap<String,Integer>();

    /** The index as a hashtable. */
    private HashMap<String,PostingsList> index = new HashMap<String,PostingsList>();
    private boolean loadedFromFile = false;
    private IndexStoragerOnDisk storager = new IndexStoragerOnDisk(this);
    private HashMap<String,Double> leftEigenvector;

    public  HashedIndex(){

		/* check if the pagerank already exists on disk */
		File f = new File("indexOnDisk1/pagerank");
		if(f.exists() && !f.isDirectory()) {
			System.out.println("Pagerank già sul disco.");
			leftEigenvector = (HashMap<String,Double>) IndexStoragerOnDisk.loadObjectFromDisk("pagerank");
			PageRank.docName = (String[]) IndexStoragerOnDisk.loadObjectFromDisk("docNamePR");
		}

		else{
			int T = 100;
	    	int m = 100;
	    	double c = 0.85;

		    PageRank pr = new PageRank("./svwiki_links/links.txt", c);
	    	leftEigenvector = pr.computePagerank(algorithm.monteCarlo3, T, m);

	    	IndexStoragerOnDisk.saveObjectToFile(leftEigenvector, "pagerank");
	    	IndexStoragerOnDisk.saveObjectToFile(PageRank.docName, "docNamePR");
	    }
    }

    public HashMap<String,Double> getLeftEigenvector(){
    	return leftEigenvector;
    }

    public void load(){
    	storager.loadManagementMapsFromDisk();
    	loadedFromFile = true;
    }
    public void save(){
    	storager.saveIndexOnDisk();
    }

    public int size(){
    	return index.keySet().size();
    }

    /**
     *  Inserts this token in the index.
     */
    public void insert(String token, int docID, int offset ) {

    	/* if the term is there already I add it to the postings list */
		if(index.containsKey(token)){
		    PostingsList lista = index.get(token);
		    lista.add(docID,offset);
		}

		/* otherwise I first create the Posting's List and then add it */
		else{
		    PostingsList lista = new PostingsList();
		    lista.add(docID,offset);
		    index.put(token,lista);
		}
    }

    /**
     *  Returns all the words in the index.
     */
    public Iterator<String> getDictionary() {
    	return index.keySet().iterator();
    }

    /**
     *  Returns the postings for a specific term, or null
     *  if the term is not in the index.
     */
    public PostingsList getPostings(String token)  {

    	PostingsList temp = index.get(token);
    	if(temp!=null) return temp; // if the postingsList is in memory return

    	/** otherwise if there's an index to load I try to load the PostingsList of the token */
    	if(loadedFromFile==true) {
    		storager.loadPostingsListFromDisk(index,token);
    	}

    	/* I return everything I have got. Could be null*/
    	return index.get(token);
    }

    public HashMap<String,String> docIDsToFilepath(){return docIDs;}
    public HashMap<String,Integer> docIDsToLengths(){return docLengths;}

    /**
     *  No need for cleanup in a HashedIndex.
     */
    public void cleanup() {
    }
}


text:
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>sciamlab</groupId>
	<artifactId>ckan4j-webapi</artifactId>
	<packaging>war</packaging>
	<version>2.0.0-SNAPSHOT</version>
	<name>CKAN4J Web API</name>

	<scm>
	   <connection>scm:svn:http://dev.sciamlab.com/svn/repo/main/${project.groupId}/${project.artifactId}/trunk</connection>
	   <developerConnection>scm:svn:http://dev.sciamlab.com/svn/repo/main/${project.groupId}/${project.artifactId}/trunk</developerConnection>
	</scm>

	<distributionManagement>
		<repository>
			<id>releases</id>
			<url>http://dev.sciamlab.com/nexus/content/repositories/releases</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<url>http://dev.sciamlab.com/nexus/content/repositories/snapshots</url>
		</snapshotRepository>
	</distributionManagement>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.glassfish.jersey</groupId>
				<artifactId>jersey-bom</artifactId>
				<version>${jersey.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
	<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.1</version>
</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet-core</artifactId>
			<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
			<!-- artifactId>jersey-container-servlet</artifactId -->
		</dependency>
		<!-- uncomment this to get JSON support <dependency> <groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-moxy</artifactId> </dependency> -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.11</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20140107</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>9.4-1201-jdbc41</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>sciamlab</groupId>
			<artifactId>ckan4j</artifactId>
			<version>2.0.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>sciamlab</groupId>
			<artifactId>auth-lib</artifactId>
			<version>1.0.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>sciamlab</groupId>
			<artifactId>common-lib</artifactId>
			<version>1.0.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.google.apis</groupId>
			<artifactId>google-api-services-plus</artifactId>
			<version>v1-rev126-1.18.0-rc</version>
		</dependency>
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client-jackson2</artifactId>
			<version>1.18.0-rc</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
		</dependency>

	</dependencies>
	<properties>
		<jersey.version>2.7</jersey.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>
		<finalName>ckan4j</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<inherited>true</inherited>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package com.todoist.mediaparser.mediaentity;

import com.todoist.mediaparser.util.Size;

import java.util.regex.Pattern;

/*
 * See: http://dev.twitpic.com/docs/thumbnails/ and http://dev.twitpic.com/docs/2/faces_create/ (inside "Description")
 */
public class TwitpicEntity extends BaseImageMediaEntity {
    private static Pattern sIdPattern;
    private static Size[] sSizes;

    TwitpicEntity(String url) {
        super(url);
    }

    @Override
    protected Size[] getAvailableSizes() {
        if (sSizes == null) {
            sSizes = new Size[]{
                    new Size("mini", 75),
                    new Size("thumb", 150),
                    new Size("large", -1)
            };
        }
        return sSizes;
    }

    @Override
    protected String getUrlTemplate() {
        return "http://twitpic.com/show/%2$s/%1$s";
    }

    @Override
    protected Pattern getIdPattern() {
        if (sIdPattern == null) {
            sIdPattern = Pattern.compile("https?://(?:www\\.)?twitpic\\.com/(\\w+)/?", Pattern.CASE_INSENSITIVE);
        }
        return sIdPattern;
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"strings"
	"text/template"

	"github.com/coreos/rocket/version"
)

var (
	cmdHelp = &Command{
		Name:        "help",
		Summary:     "Show a list of commands or help for one command",
		Usage:       "[COMMAND]",
		Description: "Show a list of commands or detailed help for one command",
		Run:         runHelp,
	}

	globalUsageTemplate  *template.Template
	commandUsageTemplate *template.Template
	templFuncs           = template.FuncMap{
		"descToLines": func(s string) []string {
			// trim leading/trailing whitespace and split into slice of lines
			return strings.Split(strings.Trim(s, "\n\t "), "\n")
		},
		"printOption": func(name, defvalue, usage string) string {
			prefix := "--"
			if len(name) == 1 {
				prefix = "-"
			}
			return fmt.Sprintf("\t%s%s=%s\t%s", prefix, name, defvalue, usage)
		},
	}
)

func init() {
	commands = append(commands, cmdHelp)

	globalUsageTemplate = template.Must(template.New("global_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Executable .Description}}

USAGE:
{{printf "\t%s" .Executable}} [global options] <command> [command options] [arguments...]

VERSION:
{{printf "\t%s" .Version}}

COMMANDS:{{range .Commands}}
{{printf "\t%s\t%s" .Name .Summary}}{{end}}

GLOBAL OPTIONS:{{range .Flags}}
{{printOption .Name .DefValue .Usage}}{{end}}

Run "{{.Executable}} help <command>" for more details on a specific command.
`[1:]))
	commandUsageTemplate = template.Must(template.New("command_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Cmd.Name .Cmd.Summary}}

USAGE:
{{printf "\t%s %s %s" .Executable .Cmd.Name .Cmd.Usage}}

DESCRIPTION:
{{range $line := descToLines .Cmd.Description}}{{printf "\t%s" $line}}
{{end}}
{{if .CmdFlags}}OPTIONS:{{range .CmdFlags}}
{{printOption .Name .DefValue .Usage}}{{end}}

{{end}}For help on global options run "{{.Executable}} help"
`[1:]))
}

func runHelp(args []string) (exit int) {
	if len(args) < 1 {
		printGlobalUsage()
		return
	}

	if err := printCommandUsageByName(args[0]); err != nil {
		printGlobalUsage()
		stderr("\nHelp error: %v\n", err)
		return 1
	}
	return
}

func printGlobalUsage() {
	globalUsageTemplate.Execute(tabOut, struct {
		Executable  string
		Commands    []*Command
		Flags       []*flag.Flag
		Description string
		Version     string
	}{
		cliName,
		commands,
		getAllFlags(),
		cliDescription,
		version.Version,
	})
	tabOut.Flush()
}

func printCommandUsage(cmd *Command) {
	commandUsageTemplate.Execute(tabOut, struct {
		Executable string
		Cmd        *Command
		CmdFlags   []*flag.Flag
	}{
		cliName,
		cmd,
		getFlags(&cmd.Flags),
	})
	tabOut.Flush()
}

func printCommandUsageByName(name string) error {
	var cmd *Command

	for _, c := range commands {
		if c.Name == name {
			cmd = c
			break
		}
	}

	if cmd == nil {
		return fmt.Errorf("unrecognized command: %s", name)
	}

	printCommandUsage(cmd)

	return nil
}


text:
#ifndef QNSWINDOWDELEGATE_H
#define QNSWINDOWDELEGATE_H

#include <Cocoa/Cocoa.h>

#include "qcocoawindow.h"

@interface QNSWindowDelegate : NSObject <NSWindowDelegate>
{
    QCocoaWindow *m_cocoaWindow;
}

- (id)initWithQCocoaWindow: (QCocoaWindow *) cocoaWindow;

- (void)windowDidResize:(NSNotification *)notification;
- (void)windowWillClose:(NSNotification *)notification;

@end

#endif // QNSWINDOWDELEGATE_H


text:
<?php
namespace Onion\Framework\Router\Strategy;

use function Onion\Framework\Common\merge;
use function Onion\Framework\Common\normalize_tree_keys;
use Onion\Framework\Router\Exceptions\MethodNotAllowedException;
use Onion\Framework\Router\Exceptions\NotFoundException;
use Onion\Framework\Router\Interfaces\ResolverInterface;
use Onion\Framework\Router\Interfaces\RouteInterface;

class TreeStrategy implements ResolverInterface
{
    /** @var RouteInterface[] $routes */
    private $routes = [];

    /**
     * @var RouteInterface[] $routes
     */
    public function __construct(array $routes)
    {
        foreach ($routes as $route) {
            $this->routes[$route->getPattern()] = $route;
        }

        $this->routes = normalize_tree_keys($this->routes, '/');
    }

    public function resolve(string $method, string $path): RouteInterface
    {
        $params = [];
        $route = $this->match($this->routes, explode('/', trim($path, '/')), $params);

        if ($route === null) {
            throw new NotFoundException("No match for '{$path}' found");
        }

        if (!$route->hasMethod($method)) {
            throw new MethodNotAllowedException($route->getMethods());
        }

        return $route->withParameters(array_filter($params, function ($key) {
            return !is_integer($key);
        }, ARRAY_FILTER_USE_KEY));
    }

    private function match(array $routes, array $parts, array &$params = []): ?RouteInterface
    {
        $part = array_shift($parts);

        foreach ($routes as $segment => $remaining) {
            $compiled = $this->compile($segment);

            foreach ($compiled as $segment => $param) {
                $segment = trim($segment, '/');
                if (preg_match("~^{$segment}$~i", $part, $matches, PREG_OFFSET_CAPTURE) > 0) {
                    foreach ($param as $index => $key) {
                        $params[$key] = $matches[$index][0];
                    }

                    if (is_array($remaining)) {
                        return $this->match($remaining, $parts, $params);
                    }

                    return $remaining;
                }
            }
        }

        return null;
    }

    private function compile(string $pattern): array
    {
        $segments = explode('/', $pattern);
        $params = [];
        $patterns = [];
        $path = '';

        foreach ($segments as $index => $segment) {
            if ($segment === '*') {
                $segment = "{{$index}}";
            }
            $matched = preg_match(self::PARAM_REGEX, $segment, $matches);
            if ($matched) {
                $params[] = $matches['name'];
                $path = "{$path}/(" . (!empty($matches['pattern']) ? $matches['pattern'] : '[^/]+') . ')';
                $patterns[$path] = $params;
            }

            if (!$matched) {
                $path = "{$path}/{$segment}";
            }
        }

        $patterns[$path] = $params;

        return $patterns;
    }
}


text:
import mock

from django.test import TestCase
from django.test.utils import override_settings
from django.contrib.auth.models import User

from readthedocs.projects.forms import SubprojectForm
from readthedocs.projects.models import Project
from readthedocs.rtd_tests.utils import create_user

from django_dynamic_fixture import get

class SubprojectFormTests(TestCase):

    def test_name_validation(self):
        user = get(User)
        project = get(Project, slug='mainproject')

        form = SubprojectForm({},
                              parent=project, user=user)
        form.full_clean()
        self.assertTrue('subproject' in form.errors)

        form = SubprojectForm({'name': 'not-existent'},
                              parent=project, user=user)
        form.full_clean()
        self.assertTrue('subproject' in form.errors)

    def test_adding_subproject_fails_when_user_is_not_admin(self):
        # Make sure that a user cannot add a subproject that he is not the
        # admin of.

        user = get(User)
        project = get(Project, slug='mainproject')
        project.users.add(user)
        subproject = get(Project, slug='subproject')

        form = SubprojectForm({'subproject': subproject.slug},
                              parent=project, user=user)
        # Fails because user does not own subproject.
        form.full_clean()
        self.assertTrue('subproject' in form.errors)

    def test_admin_of_subproject_can_add_it(self):
        user = get(User)
        project = get(Project, slug='mainproject')
        project.users.add(user)
        subproject = get(Project, slug='subproject')
        subproject.users.add(user)

        # Works now as user is admin of subproject.
        form = SubprojectForm({'subproject': subproject.slug},
                              parent=project, user=user)
        # Fails because user does not own subproject.
        form.full_clean()
        self.assertTrue(form.is_valid())
        form.save()

        self.assertEqual(
            [r.child for r in project.subprojects.all()],
            [subproject])

@override_settings(PUBLIC_DOMAIN='readthedocs.org')
class ResolverBase(TestCase):

    def setUp(self):
        with mock.patch('readthedocs.projects.models.broadcast'):
            with mock.patch('readthedocs.projects.models.update_static_metadata'):
                self.owner = create_user(username='owner', password='test')
                self.tester = create_user(username='tester', password='test')
                self.pip = get(Project, slug='pip', users=[self.owner], main_language_project=None)
                self.subproject = get(Project, slug='sub', language='ja', users=[
                                      self.owner], main_language_project=None)
                self.translation = get(Project, slug='trans', language='ja', users=[
                                       self.owner], main_language_project=None)
                self.pip.add_subproject(self.subproject)
                self.pip.translations.add(self.translation)

    @override_settings(PRODUCTION_DOMAIN='readthedocs.org')
    def test_resolver_subproject_alias(self):
        relation = self.pip.subprojects.first()
        relation.alias = 'sub_alias'
        relation.save()
        with override_settings(USE_SUBDOMAIN=False):
            resp = self.client.get('/docs/pip/projects/sub_alias/')
            self.assertEqual(resp.status_code, 302)
            self.assertEqual(
                resp._headers['location'][1],
                'http://readthedocs.org/docs/pip/projects/sub_alias/ja/latest/'
            )


text:
/**
 * A subclass of CalcInputTokenManager so that we can do better error reporting
 * via the GUI object.
 */
class MyLexer extends CalcInputParserTokenManager {

   /**
    * We redefined the lexical error reporting function so that it beeps
    * and displays a messgae thru the GUI.
    */
   protected void LexicalError() {
     CalcGUI.Error("ERROR (click 0)");
     ReInit(gui.getCollector(), OPERAND);
     result = 0.0;
   }

   public MyLexer(CalcGUI guiObj)
   {
      super(guiObj.getCollector(), OPERAND);
      gui = guiObj;
   }
}


text:
let prompt = require('prompt');
let read = require('./custom_modules/read-number');

// Prompt
prompt.start();
prompt.get('number', (err, res) => {
	let output = read(res.number);
	console.log('Output: ' + output);
});