text:
describe('Backbone.Memoize', function(){
    describe('Simple Model', function(){
        var SimpleModel = Backbone.Model.extend({
            defaults: {
                name: null,
                brand: null,
                year: null
            },

            initialize: function(){
                this.compoundName = this.memoize('compoundName');
            },

            compoundName: function(){
                return this.get('brand') + ' ' + this.get('name');
            }
        });

        var model;

        beforeEach(function(){
            model = new SimpleModel({
                name: 'Prius',
                brand: 'Toyota',
                year: '2010'
            });
        });

        it('should return the correct value', function(){
            expect(model.compoundName()).toEqual('Toyota Prius');
        });

        it('should not get property values more than once', function(){
            spyOn(model, 'get').andCallThrough();

            var name = model.compoundName();

            expect(model.get.callCount).toEqual(2);

            expect(model.compoundName()).toEqual(name);
            expect(model.get.callCount).toEqual(2);
        });

        it('should update value when any model attributes change', function(){
            spyOn(model, 'get').andCallThrough();

            var name = model.compoundName();

            expect(model.get.callCount).toEqual(2);

            model.set('year', '2011');

            expect(model.compoundName()).toEqual(name);
            expect(model.get.callCount).toEqual(4);

            model.set('brand', 'GM');

            expect(model.compoundName()).toEqual('GM Prius');
            expect(model.get.callCount).toEqual(6);
        });
    }); // describe('Simple Model')

    describe('Complex Model', function(){
        var ComplexModel = Backbone.Model.extend({
            defaults: {
                name: null,
                brand: null,
                year: null
            },

            initialize: function(){
                this.compoundName = this.memoize('compoundName', 'name brand');
            },

            compoundName: function(){
                return this.get('brand') + ' ' + this.get('name');
            }
        });

        var model;

        beforeEach(function(){
            model = new ComplexModel({
                name: 'Prius',
                brand: 'Toyota',
                year: '2010'
            });
        });

        it('should return the correct value', function(){
            expect(model.compoundName()).toEqual('Toyota Prius');
        });

        it('should not get property values more than once', function(){
            spyOn(model, 'get').andCallThrough();

            var name = model.compoundName();

            expect(model.get.callCount).toEqual(2);

            expect(model.compoundName()).toEqual(name);
            expect(model.get.callCount).toEqual(2);
        });

        it('should update value only when specified attrs change', function(){
            spyOn(model, 'get').andCallThrough();

            var name = model.compoundName();

            expect(model.get.callCount).toEqual(2);

            model.set('year', '2011');

            expect(model.compoundName()).toEqual(name);
            expect(model.get.callCount).toEqual(2);

            model.set('brand', 'GM');

            expect(model.compoundName()).toEqual('GM Prius');
            expect(model.get.callCount).toEqual(4);
        });
    }); // describe('Complex Model')
}); // describe('Backbone.Memoize')


text:
package model.fsb

import model.SchemeId

object FSBProgressStatus {
  def awaitingAllocation(scheme: SchemeId) = s"FSB_AWAITING_ALLOCATION_${scheme.value.toUpperCase}"
  def allocationConfirmed(scheme: SchemeId) = s"FSB_ALLOCATION_CONFIRMED_${scheme.value.toUpperCase}"
  def allocationUnconfirmed(scheme: SchemeId) = s"FSB_ALLOCATION_UNCONFIRMED_${scheme.value.toUpperCase}"
  def failedToAttend(scheme: SchemeId) = s"FSB_FAILED_TO_ATTEND_${scheme.value.toUpperCase}"
  def resultEntered(scheme: SchemeId) = s"FSB_RESULT_ENTERED_${scheme.value.toUpperCase}"
  def passed(scheme: SchemeId) = s"FSB_PASSED_${scheme.value.toUpperCase}"
  def failed(scheme: SchemeId) = s"FSB_FAILED_${scheme.value.toUpperCase}"
  def failedNotified(scheme: SchemeId) = s"FSB_FAILED_NOTIFIED_${scheme.value.toUpperCase}"
}

redpajama_set_name: RedPajamaGithub


text:
"""Game 'board' and environment for the mbti_types interactions."""

from __future__ import print_function

from random import choice

import mbti_types

NEIGHBORHOOD_SIZE = 8  # Must be a multiple of 8.

types = dict(
    istj=mbti_types.Istj,
    isfj=mbti_types.Isfj,
    infj=mbti_types.Infj,
    intj=mbti_types.Intj,
    istp=mbti_types.Istp,
    isfp=mbti_types.Isfp,
    infp=mbti_types.Infp,
    intp=mbti_types.Intp,
    estp=mbti_types.Estp,
    esfp=mbti_types.Esfp,
    enfp=mbti_types.Enfp,
    entp=mbti_types.Entp,
    estj=mbti_types.Estj,
    esfj=mbti_types.Esfj,
    enfj=mbti_types.Enfj,
    entj=mbti_types.Entj,
)

choice_typed = zip(types.keys(), types.values())

class Grid(list):
    """Overloaded list with some convenience methods for the grid."""

    def __init__(self, grid):
        """Add initial grid."""
        self += grid

    def cell(self, row, col):
        """Try to get a cell."""
        try:
            return self[row][col]
        except IndexError:
            return None

    def get_neighborhood(self, col=0, row=0):
        """Get the neighborhood of a given cell.

        Example of neighborhood below:

        [1] [2] [3]
        [4] [X] [5]
        [6] [7] [8]
        """
        # Top row
        tl = self.cell(row - 1, col - 1)
        tc = self.cell(row, col - 1)
        tr = self.cell(row - 1, col + 1)
        # Left and right
        ml, mr = self.cell(row - 1, col), self.cell(row + 1, col)
        # Bottom row
        bl = self.cell(row + 1, col - 1)
        bc = self.cell(row, col + 1)
        br = self.cell(row + 1, col + 1)
        return [
            tl, tc, tr,
            ml, mr,
            bl, bc, br,
        ]

def new_grid(size):
    """Generate an empty grid of `size`."""
    return [[0 for _ in range(size)] for _ in range(size)]

def get_pos(grid, x, y):
    """Get a position."""
    return grid[x][y]

def evaluate(currcell, neighbors):
    """Evaluate the current cell against its neighbors."""
    for neighbor in neighbors:
        if neighbor is not None:
            neighbor.interact_with(currcell)

def random_grid(size=10):
    """Generate a grid of random types."""
    grid = new_grid(size)
    for rownum, row in enumerate(grid):
        for colnum, _ in enumerate(row):
            name, typecls = choice(choice_typed)
            grid[rownum][colnum] = typecls(name)
    return grid

def print_grid(grid):
    """Print the grid in a uniform, intuitive way."""
    for rownum, row in enumerate(grid):
        printrow = ''  # accumulate the characters in a single row
        for colnum, col in enumerate(row):
            cell = grid.cell(rownum, colnum)
            if colnum >= NEIGHBORHOOD_SIZE:
                # print a new line if the current
                # col count is > standard "width"
                print(printrow)
            else:
                if cell.is_dead():
                    printrow += '   -DEAD-   '
                else:
                    printrow += ' {} ({}) '.format(
                        cell.name.upper(),
                        str(cell.hp).zfill(3))

def run_game(types, grid=None, iterations=20):
    """Run a game.

    NEIGHBORHOOD_SIZE determines the surrounding elements, in much the same
    format as Conway's game of life.

    [0, 1, 2, 3, 4]
    [0, 1, 2, 3, 4]
    [0, 1, 2, 3, 4]
    [0, 1, 2, 3, 4]

    x = lst[0][2]  # Row one, column three (2, here)
    """
    if grid is None:
        grid = Grid(random_grid(size=10))
    curr_step = iterations

    while curr_step <= iterations:
        for rownum, row in enumerate(grid):
            for colnum, col in enumerate(row):
                neighbors = grid.get_neighborhood(row=rownum, col=colnum)
                currcell = grid.cell(rownum, colnum)
                evaluate(currcell, neighbors)
        print('=============== Iteration: {}'.format(curr_step))
        print_grid(grid)
        curr_step += 1

if __name__ == '__main__':
    run_game(mbti_types)


text:
package org.openqa.selenium.ie;

import static java.lang.String.format;
import static org.openqa.selenium.browserlaunchers.CapabilityType.PROXY;
import static org.openqa.selenium.ie.ExportedWebDriverFunctions.SUCCESS;

import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.HasInputDevices;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keyboard;
import org.openqa.selenium.Mouse;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Speed;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.browserlaunchers.WindowsProxyManager;
import org.openqa.selenium.internal.AsyncJavascriptExecutor;
import org.openqa.selenium.internal.FileHandler;
import org.openqa.selenium.internal.TemporaryFilesystem;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class InternetExplorerDriver implements WebDriver, JavascriptExecutor, TakesScreenshot,
    HasInputDevices {

  private static ExportedWebDriverFunctions lib;
  private Pointer driver;
  private Speed speed = Speed.FAST;
  private ErrorHandler errors = new ErrorHandler();
  private Thread cleanupThread;
  private WindowsProxyManager proxyManager;
  private InternetExplorerKeyboard keyboard;

  private final AsyncJavascriptExecutor asyncJsExecutor =
      new AsyncJavascriptExecutor(this, 0, TimeUnit.MILLISECONDS);

  public InternetExplorerDriver() {
    this(null);
  }

  public InternetExplorerDriver(Capabilities caps) {
    assertOnWindows();

    proxyManager = new WindowsProxyManager(true, "webdriver-ie", 0, 0);

    prepareProxy(caps);

    initializeLib();
    PointerByReference ptr = new PointerByReference();
    int result = lib.wdNewDriverInstance(ptr);
    if (result != SUCCESS) {
      throw new IllegalStateException("Cannot create new browser instance: " + result);
    }
    driver = ptr.getValue();
    keyboard = new InternetExplorerKeyboard(this, lib);
  }

  protected void assertOnWindows() {
    Platform current = Platform.getCurrent();
    if (!current.is(Platform.WINDOWS)) {
      throw new WebDriverException(
          format("You appear to be running %s. The IE driver only runs on Windows.", current));
    }
  }

  private void prepareProxy(Capabilities caps) {
    if (caps == null || caps.getCapability(PROXY) == null) {
      return;
    }

    // Because of the way that the proxying is currently implemented,
    // we can only set a single host.

    try {
      proxyManager.backupRegistrySettings();
      proxyManager.changeRegistrySettings(caps);
    } catch (IOException e) {
      throw new WebDriverException(e);
    }

    cleanupThread = new Thread() {
      @Override
      public void run() {
        proxyManager.restoreRegistrySettings(true);
      }
    };
    Runtime.getRuntime().addShutdownHook(cleanupThread);
  }

  public String getPageSource() {
    PointerByReference wrapper = new PointerByReference();
    int result = lib.wdGetPageSource(driver, wrapper);

    errors.verifyErrorCode(result, "Unable to get page source");

    return new StringWrapper(lib, wrapper).toString();
  }

  public void close() {
    int result = lib.wdClose(driver);
    if (result != SUCCESS) {
      throw new IllegalStateException("Unable to close driver: " + result);
    }
  }

  public void quit() {
    if (proxyManager != null) {
      proxyManager.restoreRegistrySettings(true);
    }
    if (cleanupThread != null) {
      Runtime.getRuntime().removeShutdownHook(cleanupThread);
    }

    try {
      for (String handle : getWindowHandles()) {
      try {
        switchTo().window(handle);
        close();
      } catch (NoSuchWindowException e) {
        // doesn't matter one jot.
      }
    }
    } catch (IllegalStateException e) {
      // Stuff happens. Bail out
      lib.wdFreeDriver(driver);
      driver = null;
    }

    lib.wdFreeDriver(driver);
    driver = null;
  }

  public Set<String> getWindowHandles() {
    PointerByReference rawHandles = new PointerByReference();
    int result = lib.wdGetAllWindowHandles(driver, rawHandles);

    errors.verifyErrorCode(result, "Unable to obtain all window handles");

    return new StringCollection(lib, rawHandles.getValue()).toSet();
  }

  public String getWindowHandle() {
    PointerByReference handle = new PointerByReference();
    int result = lib.wdGetCurrentWindowHandle(driver, handle);

    errors.verifyErrorCode(result, "Unable to obtain current window handle");

    return new StringWrapper(lib, handle).toString();
  }

  /**
   * Execute javascript in the context of the currently selected frame or
   * window. This means that "document" will refer to the current document.
   * If the script has a return value, then the following steps will be taken:
   *
   *

For an HTML element, this method returns a WebElement

   *
For a number, a Long is returned

   *
For a boolean, a Boolean is returned

   *
For all other cases, a String is returned.

   *
Unless the value is null or there is no return value,
   * in which null is returned

   *
Does not support lists or arrays. See Webdriver issue #110

   *
   *
Arguments must be a number, a boolean, a String or WebElement.
   * An exception will be thrown if the arguments do not meet these criteria.
   * The arguments will be made available to the javascript via the "arguments"
   * magic variable, as if the function were called via "Function.apply"
   *
   * @param script The javascript to execute
   * @param args The arguments to the script. May be empty
   * @return One of Boolean, Long, String or WebElement. Or null.
   */
  public Object executeScript(String script, Object... args) {
    PointerByReference scriptArgsRef = new PointerByReference();
    int result = lib.wdNewScriptArgs(scriptArgsRef, args.length);
    errors.verifyErrorCode(result, "Unable to create new script arguments array");
    Pointer scriptArgs = scriptArgsRef.getValue();

    try {
      populateArguments(result, scriptArgs, args);

      script = "(function() { return function(){" + script + "};})();";

      PointerByReference scriptResultRef = new PointerByReference();
      result = lib.wdExecuteScript(driver, new WString(script), scriptArgs, scriptResultRef);

      errors.verifyErrorCode(result, "Cannot execute script");
      return new JavascriptResultCollection(lib, this).extractReturnValue(scriptResultRef);
    } finally {
      lib.wdFreeScriptArgs(scriptArgs);
    }
  }

  public Object executeAsyncScript(String script, Object... args) {
    return asyncJsExecutor.executeScript(script, args);
  }

  public boolean isJavascriptEnabled() {
    return true;
  }

  private int populateArguments(int result, Pointer scriptArgs, Object... args) {
    for (Object arg : args) {
      if (arg instanceof String) {
        result = lib.wdAddStringScriptArg(scriptArgs, new WString((String) arg));
      } else if (arg instanceof Boolean) {
        Boolean param = (Boolean) arg;
        result = lib.wdAddBooleanScriptArg(scriptArgs, param == null || !param ? 0 : 1);
      } else if (arg instanceof Double || arg instanceof Float) {
        Double number = ((Number) arg).doubleValue();
        result = lib.wdAddDoubleScriptArg(scriptArgs, number);
      } else if (arg instanceof Number) {
        long number = ((Number) arg).longValue();
        result = lib.wdAddNumberScriptArg(scriptArgs, new NativeLong(number));
      } else if (arg instanceof InternetExplorerElement) {
        result = ((InternetExplorerElement) arg).addToScriptArgs(scriptArgs);
      } else {
        throw new IllegalArgumentException("Parameter is not of recognized type: " + arg);
      }

      errors.verifyErrorCode(result, ("Unable to add argument: " + arg));
    }
    return result;
  }

  public void get(String url) {
    int result = lib.wdGet(driver, new WString(url));
    if (result != SUCCESS) {
      errors.verifyErrorCode(result, format("Cannot get \"%s\": %s", url, result));
    }
  }

  public String getCurrentUrl() {
    PointerByReference ptr = new PointerByReference();
    int result = lib.wdGetCurrentUrl(driver, ptr);
    if (result != SUCCESS) {
      throw new IllegalStateException("Unable to get current URL: " + result);
    }

    return new StringWrapper(lib, ptr).toString();
  }

  public String getTitle() {
    PointerByReference ptr = new PointerByReference();
    int result = lib.wdGetTitle(driver, ptr);
    if (result != SUCCESS) {
      throw new IllegalStateException("Unable to get title: " + result);
    }

    return new StringWrapper(lib, ptr).toString();
  }

  /**
   * Is the browser visible or not?
   *
   * @return True if the browser can be seen, or false otherwise
   */
  public boolean getVisible() {
    IntByReference toReturn = new IntByReference();
    int result = lib.wdGetVisible(driver, toReturn);

    errors.verifyErrorCode(result, "Unable to determine if browser is visible");

    return toReturn.getValue() == 1;
  }

  /**
   * Make the browser visible or not.
   *
   * @param visible Set whether or not the browser is visible
   */
  public void setVisible(boolean visible) {
    int result = lib.wdSetVisible(driver, visible ? 1 : 0);

    errors.verifyErrorCode(result, "Unable to change the visibility of the browser");
  }

  public List<WebElement> findElements(By by) {
    return new Finder(lib, this, null).findElements(by);
  }

  public WebElement findElement(By by) {
    return new Finder(lib, this, null).findElement(by);
  }

  @Override
  public String toString() {
    return getClass().getName() + ": Implement me!";
  }

  public TargetLocator switchTo() {
    return new InternetExplorerTargetLocator();
  }

  public Navigation navigate() {
    return new InternetExplorerNavigation();
  }

  public Options manage() {
    return new InternetExplorerOptions();
  }

  protected void waitForLoadToComplete() {
    lib.wdWaitForLoadToComplete(driver);
  }

  public Pointer getDriverPointer() {
    return driver;
  }

  public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
	// Get the screenshot as base64.
	PointerByReference ptr = new PointerByReference();
	int result = lib.wdCaptureScreenshotAsBase64(driver, ptr);
	if (result != SUCCESS) {
	  throw new IllegalStateException("Unable to capture screenshot: " + result);
    }
    // ... and convert it.
    return target.convertFromBase64Png(new StringWrapper(lib, ptr).toString());
  }

  @Override
  protected void finalize() throws Throwable {
    super.finalize();
    if (driver != null) {
      lib.wdFreeDriver(driver);
    }
  }

  // Deliberately package level visibility
  Pointer getUnderlyingPointer() {
    return driver;
  }

  public Keyboard getKeyboard() {
    return keyboard;
  }

  public Mouse getMouse() {
    throw new UnsupportedOperationException("Mouse interface is not implemented yet.");
  }

  private class InternetExplorerTargetLocator implements TargetLocator {

    public WebDriver frame(int frameIndex) {
      return frame(String.valueOf(frameIndex));
    }

    public WebDriver frame(String frameName) {
      int result = lib.wdSwitchToFrame(driver, new WString(frameName));

      errors.verifyErrorCode(result, ("Unable to switch to frame: " + frameName));

      return InternetExplorerDriver.this;
    }

    public WebDriver frame(WebElement frameElement) {
      throw new UnsupportedOperationException("Not implemented yet");
    }

    public WebDriver window(String windowName) {
      int result = lib.wdSwitchToWindow(driver, new WString(windowName));
      errors.verifyErrorCode(result, "Unable to locate window: " + windowName);
      return InternetExplorerDriver.this;
    }

    public WebDriver defaultContent() {
      return frame("");
    }

    public WebElement activeElement() {
      PointerByReference element = new PointerByReference();
      int result = lib.wdSwitchToActiveElement(driver, element);

      errors.verifyErrorCode(result, "Unable to find active element");

      return new InternetExplorerElement(lib, InternetExplorerDriver.this, element.getValue());
    }

    public Alert alert() {
      throw new UnsupportedOperationException("alert");
    }
  }

  private class InternetExplorerNavigation implements Navigation {

    public void back() {
      int result = lib.wdGoBack(driver);
      errors.verifyErrorCode(result, "Unable to go back");
    }

    public void forward() {
      int result = lib.wdGoForward(driver);
      errors.verifyErrorCode(result, "Unable to go forward");
    }

    public void to(String url) {
      get(url);
    }

    public void to(URL url) {
      get(String.valueOf(url));
    }

    public void refresh() {
      int result = lib.wdRefresh(driver);
      errors.verifyErrorCode(result, "Unable to refresh current page");
    }
  }

  private class InternetExplorerOptions implements Options {

    public void addCookie(Cookie cookie) {
      StringBuilder sb = new StringBuilder(cookie.getName());
      sb.append("=").append(cookie.getValue()).append("; ");
      if (cookie.getPath() != null && !"".equals(cookie.getPath())) {
        sb.append("path=").append(cookie.getPath()).append("; ");
      }
      if (cookie.getDomain() != null && !"".equals(cookie.getDomain())) {
        String domain = cookie.getDomain();
        int colon = domain.indexOf(":");
        if (colon != -1) {
          domain = domain.substring(0, colon);
        }
        sb.append("domain=").append(domain).append("; ");
      }
      if (cookie.getExpiry() != null) {
        sb.append("expires=");
        sb.append(new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss z").format(cookie.getExpiry()));
      }

      executeScript("document.cookie = arguments[0]", sb.toString());
    }

    public void deleteAllCookies() {
      Set<Cookie> cookies = getCookies();
      for (Cookie cookie : cookies) {
        deleteCookie(cookie);
      }
    }

    public void deleteCookie(Cookie cookie) {
      if (cookie == null) {
        throw new WebDriverException("Cookie to delete cannot be null");
      }

      deleteCookieNamed(cookie.getName());
    }

    public void deleteCookieNamed(String name) {
      if (name == null) {
        throw new WebDriverException("Cookie to delete cannot be null");
      }

      int result = lib.wdDeleteCookie(driver, new WString(name));
      errors.verifyErrorCode(result, "Cannot delete cookie " + name);
    }

    public Set<Cookie> getCookies() {
      String currentUrl = getCurrentHost();

      PointerByReference wrapper = new PointerByReference();
      int result = lib.wdGetCookies(driver, wrapper);

      errors.verifyErrorCode(result, "Unable to extract visible cookies");

      Set<Cookie> toReturn = new HashSet<Cookie>();
      String allDomainCookies = new StringWrapper(lib, wrapper).toString();

      String[] cookies = allDomainCookies.split("; ");
      for (String cookie : cookies) {
        String[] parts = cookie.split("=");
        if (parts.length != 2) {
          continue;
        }

        toReturn.add(new Cookie.Builder(parts[0], parts[1])
            .domain(currentUrl)
            .path("")
            .expiresOn(null)
            .isSecure(false)
            .build());
      }

      return toReturn;
    }

    public Cookie getCookieNamed(String name) {
      Set<Cookie> allCookies = getCookies();
      for (Cookie cookie : allCookies) {
        if (name.equals(cookie.getName())) {
          return cookie;
        }
      }

      return null;
    }

    private String getCurrentHost() {
      try {
        URL url = new URL(getCurrentUrl());
        return url.getHost();
      } catch (MalformedURLException e) {
        return "";
      }
    }

    public Speed getSpeed() {
      return speed;
    }

    public void setSpeed(Speed speed) {
      InternetExplorerDriver.this.speed = speed;
    }

    public Timeouts timeouts() {
      return new InternetExplorerTimeouts();
    }
  }

  private class InternetExplorerTimeouts implements Timeouts {
    public Timeouts implicitlyWait(long time, TimeUnit unit) {
      NativeLong timeout = new NativeLong(unit.toMillis(time));
      int result = lib.wdSetImplicitWaitTimeout(driver, timeout);
      errors.verifyErrorCode(result, "Unable to set implicit wait timeout.");
      return this;
    }

    public Timeouts setScriptTimeout(long time, TimeUnit unit) {
      asyncJsExecutor.setTimeout(time, unit);
      return this;
    }
  }

  private void initializeLib() {
    synchronized (this) {
      if (lib != null) {
        return;
      }

      File parentDir = TemporaryFilesystem.createTempDir("webdriver", "libs");

      // We need to do this before calling any JNA methods because
      // the map of paths to search is static. Apparently.
      StringBuilder jnaPath = new StringBuilder(System.getProperty("jna.library.path", ""));
      jnaPath.append(File.pathSeparator);
      jnaPath.append(System.getProperty("java.class.path"));
      jnaPath.append(File.pathSeparator);
      jnaPath.append(parentDir.getAbsolutePath());
      jnaPath.append(File.pathSeparator);

      try {
        FileHandler.copyResource(parentDir, getClass(), "InternetExplorerDriver.dll");
      } catch (IOException e) {
        if (Boolean.getBoolean("webdriver.development")) {
          System.err.println(
                  "Exception unpacking required libraries, but in development mode. Continuing");
        } else {
          throw new WebDriverException(e);
        }
      }

      System.setProperty("jna.library.path", jnaPath.toString());

      try {
        lib = (ExportedWebDriverFunctions) Native.loadLibrary(
            "InternetExplorerDriver", ExportedWebDriverFunctions.class);
      } catch (UnsatisfiedLinkError e) {
        System.out.println("new File(\".\").getAbsolutePath() = " + new File(".").getAbsolutePath());
        throw new WebDriverException(e);
      }
    }
  }

  private class NullPathCookie extends Cookie {
    private final String path;

    private NullPathCookie(String name, String value, String domain, String path, Date expiry) {
      super(name, value, domain, path, expiry);
      this.path = path;
    }

    @Override
    public String getPath() {
      return path;
    }
  }
}


text:
- [Application container](#app-container)
- [Service providers](#service-providers)
- [Application events](#application-events)
- [Application helpers](#application-helpers)

## Application container

The inversion of control (IoC) container is a tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.

#### Binding a type into the container

There are two ways the IoC container can resolve dependencies: via Closure callbacks or automatic resolution. First, we'll explore Closure callbacks. First, a "type" may be bound into the container:

    App::bind('foo', function($app) {
        return new FooBar;
    });

#### Resolving a type from the container

    $value = App::make('foo');

When the `App::make` method is called, the Closure callback is executed and the result is returned.

#### Binding a "shared" type into the container

Sometimes you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

    App::singleton('foo', function() {
        return new FooBar;
    });

#### Binding an existing instance into the container

You may also bind an existing object instance into the container using the `instance` method:

    $foo = new Foo;

    App::instance('foo', $foo);

#### Binding an interface to an implementation

In some cases, a class may depend on an interface implementation, not a "concrete type". When this is the case, the `App::bind` method must be used to inform the container which interface implementation to inject:

    App::bind('UserRepositoryInterface', 'DbUserRepository');

Now consider the following code:

    $users = App::make('UserRepositoryInterface');

Since we have bound the `UserRepositoryInterface` to a concrete type, the `DbUserRepository` will automatically be injected into this controller when it is created.

### Where to register bindings

IoC bindings, like [event handlers](events), generally fall under the category of "bootstrap code". In other words, they prepare your application to actually handle requests, and usually need to be executed before a route or controller is actually called. The most common place is the `boot()` method of a [Plugin registration file](../plugin/registration#registration-methods). Alternatively, plugins can supply a file named **init.php** in the plugin directory that you can use to place IoC registration logic.

## Service providers

Service providers are a great way to create libraries and perform group related IoC registrations in a single location. Within a service provider, you might register a custom authentication driver, register your application's repository classes with the IoC container, or even setup a custom Artisan command.

In fact, [plugin registration files](../plugin/registration) inherit service providers and most of the core components include service providers. All of the registered service providers for your application are listed in the `providers` array of the `config/app.php` configuration file.

#### Defining a service provider

To create a service provider, simply extend the `October\Rain\Support\ServiceProvider` class and define a `register` method:

    use October\Rain\Support\ServiceProvider;

    class FooServiceProvider extends ServiceProvider
    {

        public function register()
        {
            $this->app->bind('foo', function() {
                return new Foo;
            });
        }

    }

Note that in the `register` method, the application IoC container is available to you via the `$this->app` property. Once you have created a provider and are ready to register it with your application, simply add it to the `providers` array in your `app` configuration file.

#### Registering a service provider at run-time

You may also register a service provider at run-time using the `App::register` method:

    App::register('FooServiceProvider');

## Application events

#### Request events

You can register special events before a requested is routed using the `before` and `after` methods:

    App::before(function ($request) {
        // Code to execute before the request is routed
    });

    App::after(function ($request) {
        // Code to execute after the request is routed
    });

#### Container events

The service container fires an event each time it resolves an object. You may listen to this event using the `resolving` method:

    App::resolving(function ($object, $app) {
        // Called when container resolves object of any type...
    });

    App::resolving('foo', function ($fooBar, $app) {
        // Called when container resolves objects using hint "foo"...
    });

    App::resolving('Acme\Blog\Classes\FooBar', function ($fooBar, $app) {
        // Called when container resolves objects of type "FooBar"...
    });

As you can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer.

## Application helpers

#### Finding the application environment

You may use the `environment` method to discover the application environment as determined by the [environment configuration](../setup/configuration#environment-config).

    // production
    App::environment();

#### Determine the execution context

It is possible to know if the current request is being performed in the administrative back-end area using the `runningInBackend` method.

    App::runningInBackend();

You may also use the `runningInConsole` method to check if the executing code is taking place inside the [command line interface](../console/commands):

    App::runningInConsole();


text:
<html>
<head>
</head>
<body>
  <p>The stable API defining Matcher and its associated interfaces and classes.
  Hamcrest sub-projects define their convenience classes in the org.hamcrest package.
  </p>
</body>
</html>


text:
'use strict';

/*
 *  Generic require login routing middleware
 */

exports.requiresLogin = function (req, res, next) {
    if (req.isAuthenticated()) return next();
    if (req.method == 'GET') req.session.returnTo = req.originalUrl;
    res.redirect('/login');
};

/*
 *  User authorization routing middleware
 */

exports.user = {
    hasAuthorization: function (req, res, next) {
        if (req.profile.id != req.user.id) {
            req.flash('info', 'You are not authorized');
            return res.redirect('/users/' + req.profile.id);
        }
        next();
    }
};

/*
 *  Article authorization routing middleware
 */

exports.article = {
    hasAuthorization: function (req, res, next) {
        if (req.article.user.id != req.user.id) {
            req.flash('info', 'You are not authorized');
            return res.redirect('/articles/' + req.article.id);
        }
        next();
    }
};

/**
 * Comment authorization routing middleware
 */

exports.comment = {
    hasAuthorization: function (req, res, next) {
        // if the current user is comment owner or article owner
        // give them authority to delete
        if (req.user.id === req.comment.user.id || req.user.id === req.article.user.id) {
            next();
        } else {
            req.flash('info', 'You are not authorized');
            res.redirect('/articles/' + req.article.id);
        }
    }
};


text:
package cl.lezorich.ok_volley.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;

/**
 * Class that implements CookieStore interface. The cookie store saves to SharedPreferences the
 * session cookie.
 *
 * The cookie is saved serializing the cookie to a json string using gson.
 *
 * Created by lukas on 04-08-14.
 */
public class PersistentCookieStore implements CookieStore {

    /**
     * The default preferences string.
     */
    private final static String PREF_DEFAULT_STRING = "";

    /**
     * The preferences name.
     */
    private final static String PREFS_NAME = PersistentCookieStore.class.getName();

    /**
     * The preferences session cookie key.
     */
    private final static String PREF_SESSION_COOKIE = "session_cookie";

    private CookieStore mStore;
    private Context mContext;
    private Gson mGson;

    public PersistentCookieStore(Context context) {
        // prevent context leaking by getting the application context
        mContext = context.getApplicationContext();
        mGson = new Gson();

        // get the default in memory store and if there is a cookie stored in shared preferences,
        // we added it to the cookie store
        mStore = new CookieManager().getCookieStore();
        String jsonSessionCookie = getJsonSessionCookieString();
        if (!jsonSessionCookie.equals(PREF_SESSION_COOKIE)) {
            HttpCookie cookie = mGson.fromJson(jsonSessionCookie, HttpCookie.class);
            mStore.add(URI.create(cookie.getDomain()), cookie);
        }
    }

    @Override
    public void add(URI uri, HttpCookie cookie) {
        if (cookie.getName().equals("sessionid")) {
            // if the cookie that the cookie store attempt to add is a session cookie,
            // we remove the older cookie and save the new one in shared preferences
            remove(URI.create(cookie.getDomain()), cookie);
            saveSessionCookie(cookie);
        }

        mStore.add(URI.create(cookie.getDomain()), cookie);
    }

    @Override
    public List<HttpCookie> get(URI uri) {
        return mStore.get(uri);
    }

    @Override
    public List<HttpCookie> getCookies() {
        return mStore.getCookies();
    }

    @Override
    public List<URI> getURIs() {
        return mStore.getURIs();
    }

    @Override
    public boolean remove(URI uri, HttpCookie cookie) {
        return mStore.remove(uri, cookie);
    }

    @Override
    public boolean removeAll() {
        return mStore.removeAll();
    }

    private String getJsonSessionCookieString() {
        return getPrefs().getString(PREF_SESSION_COOKIE, PREF_DEFAULT_STRING);
    }

    /**
     * Saves the HttpCookie to SharedPreferences as a json string.
     *
     * @param cookie The cookie to save in SharedPreferences.
     */
    private void saveSessionCookie(HttpCookie cookie) {
        String jsonSessionCookieString = mGson.toJson(cookie);
        SharedPreferences.Editor editor = getPrefs().edit();
        editor.putString(PREF_SESSION_COOKIE, jsonSessionCookieString);
        editor.apply();
    }

    private SharedPreferences getPrefs() {
        return mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
}


text:
Wordpress plugin for report errors by "ctrl + enter", has table in adminpanel and send mail notification for post author.

For custom ajax callback, add js function **nmax_report_errors_modal** in your theme, for example:

```
function nmax_report_errors_modal(response){
  $.modal({
    title: response ? "Success" : "Fail",
    description: response ? 'true' : 'false',
    close: "toggle",
    content: '<div class="report-errors-modal"></div>'
  });
}
```


text:
var async = require("async"),
    fs    = require("fs"),
   _log   = require("./log");

/**
 * Monkey patch a file.
 *
 * @param {string} filePath - path to file.
 * @param {function} monkeyPatched - function to process contents
 * @param {function} processor - TODO: detail what this is
 * @param {function} complete - callback
 *
 * @return undefined
 */
function _monkeypatch (filePath, monkeyPatched, processor, complete) {

  async.waterfall([

    function read (next) {
      fs.readFile(filePath, "utf8", next);
    },

    // TODO - need to parse gyp file - this is a bit hacker
    function monkeypatch (content, next) {

      if (monkeyPatched(content)) return complete();

      _log("monkey patch %s", filePath);
      processor(content, next);
    },

    function write (content, next) {
      fs.writeFile(filePath, content, "utf8", next);
    }
  ], complete);
}

// export the function for require()
module.exports = _monkeypatch;


text:
import pytds
import os

def main():
    conn = pytds.connect(dsn=os.getenv("HOST", "localhost"),
                         user=os.getenv("SQLUSER", "sa"),
                         password=os.getenv("SQLPASSWORD"),
                         cafile="/Users/denisenk/opensource/pytds/ca.pem",
                         enc_login_only=True)
    while True:
        try:
            sql = input("sql> ")
        except KeyboardInterrupt:
            return
        with conn.cursor() as cursor:
            try:
                cursor.execute(sql)
            except pytds.ProgrammingError as e:
                print("Error: " + str(e))
            else:
                for _, msg in cursor.messages:
                    print(msg.text)
                if cursor.description:
                    print('\t'.join(col[0] for col in cursor.description))
                    print('-' * 80)
                    count = 0
                    for row in cursor:
                        print('\t'.join(str(col) for col in row))
                        count += 1
                    print('-' * 80)
                    print("Returned {} rows".format(count))
                print()

main()


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFighter.Data
{

    public class PlayerData
    {
        [Key]
        public int Id { get; set; }
        public Guid PlayerGUID { get; set; }
        public string Name { get; set; }
    }
}


text:
This application makes use of the following third party libraries:

## Firebase

Copyright 2016 Google Inc.

## FirebaseAnalytics

Copyright 2016 Google Inc.

## FirebaseAuth

Copyright 2016 Google Inc. All Rights Reserved.

## FirebaseDatabase

Copyright 2016 Google

## FirebaseInstanceID

Copyright 2016 Google Inc.

## FirebaseRemoteConfig

Copyright 2016 Google Inc.

## FirebaseStorage

Copyright 2016 Google Inc.

## GoogleIPhoneUtilities

Copyright 2015 Google Inc.

## GoogleInterchangeUtilities

Copyright 2015 Google Inc.

## GoogleNetworkingUtilities

Copyright 2015 Google Inc.

## GoogleSymbolUtilities

Copyright 2015 Google Inc.

## GoogleUtilities

Copyright 2015 Google Inc.

## RxFirebase

<<<<<<< HEAD
Copyright (c) 2016 David Wong <neoplastic@gmail.com>
=======
The MIT License (MIT)

Copyright (c) 2016 neoplastic
>>>>>>> 7abec0c3d0e06e9543c88733a5bce615292552b8

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

<<<<<<< HEAD
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
=======
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
>>>>>>> 7abec0c3d0e06e9543c88733a5bce615292552b8

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

## RxSwift

**The MIT License**
**Copyright © 2015 Krunoslav Zaher**
**All rights reserved.**

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

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

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


text:
module Handler.Record where

import Import
import Models.Record

postRecordsR :: ReadableId -> Handler Html
postRecordsR readableId = do
  userId <- requireAuthId
  ((res, _), _) <- runFormPost $ recordForm readableId userId Nothing

  case res of
    FormSuccess record -> do
      void . runDB $ insert record
      setMessage "Reading record saved"

    _ -> setMessage "Invalid data"

  redirect $ ReadableR readableId


text:
package v1alpha1

import (
	"reflect"
	"sort"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"

	"github.com/knative/pkg/apis"
	"github.com/knative/pkg/kmeta"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Image is a Knative abstraction that encapsulates the interface by which Knative
// components express a desire to have a particular image cached.
type Image struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// Spec holds the desired state of the Image (from the client).
	// +optional
	Spec ImageSpec `json:"spec,omitempty"`

	// Status communicates the observed state of the Image (from the controller).
	// +optional
	Status ImageStatus `json:"status,omitempty"`
}

// Check that Image can be validated and defaulted.
var _ apis.Validatable = (*Image)(nil)
var _ apis.Defaultable = (*Image)(nil)
var _ kmeta.OwnerRefable = (*Image)(nil)

// ImageSpec holds the desired state of the Image (from the client).
type ImageSpec struct {

	// Image is the name of the container image url to cache across the cluster.
	Image string `json:"image"`

	// ServiceAccountName is the name of the Kubernetes ServiceAccount as which the Pods
	// will run this container.  This is potentially used to authenticate the image pull
	// if the service account has attached pull secrets.  For more information:
	// https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#add-imagepullsecrets-to-a-service-account
	// +optional
	ServiceAccountName string `json:"serviceAccountName,omitempty"`

	// ImagePullSecrets contains the names of the Kubernetes Secrets containing login
	// information used by the Pods which will run this container.
	// +optional
	ImagePullSecrets []corev1.LocalObjectReference `json:"imagePullSecrets,omitempty"`
}

// ImageConditionType is used to communicate the status of the reconciliation process.
type ImageConditionType string

const (
	// ImageConditionReady is set when the revision is starting to materialize
	// runtime resources, and becomes true when those resources are ready.
	ImageConditionReady ImageConditionType = "Ready"
)

// ImageCondition defines a readiness condition for a Image.
// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties
type ImageCondition struct {
	Type ImageConditionType `json:"type" description:"type of Image condition"`

	Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"`

	// +optional
	// We use VolatileTime in place of metav1.Time to exclude this from creating equality.Semantic
	// differences (all other things held constant).
	LastTransitionTime apis.VolatileTime `json:"lastTransitionTime,omitempty" description:"last time the condition transit from one status to another"`

	// +optional
	Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"`

	// +optional
	Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"`
}

// ImageStatus communicates the observed state of the Image (from the controller).
type ImageStatus struct {
	// Conditions communicates information about ongoing/complete
	// reconciliation processes that bring the "spec" inline with the observed
	// state of the world.
	// +optional
	Conditions []ImageCondition `json:"conditions,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ImageList is a list of Image resources
type ImageList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata"`

	Items []Image `json:"items"`
}

// IsReady looks at the conditions and if the Status has a condition
// ImageConditionReady returns true if ConditionStatus is True
func (rs *ImageStatus) IsReady() bool {
	if c := rs.GetCondition(ImageConditionReady); c != nil {
		return c.Status == corev1.ConditionTrue
	}
	return false
}

func (rs *ImageStatus) GetCondition(t ImageConditionType) *ImageCondition {
	for _, cond := range rs.Conditions {
		if cond.Type == t {
			return &cond
		}
	}
	return nil
}

func (rs *ImageStatus) SetCondition(new *ImageCondition) {
	if new == nil {
		return
	}

	t := new.Type
	var conditions []ImageCondition
	for _, cond := range rs.Conditions {
		if cond.Type != t {
			conditions = append(conditions, cond)
		} else {
			// If we'd only update the LastTransitionTime, then return.
			new.LastTransitionTime = cond.LastTransitionTime
			if reflect.DeepEqual(new, &cond) {
				return
			}
		}
	}
	new.LastTransitionTime = apis.VolatileTime{metav1.NewTime(time.Now())}
	conditions = append(conditions, *new)
	// Deterministically order the conditions
	sort.Slice(conditions, func(i, j int) bool { return conditions[i].Type < conditions[j].Type })
	rs.Conditions = conditions
}

func (rs *ImageStatus) InitializeConditions() {
	for _, cond := range []ImageConditionType{
		ImageConditionReady,
	} {
		if rc := rs.GetCondition(cond); rc == nil {
			rs.SetCondition(&ImageCondition{
				Type:   cond,
				Status: corev1.ConditionUnknown,
			})
		}
	}
}

func (i *Image) GetGroupVersionKind() schema.GroupVersionKind {
	return SchemeGroupVersion.WithKind("Image")
}


text:
//
// Note : Calibration stuffs are fully re-designed by SJ in July ~ June '15.
//

#ifndef _PLR_CALIBRATION_H_
#define _PLR_CALIBRATION_H_

#include "plr_emmc_internal_state.h"				//@sj 150702 to use processing_phase_e

typedef struct {
	s32						eod;					// tick for End of DMA
	s32 					eob;					// tick for End of BUSY
	s32 					eof;					// tick for End of CACHE FLUSH
} tick_s;

//
// Note: Now all the published calibration functions have prefix calib_
//

void 	calib_init(void);
int 	calib_make_table(void);
int 	calib_generate_internal_po_time(uint req_size);
void 	calib_print_table(void);
void 	calib_calc_ticks_min_max(s32 cnk_siz, tick_s* t);

extern processing_phase_e calib_get_last_calib_phase(void); //@sj 150702, used for calibration time calc

//
// Helper functions for cache flush
//

void calib_add_cached_write_data_size(int data_size);
uint calib_get_cached_write_size_before_flush(void);
void calib_reset_cached_write_data_size(void);

//
// Calibration common
//

int send_internal_calibration_info(int action, bool cal_test_enable); // @sj 150708

#endif


text:
<?php
namespace Neos\Flow\ResourceManagement\Storage;

use Neos\Flow\ResourceManagement\CollectionInterface;
use Neos\Flow\ResourceManagement\PersistentResource;

/**
 * Interface for a resource storage
 *
 * @api
 */
interface StorageInterface
{
    /**
     * Returns the instance name of this storage
     *
     * @return string
     * @api
     */
    public function getName();

    /**
     * Returns a stream handle which can be used internally to open / copy the given resource
     * stored in this storage.
     *
     * @param PersistentResource $resource The resource stored in this storage
     * @return resource | boolean The resource stream or FALSE if the stream could not be obtained
     * @api
     */
    public function getStreamByResource(PersistentResource $resource);

    /**
     * Returns a stream handle which can be used internally to open / copy the given resource
     * stored in this storage.
     *
     * @param string $relativePath A path relative to the storage root, for example "MyFirstDirectory/SecondDirectory/Foo.css"
     * @return resource | boolean A URI (for example the full path and filename) leading to the resource file or FALSE if it does not exist
     * @api
     */
    public function getStreamByResourcePath($relativePath);

    /**
     * Retrieve all Objects stored in this storage.
     *
     * @return \Generator<StorageObject>
     * @api
     */
    public function getObjects();

    /**
     * Retrieve all Objects stored in this storage, filtered by the given collection name
     *
     * @param CollectionInterface $collection
     * @return \Generator<StorageObject>
     * @api
     */
    public function getObjectsByCollection(CollectionInterface $collection);
}


text:
class Post < ActiveRecord::Base
  require 'tempfile'

  def self.MaxUploadSize
    102400 # 100kb
  end

  validate :valid_upload_size
  validates_presence_of :content
  validates_presence_of :content_type
  # not more content then 1MB
  validates_length_of :content, :maximum => Post.MaxUploadSize
  validates_length_of :title, :maximum => 255
  validates_length_of :author, :maximum => 255

  has_many :likedislikes, :dependent => :destroy
  has_many :likes, -> {where liked: true}, :class_name => "Likedislike"
  has_many :dislikes, -> {where liked: false},:class_name => "Likedislike"
  has_many :comments, :dependent => :destroy
  has_many :linecomments, :dependent => :destroy
  has_one :child, :class_name => "Post",
    :foreign_key => :parent_id, :dependent => :destroy
  belongs_to :parent, :class_name => "Post"

  attr_accessor :uploaded_file

  def self.file_extensions
    { '' => 'Text',
      'rb' => 'Ruby',
      'cs' => 'C#',
      'c' => 'C',
      'h' => 'C',
      'sh' => 'Shell',
      'pl' => 'Perl',
      'diff' => 'Diff',
      'patch' => 'Diff',
      'java' => 'Java',
      'js' => 'JavaScript',
      'py' => 'Python'
    }
  end

  def self.MaxPreviewLines
    10
  end

  def self.feed(last)
    self.includes(:comments, :likes, :dislikes)
      .where("created_at < ? ", last).where(:newest => true)
      .order('created_at desc').limit(20)
  end

  def collect_parent_ids
    if parent.nil?
      return [ self.id ]
    else
      return [ parent_id, self.id ] +  parent.collect_parent_ids
    end
  end

  def all_comments
    Comment.where(:post_id => self.collect_parent_ids).order('created_at desc')
  end

  def create_version(params)
    child = self.class.new(params)
    child.parent_id = self.id
    self.newest = false
    self.save
    return child
  end

  def self.new_from_file(params, data)
    new_post = self.new
    new_post.title = params[:post][:title].blank? ?
      data.original_filename : params[:post][:title]
    file_content = data.read.force_encoding("UTF-8")
    new_post.content = params[:post][:content]
    new_post.content << file_content
    new_post.content_type = get_content_type(data)
    return new_post
  end

  def valid_upload_size
    if self.content.nil?
      self.errors.add(:upload_file, "no file found")
      return
    end

    if self.content.size > Post.MaxUploadSize
      self.errors.add(:upload_file, "file too large:" +
                       " #{self.content.size / 1024} kb" +
                       " only #{Post.MaxUploadSize} allowd")
    end
  end

  def self.get_content_type(data)
    content_type = 'Text'
    content = data.read.force_encoding("UTF-8")

    Tempfile.open(['uploaded', data.original_filename.downcase],
                  Rails.root.join('tmp')) do |f|
      # set executable bits so Linguist will check for shebangs
      f.chmod(0755)
      f.print(content)
      f.flush
      unless Linguist::FileBlob.new(f.path).language.nil?
        content_type = Linguist::FileBlob.new(f.path).language.name
      end
                  end
    return content_type
  end

  def errors=(errors)
    @errors = errors
  end

  def self.search(search_string)
    return [] if search_string.blank?
    post_arel_table = Post.arel_table
    self.where(
      post_arel_table[:content].matches("%#{search_string}%").or(
      post_arel_table[:title].matches("%#{search_string}%")).or(
      post_arel_table[:author].matches("%#{search_string}%"))).
      order("#{table_name}.created_at desc").includes(:likes, :dislikes,
        :comments).references(:content)
  end

  def diff_to_parent(post_id = nil)
    post_to_diff = Post.find_by_id(post_id) || self.parent
    if post_to_diff
      Diffy::Diff.new(post_to_diff.content, self.content,
        :include_plus_and_minus_in_html => true).to_s(:html)
    else
      ""
    end
  end

  def parents
    return [] if parent_id.nil?
    return parent.parents + [parent]
  end
end


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>hello-backbonejs</title>
</head>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
  <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
  <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

  <script src="5.js"></script>
</body>
</html>


text:
<?php

namespace Omnipay\PayPal\Message;

use DateTime;
use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RequestInterface;

/**
 * PayPal Response
 *
 * @author Adrian Macneil <adrian@adrianmacneil.com>
 * @author Joao Dias <joao.dias@cherrygroup.com>
 * @license http://opensource.org/licenses/mit-license.php MIT
 */
class Response extends AbstractResponse
{
    public function __construct(RequestInterface $request, $data)
    {
        $this->request = $request;
        parse_str($data, $this->data);
    }

    public function isSuccessful()
    {
        return isset($this->data['ACK'])
            && in_array($this->data['ACK'], array('Success', 'SuccessWithWarning'));
    }

    public function getTransactionReference()
    {
        foreach (array('REFUNDTRANSACTIONID', 'TRANSACTIONID', 'PAYMENTINFO_0_TRANSACTIONID') as $key) {
            if (isset($this->data[$key])) {
                return $this->data[$key];
            }
        }
    }

    /**
     * Get the correlation ID, which uniquely identifies the transaction to PayPal.
     *
     * @return string correlation id
     */
    public function getCorrelationId()
    {
        return $this->data['CORRELATIONID'];
    }

    /**
     * Get the date and time that the requested API operation was performed.
     *
     * @return DateTime timestamp
     */
    public function getTimestamp()
    {
        return new DateTime($this->data['TIMESTAMP']);
    }

    /**
     * Get the version of the API.
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->data['VERSION'];
    }

    /**
     * Get the sub-version of the API.
     *
     * @return int
     */
    public function getVersionBuild()
    {
        return (int) $this->data['BUILD'];
    }

    /**
     * Get the payment error code.
     *
     * @return int
     */
    public function getCode()
    {
        // @todo parse list
        foreach (array('L_ERRORCODE0', 'PAYMENTREQUESTINFO_0_ERRORCODE') as $key) {
            if (isset($this->data[$key])) {
                return (int) $this->data[$key];
            }
        }
        return 0;
    }

    public function getMessage()
    {
        return isset($this->data['L_LONGMESSAGE0']) ? $this->data['L_LONGMESSAGE0'] : null;
    }
}


text:
A new, open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript. Powered by node.js and socket.io.

Learn more at [VorlonJS](http://vorlonjs.com).

## Deploy on Azure
 [![Deploy to Azure](http://azuredeploy.net/deploybutton.png)](https://azuredeploy.net/)

## Easy setup

Install and run the Vorlon.JS server from npm:

```console
$ npm i -g vorlon
$ vorlon
With the server is running, open http://localhost:1337 in your browser to see the Vorlon.JS dashboard.
```

**You may notice errors from Python, node-gyp and socket.io. This is a known issue already reported to socket.io team. This is not a blocking issue though as socket.io still works well even with this error :)**

### Custom port

[Linux]
```sh
$ PORT=3000 vorlon
```
[Windows]
```sh
c:\>SET PORT=3000 && vorlon
```
```sh
//Vorlon listening on port 3000
```

The last step is to enable Vorlon.JS by adding this to your app:

```html
<script src="http://localhost:1337/vorlon.js"></script>
```

## SSL Support

If you want to run the server with SSL support proceed as follows:

1. Install Vorlonjs following the steps in Easy Setup
2. Navigate to the installation folder
3. Modify JSON file for activation SSL support
4. In JSON file set to true
5. If you want to replace our localhost certificate should only change the path of the files with the private key and certificate
6. Exit and save JSON file

```console
[Windows]
C:\>cd %HOMEPATH%\node_modules\vorlon
C:\Users\Username\node_modules\vorlon>notepad Server/config.json

## JSON FILE ##
{
    "useSSL": true,
    "SSLkey": "server/cert/server.key",
    "SSLcert": "server/cert/server.crt",
    "includeSocketIO": true,
    "plugins": [
        { "id": "CONSOLE", "name": "Interactive Console", "panel": "bottom", "foldername" : "interactiveConsole", "enabled": true},
        { "id": "DOM", "name": "Dom Explorer", "panel": "top", "foldername" : "domExplorer", "enabled": true },
        { "id": "MODERNIZR", "name": "Modernizr","panel": "bottom", "foldername" : "modernizrReport", "enabled": true },
        { "id" : "OBJEXPLORER", "name" : "Obj. Explorer","panel": "top", "foldername" : "objectExplorer", "enabled": true },
        { "id" : "XHRPANEL", "name" : "XHR","panel": "top", "foldername" : "xhrPanel", "enabled": true },
        { "id" : "NGINSPECTOR", "name" : "ngInspector","panel": "top", "foldername" : "ngInspector", "enabled": false  }
    ]
}

C:\Users\Username\node_modules\vorlon>vorlon
Vorlon with SSL listening on port 1337

With the server is running, open https://localhost:1337 in your browser to see the Vorlon.JS dashboard.
```

The last step is to enable Vorlon.JS by adding this to your app:

```html
<script src="https://localhost:1337/vorlon.js"></script>
```

## Documentation

Read further documentation about Vorlon.JS, and writing your own plugins at [http://vorlonjs.com/documentation](http://vorlonjs.com/documentation).

## Developing on Vorlon.JS

If you wish to work on Vorlon.JS's server or core plugin code, you'll need to clone this directory and work in it.

Vorlon is written in typescript, which is compiled with gulp. There are two main directories:

* [/Server](./Server) contains the code for the vorlon server, and the dashboard code
 * [/Server/Scripts](./Server/Scripts) contains the server and dashboard code
 * [/Server/public](./Server/public) contains the dashboard files served by express web server
* [/Plugins](./Plugins) contains the code for vorlon core, and for the plugins
 *  [/Plugins/samples](./Plugins/samples) contains the sample client web page you can use to test your dashboard
 *  [/Plugins/Vorlon](./Plugins/Vorlon) contains the client infrastructure code
 *  [/Plugins/Vorlon/plugins](./Plugins/Vorlon/plugins) contains default plugins

### Compiling from source

There is a `gulpfile.js` in each of the `Plugin` and `Server` directories, which compiles gulp to typescript. In addition, [/Plugins/gulpfile.js](./Plugins/gulpfile.js) ensures that the compiled plugin code is copied in to the right place in the `Server` directory.

#### Compiling

The simplest way to run Vorlon.JS is to run `npm start` from the root directory. This will run both gulpfiles to compile typescript and start the server.

#### `gulp watch`

You can also run the gulp commands individually. This is useful if you wish to work on plugins in particular, as `gulp watch` will compile typescript for you automatically.

If you want to run `gulp` commands from command line, you will need to first install gulp globally on your system with:

```console
$ npm install -g gulp
```

You can now run `gulp watch` from the `Server` or `Plugin` directories to have gulp compile typescript to javascript automatically.

#### Plugin test page

There is a demo webpage that includes the vorlon code that you can open to test the dashboard behaviour. It lives at [./Plugins/samples/index.html](./Plugins/samples/index.html). There is a gulptask in the `Plugins` gulpfile to host it, just run `gulp webserver`, and then navigate to [http://localhost:1338/index.html](http://localhost:1338/index.html) to view the page.

### Visual Studio users

For Visual Studio users, we provide an integrated solution through VorlonJS.sln. In order to interact with Node.js, you just need to install the NodeJS Tool for Visual Studio [plugin](https://nodejstools.codeplex.com/).
Once the plugin is installed, just open the solution and you'll be ready to develop for Vorlon.js.

### Committing & Pull Requests

Once you've made a change, you can commit and submit a pull request to this repository. You will also need to electronically sign the `Microsoft Contributor License Agreement (CLA)[https://cla.microsoft.com/] if you wish for your changes to be merged.

When committing changes, ensure that compiled JavaScript files (those compiled from TypeScript) are not committed, only the original TypeScript files should be committed.

## Contributing

Read [CONTRIBUTING.md](./CONTRIBUTING.md) for more info on contributing to Vorlon.JS.

## License

Vorlon.JS is released under the MIT license. Please see [LICENSE](./LICENSE) for full details.


text:
import mari

mariGeoList = mari.geo.list()

for geo in mariGeoList:

    mariChannelList = geo.channelList()

    for channel in mariChannelList:
        SRGBtoLinearLayer = channel.createAdjustmentLayer("sRGB2Linear", "Filter/sRGB2Linear")