text:
Ever wanted an easy way to validate your API parameters and spit out clean, developer friendly error messages? Ever notice how there's no good way to do that in Rails?

Enter ApeRawr!

## Contributions

ApeRawr is an amalgamation of two awesome gems: Grape and RocketPants. This gem combines the error handling capabilities of RocketPants with the parameter validation of Grape into a single cohesive tool used for making API parameter validation easier. The maintainers of RocketPants and Grape deserve most of the credit for this gem. I just provided the glue.

## Installation

Add this line to your application's Gemfile:

    gem 'ape-rawr'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ape-rawr

## Usage

### Parameter Validation and Coercion
You can define validations and coercion options for you parameters using a params block.

```ruby
params do
  requires :id, type: Integer
  optional :text, type: String, regexp: /^[a-z]+$/
  group :media do
    requires :url
  end
end

def :create
  ...
end
```

When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.

Optional parameters can have a default value.

```ruby
params do
  options :color, type: String, default: 'blue'
end
```

Parameters can be nested using `group`. In the above example, this means `params[:media][:url]` is required along with `params[:id]`.

Validations can also be defined for a specific action.

```ruby
params :create do
  ...
end

def create
  ...
end
```

### Custom Validators

```ruby
class AlphaNumeric < Grape::Validations::Validator
  def validate_param!(attr_name, params)
    unless params[attr_name] =~ /^[[:alnum:]]+$/
      error!(:alpha_numeric_error, :attribute => attr_name)
    end
  end
end
```

```ruby
params do
  requires :text, alpha_numeric: true
end
```

You can also create custom classes that take parameters.

```ruby
class Length < Grape::Validations::SingleOptionValidator
  def validate_param!(attr_name, params)
    unless params[attr_name].length <= @option
      error!(:length_error, :attribute => attr_name, :expected_length => @option)
    end
  end
end
```

```ruby
params do
  requires :text, length: 140
end
```

### Handling Errors

One of the built in features of ApeRawr is the ability to handle rescuing / controlling exceptions and more importantly to handle mapping exceptions to names, messages and error codes.

This comes in useful when you wish to automatically convert exceptions such as `ActiveRecord::RecordNotFound` (Note: This case is handled already) to a structured bit of data in the response. Namely, it makes it trivial to generate objects that follow the JSON structure of:

```json
{
  "error":             "standard_error_name",
  "error_description": "A translated error message describing what happened."
}
```

It also adds a facilities to make it easy to add extra information to the response.

ApeRawr will also attempt to convert all errors in the controller, defaulting to the `"system"` exception name and message as the error description. We also provide a registry to allow throwing exception from their symbolic name like so:

```ruby
error! :not_found
```

In the controller.

Out of the box, the following exceptions come pre-registered and setup. For each of them, you can either use the error form (`error! :error_key) or you can raise an instance of the exception class like normal.

    Error Key
    Exception Class
    HTTP Status
    Description

    :throttled
    ApeRawr::Throttled
    503 Unavailable
    The user has hit an api throttled error.

    :unauthenticated
    ApeRawr::Unauthenticated
    401 Unauthorized
    The user doesn't have valid authentication details.

    :invalid_version
    ApeRawr::Invalidversion
    404 Not Found
    An invalid API version was specified.

    :not_implemented
    ApeRawr::NotImplemented
    503 Unavailable
    The specified endpoint is not yet implemented.

    :not_found
    ApeRawr::NotFound
    404 Not Found
    The given resource could not be found.

    :invalid_resource
    ApeRawr::InvalidResource
    422 Unprocessable Entity
    The given resource was invalid.

    :bad_request
    ApeRawr::BadRequest
    400 Bad Request
    The given request was not as expected.

    :conflict
    ApeRawr::Conflict
    409 Conflict
    The resource was a conflict with the existing version.

    :forbidden
    ApeRawr::Forbidden
    403 Forbidden
    The requested action was forbidden.

    :presence
    ApeRawr::BadRequest
    400 Bad Request
    missing parameter: %{attribute}

    :coerce
    ApeRawr::BadRequest
    400 Bad Request
    invalid parameter: %{attribute}

    :regexp
    ApeRawr::BadRequest
    400 Bad Request
    invalid parameter: %{attribute}

Note that error also excepts a Hash of contextual options, many which will be passed through to the Rails I18N subsystem. E.g:

```ruby
error! :throttled, :max_per_hour => 100
```

Will look up the translation `ape_rawr.errors.throttled` in your I18N files, and call them with `:max_per_hour` as an argument.

Finally, You can use this to also pass custom values to include in the response, e.g:

```ruby
error! :throttled, :metadata => {:code => 123}
```

Will return something similar to:

```json
{
  "error":             "throttled",
  "error_description": "The example error message goes here",
  "code":              123
}
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
import React from 'react';
import { FormattedMessage } from 'react-intl';

// Import Style
import styles from './Footer.css';

export function Footer() {
  return (

All human rights reserved

<FormattedMessage id="twitterMessage" /> : @fc_vova

  );
}

export default Footer;

redpajama_set_name: RedPajamaGithub


text:
package granulej.gui.action;

import granulej.gui.MainFrame;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class StopAction implements ActionListener {
	public MainFrame main;
	public StopAction(MainFrame m) {
		main = m;
	}

	public void runShell(String shStr) {
		try {
			//Runtime.getRuntime().exec(
					//new String[] { "/bin/sh", "-c", shStr }, null, null);
			Runtime.getRuntime().exec(
					new String[]{"cmd.exe","-c",shStr},null,null);
			main.stop();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void actionPerformed(ActionEvent arg0) {
		runShell("killall jamvm");
	}
}


text:
package ru.stqa.selenium;

import org.testng.annotations.*;

import org.openqa.selenium.*;

public class LoginTest extends TestNgTestBase {
  @Test
  public void testLogin() throws Exception {
    driver.get(baseUrl + "/php4dvd/");
    driver.findElement(By.id("username")).clear();
    driver.findElement(By.id("username")).sendKeys("admin");
    driver.findElement(By.name("password")).clear();
    driver.findElement(By.name("password")).sendKeys("admin");
    driver.findElement(By.name("submit")).click();
    driver.quit();
  }

}


text:
package org.openkilda.messaging.command.yflow;

import org.openkilda.messaging.command.CommandData;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * Represents a dump request for y-flows.
 */
@Data
@EqualsAndHashCode(callSuper = false)
@JsonNaming(SnakeCaseStrategy.class)
public class YFlowsDumpRequest extends CommandData {
    private static final long serialVersionUID = 1L;
}


text:
#pragma once

#include <depthai/pipeline/Node.hpp>

// shared
#include <depthai-shared/properties/AprilTagProperties.hpp>

#include "depthai/pipeline/datatype/AprilTagConfig.hpp"

namespace dai {
namespace node {

/**
 * @brief AprilTag node.
 */
class AprilTag : public NodeCRTP<Node, AprilTag, AprilTagProperties> {
   public:
    constexpr static const char* NAME = "AprilTag";

   protected:
    Properties& getProperties();

   private:
    std::shared_ptr<RawAprilTagConfig> rawConfig;

   public:
    AprilTag(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId);
    AprilTag(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId, std::unique_ptr<Properties> props);

    /**
     * Initial config to use when calculating spatial location data.
     */
    AprilTagConfig initialConfig;

    /**
     * Input AprilTagConfig message with ability to modify parameters in runtime.
     * Default queue is non-blocking with size 4.
     */
    Input inputConfig{*this, "inputConfig", Input::Type::SReceiver, false, 4, {{DatatypeEnum::AprilTagConfig, false}}};
    /**
     * Input message with depth data used to retrieve spatial information about detected object.
     * Default queue is non-blocking with size 4.
     */
    Input inputImage{*this, "inputImage", Input::Type::SReceiver, false, 4, {{DatatypeEnum::ImgFrame, false}}};

    /**
     * Outputs AprilTags message that carries spatial location results.
     */
    Output out{*this, "out", Output::Type::MSender, {{DatatypeEnum::AprilTags, false}}};

    /**
     * Outputs AprilTagConfig message that contains current configuration.
     */
    Output outConfig{*this, "outConfig", Output::Type::MSender, {{DatatypeEnum::AprilTagConfig, false}}};

    /**
     * Passthrough message on which the calculation was performed.
     * Suitable for when input queue is set to non-blocking behavior.
     */
    Output passthroughInputImage{*this, "passthroughInputImage", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}};

    // Functions to set properties
    /**
     * Specify whether or not wait until configuration message arrives to inputConfig Input.
     * @param wait True to wait for configuration message, false otherwise.
     */
    void setWaitForConfigInput(bool wait);
};

}  // namespace node
}  // namespace dai


text:
require 'rspec'
require_relative '../lib/paypal-ipn-forwarder/ipn'

include PaypalIpnForwarder

describe Ipn do

  before do
    @ipn = Ipn.generate
  end

  it 'identifies a unique ID for the PayPal sandbox' do
    @ipn.paypal_id.should == 'gpmac_1231902686_biz@paypal.com'
  end

  ['VERIFIED', 'INVALID', ''].each do |word|
    it "should reject IPNs which have a value of #{word}" do
      ipn = Ipn.new(word)
      ipn.ipn_valid?.should == false
    end
  end

end


text:
package org.springframework.expression.spel.ast;

/**
 * Captures primitive types and their corresponding class objects, plus one special entry
 * that represents all reference (non-primitive) types.
 *
 * @author Andy Clement
 */
public enum TypeCode {

	OBJECT(Object.class),

	BOOLEAN(Boolean.TYPE),

	BYTE(Byte.TYPE),

	CHAR(Character.TYPE),

	SHORT(Short.TYPE),

	INT(Integer.TYPE),

	LONG(Long.TYPE),

	FLOAT(Float.TYPE),

	DOUBLE(Double.TYPE);

	private Class<?> type;

	TypeCode(Class<?> type) {
		this.type = type;
	}

	public Class<?> getType() {
		return this.type;
	}

	public static TypeCode forName(String name) {
		String searchingFor = name.toUpperCase();
		TypeCode[] tcs = values();
		for (int i = 1; i < tcs.length; i++) {
			if (tcs[i].name().equals(searchingFor)) {
				return tcs[i];
			}
		}
		return TypeCode.OBJECT;
	}

	public static TypeCode forClass(Class<?> clazz) {
		TypeCode[] allValues = TypeCode.values();
		for (TypeCode typeCode : allValues) {
			if (clazz == typeCode.getType()) {
				return typeCode;
			}
		}
		return OBJECT;
	}

}


text:
/*global Dropbox */
require("../../dep/dropbox.js");

// var callbackUrl = "https://" + chrome.runtime.id + ".chromiumapp.org/";
// console.log("Requires Dropbox oauth callback URL:", callbackUrl);

var dropbox = new Dropbox.Client({
    key: "g2qi3iece6qlu2n"
});

module.exports = dropbox;


text:
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Col } from '..';

describe('Col', () => {
  it('should render default .col markup', () => {
    render(<Col data-testid="col" />);

    expect(screen.getByTestId('col')).toHaveClass('col');
  });

  it('should render children', () => {
    render(<Col data-testid="col">Children</Col>);

    expect(screen.getByText(/children/i)).toBeInTheDocument();
  });

  it('should pass additional classNames', () => {
    render(<Col className="extra" data-testid="col" />);

    expect(screen.getByTestId('col')).toHaveClass('extra');
  });

  it('should allow custom columns to be defined', () => {
    render(
      <Col widths={['base', 'jumbo']} base="4" jumbo="6" data-testid="col" />,
    );

    expect(screen.getByTestId('col')).toHaveClass('col-4');
    expect(screen.getByTestId('col')).toHaveClass('col-jumbo-6');
    expect(screen.getByTestId('col')).not.toHaveClass('col');
  });

  it('should allow custom columns to be defined with objects', () => {
    render(
      <Col
        widths={['base', 'jumbo', 'spaceship']}
        spaceship={{ size: 1, order: 2, offset: 4 }}
        data-testid="col"
      />,
    );

    expect(screen.getByTestId('col')).toHaveClass('col-spaceship-1');
    expect(screen.getByTestId('col')).toHaveClass('order-spaceship-2');
    expect(screen.getByTestId('col')).toHaveClass('offset-spaceship-4');
    expect(screen.getByTestId('col')).not.toHaveClass('col');
  });

  it('should pass col size specific classes as Strings', () => {
    render(<Col sm="6" data-testid="col" />);

    expect(screen.getByTestId('col')).toHaveClass('col-sm-6');
    expect(screen.getByTestId('col')).not.toHaveClass('col');
  });

  it('should pass col size specific classes as Numbers', () => {
    render(<Col sm={6} data-testid="col" />);

    expect(screen.getByTestId('col')).toHaveClass('col-sm-6');
    expect(screen.getByTestId('col')).not.toHaveClass('col');
  });

  it('should pass col size as flex with values "auto" or without value', () => {
    render(<Col xs="auto" sm data-testid="col" />);

    expect(screen.getByTestId('col')).not.toHaveClass('col');
    expect(screen.getByTestId('col')).toHaveClass('col-auto');
    expect(screen.getByTestId('col')).toHaveClass('col-sm');
  });

  it('should pass col size specific classes via Objects', () => {
    render(<Col sm={{ size: 6, order: 2, offset: 2 }} data-testid="col" />);

    expect(screen.getByTestId('col')).not.toHaveClass('col');
    expect(screen.getByTestId('col')).toHaveClass('col-sm-6');
    expect(screen.getByTestId('col')).toHaveClass('order-sm-2');
    expect(screen.getByTestId('col')).toHaveClass('offset-sm-2');
  });

  it('should pass col size specific classes via Objects including 0', () => {
    render(<Col sm={{ size: 6, order: 0, offset: 0 }} data-testid="col" />);

    expect(screen.getByTestId('col')).not.toHaveClass('col');
    expect(screen.getByTestId('col')).toHaveClass('col-sm-6');
    expect(screen.getByTestId('col')).toHaveClass('order-sm-0');
    expect(screen.getByTestId('col')).toHaveClass('offset-sm-0');
  });

  it('should pass col size when passing via object with size "auto"', () => {
    render(<Col sm={{ size: 'auto', offset: 2 }} data-testid="col" />);

    expect(screen.getByTestId('col')).toHaveClass('col-sm-auto');
    expect(screen.getByTestId('col')).not.toHaveClass('col');
  });

  it('should render custom tag', () => {
    render(<Col tag="main">Yo!</Col>);

    expect(screen.getByText(/yo!/i).tagName.toLowerCase()).toBe('main');
  });
});


text:
package com.reason.lang.rescript;

import com.intellij.lang.*;
import com.intellij.lexer.*;
import com.intellij.openapi.project.*;
import com.intellij.psi.*;
import com.intellij.psi.tree.*;
import com.reason.ide.files.*;
import com.reason.lang.core.stub.type.*;
import org.jetbrains.annotations.*;

public class ResParserDefinition implements ParserDefinition {
    @Override
    public @NotNull Lexer createLexer(Project project) {
        return new ResLexer();
    }

    public @NotNull TokenSet getWhitespaceTokens() {
        return TokenSet.create(TokenType.WHITE_SPACE);
    }

    public @NotNull TokenSet getCommentTokens() {
        return TokenSet.create(ResTypes.INSTANCE.MULTI_COMMENT, ResTypes.INSTANCE.SINGLE_COMMENT);
    }

    public @NotNull TokenSet getStringLiteralElements() {
        return TokenSet.create(ResTypes.INSTANCE.STRING_VALUE);
    }

    public @NotNull PsiParser createParser(Project project) {
        return new ResParser(false);
    }

    @Override
    public @NotNull IFileElementType getFileNodeType() {
        return ResFileStubElementType.INSTANCE;
    }

    public @NotNull PsiFile createFile(@NotNull FileViewProvider viewProvider) {
        return viewProvider.getFileType() instanceof ResInterfaceFileType
                ? new ResInterfaceFile(viewProvider)
                : new ResFile(viewProvider);
    }

    public @NotNull SpaceRequirements spaceExistenceTypeBetweenTokens(ASTNode left, ASTNode right) {
        return SpaceRequirements.MAY;
    }

    public @NotNull PsiElement createElement(@NotNull ASTNode node) {
        IElementType type = node.getElementType();
        if (type instanceof ORStubElementType) {
            //noinspection rawtypes
            return ((ORStubElementType) node.getElementType()).createPsi(node);
        }

        throw new IllegalArgumentException("Not a Rescript node: " + node + " (" + type + ", " + type.getLanguage() + ")");
    }
}


text:
const runningOnBrowser = typeof window !== "undefined";

const isBot =
    (runningOnBrowser && !("onscroll" in window)) ||
    (typeof navigator !== "undefined" && /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent));

const supportsIntersectionObserver = runningOnBrowser && "IntersectionObserver" in window;

const supportsClassList = runningOnBrowser && "classList" in document.createElement("p");

const isHiDpi = runningOnBrowser && window.devicePixelRatio > 1;

const defaultSettings = {
    elements_selector: ".lazy",
    container: isBot || runningOnBrowser ? document : null,
    threshold: 300,
    thresholds: null,
    data_src: "src",
    data_srcset: "srcset",
    data_sizes: "sizes",
    data_bg: "bg",
    data_bg_hidpi: "bg-hidpi",
    data_bg_multi: "bg-multi",
    data_bg_multi_hidpi: "bg-multi-hidpi",
    data_bg_set: "bg-set",
    data_poster: "poster",
    class_applied: "applied",
    class_loading: "loading",
    class_loaded: "loaded",
    class_error: "error",
    class_entered: "entered",
    class_exited: "exited",
    unobserve_completed: true,
    unobserve_entered: false,
    cancel_on_exit: true,
    callback_enter: null,
    callback_exit: null,
    callback_applied: null,
    callback_loading: null,
    callback_loaded: null,
    callback_error: null,
    callback_finish: null,
    callback_cancel: null,
    use_native: false,
    restore_on_error: false,
};

const getExtendedSettings = (customSettings) => {
    return Object.assign({}, defaultSettings, customSettings);
};

/* Creates instance and notifies it through the window element */
const createInstance = function(classObj, options) {
    let event;
    const eventString = "LazyLoad::Initialized";
    const instance = new classObj(options);
    try {
        // Works in modern browsers
        event = new CustomEvent(eventString, { detail: { instance } });
    } catch (err) {
        // Works in Internet Explorer (all versions)
        event = document.createEvent("CustomEvent");
        event.initCustomEvent(eventString, false, false, { instance });
    }
    window.dispatchEvent(event);
};

/* Auto initialization of one or more instances of lazyload, depending on the
    options passed in (plain object or an array) */
const autoInitialize = (classObj, options) => {
    if (!options) {
        return;
    }
    if (!options.length) {
        // Plain object
        createInstance(classObj, options);
    } else {
        // Array of objects
        for (let i = 0, optionsItem; (optionsItem = options[i]); i += 1) {
            createInstance(classObj, optionsItem);
        }
    }
};

const SRC = "src";
const SRCSET = "srcset";
const SIZES = "sizes";
const POSTER = "poster";
const ORIGINALS = "llOriginalAttrs";
const DATA = "data";

const statusLoading = "loading";
const statusLoaded = "loaded";
const statusApplied = "applied";
const statusEntered = "entered";
const statusError = "error";
const statusNative = "native";

const dataPrefix = "data-";
const statusDataName = "ll-status";

const getData = (element, attribute) => {
    return element.getAttribute(dataPrefix + attribute);
};

const setData = (element, attribute, value) => {
    var attrName = dataPrefix + attribute;
    if (value === null) {
        element.removeAttribute(attrName);
        return;
    }
    element.setAttribute(attrName, value);
};

const getStatus = (element) => getData(element, statusDataName);
const setStatus = (element, status) => setData(element, statusDataName, status);
const resetStatus = (element) => setStatus(element, null);

const hasEmptyStatus = (element) => getStatus(element) === null;
const hasStatusLoading = (element) => getStatus(element) === statusLoading;
const hasStatusError = (element) => getStatus(element) === statusError;
const hasStatusNative = (element) => getStatus(element) === statusNative;

const statusesAfterLoading = [statusLoading, statusLoaded, statusApplied, statusError];
const hadStartedLoading = (element) => statusesAfterLoading.indexOf(getStatus(element)) >= 0;

const safeCallback = (callback, arg1, arg2, arg3) => {
	if (!callback) {
		return;
	}

	if (arg3 !== undefined) {
		callback(arg1, arg2, arg3);
		return;
	}
	if (arg2 !== undefined) {
		callback(arg1, arg2);
		return;
	}
	callback(arg1);
};

const addClass = (element, className) => {
	if (supportsClassList) {
		element.classList.add(className);
		return;
	}
	element.className += (element.className ? " " : "") + className;
};

const removeClass = (element, className) => {
	if (supportsClassList) {
		element.classList.remove(className);
		return;
	}
	element.className = element.className.
		replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " ").
		replace(/^\s+/, "").
		replace(/\s+$/, "");
};

const addTempImage = (element) => {
    element.llTempImage = document.createElement("IMG");
};

const deleteTempImage = (element) => {
    delete element.llTempImage;
};

const getTempImage = (element) => element.llTempImage;

const unobserve = (element, instance) => {
    if (!instance) return;
    const observer = instance._observer;
    if (!observer) return;
    observer.unobserve(element);
};

const resetObserver = (observer) => {
    observer.disconnect();
};

const unobserveEntered = (element, settings, instance) => {
    if (settings.unobserve_entered) unobserve(element, instance);
};

const updateLoadingCount = (instance, delta) => {
    if (!instance) return;
    instance.loadingCount += delta;
};

const decreaseToLoadCount = (instance) => {
    if (!instance) return;
    instance.toLoadCount -= 1;
};

const setToLoadCount = (instance, value) => {
    if (!instance) return;
    instance.toLoadCount = value;
};

const isSomethingLoading = (instance) => instance.loadingCount > 0;

const haveElementsToLoad = (instance) => instance.toLoadCount > 0;

const getSourceTags = (parentTag) => {
  let sourceTags = [];
  for (let i = 0, childTag; (childTag = parentTag.children[i]); i += 1) {
      if (childTag.tagName === "SOURCE") {
          sourceTags.push(childTag);
      }
  }
  return sourceTags;
};

const forEachPictureSource = (element, fn) => {
  const parent = element.parentNode;
  if (!parent || parent.tagName !== "PICTURE") {
      return;
  }
  let sourceTags = getSourceTags(parent);
  sourceTags.forEach(fn);
};

const forEachVideoSource = (element, fn) => {
  let sourceTags = getSourceTags(element);
  sourceTags.forEach(fn);
};

const attrsSrc = [SRC];
const attrsSrcPoster = [SRC, POSTER];
const attrsSrcSrcsetSizes = [SRC, SRCSET, SIZES];
const attrsData = [DATA];

const hasOriginalAttrs = (element) => !!element[ORIGINALS];
const getOriginalAttrs = (element) => element[ORIGINALS];
const deleteOriginalAttrs = (element) => delete element[ORIGINALS];

// ## SAVE ##

const setOriginalsObject = (element, attributes) => {
    if (hasOriginalAttrs(element)) {
        return;
    }
    const originals = {};
    attributes.forEach((attribute) => {
        originals[attribute] = element.getAttribute(attribute);
    });
    element[ORIGINALS] = originals;
};

const saveOriginalBackgroundStyle = (element) => {
    if (hasOriginalAttrs(element)) {
        return;
    }
    element[ORIGINALS] = { backgroundImage: element.style.backgroundImage };
};

// ## RESTORE ##

const setOrResetAttribute = (element, attrName, value) => {
    if (!value) {
        element.removeAttribute(attrName);
        return;
    }
    element.setAttribute(attrName, value);
};

const restoreOriginalAttrs = (element, attributes) => {
    if (!hasOriginalAttrs(element)) {
        return;
    }
    const originals = getOriginalAttrs(element);
    attributes.forEach((attribute) => {
        setOrResetAttribute(element, attribute, originals[attribute]);
    });
};

const restoreOriginalBgImage = (element) => {
    if (!hasOriginalAttrs(element)) {
        return;
    }
    const originals = getOriginalAttrs(element);
    element.style.backgroundImage = originals.backgroundImage;
};

const manageApplied = (element, settings, instance) => {
    addClass(element, settings.class_applied);
    setStatus(element, statusApplied);
    // Instance is not provided when loading is called from static class
    if (!instance) return;
    if (settings.unobserve_completed) {
        // Unobserve now because we can't do it on load
        unobserve(element, settings);
    }
    safeCallback(settings.callback_applied, element, instance);
};

const manageLoading = (element, settings, instance) => {
    addClass(element, settings.class_loading);
    setStatus(element, statusLoading);
    // Instance is not provided when loading is called from static class
    if (!instance) return;
    updateLoadingCount(instance, +1);
    safeCallback(settings.callback_loading, element, instance);
};

const setAttributeIfValue = (element, attrName, value) => {
    if (!value) {
        return;
    }
    element.setAttribute(attrName, value);
};

const setImageAttributes = (element, settings) => {
    setAttributeIfValue(element, SIZES, getData(element, settings.data_sizes));
    setAttributeIfValue(element, SRCSET, getData(element, settings.data_srcset));
    setAttributeIfValue(element, SRC, getData(element, settings.data_src));
};

const setSourcesImg = (imgEl, settings) => {
    forEachPictureSource(imgEl, (sourceTag) => {
        setOriginalsObject(sourceTag, attrsSrcSrcsetSizes);
        setImageAttributes(sourceTag, settings);
    });
    setOriginalsObject(imgEl, attrsSrcSrcsetSizes);
    setImageAttributes(imgEl, settings);
};

const setSourcesIframe = (iframe, settings) => {
    setOriginalsObject(iframe, attrsSrc);
    setAttributeIfValue(iframe, SRC, getData(iframe, settings.data_src));
};

const setSourcesVideo = (videoEl, settings) => {
    forEachVideoSource(videoEl, (sourceEl) => {
        setOriginalsObject(sourceEl, attrsSrc);
        setAttributeIfValue(sourceEl, SRC, getData(sourceEl, settings.data_src));
    });
    setOriginalsObject(videoEl, attrsSrcPoster);

    setAttributeIfValue(videoEl, POSTER, getData(videoEl, settings.data_poster));
    setAttributeIfValue(videoEl, SRC, getData(videoEl, settings.data_src));
    videoEl.load();
};

const setSourcesObject = (object, settings) => {
    setOriginalsObject(object, attrsData);
    setAttributeIfValue(object, DATA, getData(object, settings.data_src));
};

const setBackground = (element, settings, instance) => {
    const bg1xValue = getData(element, settings.data_bg);
    const bgHiDpiValue = getData(element, settings.data_bg_hidpi);
    const bgDataValue = isHiDpi && bgHiDpiValue ? bgHiDpiValue : bg1xValue;
    if (!bgDataValue) return;
    element.style.backgroundImage = `url("${bgDataValue}")`;
    getTempImage(element).setAttribute(SRC, bgDataValue);
    manageLoading(element, settings, instance);
};

// NOTE: THE TEMP IMAGE TRICK CANNOT BE DONE WITH data-multi-bg
// BECAUSE INSIDE ITS VALUES MUST BE WRAPPED WITH URL() AND ONE OF THEM
// COULD BE A GRADIENT BACKGROUND IMAGE
const setMultiBackground = (element, settings, instance) => {
    const bg1xValue = getData(element, settings.data_bg_multi);
    const bgHiDpiValue = getData(element, settings.data_bg_multi_hidpi);
    const bgDataValue = isHiDpi && bgHiDpiValue ? bgHiDpiValue : bg1xValue;
    if (!bgDataValue) {
        return;
    }
    element.style.backgroundImage = bgDataValue;
    manageApplied(element, settings, instance);
};

const setImgsetBackground = (element, settings, instance) => {
    const bgImgSetDataValue = getData(element, settings.data_bg_set);
    if (!bgImgSetDataValue) {
        return;
    }
    const imgSetValues = bgImgSetDataValue.split("|");
    let bgImageValues = imgSetValues.map((value) => `image-set(${value})`);
    element.style.backgroundImage = bgImageValues.join();
    // Temporary fix for Chromeium with the -webkit- prefix
    if (element.style.backgroundImage === '') {
        bgImageValues = imgSetValues.map((value) => `-webkit-image-set(${value})`);
        element.style.backgroundImage = bgImageValues.join();
    }
    manageApplied(element, settings, instance);
};

const setSourcesFunctions = {
    IMG: setSourcesImg,
    IFRAME: setSourcesIframe,
    VIDEO: setSourcesVideo,
    OBJECT: setSourcesObject
};

const setSourcesNative = (element, settings) => {
    const setSourcesFunction = setSourcesFunctions[element.tagName];
    if (!setSourcesFunction) {
        return;
    }
    setSourcesFunction(element, settings);
};

const setSources = (element, settings, instance) => {
    const setSourcesFunction = setSourcesFunctions[element.tagName];
    if (!setSourcesFunction) {
        return;
    }
    setSourcesFunction(element, settings);
    manageLoading(element, settings, instance);
};

const elementsWithLoadEvent = ["IMG", "IFRAME", "VIDEO", "OBJECT"];
const hasLoadEvent = (element) => elementsWithLoadEvent.indexOf(element.tagName) > -1;

const checkFinish = (settings, instance) => {
    if (instance && !isSomethingLoading(instance) && !haveElementsToLoad(instance)) {
        safeCallback(settings.callback_finish, instance);
    }
};

const addEventListener = (element, eventName, handler) => {
    element.addEventListener(eventName, handler);
    element.llEvLisnrs[eventName] = handler;
};

const removeEventListener = (element, eventName, handler) => {
    element.removeEventListener(eventName, handler);
};

const hasEventListeners = (element) => {
    return !!element.llEvLisnrs;
};

const addEventListeners = (element, loadHandler, errorHandler) => {
    if (!hasEventListeners(element)) element.llEvLisnrs = {};
    const loadEventName = element.tagName === "VIDEO" ? "loadeddata" : "load";
    addEventListener(element, loadEventName, loadHandler);
    addEventListener(element, "error", errorHandler);
};

const removeEventListeners = (element) => {
    if (!hasEventListeners(element)) {
        return;
    }
    const eventListeners = element.llEvLisnrs;
    for (let eventName in eventListeners) {
        const handler = eventListeners[eventName];
        removeEventListener(element, eventName, handler);
    }
    delete element.llEvLisnrs;
};

const doneHandler = (element, settings, instance) => {
    deleteTempImage(element);
    updateLoadingCount(instance, -1);
    decreaseToLoadCount(instance);
    removeClass(element, settings.class_loading);
    if (settings.unobserve_completed) {
        unobserve(element, instance);
    }
};

const loadHandler = (event, element, settings, instance) => {
    const goingNative = hasStatusNative(element);
    doneHandler(element, settings, instance);
    addClass(element, settings.class_loaded);
    setStatus(element, statusLoaded);
    safeCallback(settings.callback_loaded, element, instance);
    if (!goingNative) checkFinish(settings, instance);
};

const errorHandler = (event, element, settings, instance) => {
    const goingNative = hasStatusNative(element);
    doneHandler(element, settings, instance);
    addClass(element, settings.class_error);
    setStatus(element, statusError);
    safeCallback(settings.callback_error, element, instance);
    if (settings.restore_on_error) restoreOriginalAttrs(element, attrsSrcSrcsetSizes);
    if (!goingNative) checkFinish(settings, instance);
};

const addOneShotEventListeners = (element, settings, instance) => {
    const elementToListenTo = getTempImage(element) || element;
    if (hasEventListeners(elementToListenTo)) {
        // This happens when loading is retried twice
        return;
    }
    const _loadHandler = (event) => {
        loadHandler(event, element, settings, instance);
        removeEventListeners(elementToListenTo);
    };
    const _errorHandler = (event) => {
        errorHandler(event, element, settings, instance);
        removeEventListeners(elementToListenTo);
    };
    addEventListeners(elementToListenTo, _loadHandler, _errorHandler);
};

const loadBackground = (element, settings, instance) => {
    addTempImage(element);
    addOneShotEventListeners(element, settings, instance);
    saveOriginalBackgroundStyle(element);
    setBackground(element, settings, instance);
    setMultiBackground(element, settings, instance);
    setImgsetBackground(element, settings, instance);
};

const loadRegular = (element, settings, instance) => {
    addOneShotEventListeners(element, settings, instance);
    setSources(element, settings, instance);
};

const load = (element, settings, instance) => {
    if (hasLoadEvent(element)) {
        loadRegular(element, settings, instance);
    } else {
        loadBackground(element, settings, instance);
    }
};

const loadNative = (element, settings, instance) => {
    element.setAttribute("loading", "lazy");
    addOneShotEventListeners(element, settings, instance);
    setSourcesNative(element, settings);
    setStatus(element, statusNative);
};

const removeImageAttributes = (element) => {
    element.removeAttribute(SRC);
    element.removeAttribute(SRCSET);
    element.removeAttribute(SIZES);
};

const resetSourcesImg = (element) => {
    forEachPictureSource(element, (sourceTag) => {
        removeImageAttributes(sourceTag);
    });
    removeImageAttributes(element);
};

const restoreImg = (imgEl) => {
    forEachPictureSource(imgEl, (sourceEl) => {
        restoreOriginalAttrs(sourceEl, attrsSrcSrcsetSizes);
    });
    restoreOriginalAttrs(imgEl, attrsSrcSrcsetSizes);
};

const restoreVideo = (videoEl) => {
    forEachVideoSource(videoEl, (sourceEl) => {
        restoreOriginalAttrs(sourceEl, attrsSrc);
    });
    restoreOriginalAttrs(videoEl, attrsSrcPoster);
    videoEl.load();
};

const restoreIframe = (iframeEl) => {
    restoreOriginalAttrs(iframeEl, attrsSrc);
};

const restoreObject = (objectEl) => {
    restoreOriginalAttrs(objectEl, attrsData);
};

const restoreFunctions = {
    IMG: restoreImg,
    IFRAME: restoreIframe,
    VIDEO: restoreVideo,
    OBJECT: restoreObject
};

const restoreAttributes = (element) => {
    const restoreFunction = restoreFunctions[element.tagName];
    if (!restoreFunction) {
        restoreOriginalBgImage(element);
        return;
    }
    restoreFunction(element);
};

const resetClasses = (element, settings) => {
    if (hasEmptyStatus(element) || hasStatusNative(element)) {
        return;
    }
    removeClass(element, settings.class_entered);
    removeClass(element, settings.class_exited);
    removeClass(element, settings.class_applied);
    removeClass(element, settings.class_loading);
    removeClass(element, settings.class_loaded);
    removeClass(element, settings.class_error);
};

const restore = (element, settings) => {
    restoreAttributes(element);
    resetClasses(element, settings);
    resetStatus(element);
    deleteOriginalAttrs(element);
};

const cancelLoading = (element, entry, settings, instance) => {
    if (!settings.cancel_on_exit) return;
    if (!hasStatusLoading(element)) return;
    if (element.tagName !== "IMG") return; //Works only on images
    removeEventListeners(element);
    resetSourcesImg(element);
    restoreImg(element);
    removeClass(element, settings.class_loading);
    updateLoadingCount(instance, -1);
    resetStatus(element);
    safeCallback(settings.callback_cancel, element, entry, instance);
};

const onEnter = (element, entry, settings, instance) => {
    const dontLoad = hadStartedLoading(element); /* Save status
        before setting it, to prevent loading it again. Fixes #526. */
    setStatus(element, statusEntered);
    addClass(element, settings.class_entered);
    removeClass(element, settings.class_exited);
    unobserveEntered(element, settings, instance);
    safeCallback(settings.callback_enter, element, entry, instance);
    if (dontLoad) return;
    load(element, settings, instance);
};

const onExit = (element, entry, settings, instance) => {
    if (hasEmptyStatus(element)) return; //Ignore the first pass, at landing
    addClass(element, settings.class_exited);
    cancelLoading(element, entry, settings, instance);
    safeCallback(settings.callback_exit, element, entry, instance);
};

const tagsWithNativeLazy = ["IMG", "IFRAME", "VIDEO"];

const shouldUseNative = (settings) =>
    settings.use_native && "loading" in HTMLImageElement.prototype;

const loadAllNative = (elements, settings, instance) => {
    elements.forEach((element) => {
        if (tagsWithNativeLazy.indexOf(element.tagName) === -1) {
            return;
        }
        loadNative(element, settings, instance);
    });
    setToLoadCount(instance, 0);
};

const isIntersecting = (entry) => entry.isIntersecting || entry.intersectionRatio > 0;

const getObserverSettings = (settings) => ({
    root: settings.container === document ? null : settings.container,
    rootMargin: settings.thresholds || settings.threshold + "px"
});

const intersectionHandler = (entries, settings, instance) => {
    entries.forEach((entry) =>
        isIntersecting(entry)
            ? onEnter(entry.target, entry, settings, instance)
            : onExit(entry.target, entry, settings, instance)
    );
};

const observeElements = (observer, elements) => {
    elements.forEach((element) => {
        observer.observe(element);
    });
};

const updateObserver = (observer, elementsToObserve) => {
    resetObserver(observer);
    observeElements(observer, elementsToObserve);
};

const setObserver = (settings, instance) => {
    if (!supportsIntersectionObserver || shouldUseNative(settings)) {
        return;
    }
    instance._observer = new IntersectionObserver((entries) => {
        intersectionHandler(entries, settings, instance);
    }, getObserverSettings(settings));
};

const toArray = (nodeSet) => Array.prototype.slice.call(nodeSet);

const queryElements = (settings) =>
    settings.container.querySelectorAll(settings.elements_selector);

const excludeManagedElements = (elements) => toArray(elements).filter(hasEmptyStatus);

const hasError = (element) => hasStatusError(element);
const filterErrorElements = (elements) => toArray(elements).filter(hasError);

const getElementsToLoad = (elements, settings) =>
    excludeManagedElements(elements || queryElements(settings));

const retryLazyLoad = (settings, instance) => {
    const errorElements = filterErrorElements(queryElements(settings));
    errorElements.forEach((element) => {
        removeClass(element, settings.class_error);
        resetStatus(element);
    });
    instance.update();
};

const setOnlineCheck = (settings, instance) => {
    if (!runningOnBrowser) {
        return;
    }
    instance._onlineHandler = () => {
        retryLazyLoad(settings, instance);
    };
    window.addEventListener("online", instance._onlineHandler);
};

const resetOnlineCheck = (instance) => {
    if (!runningOnBrowser) {
        return;
    }
    window.removeEventListener("online", instance._onlineHandler);
};

const LazyLoad = function (customSettings, elements) {
    const settings = getExtendedSettings(customSettings);
    this._settings = settings;
    this.loadingCount = 0;
    setObserver(settings, this);
    setOnlineCheck(settings, this);
    this.update(elements);
};

LazyLoad.prototype = {
    update: function (givenNodeset) {
        const settings = this._settings;
        const elementsToLoad = getElementsToLoad(givenNodeset, settings);
        setToLoadCount(this, elementsToLoad.length);

        if (isBot || !supportsIntersectionObserver) {
            this.loadAll(elementsToLoad);
            return;
        }
        if (shouldUseNative(settings)) {
            loadAllNative(elementsToLoad, settings, this);
            return;
        }

        updateObserver(this._observer, elementsToLoad);
    },

    destroy: function () {
        // Observer
        if (this._observer) {
            this._observer.disconnect();
        }
        // Clean handlers
        resetOnlineCheck(this);
        // Clean custom attributes on elements
        queryElements(this._settings).forEach((element) => {
            deleteOriginalAttrs(element);
        });
        // Delete all internal props
        delete this._observer;
        delete this._settings;
        delete this._onlineHandler;
        delete this.loadingCount;
        delete this.toLoadCount;
    },

    loadAll: function (elements) {
        const settings = this._settings;
        const elementsToLoad = getElementsToLoad(elements, settings);
        elementsToLoad.forEach((element) => {
            unobserve(element, this);
            load(element, settings, this);
        });
    },

    restoreAll: function() {
        const settings = this._settings;
        queryElements(settings).forEach((element) => {
            restore(element, settings);
        });
    }
};

LazyLoad.load = (element, customSettings) => {
    const settings = getExtendedSettings(customSettings);
    load(element, settings);
};

LazyLoad.resetStatus = (element) => {
    resetStatus(element);
};

// Automatic instances creation if required (useful for async script loading)
if (runningOnBrowser) {
    autoInitialize(LazyLoad, window.lazyLoadOptions);
}

export { LazyLoad as default };


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AxosoftAPI.NET.Models
{
	public class Item : BaseModel
	{
		[JsonProperty("number")]
		public string Number { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("customer")]
		public Customer Customer { get; set; }

		[JsonProperty("description")]
		public string Description { get; set; }

		[JsonProperty("notes")]
		public string Notes { get; set; }

		[JsonProperty("resolution")]
		public string Resolution { get; set; }

		[JsonProperty("replication_procedures")]
		public string ReplicationProcedures { get; set; }

		[JsonProperty("percent_complete")]
		public int? PercentComplete { get; set; }

		[JsonProperty("archived")]
		public bool? Archived { get; set; }

		[JsonProperty("publicly_viewable")]
		public bool? PubliclyViewable { get; set; }

		[JsonProperty("is_completed")]
		public bool? IsCompleted { get; set; }

		[JsonProperty("completion_date")]
		public DateTime? CompletionDate { get; set; }

		[JsonProperty("due_date")]
		public DateTime? DueDate { get; set; }

		[JsonProperty("reported_date")]
		public DateTime? ReportedDate { get; set; }

		[JsonProperty("start_date")]
		public DateTime? StartDate { get; set; }

		[JsonProperty("assigned_to")]
		public Assignee AssignedTo { get; set; }

		[JsonProperty("priority")]
		public Priority Priority { get; set; }

		[JsonProperty("project")]
		public Project Project { get; set; }

		[JsonProperty("release")]
		public Release Release { get; set; }

		[JsonProperty("reported_by")]
		public User ReportedBy { get; set; }

		[JsonProperty("reported_by_customer_contact")]
		public Contact ReportedByCustomerContact { get; set; }

		[JsonProperty("status")]
		public Status Status { get; set; }

		[JsonProperty("severity")]
		public Severity Severity { get; set; }

		[JsonProperty("category")]
		public Category Category { get; set; }

		[JsonProperty("escalation_level")]
		public Escalation EscalationLevel { get; set; }

		[JsonProperty("actual_duration")]
		public DurationUnit ActualDuration { get; set; }

		[JsonProperty("estimated_duration")]
		public DurationUnit EstimatedDuration { get; set; }

		[JsonProperty("remaining_duration")]
		public DurationUnit RemainingDuration { get; set; }

		[JsonProperty("custom_fields")]
		public IDictionary<string, object> CustomFields { get; set; }

		[JsonProperty("parent")]
		public Item Parent { get; set; }

		[JsonProperty("item_type")]
		public string ItemType { get; set; }

		[JsonProperty("build_number")]
		public string BuildNumber { get; set; }

		[JsonProperty("build_number_of_fix")]
		public string BuildNumberOfFix { get; set; }

		[JsonProperty("workflow_step")]
		public WorkflowStep WorkflowStep { get; set; }

        [JsonProperty("comments")]
        public Total Comments { get; set; }

        [JsonProperty("subitems")]
        public Total SubItems { get; set; }

        [JsonProperty("notifications")]
        public Total Notifications { get; set; }

        [JsonProperty("related_items")]
        public Total RelatedItmes { get; set; }

        [JsonProperty("emails")]
        public Total Emails { get; set; }

        [JsonProperty("work_logs")]
        public Total WorkLogs { get; set; }

        [JsonProperty("attachments")]
        public Total Attachments { get; set; }

        [JsonProperty("zendesk_tickets")]
        public Total ZendeskTickets { get; set; }
    }
}


text:
@extends('app')

@section('header')

Team ("

@stop

@section('content')

this is our game called '{{ $stuff['Game_Name'] }}' and stuff

and by 'our' we mean:

	@forelse ($stuff['Authors'] as $author)

{{$author}}

	@empty

NOBODY OMG NO ONE

	@endforelse

I'm actually just making sure routing works and being waay too verbose

aaand that was Truck's lesson in 'oh yeah this is how css works' for today

@stop

@section('footer')

this is totally taking too much time go code something

@stop


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.30  08/16/14            */
   /*                                                     */
   /*             EXPRESSION OPERATIONS MODULE            */
   /*******************************************************/

/*************************************************************/
/* Purpose: Provides utility routines for manipulating and   */
/*   examining expressions.                                  */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*      6.24: Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*      6.30: Add NegateExpression function.                 */
/*                                                           */
/*            Added const qualifiers to remove C++           */
/*            deprecation warnings.                          */
/*                                                           */
/*************************************************************/

#define _EXPRNOPS_SOURCE_

#include "setup.h"

#include <stdio.h>
#define _STDIO_INCLUDED_
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "memalloc.h"
#include "envrnmnt.h"
#include "router.h"
#include "extnfunc.h"
#include "cstrnchk.h"
#include "prntutil.h"
#include "cstrnutl.h"
#include "cstrnops.h"

#include "exprnops.h"

#if (! RUN_TIME)

/**************************************************************/
/* CheckArgumentAgainstRestriction: Compares an argument to a */
/*   function to the set of restrictions for that function to */
/*   determine if any incompatibilities exist. If so, the     */
/*   value TRUE is returned, otherwise FALSE is returned.     */
/*   Restrictions checked are:                                */
/*     a - external address                                   */
/*     d - float                                              */
/*     e - instance address, instance name, or symbol         */
/*     f - float                                              */
/*     g - integer, float, or symbol                          */
/*     h - instance address, instance name, fact address,     */
/*         integer, or symbol                                 */
/*     i - integer                                            */
/*     j - symbol, string, or instance name                   */
/*     k - symbol or string                                   */
/*     l - integer                                            */
/*     m - multifield                                         */
/*     n - float or integer                                   */
/*     o - instance name                                      */
/*     p - instance name or symbol                            */
/*     q - string, symbol, or multifield                      */
/*     s - string                                             */
/*     u - unknown (any type allowed)                         */
/*     w - symbol                                             */
/*     x - instance address                                   */
/*     y - fact address                                       */
/*     z - fact address, integer, or symbol (*)               */
/**************************************************************/
globle int CheckArgumentAgainstRestriction(
  void *theEnv,
  struct expr *theExpression,
  int theRestriction)
  {
   CONSTRAINT_RECORD *cr1, *cr2, *cr3;

   /*=============================================*/
   /* Generate a constraint record for the actual */
   /* argument passed to the function.            */
   /*=============================================*/

   cr1 = ExpressionToConstraintRecord(theEnv,theExpression);

   /*================================================*/
   /* Generate a constraint record based on the type */
   /* of argument expected by the function.          */
   /*================================================*/

   cr2 = ArgumentTypeToConstraintRecord(theEnv,theRestriction);

   /*===============================================*/
   /* Intersect the two constraint records and then */
   /* discard them.                                 */
   /*===============================================*/

   cr3 = IntersectConstraints(theEnv,cr1,cr2);

   RemoveConstraint(theEnv,cr1);
   RemoveConstraint(theEnv,cr2);

   /*====================================================*/
   /* If the intersection of the two constraint records  */
   /* is empty, then the argument passed to the function */
   /* doesn't satisfy the restrictions for the argument. */
   /*====================================================*/

   if (UnmatchableConstraint(cr3))
     {
      RemoveConstraint(theEnv,cr3);
      return(TRUE);
     }

   /*===================================================*/
   /* The argument satisfies the function restrictions. */
   /*===================================================*/

   RemoveConstraint(theEnv,cr3);
   return(FALSE);
  }

#endif /* (! RUN_TIME) */

/************************************************************/
/* ConstantExpression: Returns TRUE if the expression */
/*   is a constant, otherwise FALSE.                  */
/************************************************************/
globle intBool ConstantExpression(
  struct expr *testPtr)
  {
   while (testPtr != NULL)
     {
      if ((testPtr->type != SYMBOL) && (testPtr->type != STRING) &&
#if OBJECT_SYSTEM
          (testPtr->type != INSTANCE_NAME) && (testPtr->type != INSTANCE_ADDRESS) &&
#endif
          (testPtr->type != INTEGER) && (testPtr->type != FLOAT))
        { return(FALSE); }
      testPtr = testPtr->nextArg;
     }

   return(TRUE);
  }

/************************************************/
/* ConstantType: Returns TRUE if the type */
/*   is a constant, otherwise FALSE.      */
/************************************************/
globle intBool ConstantType(
  int theType)
  {
   switch (theType)
     {
      case SYMBOL:
      case STRING:
      case INTEGER:
      case FLOAT:
#if OBJECT_SYSTEM
      case INSTANCE_NAME:
      case INSTANCE_ADDRESS:
#endif
        return(TRUE);
     }

   return(FALSE);
  }

/*****************************************************************************/
/* IdenticalExpression: Determines if two expressions are identical. Returns */
/*   TRUE if the expressions are identical, otherwise FALSE is returned.     */
/*****************************************************************************/
globle intBool IdenticalExpression(
  struct expr *firstList,
  struct expr *secondList)
  {
   /*==============================================*/
   /* Compare each argument in both expressions by */
   /* following the nextArg list.                  */
   /*==============================================*/

   for (;
        (firstList != NULL) && (secondList != NULL);
        firstList = firstList->nextArg, secondList = secondList->nextArg)
     {
      /*=========================*/
      /* Compare type and value. */
      /*=========================*/

      if (firstList->type != secondList->type)
        { return(FALSE); }

      if (firstList->value != secondList->value)
        { return (FALSE); }

      /*==============================*/
      /* Compare the arguments lists. */
      /*==============================*/

      if (IdenticalExpression(firstList->argList,secondList->argList) == FALSE)
        { return(FALSE); }
     }

   /*=====================================================*/
   /* If firstList and secondList aren't both NULL, then  */
   /* one of the lists contains more expressions than the */
   /* other.                                              */
   /*=====================================================*/

   if (firstList != secondList) return(FALSE);

   /*============================*/
   /* Expressions are identical. */
   /*============================*/

   return(TRUE);
  }

/****************************************************/
/* CountArguments: Returns the number of structures */
/*   stored in an expression as traversed through   */
/*   the nextArg pointer but not the argList        */
/*   pointer.                                       */
/****************************************************/
globle int CountArguments(
  struct expr *testPtr)
  {
   int size = 0;

   while (testPtr != NULL)
     {
      size++;
      testPtr = testPtr->nextArg;
     }

   return(size);
  }

/******************************************/
/* CopyExpresssion: Copies an expression. */
/******************************************/
globle struct expr *CopyExpression(
  void *theEnv,
  struct expr *original)
  {
   struct expr *topLevel, *next, *last;

   if (original == NULL) return(NULL);

   topLevel = GenConstant(theEnv,original->type,original->value);
   topLevel->argList = CopyExpression(theEnv,original->argList);

   last = topLevel;
   original = original->nextArg;
   while (original != NULL)
     {
      next = GenConstant(theEnv,original->type,original->value);
      next->argList = CopyExpression(theEnv,original->argList);

      last->nextArg = next;
      last = next;
      original = original->nextArg;
     }

   return(topLevel);
  }

/************************************************************/
/* ExpressionContainsVariables: Determines if an expression */
/*   contains any variables. Returns TRUE if the expression */
/*   contains any variables, otherwise FALSE is returned.   */
/************************************************************/
globle intBool ExpressionContainsVariables(
  struct expr *theExpression,
  intBool globalsAreVariables)
  {
   while (theExpression != NULL)
     {
      if (theExpression->argList != NULL)
        {
         if (ExpressionContainsVariables(theExpression->argList,globalsAreVariables))
           { return(TRUE); }
        }

      if ((theExpression->type == MF_VARIABLE) ||
          (theExpression->type == SF_VARIABLE) ||
          (theExpression->type == FACT_ADDRESS) ||
          (((theExpression->type == GBL_VARIABLE) ||
            (theExpression->type == MF_GBL_VARIABLE)) &&
           (globalsAreVariables == TRUE)))
        { return(TRUE); }

      theExpression = theExpression->nextArg;
     }

   return(FALSE);
  }

/*****************************************/
/* ExpressionSize: Returns the number of */
/*   structures stored in an expression. */
/*****************************************/
globle long ExpressionSize(
  struct expr *testPtr)
  {
   long size = 0;

   while (testPtr != NULL)
     {
      size++;
      if (testPtr->argList != NULL)
        { size += ExpressionSize(testPtr->argList); }
      testPtr = testPtr->nextArg;
     }
   return(size);
  }

/************************************************/
/* GenConstant: Generates a constant expression */
/*   value of type string, symbol, or number.   */
/************************************************/
globle struct expr *GenConstant(
  void *theEnv,
  unsigned short type,
  void *value)
  {
   struct expr *top;

   top = get_struct(theEnv,expr);
   top->nextArg = NULL;
   top->argList = NULL;
   top->type = type;
   top->value = value;

   return(top);
  }

/*************************************************/
/* PrintExpression: Pretty prints an expression. */
/*************************************************/
globle void PrintExpression(
  void *theEnv,
  const char *fileid,
  struct expr *theExpression)
  {
   struct expr *oldExpression;

   if (theExpression == NULL)
     { return; }

   while (theExpression != NULL)
     {
      switch (theExpression->type)
        {
         case SF_VARIABLE:
         case GBL_VARIABLE:
            EnvPrintRouter(theEnv,fileid,"?");
            EnvPrintRouter(theEnv,fileid,ValueToString(theExpression->value));
            break;

         case MF_VARIABLE:
         case MF_GBL_VARIABLE:
            EnvPrintRouter(theEnv,fileid,"$?");
            EnvPrintRouter(theEnv,fileid,ValueToString(theExpression->value));
            break;

         case FCALL:
           EnvPrintRouter(theEnv,fileid,"(");
           EnvPrintRouter(theEnv,fileid,ValueToString(ExpressionFunctionCallName(theExpression)));
           if (theExpression->argList != NULL) { EnvPrintRouter(theEnv,fileid," "); }
           PrintExpression(theEnv,fileid,theExpression->argList);
           EnvPrintRouter(theEnv,fileid,")");
           break;

         default:
           oldExpression = EvaluationData(theEnv)->CurrentExpression;
           EvaluationData(theEnv)->CurrentExpression = theExpression;
           PrintAtom(theEnv,fileid,theExpression->type,theExpression->value);
           EvaluationData(theEnv)->CurrentExpression = oldExpression;
           break;
        }

      theExpression = theExpression->nextArg;
      if (theExpression != NULL) EnvPrintRouter(theEnv,fileid," ");
     }

   return;
  }

/*************************************************************************/
/* CombineExpressions: Combines two expressions into a single equivalent */
/*   expression. Mainly serves to merge expressions containing "and"     */
/*   and "or" expressions without unnecessary duplication of the "and"   */
/*   and "or" expressions (i.e., two "and" expressions can be merged by  */
/*   placing them as arguments within another "and" expression, but it   */
/*   is more efficient to add the arguments of one of the "and"          */
/*   expressions to the list of arguments for the other and expression). */
/*************************************************************************/
globle struct expr *CombineExpressions(
  void *theEnv,
  struct expr *expr1,
  struct expr *expr2)
  {
   struct expr *tempPtr;

   /*===========================================================*/
   /* If the 1st expression is NULL, return the 2nd expression. */
   /*===========================================================*/

   if (expr1 == NULL) return(expr2);

   /*===========================================================*/
   /* If the 2nd expression is NULL, return the 1st expression. */
   /*===========================================================*/

   if (expr2 == NULL) return(expr1);

   /*============================================================*/
   /* If the 1st expression is an "and" expression, and the 2nd  */
   /* expression is not an "and" expression, then include the    */
   /* 2nd expression in the argument list of the 1st expression. */
   /*============================================================*/

   if ((expr1->value == ExpressionData(theEnv)->PTR_AND) &&
       (expr2->value != ExpressionData(theEnv)->PTR_AND))
     {
      tempPtr = expr1->argList;
      if (tempPtr == NULL)
        {
         rtn_struct(theEnv,expr,expr1);
         return(expr2);
        }

      while (tempPtr->nextArg != NULL)
        { tempPtr = tempPtr->nextArg; }

      tempPtr->nextArg = expr2;
      return(expr1);
     }

   /*============================================================*/
   /* If the 2nd expression is an "and" expression, and the 1st  */
   /* expression is not an "and" expression, then include the    */
   /* 1st expression in the argument list of the 2nd expression. */
   /*============================================================*/

   if ((expr1->value != ExpressionData(theEnv)->PTR_AND) &&
       (expr2->value == ExpressionData(theEnv)->PTR_AND))
     {
      tempPtr = expr2->argList;
      if (tempPtr == NULL)
        {
         rtn_struct(theEnv,expr,expr2);
         return(expr1);
        }

      expr2->argList = expr1;
      expr1->nextArg = tempPtr;

      return(expr2);
     }

   /*===========================================================*/
   /* If both expressions are "and" expressions, then add the   */
   /* 2nd expression to the argument list of the 1st expression */
   /* and throw away the extraneous "and" expression.           */
   /*===========================================================*/

   if ((expr1->value == ExpressionData(theEnv)->PTR_AND) &&
       (expr2->value == ExpressionData(theEnv)->PTR_AND))
     {
      tempPtr = expr1->argList;
      if (tempPtr == NULL)
        {
         rtn_struct(theEnv,expr,expr1);
         return(expr2);
        }

      while (tempPtr->nextArg != NULL)
        { tempPtr = tempPtr->nextArg; }

      tempPtr->nextArg = expr2->argList;
      rtn_struct(theEnv,expr,expr2);

      return(expr1);
     }

   /*=====================================================*/
   /* If neither expression is an "and" expression, then  */
   /* create an "and" expression and add both expressions */
   /* to the argument list of that "and" expression.      */
   /*=====================================================*/

   tempPtr = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_AND);
   tempPtr->argList = expr1;
   expr1->nextArg = expr2;
   return(tempPtr);
  }

/*********************/
/* NegateExpression: */
/*********************/
globle struct expr *NegateExpression(
  void *theEnv,
  struct expr *theExpression)
  {
   struct expr *tempPtr;

   /*=========================================*/
   /* If the expression is NULL, return NULL. */
   /*=========================================*/

   if (theExpression == NULL) return(NULL);

   /*==================================================*/
   /* The expression is already wrapped within a "not" */
   /* function call, just remove the function call.    */
   /*==================================================*/

   if (theExpression->value == ExpressionData(theEnv)->PTR_NOT)
     {
      tempPtr = theExpression->argList;
      rtn_struct(theEnv,expr,theExpression);
      return(tempPtr);
     }

   /*===================================================*/
   /* Wrap the expression within a "not" function call. */
   /*===================================================*/

   tempPtr = GenConstant(theEnv,FCALL,ExpressionData(theEnv)->PTR_NOT);
   tempPtr->argList = theExpression;

   return(tempPtr);
  }

/********************************************************/
/* AppendExpressions: Attaches an expression to the end */
/*   of another expression's nextArg list.              */
/********************************************************/
globle struct expr *AppendExpressions(
  struct expr *expr1,
  struct expr *expr2)
  {
   struct expr *tempPtr;

   /*===========================================================*/
   /* If the 1st expression is NULL, return the 2nd expression. */
   /*===========================================================*/

   if (expr1 == NULL) return(expr2);

   /*===========================================================*/
   /* If the 2nd expression is NULL, return the 1st expression. */
   /*===========================================================*/

   if (expr2 == NULL) return(expr1);

   /*====================================*/
   /* Find the end of the 1st expression */
   /* and attach the 2nd expression.     */
   /*====================================*/

   tempPtr = expr1;
   while (tempPtr->nextArg != NULL) tempPtr = tempPtr->nextArg;
   tempPtr->nextArg = expr2;

   /*===============================*/
   /* Return the merged expression. */
   /*===============================*/

   return(expr1);
  }


text: require('./scss/pyconcz.scss');


text:
from lode.database.utilities import (
        check_required_range, check_optional_range, multi_query, merge_meta)
import query_builders as qb
import warnings

def query_nodal_price(begin_date=None, end_date=None, dates=None,
                      begin_period=None, end_period=None, periods=None,
                      minimum_price=None, maximum_price=None, nodes="Major",
                      apply_meta=False, database=None):
    """
    Query the Nodal Price in a simplified fashion with all of the information
    held behind the scenes. This function is one of the primary interfaces
    with the database although the queries can be run directly as needed using
    other hidden functionality.

    Parameters:
    -----------
    begin_date: What begin point of a date range to query, string or datetime
    end_date: What end point of a date range to query, string or datetime
    dates: What dates to specifically query, string, list
    begin_period: Beginning point of a query range, int
    end_period: End point of a query range, int
    periods: What periods to query, defaults to all
    nodes: What nodes to query, defaults to the Major nodes
    minimum_price: Minimum price to query, useful for finding specific
                   instances of a priced situation over a wide number of time
                   instances
    maximum_price: Maximum price to query, e.g. use in combination with
                   minimum_price
    apply_meta: Whether to apply the associated meta information to the
                returned dataframe
    database: What database to connect to, leave None for the default setup

    Returns:
    --------
    A DataFrame containing all of the information with the specific filters
    applied

    """

    # Set Database to the default nodal prices one
    if database is None:
        database = 'nodal_database'

    # Core nodes are those of some importance to the market in some way
    # E.g. major population centre, generation site, HVDC etc
    if nodes == "Core":
        nodes = ("OTA2201", "BEN2201", "HAY2201", "HLY2201",
                 "MAN2201", "BPE2201", "PEN2201", "ISL2201")
    # Major nodes are the big three, Auckland, NI HVDC, SI HVDC
    elif nodes == "Major":
        nodes = ("OTA2201", "HAY2201", "BEN2201")

    # Check the dates
    check_required_range(dates, begin_date, end_date)
    check_optional_range(periods, begin_period, end_period)

    all_queries = qb.create_date_limited_sql("nodal_prices", dates=dates,
                                             begin_date=begin_date,
                                             end_date=end_date,
                                             date_col="Trading_date")

    completed_queries = []
    for sql in all_queries:
        if periods:
            sql += qb.add_equality_constraint('Trading_period', periods)

        if (begin_period and end_period):
            sql += qb.add_range_constraint('Trading_period',
                                           begin_period, end_period)

        if nodes:
            sql += qb.add_equality_constraint('Node', nodes)

        if minimum_price:
            sql += qb.add_minimum_constraint('Price', minimum_price)

        if maximum_price:
            sql += qb.add_maximum_constraint('Price', maximum_price)

        # Finish modifying the SQL so add a semicolon to end it
        sql += ';'

        # Add to the completed queries
        completed_queries.append(sql)

    # Query using the query to dataframe method and a generator
    prices = multi_query(database, completed_queries)

    if apply_meta:
        warnings.warn('Metadata may be incomplete')
        prices = merge_meta(prices, 'price')

    return prices

def query_nodal_demand(begin_date=None, end_date=None, dates=None,
                       begin_period=None, end_period=None, periods=None,
                       nodes=None, minimum_demand=None,
                       maximum_demand=None, apply_meta=False,
                       meta_group=None, meta_agg=None,
                       excl_nodes=None, database=None):
    """
    Query the nodal demand from the database at the GXP level. This results
    in very large DataFrames as there are approximately 450 nodes to query
    at any given point in time. Some values may be negative (for generation)
    and these can be excluded by setting a minimum demand or specifically via
    the various nodes.

    Meta information can also be applied but this may be incomplete at the
    current point in time. Use at your own risk.

    Parameters:
    -----------
    begin_date: What begin point of a date range to query, string or datetime
    end_date: What end point of a date range to query, string or datetime
    dates: What dates to specifically query, string, list
    begin_period: Beginning point of a query range, int
    end_period: End point of a query range, int
    periods: What periods to query, defaults to all
    nodes: What nodes to query, defaults to all
    minimum_demand: Minimum GXP demand figure, may wish to set to 0.
    maximum_demand: Maximum GXP demand figure
    apply_meta: Whether to add the meta information such as richer locations
    meta_group: Whether to group the nodes by any particular reference point
    meta_agg: Apply a meta aggregation function
    excl_nodes: What nodes to exclude, optionally set this to "Wind"
    database: Optional, what Database to connect to, leave this Node for the
              default, useful if you have changed the database names.

    Returns:
    --------
    DataFrame: Pandas Dataframe containing the query information
    """

    if database is None:
        database = 'nodal_database'

    # Helper function for the wind nodes as wind is a negative load at the
    # moment on the GXPs
    if excl_nodes == "Wind":
        excl_nodes = ("TWC2201", "WDV1101", "WWD1101", "WWD1102",
                      "WWD1103", "TWH0331")

    # Error checking on the dates and period range consistencies
    check_required_range(dates, begin_date, end_date)
    check_optional_range(periods, begin_period, end_period)

    # Set up the initial SQL queries with dates loaded in
    all_queries = qb.create_date_limited_sql("nodal_demand", dates=dates,
                                             begin_date=begin_date,
                                             end_date=end_date,
                                             date_col="Trading_date")

    completed_queries = []
    for sql in all_queries:
        if periods:
            sql += qb.add_equality_constraint('Trading_period', periods)

        if (begin_period and end_period):
            sql += qb.add_range_constraint('Trading_period',
                                           begin_period, end_period)

        if nodes:
            sql += qb.add_equality_constraint("Node", nodes)

        if minimum_demand:
            # Don't use zero values, instead use a very small float
            if minimum_demand == 0:
                minimum_demand = 0.0001
            sql += qb.add_minimum_constraint("Demand", minimum_demand)

        if maximum_demand:
            sql += qb.add_maximum_constraint("Demand", maximum_demand)

        # Exclude certain nodes
        if excl_nodes:
            sql += qb.add_exclusion_constraint("Node", excl_nodes)

        sql += ';'
        completed_queries.append(sql)

    demand = multi_query(database, completed_queries)

    if apply_meta:
        warnings.warn('Metadata may be incomplete')
        demand = merge_meta(demand, 'demand')

        if meta_group and meta_agg:
            grouped = demand.groupby(meta_group)
            aggregate = grouped.aggregate(meta_agg)

            return aggregate

    return demand

def query_offer(offer_type, dates=None, begin_date=None, end_date=None,
                periods=None, begin_period=None, end_period=None,
                companies=None, stations=None, nodes=None,
                as_offerframe=True, database=None):
    """

    Master function to query the submitted Energy, Generator Reserve and IL
    offers in the NZEM. Has some basic filters as well as the ability to return
    the

    Parameters:
    -----------
    offer_type: What type of offer to query, e.g. Energy, PLSR or IL
    begin_date: What begin point of a date range to query, string or datetime
    end_date: What end point of a date range to query, string or datetime
    dates: What dates to specifically query, string, list
    begin_period: Beginning point of a query range, int
    end_period: End point of a query range, int
    periods: What periods to query, defaults to all
    nodes: What nodes to query, defaults to all
    companies: What companies to query, e.g. MRPL, this is a four letter code
    stations: What stations to query, three letter code
    as_offerframe: Convert the raw offer to an OfferFrame, note requires
                   OfferFrame to be installed

    Returns:
    --------
    OfferFrame or DataFrame of the offers queried

    """

    if database is None:
        database = 'offer_database'

    # Create the tables
    tables = {"Energy": 'energy_offers',
              "PLSR": 'generatorreserves_offers',
              "IL": 'ilreserves_offers'}

    # Map grid locations based upon which query is being run.
    grid_map = {"Energy": "grid_injection_point",
                "PLSR": "grid_point",
                "IL": "grid_exit_point"}

    check_required_range(dates, begin_date, end_date)
    check_optional_range(periods, begin_period, end_period)

    # Create the queries
    all_queries = qb.create_date_limited_sql(tables[offer_type], dates=dates,
                                            begin_date=begin_date,
                                            end_date=end_date)

    # Add all of the other constraints:
    completed_queries = []
    for sql in all_queries:

        if periods:
            sql += qb.add_equality_constraint('trading_period', periods)

        elif (begin_period and end_period):
            sql += qb.add_range_constraint('trading_period',
                                           begin_period, end_period)

        if companies:
            sql += qb.add_equality_constraint('company', companies)

        if stations:
            sql += qb.add_equality_constraint('station', stations)

        if nodes:
            sql += qb.add_equality_constraint(grid_map[offer_type], nodes)

        # Once all constraints have been added end the SQL statement
        sql += ';'
        completed_queries.append(sql)

    offers = multi_query(database, completed_queries)

    # Optional to return it as an OfferFrame
    if as_offerframe:
        try:
            from OfferPandas import Frame
        except ImportError:
            raise ImportError('OfferPandas has not been installed')

        warnings.warn(
            'Metadata may be incomplete or erroneous use at your own risk')

        df = Frame(offers)
        return df.modify_frame()

    return offers

if __name__ == '__main__':
    pass


text:
LEDs provide status about the following:

-   Dedicated battery state/charging state
-   Chromebook power
-   Adapter power
-   Left side USB-C port (battery state/charging state)
-   Right side USB-C port (battery state/charging state)
-   Recovery mode
-   Debug mode

LEDs can be configured as simple GPIOs, with on/off control only, or as PWM with
adjustment brightness and color.

## Config options

In [config.h], search for options that start with `CONFIG_LED*` and evaluate
whether each option is appropriate to add to `baseboard.h` or `board.h`.

-   `CONFIG_LED_COMMON` - Should be defined for both GPIO and PWM style LEDs.
-   `CONFIG_LED_ONOFF_STATES` - used for GPIO controlled LEDs
-   `CONFIG_LED_PWM` - used for PWM controlled LEDs. You must also define
    `CONFIG_PWM` when using PWM controlled LEDs.

## Feature Parameters

-   `CONFIG_LED_PWM_COUNT <count>` - Must be defined when using PWM LEDs

Override the following parameters when using PWM LEDs if you don't want to use
the recommended LED color settings. - `CONFIG_LED_PWM_CHARGE_COLOR
<ec_led_color>` - `CONFIG_LED_PWM_NEAR_FULL_COLOR <ec_led_color>` -
`CONFIG_LED_PWM_CHARGE_ERROR_COLOR <ec_led_color>` -
`CONFIG_LED_PWM_SOC_ON_COLOR <ec_led_color>` - `CONFIG_LED_PWM_SOC_SUSPEND_COLOR
<ec_led_color>` - `CONFIG_LED_PWM_LOW_BATT_COLOR <ec_led_color>`

## GPIOs and Alternate Pins

For GPIO based LEDs, create `GPIO()` entries for all signals that connect to
platform LEDs. The default state of the pins should be set so that the LED is
off (typically high output).

For PWM LEDs, configure the `ALTERNATE()` macro, setting the module type to
`MODULE_PWM`.

## Data structures

For GPIO based LEDs: - `struct led_descriptor
led_bat_state_table[LED_NUM_STATES][LED_NUM_PHASES]` - Must be defined when
`CONFIG_LED_ONOFF_STATES` is used. Defines the LED states for the platform for
various charging states.

For PWM based LEDs: - `const enum ec_led_id supported_led_ids[]` - Defines the
LED type for all PWM LEDs in the system. See [./include/ec_commands.h] for a
description of the supported LED types. - `struct pwm_led led_color_map[]` -
Defines the PWM intensity of the individual LEDs to generate the corresponding
color. This table allows for custom tuning of the LED brightness and color. -
`const struct pwm_channels[]` - Configures the PWM module, refer to the
[Configuring PWM](./pwm.md) section for details.

See the [GPIO](./gpio.md) documentation for additional details on the GPIO
macros.

## Tasks

None required by this feature.

## Testing and Debugging

### Console Commands

-   `pwmduty` - *TODO* add description.
-   `gpioset` - For GPIO based LEDs, this command lets you directly change the
    state of the LED.
-   `gpioget` - For GPIO based LEDs, this reads current state of the pin. If the
    current state does not track changes made with `gpioset`, check your board
    for stuck at high or stuck at low condition.

If you're having problems with a PWM LED, try reconfiguring the pin as a GPIO to
verify the board operation independent of the PWM module.

## LED Driver Chips

LED driver chips are used to control the LCD panel backlight. The backlight
control is separate from the platform LEDs.

[config.h]: ../new_board_checklist.md#config_h
[./include/ec_commands.h]: ../../include/ec_commands.h


text:
<?php

namespace Guzzle\Plugin\Backoff;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\HttpException;

class ExponentialBackoffStrategy extends AbstractBackoffStrategy
{
public function makesDecision()
{
return false;
}

protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
return (int) pow(2, $retries);
}
}


text:
#include "Python.h"
#include "frameobject.h"
#include "pystate.h"

static long debuggerThreadIdent = 0;  // Track debugger thread ident

/*
 * Cached interned string objects used for calling the profile and
 * trace functions.  Initialized by trace_init().
 */
static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
static int
trace_init(void)
{
    static char *whatnames[7] = {"call", "exception", "line", "return",
                                    "c_call", "c_exception", "c_return"};
    PyObject *name;
    int i;
    for (i = 0; i < 7; ++i) {
        if (whatstrings[i] == NULL) {
            name = PyString_InternFromString(whatnames[i]);
            if (name == NULL)
                return -1;
            whatstrings[i] = name;
        }
    }
    return 0;
}

static PyObject *
call_trampoline(PyThreadState *tstate, PyObject* callback,
                PyFrameObject *frame, int what, PyObject *arg)
{
    PyObject *args = PyTuple_New(3);
    PyObject *whatstr;
    PyObject *result;

    if (args == NULL)
        return NULL;
    Py_INCREF(frame);
    whatstr = whatstrings[what];
    Py_INCREF(whatstr);
    if (arg == NULL)
        arg = Py_None;
    Py_INCREF(arg);
    PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
    PyTuple_SET_ITEM(args, 1, whatstr);
    PyTuple_SET_ITEM(args, 2, arg);

    /* call the Python-level function */
    PyFrame_FastToLocals(frame);
    result = PyEval_CallObject(callback, args);
    PyFrame_LocalsToFast(frame, 1);
    if (result == NULL)
        PyTraceBack_Here(frame);

    /* cleanup */
    Py_DECREF(args);
    return result;
}

static int
_tracer_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg)
{
    PyThreadState *tstate = frame->f_tstate;
    PyObject *callback;
    PyObject *result;

    if (what == PyTrace_CALL)
        callback = self;
    else
        callback = frame->f_trace;
    if (callback == NULL)
        return 0;

    result = call_trampoline(tstate, callback, frame, what, arg);
    if (result == NULL) {
        PyEval_SetTrace(NULL, NULL);
        Py_CLEAR(frame->f_trace);
        return -1;
    }

    if (result != Py_None) {
        PyObject *temp = frame->f_trace;
        frame->f_trace = NULL;
        Py_XDECREF(temp);
        frame->f_trace = result;
    }
    else {
        Py_DECREF(result);
    }
    return 0;
}

void
IK_SetTrace(Py_tracefunc func, PyObject *arg)
{
    // Ensure _Py_TracingPossible is correctly set
    PyEval_SetTrace(func, arg);

    // Now iterate over all threads to set tracing
    PyInterpreterState *interp = PyInterpreterState_Head();
    PyThreadState *loopThreadState = PyInterpreterState_ThreadHead(interp);
    while(loopThreadState) {
        if(loopThreadState->thread_id!=debuggerThreadIdent) {
            PyObject *temp = loopThreadState->c_traceobj;
            Py_XINCREF(arg);
            loopThreadState->c_tracefunc = NULL;
            loopThreadState->c_traceobj = NULL;
            /* Must make sure that profiling is not ignored if 'temp' is freed */
            loopThreadState->use_tracing = loopThreadState->c_profilefunc != NULL;
            Py_XDECREF(temp);
            loopThreadState->c_tracefunc = func;
            loopThreadState->c_traceobj = arg;
            /* Flag that tracing or profiling is turned on */
            loopThreadState->use_tracing = ((func != NULL) || (loopThreadState->c_profilefunc != NULL));
        } else {
            PyObject *temp = loopThreadState->c_traceobj;
            loopThreadState->c_tracefunc = NULL;
            loopThreadState->c_traceobj = NULL;
            /* Must make sure that profiling is not ignored if 'temp' is freed */
            loopThreadState->use_tracing = loopThreadState->c_profilefunc != NULL;
            Py_XDECREF(temp);

        };
        loopThreadState = PyThreadState_Next(loopThreadState);
    };
}

static PyObject *
_ik_set_trace_on(PyObject *self, PyObject *args)
{
    PyObject *traceObject = NULL;

    if (trace_init() == -1)
        return NULL;

    if (!PyArg_ParseTuple(args, "Ol", &traceObject, &debuggerThreadIdent)) {
        return NULL;
    }

    IK_SetTrace(_tracer_trampoline, traceObject);

    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(_ik_set_trace_on_doc,
"_set_trace_on(tracer, thread_id)\n\
\n\
Activate tracing with tracer function, on all threads but the one specified.\n\
See the debugger chapter in the library manual.\n\
This function do not call threading.settrace(), user must do it."
);

static PyObject *
_ik_set_trace_off(PyObject *self)
{
    IK_SetTrace(NULL, NULL);
    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(_ik_set_trace_off_doc,
"_set_trace_off()\n\
\n\
Disable tracing on all threads.\n\
See the debugger chapter in the library manual.\n\
This function do not call threading.settrace(), user must do it."
);

static PyMethodDef InoukMethods[] = {
    {"_set_trace_on", _ik_set_trace_on, METH_VARARGS, _ik_set_trace_on_doc},
    {"_set_trace_off", (PyCFunction)_ik_set_trace_off, METH_NOARGS, _ik_set_trace_off_doc},
    {NULL,           NULL}           /* sentinel */
};

PyMODINIT_FUNC
initiksettrace(void)
{
    (void) Py_InitModule("iksettrace", InoukMethods);
}


text:
module Contraband
  module Errors

    ##
    # Ripped from https://github.com/mongoid/mongoid/blob/master/lib/mongoid/errors/mongoid_error.rb
    class ContrabandError < StandardError

      BASE_KEY = 'contraband.errors.messages'

      ##
      # Compose the message.
      #
      # @example Create the message
      #   error.compose_message
      #
      # @return [String]
      #   The composed message.
      def compose_message(key, attributes = {})
        @problem = problem(key, attributes)
        @summary = summary(key, attributes)
        @resolution = resolution(key, attributes)

        "\nProblem:\n  #{@problem}"+
        "\nSummary:\n  #{@summary}"+
        "\nResolution:\n  #{@resolution}"
      end

      private

      ##
      # Given the key of the specific error and the options hash, translate the
      # message.
      #
      # @example Translate the message.
      #   error.translate("errors", :key => value)
      #
      # @param [String] key
      #   The key of the error in the locales.
      #
      # @param [Hash] options
      #   The objects to pass to create the message.
      #
      # @return [String]
      #   A localized error message string.
      def translate(key, options)
        ::I18n.translate("#{BASE_KEY}.#{key}", { locale: :en }.merge(options))
      end

      # Create the problem.
      #
      # @example Create the problem.
      #   error.problem("error", {})
      #
      # @param [String, Symbol] key
      #   The error key.
      #
      # @param [Hash] attributes
      #   The attributes to interpolate.
      #
      # @return [String]
      #   The problem.
      def problem(key, attributes)
        translate("#{key}.message", attributes)
      end

      ##
      # Create the summary.
      #
      # @example Create the summary.
      #   error.summary("error", {})
      #
      # @param [String, Symbol] key
      #   The error key.
      #
      # @param [Hash] attributes
      #   The attributes to interpolate.
      #
      # @return [String]
      #   The summary.
      def summary(key, attributes)
        translate("#{key}.summary", attributes)
      end

      ##
      # Create the resolution.
      #
      # @example Create the resolution.
      #   error.resolution("error", {})
      #
      # @param [String, Symbol] key
      #   The error key.
      # @param [Hash] attributes
      #   The attributes to interpolate.
      #
      # @return [String]
      #   The resolution.
      def resolution(key, attributes)
        translate("#{key}.resolution", attributes)
      end
    end # ContrabandError
  end # Errors
end # Contraband


text:
require 'spec_helper'
require 'rack'

include Txgh

describe GithubRequestAuth do
  let(:secret) { 'abc123' }
  let(:params) { '{"param1":"value1","param2":"value2","param3":123}' }
  let(:valid_signature) { 'ea62c3f65c8e42f155d96a25b7ba6eb5d320630e' }

  describe '.authentic_request?' do
    it 'returns true if the request is signed correctly' do
      request = Rack::Request.new(
        GithubRequestAuth::RACK_HEADER => "sha1=#{valid_signature}",
        'rack.input' => StringIO.new(params)
      )

      authentic = GithubRequestAuth.authentic_request?(request, secret)
      expect(authentic).to eq(true)
    end

    it 'returns false if the request is not signed correctly' do
      request = Rack::Request.new(
        GithubRequestAuth::RACK_HEADER => 'incorrect',
        'rack.input' => StringIO.new(params)
      )

      authentic = GithubRequestAuth.authentic_request?(request, secret)
      expect(authentic).to eq(false)
    end
  end

  describe '.header' do
    it 'calculates the signature and formats it as an http header' do
      value = GithubRequestAuth.header_value(params, secret)
      expect(value).to eq("sha1=#{valid_signature}")
    end
  end
end


text:
package httpmethodoverride

import "net/http"

// Handler returns an http.Handler that looks for a `_method` URL
// query parameter and updates the *http.Request.Method field with its
// value, and calls the original http.Handler.
func Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		params := r.URL.Query()
		if method := params.Get("_method"); method != "" {
			r.Method = method
		}

		h.ServeHTTP(w, r)
	})
}


text:
package id.biz.wonderwall.ibod.response;

/**
 * Created by winnerawan on 1/19/17.
 */

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import id.biz.wonderwall.ibod.model.FileResult;

public class ListFolderResponse {

    @SerializedName("status")
    @Expose
    private Integer status;
    @SerializedName("msg")
    @Expose
    private String msg;
    @SerializedName("result")
    @Expose
    private FileResult result;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public FileResult getResult() {
        return result;
    }

    public void setResult(FileResult result) {
        this.result = result;
    }
}


text:
require 'abstract_unit'
require 'active_support/core_ext/array'
require 'active_support/core_ext/enumerable'

Payment = Struct.new(:price)
class SummablePayment < Payment
  def +(p) self.class.new(price + p.price) end
end

class EnumerableTests < Test::Unit::TestCase
  def test_group_by
    names = %w(marcel sam david jeremy)
    klass = Struct.new(:name)
    objects = (1..50).inject([]) do |people,|
      p = klass.new
      p.name = names.sort_by { rand }.first
      people << p
    end

    grouped = objects.group_by { |object| object.name }

    grouped.each do |name, group|
      assert group.all? { |person| person.name == name }
    end

    assert_equal objects.uniq.map(&:name), grouped.keys
    assert({}.merge(grouped), "Could not convert ActiveSupport::OrderedHash into Hash")
  end

  def test_sums
    assert_equal 30, [5, 15, 10].sum
    assert_equal 30, [5, 15, 10].sum { |i| i }

    assert_equal 'abc', %w(a b c).sum
    assert_equal 'abc', %w(a b c).sum { |i| i }

    payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ]
    assert_equal 30, payments.sum(&:price)
    assert_equal 60, payments.sum { |p| p.price * 2 }

    payments = [ SummablePayment.new(5), SummablePayment.new(15) ]
    assert_equal SummablePayment.new(20), payments.sum
    assert_equal SummablePayment.new(20), payments.sum { |p| p }
  end

  def test_nil_sums
    expected_raise = TypeError

    assert_raise(expected_raise) { [5, 15, nil].sum }

    payments = [ Payment.new(5), Payment.new(15), Payment.new(10), Payment.new(nil) ]
    assert_raise(expected_raise) { payments.sum(&:price) }

    assert_equal 60, payments.sum { |p| p.price.to_i * 2 }
  end

  def test_empty_sums
    assert_equal 0, [].sum
    assert_equal 0, [].sum { |i| i }
    assert_equal Payment.new(0), [].sum(Payment.new(0))
  end

  def test_enumerable_sums
    assert_equal 20, (1..4).sum { |i| i * 2 }
    assert_equal 10, (1..4).sum
    assert_equal 10, (1..4.5).sum
    assert_equal 6, (1...4).sum
    assert_equal 'abc', ('a'..'c').sum
  end

  def test_each_with_object
    result = %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
    assert_equal({'foo' => 'FOO', 'bar' => 'BAR'}, result)
  end

  def test_index_by
    payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ]
    assert_equal({ 5 => payments[0], 15 => payments[1], 10 => payments[2] },
                 payments.index_by { |p| p.price })
  end

  def test_many
    assert ![].many?
    assert ![ 1 ].many?
    assert [ 1, 2 ].many?

    assert ![].many? {|x| x > 1 }
    assert ![ 2 ].many? {|x| x > 1 }
    assert ![ 1, 2 ].many? {|x| x > 1 }
    assert [ 1, 2, 2 ].many? {|x| x > 1 }
  end

  def test_exclude?
    assert [ 1 ].exclude?(2)
    assert ![ 1 ].exclude?(1)
  end
end


text:
package com.arellomobile.mvp.view;

import com.arellomobile.mvp.GenerateViewState;
import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;

/**
 * Date: 29.02.2016
 * Time: 9:09
 *
 * @author Savin Mikhail
 */
@GenerateViewState
public interface ParentView extends MvpView {
	void withoutStrategyMethod();

	@StateStrategyType(AddToEndSingleStrategy.class)
	void customStrategyMethod();

	@StateStrategyType(AddToEndSingleStrategy.class)
	void parentOverrideMethodWithCustomStrategy();
}


text:
__all__ = ['blip_download']

from ..common import *

import json

def blip_download(url, output_dir = '.', merge = True, info_only = False):
    p_url = url + "?skin=json&version=2&no_wrap=1"
    html = get_html(p_url)
    metadata = json.loads(html)

    title = metadata['Post']['title']
    real_url = metadata['Post']['media']['url']
    type, ext, size = url_info(real_url)

    print_info(site_info, title, type, size)
    if not info_only:
        download_urls([real_url], title, ext, size, output_dir, merge = merge)

site_info = "Blip.tv"
download = blip_download
download_playlist = playlist_not_supported('blip')


text:
describe('array-object', function() {

  beforeEach(function() {
    browser().navigateTo(mainUrl);
  });

  var s = '[ng-controller="Ctrl3"] ';
  var a = s+' input[type="checkbox"]';

  it('should initialize with correct values', function() {
    check(a, [0,1,0,0]);
    expect(element(s+'pre').text()).toMatch('id');
    expect(element(s+'pre').text()).toMatch('user');
  });

  it('should check/uncheck items', function() {
    using(s+'label:eq(0)').input('checked').check(true);
    using(s+'label:eq(1)').input('checked').check(false);
    check(a, [1,0,0,0]);
    expect(element(s+'pre').text()).toMatch('id');
    expect(element(s+'pre').text()).toMatch('guest');
  });

  it('should check all', function() {
    element(s+'button[ng-click="checkAll()"]').click();
    check(a, [1,1,1,1]);
    expect(element(s+'pre').text()).toMatch('id');
    expect(element(s+'pre').text()).toMatch('guest');
    expect(element(s+'pre').text()).toMatch('user');
    expect(element(s+'pre').text()).toMatch('customer');
    expect(element(s+'pre').text()).toMatch('admin');
  });

  it('should uncheck all', function() {
    element(s+'button[ng-click="uncheckAll()"]').click();
    check(a, [0,0,0,0]);
    expect(element(s+'pre').text()).toBe('[]');
  });

  it('should check first', function() {
    element(s+'button[ng-click="checkFirst()"]').click();
    check(a, [1,0,0,0]);
    expect(element(s+'pre').text()).toMatch('id');
    expect(element(s+'pre').text()).toMatch('guest');
  });

});


text:
require 'twilio-ruby'

# Get your Account SID, Auth Token, Service SID and Channel SID
# from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
service_sid = 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
channel_sid = 'CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
message_sid = 'IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
@client = Twilio::REST::Client.new(account_sid, auth_token)

# Retrieve the message
service = @client.chat.v2.services(service_sid)
channel = service.channels(channel_sid)
message = channel.messages(message_sid).fetch
puts "#{message.sid} #{message.body}"


text:
@interface BinaryNumbers : NSObject

+ (void)binaryNumbers;

@end


text:
from SequenceIndex import SequenceIndex

s = SequenceIndex(filepath="/Users/ernesto/Google_Drive/data/1000genomes.sequence.index")

s.runs_per_sample("low coverage")


text:
"""empty message

Revision ID: 390c1805c002
Revises: 4bbfdf089fbc
Create Date: 2014-01-21 23:53:26.082845

"""

# revision identifiers, used by Alembic.
revision = '390c1805c002'
down_revision = '4bbfdf089fbc'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('tracked_file',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('hook_id', sa.Integer(), nullable=False),
    sa.Column('path', sa.String(length=250, collation='utf8_bin'), nullable=False),
    sa.ForeignKeyConstraint(['hook_id'], ['hook.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('hook_id', 'path', name='unique_tracked_file_within_hook')
    )
    op.add_column(u'hook', sa.Column('install_script', sa.Text(), nullable=True))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column(u'hook', 'install_script')
    op.drop_table('tracked_file')
    ### end Alembic commands ###


text:
module Query
  class WaitingForPartPayment
    def initialize(user)
      @user = user
    end

    def find
      @user.office.applications.waiting_for_part_payment.order(:completed_at).
        includes(:part_payment, :user, :applicant)
    end
  end
end