text:
package org.apache.shiro.web.filter.authz;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Superclass for authorization-related filters.  If an request is unauthorized, response handling is delegated to the
 * {@link #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse) onAccessDenied} method, which
 * provides reasonable handling for most applications.
 *
 * @see #onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 * @since 0.9
 */
public abstract class AuthorizationFilter extends AccessControlFilter {

    /**
     * The URL to which users should be redirected if they are denied access to an underlying path or resource,
     * {@code null} by default which will issue a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response
     * (401 Unauthorized).
     */
    private String unauthorizedUrl;

    /**
     * Returns the URL to which users should be redirected if they are denied access to an underlying path or resource,
     * or {@code null} if a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response should be issued (401 Unauthorized).
     *

     * The default is {@code null}, ensuring default web server behavior.  Override this default by calling the
     * {@link #setUnauthorizedUrl(String) setUnauthorizedUrl} method with a meaningful path within your application
     * if you would like to show the user a 'nice' page in the event of unauthorized access.
     *
     * @return the URL to which users should be redirected if they are denied access to an underlying path or resource,
     *         or {@code null} if a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response should be issued (401 Unauthorized).
     */
    public String getUnauthorizedUrl() {
        return unauthorizedUrl;
    }

    /**
     * Sets the URL to which users should be redirected if they are denied access to an underlying path or resource.
     *

     * If the value is {@code null} a raw {@link HttpServletResponse#SC_UNAUTHORIZED} response will
     * be issued (401 Unauthorized), retaining default web server behavior.
     *

     * Unless overridden by calling this method, the default value is {@code null}.  If desired, you can specify a
     * meaningful path within your application if you would like to show the user a 'nice' page in the event of
     * unauthorized access.
     *
     * @param unauthorizedUrl the URL to which users should be redirected if they are denied access to an underlying
     *                        path or resource, or {@code null} to a ensure raw {@link HttpServletResponse#SC_UNAUTHORIZED} response is
     *                        issued (401 Unauthorized).
     */
    public void setUnauthorizedUrl(String unauthorizedUrl) {
        this.unauthorizedUrl = unauthorizedUrl;
    }

    /**
     * Handles the response when access has been denied.  It behaves as follows:
     *

     *
If the {@code Subject} is unknown[1]:
     *

The incoming request will be saved and they will be redirected to the login page for authentication
     * (via the {@link #saveRequestAndRedirectToLogin(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
     * method).

     *
Once successfully authenticated, they will be redirected back to the originally attempted page.

     *

     *
If the Subject is known:

     *

     *
The HTTP {@link HttpServletResponse#SC_UNAUTHORIZED} header will be set (401 Unauthorized)

     *
If the {@link #getUnauthorizedUrl() unauthorizedUrl} has been configured, a redirect will be issued to that
     * URL.  Otherwise the 401 response is rendered normally

     *

     * [1]: A {@code Subject} is 'known' when
     * subject.{@link org.apache.shiro.subject.Subject#getPrincipal() getPrincipal()} is not {@code null},
     * which implicitly means that the subject is either currently authenticated or they have been remembered via
     * 'remember me' services.
     *
     * @param request  the incoming ServletRequest
     * @param response the outgoing ServletResponse
     * @return {@code false} always for this implementation.
     * @throws IOException if there is any servlet error.
     */
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

        Subject subject = getSubject(request, response);
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            // If subject is known but not authorized, redirect to the unauthorized URL if there is one
            // If no unauthorized URL is specified, just return an unauthorized HTTP status code
            String unauthorizedUrl = getUnauthorizedUrl();
            //SHIRO-142 - ensure that redirect _or_ error code occurs - both cannot happen due to response commit:
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
        return false;
    }

}


text:
package com.amee.domain.auth;

import com.amee.domain.IAMEEEntityReference;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * Associates PermissionEntries with an AMEEEntity to specify desired and actual access rights.
 */
public class AccessSpecification implements Serializable {

    private IAMEEEntityReference entityReference;
    private Set<PermissionEntry> actual;
    private Set<PermissionEntry> desired = new HashSet<PermissionEntry>();

    private AccessSpecification() {
        super();
    }

    public AccessSpecification(IAMEEEntityReference entityReference) {
        this();
        this.entityReference = entityReference;
        entityReference.setAccessSpecification(this);
    }

    public AccessSpecification(IAMEEEntityReference entityReference, PermissionEntry... desired) {
        this(entityReference);
        CollectionUtils.addAll(getDesired(), desired);
    }

    public AccessSpecification(IAMEEEntityReference entityReference, Set<PermissionEntry> actual, PermissionEntry... desired) {
        this(entityReference);
        setActual(actual);
        CollectionUtils.addAll(getDesired(), desired);
    }

    public IAMEEEntityReference getEntityReference() {
        return entityReference;
    }

    public Set<PermissionEntry> getActual() {
        return actual;
    }

    public boolean hasActual() {
        return actual != null;
    }

    public void setActual(Set<PermissionEntry> actual) {
        if (actual != null) {
            this.actual = new HashSet<PermissionEntry>(actual);
        } else {
            this.actual = null;
        }
    }

    public Set<PermissionEntry> getDesired() {
        return desired;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
# utils.py
"""

import StringIO
import re
import shutil
import tarfile
from logging import getLogger

from swift_class import Swift

from keystone import get_auth_token

LOGGER = getLogger(__name__)

def delete_directory_tree(dir_path):
    """
    Cleanup a directory
    """
    if (dir_path):
        try:
            LOGGER.info('Deleting {0}'.format(dir_path))
            # Clean up working directory
            shutil.rmtree(dir_path, ignore_errors=True)
            LOGGER.info('Deleted dir: {0}'.format(dir_path))
        except Exception as e:
            err_message = \
                'Failed to clean up working directory "{0}".' \
                .format(dir_path)
            LOGGER.exception(err_message)

def extract_manifest_from_package(file_contents):
    """
    Extract the manifest from the vendor package
    """
    manifest_regex = '^.+[/]manifest.json$'
    pattern = re.compile(manifest_regex, re.IGNORECASE)

    # tarfile - https://docs.python.org/2/library/tarfile.html
    manifest = None
    with tarfile.TarFile.open(
            mode='r:gz',
            fileobj=StringIO.StringIO(file_contents)) as tar_package:
        for tarinfo in tar_package.getmembers():
            if (pattern.search(tarinfo.name)):
                manifest = tar_package.extractfile(tarinfo.name).read()
                break
    return manifest

def get_store():
    """
    Get a Swift instance per application settings
    """
    auth_token = get_auth_token()
    container = settings('swift_container')
    swift_url = settings('swift_url')
    swift = Swift(auth_token, swift_url, container)
    return swift


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	/* WEBPACK VAR INJECTION */(function(__dirname) {'use strict';

	var express = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"express\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
	var path = __webpack_require__(1);
	var compression = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"compression\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));

	var app = express();
	app.use(compression());

	// serve our static stuff like index.css
	app.use(express.static(__dirname));
	app.use(express.static(path.join(__dirname, 'public')));
	// send all requests to index.html so browserHistory in React Router works
	app.get('*', function (req, res) {
	    // and drop 'public' in the middle of here
	    res.sendFile(path.join(__dirname, 'public', 'index.html'));
	});

	var PORT = process.env.PORT || 5000;
	app.listen(PORT, function () {
	    console.log('Production Express server running at localhost:' + PORT);
	});
	/* WEBPACK VAR INJECTION */}.call(exports, ""))

/***/ },
/* 1 */
/***/ function(module, exports) {

	module.exports = require("path");

/***/ }
/******/ ]);


text:
const express = require('express');
const pkginfo = require('pkginfo')(module);

const app = express();
const server = require('http').Server(app);

// Modules
const mongo = require('./server/mongo').init();

// websockets
const io = require('socket.io')(server);
const websockets = require('./server/websockets').start(server);

// configuration
const config = require('./config/config.json');

// Get our API routes
const router = require('./server/router')(module);
const serverPort = process.env.PORT || config.port;

app.use(function (req, res, next) {
  res.removeHeader('x-powered-by');
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET');
  res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');

  next();
});

// Set our api routes
app.use('/', router);

server.listen(serverPort, () => console.log(`Server running on http://localhost:${serverPort}`));

module.exports = app;


text:
use ast;
use codemap::{BytePos, spanned};
use parse::lexer::reader;
use parse::parser::Parser;
use parse::token;

use opt_vec;
use opt_vec::OptVec;

// SeqSep : a sequence separator (token)
// and whether a trailing separator is allowed.
pub struct SeqSep {
    sep: Option<token::Token>,
    trailing_sep_allowed: bool
}

pub fn seq_sep_trailing_disallowed(t: token::Token) -> SeqSep {
    SeqSep {
        sep: Some(t),
        trailing_sep_allowed: false,
    }
}
pub fn seq_sep_trailing_allowed(t: token::Token) -> SeqSep {
    SeqSep {
        sep: Some(t),
        trailing_sep_allowed: true,
    }
}
pub fn seq_sep_none() -> SeqSep {
    SeqSep {
        sep: None,
        trailing_sep_allowed: false,
    }
}

// maps any token back to a string. not necessary if you know it's
// an identifier....
pub fn token_to_str(reader: @reader, token: &token::Token) -> ~str {
    token::to_str(reader.interner(), token)
}

pub impl Parser {
    // convert a token to a string using self's reader
    fn token_to_str(&self, token: &token::Token) -> ~str {
        token::to_str(self.reader.interner(), token)
    }

    // convert the current token to a string using self's reader
    fn this_token_to_str(&self) -> ~str {
        self.token_to_str(self.token)
    }

    fn unexpected_last(&self, t: &token::Token) -> ! {
        self.span_fatal(
            *self.last_span,
            fmt!(
                "unexpected token: `%s`",
                self.token_to_str(t)
            )
        );
    }

    fn unexpected(&self) -> ! {
        self.fatal(
            fmt!(
                "unexpected token: `%s`",
                self.this_token_to_str()
            )
        );
    }

    // expect and consume the token t. Signal an error if
    // the next token is not t.
    fn expect(&self, t: &token::Token) {
        if *self.token == *t {
            self.bump();
        } else {
            self.fatal(
                fmt!(
                    "expected `%s` but found `%s`",
                    self.token_to_str(t),
                    self.this_token_to_str()
                )
            )
        }
    }

    fn parse_ident(&self) -> ast::ident {
        self.check_strict_keywords();
        self.check_reserved_keywords();
        match *self.token {
            token::IDENT(i, _) => {
                self.bump();
                i
            }
            token::INTERPOLATED(token::nt_ident(*)) => {
                self.bug(
                    ~"ident interpolation not converted to real token"
                );
            }
            _ => {
                self.fatal(
                    fmt!(
                        "expected ident, found `%s`",
                        self.this_token_to_str()
                    )
                );
            }
        }
    }

    fn parse_path_list_ident(&self) -> ast::path_list_ident {
        let lo = self.span.lo;
        let ident = self.parse_ident();
        let hi = self.last_span.hi;
        spanned(lo, hi, ast::path_list_ident_ { name: ident,
                                                id: self.get_id() })
    }

    // consume token 'tok' if it exists. Returns true if the given
    // token was present, false otherwise.
    fn eat(&self, tok: &token::Token) -> bool {
        return if *self.token == *tok { self.bump(); true } else { false };
    }

    // Storing keywords as interned idents instead of strings would be nifty.

    // A sanity check that the word we are asking for is a known keyword
    // NOTE: this could be done statically....
    fn require_keyword(&self, word: &str) {
        if !self.keywords.contains_equiv(&word) {
            self.bug(fmt!("unknown keyword: %s", word));
        }
    }

    // return true when this token represents the given string, and is not
    // followed immediately by :: .
    fn token_is_word(&self, word: &str, tok: &token::Token) -> bool {
        match *tok {
            token::IDENT(sid, false) => { word == *self.id_to_str(sid) }
             _ => { false }
        }
    }

    fn token_is_keyword(&self, word: &str, tok: &token::Token) -> bool {
        self.require_keyword(word);
        self.token_is_word(word, tok)
    }

    fn is_keyword(&self, word: &str) -> bool {
        self.token_is_keyword(word, &copy *self.token)
    }

    fn id_is_any_keyword(&self, id: ast::ident) -> bool {
        self.keywords.contains(self.id_to_str(id))
    }

    fn is_any_keyword(&self, tok: &token::Token) -> bool {
        match *tok {
          token::IDENT(sid, false) => {
            self.keywords.contains(self.id_to_str(sid))
          }
          _ => false
        }
    }

    // if the given word is not a keyword, signal an error.
    // if the next token is the given keyword, eat it and return
    // true. Otherwise, return false.
    fn eat_keyword(&self, word: &str) -> bool {
        self.require_keyword(word);
        let is_kw = match *self.token {
            token::IDENT(sid, false) => word == *self.id_to_str(sid),
            _ => false
        };
        if is_kw { self.bump() }
        is_kw
    }

    // if the given word is not a keyword, signal an error.
    // if the next token is not the given word, signal an error.
    // otherwise, eat it.
    fn expect_keyword(&self, word: &str) {
        self.require_keyword(word);
        if !self.eat_keyword(word) {
            self.fatal(
                fmt!(
                    "expected `%s`, found `%s`",
                    word,
                    self.this_token_to_str()
                )
            );
        }
    }

    // return true if the given string is a strict keyword
    fn is_strict_keyword(&self, word: &str) -> bool {
        self.strict_keywords.contains_equiv(&word)
    }

    // signal an error if the current token is a strict keyword
    fn check_strict_keywords(&self) {
        match *self.token {
            token::IDENT(_, false) => {
                let w = token_to_str(self.reader, &copy *self.token);
                self.check_strict_keywords_(w);
            }
            _ => ()
        }
    }

    // signal an error if the given string is a strict keyword
    fn check_strict_keywords_(&self, w: &str) {
        if self.is_strict_keyword(w) {
            self.span_err(*self.last_span,
                          fmt!("found `%s` in ident position", w));
        }
    }

    // return true if this is a reserved keyword
    fn is_reserved_keyword(&self, word: &str) -> bool {
        self.reserved_keywords.contains_equiv(&word)
    }

    // signal an error if the current token is a reserved keyword
    fn check_reserved_keywords(&self) {
        match *self.token {
            token::IDENT(_, false) => {
                let w = token_to_str(self.reader, &copy *self.token);
                self.check_reserved_keywords_(w);
            }
            _ => ()
        }
    }

    // signal an error if the given string is a reserved keyword
    fn check_reserved_keywords_(&self, w: &str) {
        if self.is_reserved_keyword(w) {
            self.fatal(fmt!("`%s` is a reserved keyword", w));
        }
    }

    // expect and consume a GT. if a >> is seen, replace it
    // with a single > and continue. If a GT is not seen,
    // signal an error.
    fn expect_gt(&self) {
        if *self.token == token::GT {
            self.bump();
        } else if *self.token == token::BINOP(token::SHR) {
            self.replace_token(
                token::GT,
                self.span.lo + BytePos(1u),
                self.span.hi
            );
        } else {
            let mut s: ~str = ~"expected `";
            s += self.token_to_str(&token::GT);
            s += ~"`, found `";
            s += self.this_token_to_str();
            s += ~"`";
            self.fatal(s);
        }
    }

    // parse a sequence bracketed by '<' and '>', stopping
    // before the '>'.
    fn parse_seq_to_before_gt<T: Copy>(
        &self,
        sep: Option<token::Token>,
        f: &fn(&Parser) -> T
    ) -> OptVec<T> {
        let mut first = true;
        let mut v = opt_vec::Empty;
        while *self.token != token::GT
            && *self.token != token::BINOP(token::SHR) {
            match sep {
              Some(ref t) => {
                if first { first = false; }
                else { self.expect(t); }
              }
              _ => ()
            }
            v.push(f(self));
        }
        return v;
    }

    fn parse_seq_to_gt<T: Copy>(
        &self,
        sep: Option<token::Token>,
        f: &fn(&Parser) -> T
    ) -> OptVec<T> {
        let v = self.parse_seq_to_before_gt(sep, f);
        self.expect_gt();
        return v;
    }

    // parse a sequence, including the closing delimiter. The function
    // f must consume tokens until reaching the next separator or
    // closing bracket.
    fn parse_seq_to_end<T: Copy>(
        &self,
        ket: &token::Token,
        sep: SeqSep,
        f: &fn(&Parser) -> T
    ) -> ~[T] {
        let val = self.parse_seq_to_before_end(ket, sep, f);
        self.bump();
        val
    }

    // parse a sequence, not including the closing delimiter. The function
    // f must consume tokens until reaching the next separator or
    // closing bracket.
    fn parse_seq_to_before_end<T: Copy>(
        &self,
        ket: &token::Token,
        sep: SeqSep,
        f: &fn(&Parser) -> T
    ) -> ~[T] {
        let mut first: bool = true;
        let mut v: ~[T] = ~[];
        while *self.token != *ket {
            match sep.sep {
              Some(ref t) => {
                if first { first = false; }
                else { self.expect(t); }
              }
              _ => ()
            }
            if sep.trailing_sep_allowed && *self.token == *ket { break; }
            v.push(f(self));
        }
        return v;
    }

    // parse a sequence, including the closing delimiter. The function
    // f must consume tokens until reaching the next separator or
    // closing bracket.
    fn parse_unspanned_seq<T: Copy>(
        &self,
        bra: &token::Token,
        ket: &token::Token,
        sep: SeqSep,
        f: &fn(&Parser) -> T
    ) -> ~[T] {
        self.expect(bra);
        let result = self.parse_seq_to_before_end(ket, sep, f);
        self.bump();
        result
    }

    // NB: Do not use this function unless you actually plan to place the
    // spanned list in the AST.
    fn parse_seq<T: Copy>(
        &self,
        bra: &token::Token,
        ket: &token::Token,
        sep: SeqSep,
        f: &fn(&Parser) -> T
    ) -> spanned<~[T]> {
        let lo = self.span.lo;
        self.expect(bra);
        let result = self.parse_seq_to_before_end(ket, sep, f);
        let hi = self.span.hi;
        self.bump();
        spanned(lo, hi, result)
    }
}


text:
using System;
using Newtonsoft.Json;

namespace Alexa.NET.Management.Api
{
    public class ExtensionUri
    {
        [JsonProperty("uri")]
        public string Uri { get; set; }
    }
}


text:
@keyframes rotateOutUpRight {
  0% {
    transform-origin: right bottom;
    opacity: 1;
  }

  100% {
    transform-origin: right bottom;
    transform: rotate3d(0, 0, 1, 90deg);
    opacity: 0;
  }
}

.rotateOutUpRight {
  animation-name: rotateOutUpRight;
}


text:
package jfxtras.scene.layout.trial;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import jfxtras.scene.layout.VBox;

public class VBoxTrial1 extends Application
{

    public static void main(String[] args)
    {
        launch(args);
    }

	@Override
	public void start(Stage stage)
	{
		VBox lVBox = new VBox(5.0);
		lVBox.add(new Button("short"), new VBox.C().vgrow(Priority.ALWAYS));
		lVBox.add(new Button("medium length"), new VBox.C().vgrow(Priority.ALWAYS));
		lVBox.add(new Button("a longer description in order to test things"), new VBox.C().vgrow(Priority.ALWAYS));
		lVBox.add(new Button("margin 5 grow"), new VBox.C().margin(new Insets(5.0)).vgrow(Priority.ALWAYS));
		lVBox.getChildren().add(new Button("old style"));
		lVBox.add(new Button("margin 20 nogrow"), new VBox.C().margin(new Insets(20.0)));
		lVBox.add(new Button("grow maxwidth 150"), new VBox.C().vgrow(Priority.ALWAYS).maxWidth(150.0));

        // setup scene
		Scene scene = new Scene(lVBox, 300, 400);

        // create stage
        stage.setTitle(this.getClass().getSimpleName());
        stage.setScene(scene);
        stage.show();
	}

}


text:
'use strict';

const utils = require('../utils/utils');
const ember = require('../utils/ember');

//------------------------------------------------------------------------------
// General rule - Don't introduce side-effects in computed properties
//------------------------------------------------------------------------------

function isUnallowedMethod(name) {
  return ['set', 'setProperties'].indexOf(name) > -1;
}

module.exports = {
  meta: {
    docs: {
      description: 'Warns about unexpected side effects in computed properties',
      category: 'Possible Errors',
      recommended: true,
      url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/no-side-effects.md'
    },
    fixable: null, // or "code" or "whitespace"
  },

  create(context) {
    let emberImportAliasName;

    const message = 'Don\'t introduce side-effects in computed properties';

    const report = function (node) {
      context.report(node, message);
    };

    return {
      ImportDeclaration(node) {
        if (!emberImportAliasName) {
          emberImportAliasName = ember.getEmberImportAliasName(node);
        }
      },

      CallExpression(node) {
        const callee = node.callee;
        const isEmberSet = (
          utils.isIdentifier(callee) &&
          isUnallowedMethod(callee.name)
        ) || (
          utils.isMemberExpression(callee) &&
          (utils.isThisExpression(callee.object) || callee.object.name === 'Ember' || callee.object.name === emberImportAliasName) &&
          utils.isIdentifier(callee.property) &&
          isUnallowedMethod(callee.property.name)
        );

        if (isEmberSet) {
          const ancestors = context.getAncestors();
          const computedIndex = ancestors.findIndex(ember.isComputedProp);
          const setPropertyFunctionIndex = ancestors.findIndex(ancestor => (
            ancestor.type === 'Property' &&
            ancestor.key.name === 'set' &&
            utils.isFunctionExpression(ancestor.value)
          ));

          if (
            computedIndex > -1 &&
            (setPropertyFunctionIndex === -1 || setPropertyFunctionIndex < computedIndex)
          ) {
            report(node);
          }
        }
      },
    };
  }
};


text:
import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/pavianAnubi/01.jpg'),
  require('../../images/animals/pavianAnubi/02.jpg'),
  require('../../images/animals/pavianAnubi/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/pavianAnubi/01-thumb.jpg'),
  require('../../images/animals/pavianAnubi/02-thumb.jpg'),
  require('../../images/animals/pavianAnubi/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
        Exkluzivně vám přinášíme přepis zvukové nahrávky dvou paviánek anubi (<Text style={styles.italic}>Papio anubis</Text>) z Afriky. Je přeložen do češtiny. Všimněte si, že paviáni tvoří hierarchicky uspořádané tlupy. Níže postavení paviáni se snaží získat co největší přízeň výše postavených samic – třeba probíráním srsti. Když se oblíbené samici narodí mládě, její status se ještě posílí…
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Papio, vypadáš dnes báječně! <Text style={styles.italic}>(zvuk čumáků třoucích se o sebe na znamení pozdravu)</Text> Jak se daří? Co vůbec dělá ten tvůj obdivovatel?
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Drahá Anubis, představ si, že zrovna teď zaběhl pro něco k jídlu. Chce se mi zavděčit. Stejně ale neumí shánět žrádlo.
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Jak to myslíš?
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Bydlíme v lese, a tak mi nosí jen ovoce. Když není sezóna, můžeme žrát tak leda pryskyřici. Raději bych šla na trávu jako sousedé ze západu. Povedlo se jim obsadit kus savany.
        </AnimalText>
        <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Ty si stěžuj! Viděla jsem, jak ti jednou donesl saranče.
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> To bylo výjimečně!
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Jede po tobě! <Text style={styles.italic}>(zvuk mrkajícího očního víčka)</Text>
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Je na mě moc starý!
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Pravda, mladší samec je vždycky pro paviánku lepší. Viděla jsi toho mlaďocha, který k nám nedávno přišel z jiné tlupy? Celkem fešák, sotva přestal mutovat.
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Statná postava, široká ramena, hříva… a špičáky jak cení! V rukou má velkou sílu, a přitom jsou tak jemné, něžné…
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Jako bys s ním něco…
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Včera mi probíral srst!
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Aha, tak to tipuju, že máš s výběrem samce jasno. Jsi v tlupě vůdčí samice, tak by to mělo vyjít. Půjčíš mi mládě, až se narodí? Fascinuje mě, že jim roste černá srst. Chtěla bych si ho pohladit.
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Papio:</Text> Jsi moje nejlepší přítelkyně. Klidně můžeš být jeho teta!
        </AnimalText>

        <AnimalText>
        <Text style={styles.strong}>Anubis:</Text> Mnohokrát děkuji! <Text style={styles.italic}>(čím dál zřetelnější zvuk vibrujících hlasivek paviánů)</Text> No ne! Už sem oba samci běží! Poperou se o tebe! <Text style={styles.italic}>(zesilující se dusot paviáních tlapek)</Text>
        </AnimalText>
        <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
        … souboj byl bohužel ještě hlasitější než rozhovor paviánek a náš nahrávací přístroj se pro jistotu automaticky vypnul. Bohužel jsme už nikde nedohledali, jestli Papio nakonec zplodila mládě a jestli si udržela oblibu v tlupě.
        </AnimalText>
        <AnimalText>
        Mateřství může totiž pro samice paviánů znamenat velkou výzvu. V roce 2000 se v naší zoo narodilo mládě paviánce Polly. Měla vždy výsadní postavení ve skupině, avšak výchovu mláděte jí zkomplikoval oboustranný šedý zákal. Po porodu jí ostatní samice dítě braly a zraňovaly ho. Zoo se proto rozhodla zákal odstranit operačně. Zákrok se zdařil a Polly opět zaujala ve skupině místo první dámy.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;


text:
package org.foxbpm.engine.impl.cmd;

import java.util.Map;

import org.foxbpm.engine.impl.entity.TokenEntity;
import org.foxbpm.engine.impl.interceptor.CommandContext;

public class SignalCmd extends NeedsTokenCmd<Object> {

	private static final long serialVersionUID = 1L;

	protected String signalName;
	protected Object signalData;
	protected Map<String, Object> transientVariables;
	protected Map<String, Object> persistenceVariables;

	public SignalCmd(String tokenId, String signalName, Object signalData, Map<String, Object> transientVariables, Map<String, Object> persistenceVariables) {
		super(tokenId);
		this.signalName = signalName;
		this.signalData = signalData;
		this.transientVariables = transientVariables;
		this.persistenceVariables = persistenceVariables;
	}

	protected Object execute(CommandContext commandContext, TokenEntity token) {
		if (transientVariables != null) {
			token.setProcessInstanceVariables(transientVariables);
		}
		if(persistenceVariables != null){
			token.setProcessInstanceVariables(transientVariables);
		}

		token.signal();
		return null;
	}

}


text:
package webcrypt.reflect;
import java.awt.event.*;
import java.beans.*;
import java.lang.reflect.*;
import java.io.*;
import java.util.*;

/**
 * This class represents a Method, the list of arguments to be passed
 * to that method, and the object on which the method is to be invoked.
 * The invoke() method invokes the method.  The actionPerformed() method
 * does the same thing, allowing this class to implement ActionListener
 * and be used to respond to ActionEvents generated in a GUI or elsewhere.
 * The static parse() method parses a string representation of a method
 * and its arguments.
 **/
public class Command implements ActionListener {
    Method m;       // The method to be invoked
    Object target;  // The object to invoke it on
    Object[] args;  // The arguments to pass to the method

    // An empty array; used for methods with no arguments at all.
    static final Object[] nullargs = new Object[] {};

    /** This constructor creates a Command object for a no-arg method */
    public Command(Object target, Method m) { this(target, m, nullargs); }

    /**
     * This constructor creates a Command object for a method that takes the
     * specified array of arguments.  Note that the parse() method provides
     * another way to create a Command object
     **/
    public Command(Object target, Method m, Object[] args) {
	this.target = target;
	this.m = m;
	this.args = args;
    }

    /**
     * Invoke the Command by calling the method on its target, and passing
     * the arguments.  See also actionPerformed() which does not throw the
     * checked exceptions that this method does.
     **/
    public void invoke()
	throws IllegalAccessException, InvocationTargetException
    {
	m.invoke(target, args);  // Use reflection to invoke the method
    }

    /**
     * This method implements the ActionListener interface.  It is like
     * invoke() except that it catches the exceptions thrown by that method
     * and rethrows them as an unchecked RuntimeException
     **/
    public void actionPerformed(ActionEvent e) {
	try {
	    invoke();                           // Call the invoke method
	}
	catch (InvocationTargetException ex) {  // but handle the exceptions
	    throw new RuntimeException("Command: " +
				       ex.getTargetException().toString());
	}
	catch (IllegalAccessException ex) {
	    throw new RuntimeException("Command: " + ex.toString());
	}
    }

    /**
     * This static method creates a Command using the specified target object,
     * and the specified string.  The string should contain method name
     * followed by an optional parenthesized comma-separated argument list and
     * a semicolon.  The arguments may be boolean, integer or double literals,
     * or double-quoted strings.  The parser is lenient about missing commas,
     * semicolons and quotes, but throws an IOException if it cannot parse the
     * string.
     **/
    public static Command parse(Object target, String text) throws IOException
    {
	String methodname;                 // The name of the method
	ArrayList args = new ArrayList();  // Hold arguments as we parse them.
	ArrayList types = new ArrayList(); // Hold argument types.

	// Convert the string into a character stream, and use the
	// StreamTokenizer class to convert it into a stream of tokens
	StreamTokenizer t = new StreamTokenizer(new StringReader(text));

	// The first token must be the method name
	int c = t.nextToken();  // read a token
	if (c != t.TT_WORD)     // check the token type
	    throw new IOException("Missing method name for command");
	methodname = t.sval;    // Remember the method name

	// Now we either need a semicolon or a open paren
	c = t.nextToken();
	if (c == '(') { // If we see an open paren, then parse an arg list
	    for(;;) {                   // Loop 'till end of arglist
		c = t.nextToken();      // Read next token

		if (c == ')') {         // See if we're done parsing arguments.
		    c = t.nextToken();  // If so, parse an optional semicolon
		    if (c != ';') t.pushBack();
		    break;              // Now stop the loop.
		}

		// Otherwise, the token is an argument; figure out its type
		if (c == t.TT_WORD) {
		    // If the token is an identifier, parse boolean literals,
		    // and treat any other tokens as unquoted string literals.
		    if (t.sval.equals("true")) {       // Boolean literal
			args.add(Boolean.TRUE);
			types.add(boolean.class);
		    }
		    else if (t.sval.equals("false")) { // Boolean literal
			args.add(Boolean.FALSE);
			types.add(boolean.class);
		    }
		    else {                             // Assume its a string
			args.add(t.sval);
			types.add(String.class);
		    }
		}
		else if (c == '"') {         // If the token is a quoted string
		    args.add(t.sval);
		    types.add(String.class);
		}
		else if (c == t.TT_NUMBER) { // If the token is a number
		    int i = (int) t.nval;
		    if (i == t.nval) {           // Check if its an integer
			// Note: this code treats a token like "2.0" as an int!
			args.add(new Integer(i));
			types.add(int.class);
		    }
		    else {                       // Otherwise, its a double
			args.add(new Double(t.nval));
			types.add(double.class);
		    }
		}
		else {                        // Any other token is an error
		    throw new IOException("Unexpected token " + t.sval +
					  " in argument list of " +
					  methodname + "().");
		}

		// Next should be a comma, but we don't complain if its not
		c = t.nextToken();
		if (c != ',') t.pushBack();
	    }
	}
	else if (c != ';') { // if a method name is not followed by a paren
	    t.pushBack();    // then allow a semi-colon but don't require it.
	}

	// We've parsed the argument list.
	// Next, convert the lists of argument values and types to arrays
	Object[] argValues = args.toArray();
	Class[] argtypes = (Class[])types.toArray(new Class[argValues.length]);

	// At this point, we've got a method name, and arrays of argument
	// values and types.  Use reflection on the class of the target object
	// to find a method with the given name and argument types.  Throw
	// an exception if we can't find the named method.
	Method method;
	try { method = target.getClass().getMethod(methodname, argtypes); }
	catch (Exception e) {
	    throw new IOException("No such method found, or wrong argument " +
				  "types: " + methodname);
	}

	// Finally, create and return a Command object, using the target object
	// passed to this method, the Method object we obtained above, and
	// the array of argument values we parsed from the string.
	return new Command(target, method, argValues);
    }

    /**
     * This simple program demonstrates how a Command object can be parsed from
     * a string and used as an ActionListener object in a Swing application.
     **/
    static class Test {
	public static void main(String[] args) throws IOException {
	    javax.swing.JFrame f = new javax.swing.JFrame("Command Test");
	    javax.swing.JButton b1 = new javax.swing.JButton("Tick");
	    javax.swing.JButton b2 = new javax.swing.JButton("Tock");
	    javax.swing.JLabel label = new javax.swing.JLabel("Hello world");
	    java.awt.Container pane = f.getContentPane();

	    pane.add(b1, java.awt.BorderLayout.WEST);
	    pane.add(b2, java.awt.BorderLayout.EAST);
	    pane.add(label, java.awt.BorderLayout.NORTH);

	    b1.addActionListener(Command.parse(label, "setText(\"tick\");"));
	    b2.addActionListener(Command.parse(label, "setText(\"tock\");"));

	    f.pack();
	    f.show();
	}
    }
}


text:
<!DOCTYPE html>

<f:layout name="Default"/>

<f:section name="Title">Profile Settings</f:section>

<f:section name="Content">

<f:translate id="profile.title" package="Sandstorm.UserManagement" source="Templates/Partials/Profile"/>

      <f:if condition="{pluginArguments.__showPersonalInformation}">
          <f:render section="Personal" />
      </f:if>
      <f:if condition="{pluginArguments.__showAccountInformation}">
          <f:render section="Account" />
      </f:if>
      <f:if condition="{pluginArguments.__enableNewPassword}">
          <f:render section="Password" />
      </f:if>
</f:section>
<f:section name="Personal">

<f:translate id="profile.personal" package="Sandstorm.UserManagement" source="Templates/Partials/Profile"/>

    <usermanagement:ifAuthenticated authenticationProviderName="Sandstorm.UserManagement:Login">
        <f:then>
            <f:form action="editProfile" method="post" object="{user}" objectName="user">
                <f:render partial="Profile/PersonalForm" section="PersonalForm" arguments="{_all}"/>
            </f:form>
        </f:then>
        <f:else>
            <f:render partial="Profile/PersonalForm" section="PersonalForm" arguments="{_all}"/>
        </f:else>
    </usermanagement:ifAuthenticated>
</f:section>
<f:section name="Account">

<f:translate id="profile.account" package="Sandstorm.UserManagement" source="Templates/Partials/Profile"/>

    <f:render partial="Profile/AccountData" section="DataTable" arguments="{_all}"/>
</f:section>
<f:section name="Password">

<f:translate id="profile.password" package="Sandstorm.UserManagement" source="Templates/Partials/Profile"/>

    <usermanagement:ifAuthenticated authenticationProviderName="Sandstorm.UserManagement:Login">
        <f:then>
            <f:form action="setNewPassword" object="{account}" objectName="account">
                <f:render partial="Profile/PasswordForm" section="NewPassword" arguments="{_all}"/>
            </f:form>
        </f:then>
        <f:else>
            <f:render partial="Profile/PasswordForm" section="NewPassword" arguments="{_all}"/>
        </f:else>
    </usermanagement:ifAuthenticated>
</f:section>


text:
package acceptableLosses.work.jobs;

import acceptableLosses.components.Resume;
import acceptableLosses.map.Region;
import com.stewsters.util.math.Facing3d;
import com.stewsters.util.pathing.threeDimention.searcher.Objective3d;
import com.stewsters.util.pathing.threeDimention.shared.PathNode3d;

public class JobObjective implements Objective3d {

    private Region region;
    private Resume resume;

    public JobObjective(Region region, Resume resume) {
        this.region = region;
        this.resume = resume;
    }

    @Override
    public boolean satisfiedBy(PathNode3d current) {
        // checks to see if there is a job here that we can do

        Job job = region.getJobAt(current.x, current.y, current.z);
        if (job != null && job.satisfiedBy(resume) && job.getAssignee() == 0) {
            return true;
        }

        for (Facing3d facing3d : Facing3d.values()) {

            job = region.getJobAt(current.x + facing3d.x, current.y + facing3d.y, current.z + facing3d.z);
            if (job != null && job.satisfiedBy(resume) && job.getAssignee() == 0) {
                return true;
            }
        }

        return false;

    }
}


text:
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/cpu.h>
#include <linux/syscalls.h>
#include <linux/gfp.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/suspend.h>
#include <linux/syscore_ops.h>
#include <linux/rtc.h>
#include <linux/ftrace.h>
#include <trace/events/power.h>

#include "power.h"

const char *const pm_states[PM_SUSPEND_MAX] = {
	[PM_SUSPEND_STANDBY]	= "standby",
	[PM_SUSPEND_MEM]	= "mem",
};

static const struct platform_suspend_ops *suspend_ops;

/**
 * suspend_set_ops - Set the global suspend method table.
 * @ops: Suspend operations to use.
 */
void suspend_set_ops(const struct platform_suspend_ops *ops)
{
	lock_system_sleep();
	suspend_ops = ops;
	unlock_system_sleep();
}
EXPORT_SYMBOL_GPL(suspend_set_ops);

bool valid_state(suspend_state_t state)
{
	/*
	 * All states need lowlevel support and need to be valid to the lowlevel
	 * implementation, no valid callback implies that none are valid.
	 */
	return suspend_ops && suspend_ops->valid && suspend_ops->valid(state);
}

/**
 * suspend_valid_only_mem - Generic memory-only valid callback.
 *
 * Platform drivers that implement mem suspend only and only need to check for
 * that in their .valid() callback can use this instead of rolling their own
 * .valid() callback.
 */
int suspend_valid_only_mem(suspend_state_t state)
{
	return state == PM_SUSPEND_MEM;
}
EXPORT_SYMBOL_GPL(suspend_valid_only_mem);

static int suspend_test(int level)
{
#ifdef CONFIG_PM_DEBUG
	if (pm_test_level == level) {
		printk(KERN_INFO "suspend debug: Waiting for 5 seconds.\n");
		mdelay(5000);
		return 1;
	}
#endif /* !CONFIG_PM_DEBUG */
	return 0;
}

/**
 * suspend_prepare - Prepare for entering system sleep state.
 *
 * Common code run for every system sleep state that can be entered (except for
 * hibernation).  Run suspend notifiers, allocate the "suspend" console and
 * freeze processes.
 */
static int suspend_prepare(void)
{
	int error;

	if (!suspend_ops || !suspend_ops->enter)
		return -EPERM;

	pm_prepare_console();

	error = pm_notifier_call_chain(PM_SUSPEND_PREPARE);
	if (error)
		goto Finish;

	error = suspend_freeze_processes();
	if (!error)
		return 0;

	suspend_stats.failed_freeze++;
	dpm_save_failed_step(SUSPEND_FREEZE);
 Finish:
	pm_notifier_call_chain(PM_POST_SUSPEND);
	pm_restore_console();
	return error;
}

/* default implementation */
void __attribute__ ((weak)) arch_suspend_disable_irqs(void)
{
	local_irq_disable();
}

/* default implementation */
void __attribute__ ((weak)) arch_suspend_enable_irqs(void)
{
	local_irq_enable();
}

/**
 * suspend_enter - Make the system enter the given sleep state.
 * @state: System sleep state to enter.
 * @wakeup: Returns information that the sleep state should not be re-entered.
 *
 * This function should be called after devices have been suspended.
 */
static int suspend_enter(suspend_state_t state, bool *wakeup)
{
	int error;

	if (suspend_ops->prepare) {
		error = suspend_ops->prepare();
		if (error)
			goto Platform_finish;
	}

	error = dpm_suspend_end(PMSG_SUSPEND);
	if (error) {
		printk(KERN_ERR "PM: Some devices failed to power down\n");
		goto Platform_finish;
	}

	if (suspend_ops->prepare_late) {
		error = suspend_ops->prepare_late();
		if (error)
			goto Platform_wake;
	}

	if (suspend_test(TEST_PLATFORM))
		goto Platform_wake;

	error = disable_nonboot_cpus();
	if (error || suspend_test(TEST_CPUS))
		goto Enable_cpus;

	arch_suspend_disable_irqs();
	BUG_ON(!irqs_disabled());

	error = syscore_suspend();
	if (!error) {
		*wakeup = pm_wakeup_pending();
		if (!(suspend_test(TEST_CORE) || *wakeup)) {
			error = suspend_ops->enter(state);
			events_check_enabled = false;
		}
		syscore_resume();
	}

	arch_suspend_enable_irqs();
	BUG_ON(irqs_disabled());

 Enable_cpus:
	enable_nonboot_cpus();

 Platform_wake:
	if (suspend_ops->wake)
		suspend_ops->wake();

	dpm_resume_start(PMSG_RESUME);

 Platform_finish:
	if (suspend_ops->finish)
		suspend_ops->finish();

	return error;
}

/**
 * suspend_devices_and_enter - Suspend devices and enter system sleep state.
 * @state: System sleep state to enter.
 */
int suspend_devices_and_enter(suspend_state_t state)
{
	int error;
	bool wakeup = false;

	if (!suspend_ops)
		return -ENOSYS;

	trace_machine_suspend(state);
	if (suspend_ops->begin) {
		error = suspend_ops->begin(state);
		if (error)
			goto Close;
	}
	suspend_console();
	ftrace_stop();
	suspend_test_start();
	error = dpm_suspend_start(PMSG_SUSPEND);
	if (error) {
		printk(KERN_ERR "PM: Some devices failed to suspend\n");
		goto Recover_platform;
	}
	suspend_test_finish("suspend devices");
	if (suspend_test(TEST_DEVICES))
		goto Recover_platform;

	do {
		error = suspend_enter(state, &wakeup);
	} while (!error && !wakeup
		&& suspend_ops->suspend_again && suspend_ops->suspend_again());

 Resume_devices:
	suspend_test_start();
	dpm_resume_end(PMSG_RESUME);
	suspend_test_finish("resume devices");
	ftrace_start();
	resume_console();
 Close:
	if (suspend_ops->end)
		suspend_ops->end();
	trace_machine_suspend(PWR_EVENT_EXIT);
	return error;

 Recover_platform:
	if (suspend_ops->recover)
		suspend_ops->recover();
	goto Resume_devices;
}

/**
 * suspend_finish - Clean up before finishing the suspend sequence.
 *
 * Call platform code to clean up, restart processes, and free the console that
 * we've allocated. This routine is not called for hibernation.
 */
static void suspend_finish(void)
{
	suspend_thaw_processes();
	pm_notifier_call_chain(PM_POST_SUSPEND);
	pm_restore_console();
}

/**
 * enter_state - Do common work needed to enter system sleep state.
 * @state: System sleep state to enter.
 *
 * Make sure that no one else is trying to put the system into a sleep state.
 * Fail if that's not the case.  Otherwise, prepare for system suspend, make the
 * system enter the given sleep state and clean up after wakeup.
 */
static int enter_state(suspend_state_t state)
{
	int error;

	if (!valid_state(state))
		return -ENODEV;

	if (!mutex_trylock(&pm_mutex))
		return -EBUSY;

	printk(KERN_INFO "PM: Syncing filesystems ... ");
	sys_sync();
	printk("done.\n");

	pr_debug("PM: Preparing system for %s sleep\n", pm_states[state]);
	error = suspend_prepare();
	if (error)
		goto Unlock;

	if (suspend_test(TEST_FREEZER))
		goto Finish;

	pr_debug("PM: Entering %s sleep\n", pm_states[state]);
	pm_restrict_gfp_mask();
	error = suspend_devices_and_enter(state);
	pm_restore_gfp_mask();

 Finish:
	pr_debug("PM: Finishing wakeup.\n");
	suspend_finish();
 Unlock:
	mutex_unlock(&pm_mutex);
	return error;
}

static void pm_suspend_marker(char *annotation)
{
	struct timespec ts;
	struct rtc_time tm;

	getnstimeofday(&ts);
	rtc_time_to_tm(ts.tv_sec, &tm);
	pr_info("PM: suspend %s %d-%02d-%02d %02d:%02d:%02d.%09lu UTC\n",
		annotation, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
		tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
}

/**
 * pm_suspend - Externally visible function for suspending the system.
 * @state: System sleep state to enter.
 *
 * Check if the value of @state represents one of the supported states,
 * execute enter_state() and update system suspend statistics.
 */
int pm_suspend(suspend_state_t state)
{
	int error;

	if (state <= PM_SUSPEND_ON || state >= PM_SUSPEND_MAX)
		return -EINVAL;

	pm_suspend_marker("entry");
	error = enter_state(state);
	if (error) {
		suspend_stats.fail++;
		dpm_save_failed_errno(error);
	} else {
		suspend_stats.success++;
	}
	pm_suspend_marker("exit");
	return error;
}
EXPORT_SYMBOL(pm_suspend);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Catalogue.Controllers
{
    public class UserAccount
    {
        [Required, StringLength(128), Display(Name="Username")]
        public string UserName { get; set; }

        [Required, StringLength(128), Display(Name = "Password"), DataType(DataType.Password)]
        public string Password { get; set; }

        [Required, StringLength(128), Display(Name = "Confirm Password"), DataType(DataType.Password), Compare("Password")]
        public string ConfirmPassword { get; set; }

        [Required, StringLength(128), Display(Name = "Email"), DataType(DataType.EmailAddress)]
        public string Email { get; set; }
    }
}


text:
<scxml initial="input_manager_initial_state" name="input" version="0.9" xmlns="http://www.w3.org/2005/07/scxml">

<state id="input_manager_initial_state" initial="touch_input" name="input_manager_initial_state">

  <datamodel>
   <data expr="new Object()" id="data"></data>
  </datamodel>

  <transition event="speech_input_event" target="speech_input"></transition>
  <transition event="touch_input_event" target="touch_input"></transition>

  <state id="speech_input" name="speech_input">
    <datamodel>
      <data expr="''" id="command_name"></data>
      <data expr="{}" id="command"></data>
      <data expr="{"Emma": { "medium": "acoustic" , "mode" : "voice" }}" id="emma"></data>
    </datamodel>
    <onentry>
      <script>
          var actionName;
          for (name in _event.data) {
            if(name == 'phrase'){
              continue;
            }
            if(_event.data.hasOwnProperty(name)){
              actionName = name;
              break;
            }
          }
          console.log('InputManager: setting command_name to "'+actionName+'" for event-data '+JSON.stringify(_event.data));

          command_name = actionName;
      </script>
      <assign expr="_event.data" location="command"></assign>
    </onentry>
    <transition cond="command_name == 'Send'" target="send"></transition>
    <transition cond="command_name == 'Play'" target="play"></transition>
    <transition cond="command_name == 'Record'" target="record"></transition>
    <transition cond="command_name == 'ShowInfo'" target="show_info"></transition>
    <transition cond="command_name == 'Rating'" target="rating"></transition>
    <transition cond="command_name == 'RadarStart'" target="start_radar"></transition>
    <transition cond="command_name == 'ShowPOIs'" target="show_pois"></transition>
    <transition cond="command_name == 'ShowAppointments'" target="show_appointments"></transition>
    <transition cond="command_name == 'CreateAppointment'" target="create_appointment"></transition>
    <transition cond="command_name == 'RecordMemo'" target="record_memo"></transition>
    <transition cond="command_name == 'FindPerson'" target="find_person"></transition>
    <transition cond="command_name == 'NoMatch'" target="no_match"></transition>
  </state>
  <state id="no_match" name="no_match">
    <onentry>
      <script>
        var dm = null;//TODO: mmir.CalendarModel.getInstance().getDiscourseManager();
        if (dm == null) {
          var msg = mmir.lang.getText('did_not_understand_msg');
          mmir.media.textToSpeech(msg);
        } else {
          dm.getCommand().parse(command);
        }
     </script>
   </onentry>
  </state>
  <state id="send" name="send">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();

        //dummy code:
        console.info('sending ....')
        alert('sending ....');
      </script>
    </onentry>
  </state>
  <state id="play" name="play">
    <onentry>
      <script>
          //dummy code:
          console.info('play something ...')
          alert('play something ...');
      </script>
    </onentry>
  </state>
  <state id="record" name="record">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('click_on_rec_btn');
      </script>
    </onentry>
  </state>
  <state id="show_info" name="show_info">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('poi.display_details');
      </script>
    </onentry>
  </state>
  <state id="rating" name="rating">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        //dummy code:
        console.info('rating ...')
        alert('rating ....');
      </script>
    </onentry>
  </state>
  <state id="start_radar" name="start_radar">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('click_on_radar_btn');
      </script>
    </onentry>
  </state>
  <state id="play_radio" name="play_radio">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('click_on_start_radio_btn', emma);
      </script>
    </onentry>
  </state>
  <state id="play_audio" name="play_audio">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('click_on_start_audio_btn', emma);
      </script>
    </onentry>
  </state>
  <state id="play_voice" name="play_voice">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.MediaManager.textToSpeech('Sie können zurzeit nur Audio und lokationsbasiertes Radio abspielen.',null, null);
      </script>
    </onentry>
  </state>
  <state id="show_appointments" name="show_appointments">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('show_appointments_speech', command);
      </script>
    </onentry>
  </state>
  <state id="create_appointment" name="create_appointment">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.raise('create_appointment_speech', command);
      </script>
    </onentry>
  </state>
  <state id="record_memo" name="record_memo">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.performHelper('Calendar', 'capture');
      </script>
    </onentry>
  </state>
  <state id="find_person" name="find_person">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        mmir.dialog.perform('Calendar', 'find_person', command);
      </script>
    </onentry>
  </state>
  <state id="show_pois" name="show_pois">
    <onentry>
      <script>
        mmir.CalendarModel.getInstance().clearDiscourseManager();
        //dummy code:
        console.info('showing some pois ...')
        alert('showing some pois ...');
      </script>
    </onentry>
  </state>

  <state id="touch_input" initial="start_touch" name="touch_input">

    <state id="start_touch" name="start_touch">

<!-- EXAMPLE forward event data as EMMA object (i.e. with metadata and the original event-data as property evtdata):
    <onentry>
     <script>
         data = { "Emma" : { "medium" : "tactile" , "mode" : "gui" }};
     </script>
     <assign expr="{}" location="data.evtdata"></assign>
    </onentry>

    <onexit>
     <assign expr="_event.data" location="data.evtdata.data"></assign>
    </onexit>

    EXAMPLE forward event-data normally (without EMMA metadata)
-->
    <onentry>
       <assign expr="{}" location="data"></assign>
    </onentry>
    <onexit>
      <assign expr="_event.data" location="data"></assign>
      </onexit>

      <transition event="back" target="back"></transition>
      <transition event="click_on_login_btn" target="login"></transition>
      <transition event="click_on_register_btn" target="register"></transition>
      <transition event="click_on_sign_up_btn" target="sign_up"></transition>

      <transition event="click_on_appointment_btn" target="appointment"></transition>
      <transition event="click_on_save_appointment_btn" target="save_appointment"></transition>
      <transition event="click_on_discard_appointment_btn" target="discard_appointment"></transition>

      <transition event="click_on_language_btn" name="click_on_language_btn" target="language_btn"></transition>
      <transition event="language_choosen" name="language_choosen" target="language_chosen"></transition>

    </state>

    <state id="back" name="back">
      <onentry>
        <script>
          mmir.dialog.raise('back');
        </script>
      </onentry>
    </state>

    <state id="login" name="login">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_login_btn');
        </script>
       </onentry>
    </state>

    <state id="register" name="register">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_register_btn');
        </script>
      </onentry>
    </state>

    <state id="sign_up" name="sign_up">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_sign_up_btn');
        </script>
      </onentry>
    </state>

    <state id="appointment" name="appointment">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_appointment_btn');
        </script>
      </onentry>
    </state>

    <state id="save_appointment" name="save_appointment">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_save_appointment_btn');
        </script>
      </onentry>
    </state>

    <state id="discard_appointment" name="discard_appointment">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_discard_appointment_btn');
        </script>
      </onentry>
    </state>

    <state id="language_btn" name="language_btn">
      <onentry>
        <script>
          mmir.dialog.raise('click_on_language_btn', data);
        </script>
      </onentry>
    </state>

    <state id="language_chosen" name="language_chosen">
      <onentry>
        <script>
          mmir.dialog.raise('language_choosen', data);
        </script>
      </onentry>
    </state>

  </state>

</state>
</scxml>


text:
<?php

use MattFerris\Auth\Response;

class ResponseTest extends PHPUnit_Framework_TestCase
{
    public function testResponse()
    {
        $attr = array('foo' => 'bar');
        $response = new Response(true, $attr);
        $this->assertTrue($response->isValid());
        $this->assertEquals($response->getAttributes(), $attr);
    }
}


text:
<?php

namespace luyatests\core\web;

use Yii;
use luya\web\Request;

class RequestTest extends \luyatests\LuyaWebTestCase
{
    public function testisAdmin()
    {
        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'admin/test/';
        $this->assertEquals(true, $request->getIsAdmin(true));

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'nothing/inside/test/';
        $this->assertEquals(false, $request->isAdmin);

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'nothing/admin/test/';
        $this->assertEquals(false, $request->isAdmin);

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'newsadmin/foo/test/';
        $this->assertEquals(true, $request->isAdmin);

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'test/admin/test/';
        $this->assertEquals(false, $request->isAdmin);

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'admin/ÜÄß';
        $this->assertEquals(true, $request->isAdmin);

        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = 'de/admin/test/';
        $this->assertEquals(true, $request->isAdmin);

        // changing language code in composition pattern
        Yii::$app->composition->pattern = '<langShortCode:[0-9]{1}>';
        $request = new Request();
        $request->forceWebRequest = true;
        $request->pathInfo = '1/admin/test/';
        $this->assertEquals(true, $request->isAdmin);
    }
}


text:
<?php

namespace Incenteev\DynamicParametersBundle;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Yaml\Inline;

class ParameterRetriever
{
    private $container;
    private $parameterMap;

    public function __construct(ContainerInterface $container, array $parameterMap)
    {
        $this->container = $container;
        $this->parameterMap = $parameterMap;
    }

    /**
     * @param string $name
     *
     * @return array|string|bool|int|float|null
     */
    public function getParameter($name)
    {
        if (!isset($this->parameterMap[$name])) {
            return $this->container->getParameter($name);
        }

        $varName = $this->parameterMap[$name]['variable'];

        $var = getenv($varName);

        if (false === $var) {
            return $this->container->getParameter($name);
        }

        if ($this->parameterMap[$name]['yaml']) {
            return Inline::parse($var);
        }

        return $var;
    }
}


text:
using Expressive.Expressions;
using System.Collections.Generic;

namespace Expressive.Functions
{
    /// <summary>
    /// Interface definition for a Function that can be evaluated.
    /// </summary>
    public interface IFunction
    {
        /// <summary>
        /// Gets or sets the Variables and their values to be used in evaluating an <see cref="Expression"/>.
        /// </summary>
#pragma warning disable CA2227 // Collection properties should be read only - it is likely this can be passed in to Evaluate but it will need to be done carefully (e.g. mark this setter as obsolete first).
        IDictionary<string, object> Variables { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only

        /// <summary>
        /// Gets the name of the Function.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Forces the Function to evaluate itself using the supplied parameters.
        /// </summary>
        /// <param name="parameters">The list of parameters inside the Function.</param>
        /// <param name="context">The evaluation context to be used.</param>
        /// <returns>The result of the Function.</returns>
        object Evaluate(IExpression[] parameters, Context context);
    }
}


text:
Cypress.on('uncaught:exception', (err) => {
  if ((err.message.includes('Minified React error #418') || err.message.includes('Minified React error #423') || err.message.includes('Minified React error #425')) && Cypress.env(`TEST_PLUGIN_OFFLINE`)) {
    return false
  }
})

describe(`Client only paths`, () => {
  const routes = [
    {
      path: `/client-only-paths`,
      marker: `index`,
      label: `Index route`,
    },
    {
      path: `/client-only-paths/page/profile`,
      marker: `profile`,
      label: `Dynamic route`,
    },
    {
      path: `/client-only-paths/not-found`,
      marker: `NotFound`,
      label: `Default route (not found)`,
    },
    {
      path: `/client-only-paths/nested`,
      marker: `nested-page/index`,
      label: `Index route inside nested router`,
    },
    {
      path: `/client-only-paths/nested/foo`,
      marker: `nested-page/foo`,
      label: `Dynamic route inside nested router`,
    },
    {
      path: `/client-only-paths/static`,
      marker: `static-sibling`,
      label: `Static route that is a sibling to client only path`,
    },
    {
      path: `/app`,
      marker: `app-index-1`,
      label: `Prioritize static page over matchPath page with wildcard (static page created before matchPath page)`,
    },
    {
      path: `/app2`,
      marker: `app-index-2`,
      label: `Prioritize static page over matchPath page with wildcard (static page created after matchPath page)`,
    },
    {
      path: `/app/foo`,
      marker: `app-wildcard-1`,
      label: `Can navigate to matchPath page with wildcard #1`,
    },
    {
      path: `/app2/foo`,
      marker: `app-wildcard-2`,
      label: `Can navigate to matchPath page with wildcard #2`,
    },
    {
      path: `/event/2019/10/26/test-event`,
      marker: `static-event-1`,
      label: `Prioritize static page over matchPath page with named parameters (static page created before matchPath page)`,
    },
    {
      path: `/event/2019/10/28/test-event`,
      marker: `static-event-2`,
      label: `Prioritize static page over matchPath page with named parameters (static page created after matchPath page)`,
    },
    {
      path: `/event/2019/10/27/test-event`,
      marker: `dynamic-event`,
      label: `Prioritize matchPath page with named parameters over matchPath page with wildcard`,
    },
    {
      path: `/event/2019/10/foo`,
      marker: `dynamic-and-wildcard`,
      label: `Can navigate to matchPath page with mix of named parameters and wildcard`,
    },
  ]

  describe(`work on first load`, () => {
    routes.forEach(({ path, marker, label, skipTestingExactLocation }) => {
      it(label, () => {
        cy.on('uncaught:exception', (err, runnable) => {
          if (err.message.includes('Minified React error')) {
            return false
          }
        })
        cy.visit(path).waitForRouteChange()
        cy.getTestElement(`dom-marker`).contains(marker)

        // `serve-static` (used by `gatsby serve`) is doing some redirects when
        // navigating to static pages to always include trailing slash.
        // We want to pass this check if trailing slash is added.
        cy.url().should(
          `match`,
          new RegExp(`^${Cypress.config().baseUrl + path}/?$`)
        )
      })
    })
  })

  describe(`work on client side navigation`, () => {
    beforeEach(() => {
      cy.visit(`/`).waitForRouteChange()
    })
    routes.forEach(({ path, marker, label }) => {
      it(label, () => {
        cy.navigateAndWaitForRouteChange(path)
        cy.getTestElement(`dom-marker`).contains(marker)
        cy.url().should(`eq`, Cypress.config().baseUrl + path)
      })
    })
  })
})


text:
module SecureRooms

  class Occupancy < ApplicationRecord

    include DateTimeInput::Model

    belongs_to :secure_room, foreign_key: :product_id
    belongs_to :user
    belongs_to :account
    belongs_to :order_detail
    belongs_to :entry_event, class_name: "SecureRooms::Event"
    belongs_to :exit_event, class_name: "SecureRooms::Event"

    delegate :facility, to: :secure_room
    delegate :to_s, to: :range
    delegate :editing_time_data, to: :order_detail, allow_nil: true

    date_time_inputable :entry_at
    date_time_inputable :exit_at

    alias_attribute :actual_start_at, :entry_at
    alias_attribute :actual_end_at, :exit_at

    validates :secure_room, :user, presence: true
    validate :entry_and_exit_are_valid, if: :editing_time_data

    # Not used internally, but implemented for API compatibility with Reservation
    attr_writer :force_completion

    def self.valid
      where(orphaned_at: nil)
    end

    def self.orphaned
      where.not(orphaned_at: nil)
    end

    def self.current
      valid.order(entry_at: :desc).where(exit_at: nil).where.not(entry_at: nil)
    end

    def self.recent
      valid.order(exit_at: :desc).where.not(exit_at: nil).limit(10)
    end

    def mark_orphaned!
      update!(orphaned_at: Time.current)
    end

    def orphan?
      orphaned_at?
    end

    def associate_entry!(event)
      update!(
        entry_event: event,
        entry_at: event.occurred_at,
      )
      self
    end

    def associate_exit!(event)
      update!(
        exit_event: event,
        exit_at: event.occurred_at,
      )
      self
    end

    def order_completable?
      activity_finalized = orphaned_at? || (entry_at && exit_at)
      order_detail_id? && account_id? && activity_finalized
    end

    def actual_duration_mins
      range.duration_mins
    end

    def problem_description_key
      if entry_at.blank?
        :missing_entry
      elsif exit_at.blank?
        :missing_exit
      elsif exit_at <= entry_at
        entry_event.present? ? :missing_exit : :missing_entry
      end
    end

    def force_dirty!
      # This doesn't have to be entry_at -- it just needs to be something
      entry_at_will_change!
    end

    private

    def range
      TimeRange.new(entry_at, exit_at)
    end

    def entry_and_exit_are_valid
      if entry_at && exit_at
        errors.add(:actual_duration_mins, :zero_minutes) if exit_at <= entry_at
      elsif entry_at.blank?
        errors.add(:entry_at, :blank)
      elsif exit_at.blank?
        errors.add(:exit_at, :blank)
      end
    end

  end

end


text:
#import <Cordova/CDV.h>

@interface RareloopAppVersion : CDVPlugin <UIWebViewDelegate>
{
}

- (void)getAppVersion:(CDVInvokedUrlCommand*)command;

@end


text:
const char* enum_names[] = {
  COLOR_IDS
  CHROME_COLOR_IDS
};
// clang-format on

// Note that this second include is not redundant. The second inclusion of the
// .inc file serves to undefine the macros the first inclusion defined.
#include "ui/color/color_id_macros.inc"

// Longest color name, plus a space.  Currently, "SK_ColorTRANSPARENT ".
constexpr size_t kColorColumnWidth = 19 + 1;

std::string SkColorToString(SkColor color) {
  std::string color_string = ui::SkColorName(color);
  // Don't use the rgba() representation here. Just fall back to simple hex.
  if (color_string.find_first_of("rgb") == 0)
    color_string = base::StringPrintf("#%.8x", color);
  // Now format it into the necessary space.
  return base::StringPrintf("%-*s", int{kColorColumnWidth},
                            color_string.c_str());
}

int main(int argc, const char* argv[]) {
  const auto add_mixers = [](ui::ColorProvider* provider, auto color_mode,
                             auto contrast_mode) {
    const ui::ColorProviderManager::Key key = {
        color_mode, contrast_mode, ui::SystemTheme::kDefault,
        ui::ColorProviderManager::FrameType::kChromium};
    ui::AddColorMixers(provider, key);
    AddChromeColorMixers(provider, key);
    provider->GenerateColorMap();
  };
  ui::ColorProvider light_provider, dark_provider, light_high_contrast_provider,
      dark_high_contrast_provider;
  add_mixers(&light_provider, ui::ColorProviderManager::ColorMode::kLight,
             ui::ColorProviderManager::ContrastMode::kNormal);
  add_mixers(&dark_provider, ui::ColorProviderManager::ColorMode::kDark,
             ui::ColorProviderManager::ContrastMode::kNormal);
  add_mixers(&light_high_contrast_provider,
             ui::ColorProviderManager::ColorMode::kLight,
             ui::ColorProviderManager::ContrastMode::kHigh);
  add_mixers(&dark_high_contrast_provider,
             ui::ColorProviderManager::ColorMode::kDark,
             ui::ColorProviderManager::ContrastMode::kHigh);

  size_t longest_name = 0;
  for (const char* name : enum_names)
    longest_name = std::max(longest_name, strlen(name));
  ++longest_name;  // For trailing space.

  std::cout << std::setfill(' ') << std::left;
  std::cout << std::setw(longest_name) << "ID";
  std::cout << std::setw(kColorColumnWidth) << "Light";
  std::cout << std::setw(kColorColumnWidth) << "Dark";
  std::cout << std::setw(kColorColumnWidth) << "Light High Contrast";
  std::cout << "Dark High Contrast\n";
  std::cout << std::setfill('-') << std::right;
  std::cout << std::setw(longest_name) << ' ';
  std::cout << std::setw(kColorColumnWidth) << ' ';
  std::cout << std::setw(kColorColumnWidth) << ' ';
  std::cout << std::setw(kColorColumnWidth) << ' ';
  std::cout << std::setw(kColorColumnWidth) << '\n';

  for (ui::ColorId id = ui::kUiColorsStart; id < kChromeColorsEnd; ++id) {
    std::cout << std::setfill(' ') << std::left;
    std::cout << std::setw(longest_name) << enum_names[id];
    std::cout << SkColorToString(light_provider.GetColor(id));
    std::cout << SkColorToString(dark_provider.GetColor(id));
    std::cout << SkColorToString(light_high_contrast_provider.GetColor(id));
    std::cout << SkColorToString(dark_high_contrast_provider.GetColor(id))
              << '\n';
  }

  std::cout.flush();

  return 0;
}


text:
import logging
import os
import sys

from coverage import __version__
from coverage.misc import NoSource
from coverage.misc import NotPython
from coverage.phystokens import source_encoding
from coverage.report import Reporter

from .exception import CoverallsException

log = logging.getLogger('coveralls.reporter')

class CoverallReporter(Reporter):
    """ Custom coverage.py reporter for coveralls.io
    """

    def __init__(self, *args, **kwargs):
        self.source_files = []
        super(CoverallReporter, self).__init__(*args, **kwargs)

    def report(self, morfs=None):
        """ Generate a part of json report for coveralls

        `morfs` is a list of modules or filenames.
        `outfile` is a file object to write the json to.
        """
        units = None
        if hasattr(self, 'find_code_units'):
            self.find_code_units(morfs)
        else:
            units = self.find_file_reporters(morfs)

        if units is None:
            if hasattr(self, 'code_units'):
                units = self.code_units
            else:
                units = self.file_reporters

        for cu in units:
            try:
                analyzed = self.coverage._analyze(cu)  # pylint: disable=W0212
                self.parse_file(cu, analyzed)
            except NoSource:
                if not self.config.ignore_errors:
                    log.warning('No source for %s', cu.filename)
            except NotPython:
                # Only report errors for .py files, and only if we didn't
                # explicitly suppress those errors.
                if cu.should_be_python() and not self.config.ignore_errors:
                    log.warning('Source file is not python %s', cu.filename)
            except KeyError:
                cov3x = __version__[0] < 4
                cov40 = __version__[0] == 4 and __version__[1] < 1
                if cov3x or cov40:
                    raise CoverallsException(
                        'Old (<4.1) versions of coverage.py do not work '
                        'consistently on new versions of Python. Please '
                        'upgrade your coverage.py.'
                    )

                raise

        return self.source_files

    @staticmethod
    def get_hits(line_num, analysis):
        """ Source file stats for each line.

            * A positive integer if the line is covered,
            representing the number of times the line is hit during the test
            suite.
            * 0 if the line is not covered by the test suite.
            * null to indicate the line is not relevant to code coverage
              (it may be whitespace or a comment).
        """
        if line_num in analysis.missing:
            return 0

        if line_num not in analysis.statements:
            return None

        return 1

    @staticmethod
    def get_arcs(analysis):
        """ Hit stats for each branch.

            Returns a flat list where every four values represent a branch:
            1. line-number
            2. block-number (not used)
            3. branch-number
            4. hits (we only get 1/0 from coverage.py)
        """
        if not analysis.has_arcs():
            return None

        branch_lines = analysis.branch_lines()
        branches = []

        for l1, l2 in analysis.arcs_executed():
            if l1 in branch_lines:
                branches.extend((l1, 0, abs(l2), 1))

        for l1, l2 in analysis.arcs_missing():
            if l1 in branch_lines:
                branches.extend((l1, 0, abs(l2), 0))

        return branches

    def parse_file(self, cu, analysis):
        """ Generate data for single file """
        if hasattr(analysis, 'parser'):
            filename = cu.file_locator.relative_filename(cu.filename)
            source_lines = analysis.parser.lines
            with cu.source_file() as source_file:
                source = source_file.read()

            try:
                if sys.version_info < (3, 0):
                    encoding = source_encoding(source)
                    if encoding != 'utf-8':
                        source = source.decode(encoding).encode('utf-8')
            except UnicodeDecodeError:
                log.warning(
                    'Source file %s can not be properly decoded, skipping. '
                    'Please check if encoding declaration is ok',
                    os.path.basename(cu.filename))
                return
        else:
            if hasattr(cu, 'relative_filename'):
                filename = cu.relative_filename()
            else:
                filename = analysis.coverage.file_locator.relative_filename(
                    cu.filename)

            token_lines = analysis.file_reporter.source_token_lines()
            source_lines = list(enumerate(token_lines))
            source = analysis.file_reporter.source()

        coverage_lines = [self.get_hits(i, analysis)
                          for i in range(1, len(source_lines) + 1)]

        # ensure results are properly merged between platforms
        posix_filename = filename.replace(os.path.sep, '/')

        results = {
            'name': posix_filename,
            'source': source,
            'coverage': coverage_lines,
        }

        branches = self.get_arcs(analysis)
        if branches:
            results['branches'] = branches

        self.source_files.append(results)


text:
package org.azizkhani.service.imp;

import java.util.Date;
import java.util.List;

import org.azizkhani.core.QueryResult;
import org.azizkhani.dao.IGenericRepository;
import org.azizkhani.model.BaseEntity;
import org.azizkhani.service.IGenericService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public abstract class GenericService<T> implements IGenericService<T> {

	protected abstract IGenericRepository<T> getGenericRepo();

	@Override
	public List<T> getAll() {
		return getGenericRepo().getAll();
	}

	@Override
	public List<T> getAll(String where, String order, int pageNumber,int pageSize) {
		return getGenericRepo().getAll(where, order, pageNumber, pageSize);
	}

	@Override
	public QueryResult<T> getAllGrid(String where, String order,int pageNumber, int pageSize) {
		return getGenericRepo().getAllGrid(where, order, pageNumber, pageSize);
	}

	@Override
	public T loadByEntityId(int entityId) {
		return getGenericRepo().loadByEntityId(entityId);
	}

	@Override
	public T single(String where) {
		return null;
	}

	@Override
	public void add(T entity) {
		getGenericRepo().add(entity);
	}

	@Override
	public void delete(T entity) {
		getGenericRepo().delete(entity);
	}

	@Override
	public void deleteByEntityId(int entityId) {
		getGenericRepo().deleteByEntityId(entityId);
	}

	@Override
	public void update(T entity) {
		getGenericRepo().update(entity);
	}

	@Override
	public int count() {
		return	getGenericRepo().count();
	}

}


text:
module.exports = function (grunt) {
  var check = require('../')

  grunt.registerMultiTask('dependency-check', 'Matches used modules to listed dependencies', function () {
    var done = this.async()

    var options = this.options({
      missing: true,
      unused: true,
      excludeUnusedDev: false,
      noDefaultEntries: true,
      ignoreUnused: [],
      package: '.'
    })

    check({
      path: options.package,
      entries: this.filesSrc,
      noDefaultEntries: options.noDefaultEntries
    }, function (err, data) {
      if (err) {
        return grunt.fail.fatal(err)
      }

      var pkg = data.package
      var deps = data.used
      var results

      if (options.unused) {
        results = check.extra(pkg, deps, {
          excludeDev: options.excludeUnusedDev || options.excludeMissingDev,
          ignore: options.ignoreUnused
        })
        if (results.length !== 0) {
          grunt.log.error('Modules in package.json not used in code: ' + grunt.log.wordlist(results, {color: 'red'}))
        }
      }

      if (options.missing) {
        results = check.missing(pkg, deps)
        if (results.length !== 0) {
          grunt.fail.fatal('Dependencies not listed in package.json: ' + grunt.log.wordlist(results, {color: 'red'}))
        }
      }

      done()
    })
  })
}


text:
var gulp = require('gulp');
var browserSync = require('browser-sync');

require('./tasks/spec_unit')([
  {name: 'spec:unit', deps: ['build:app', 'build:spec'], specs: './dist/spec.js', implementation: './dist/app.js', runner: './dist/spec.html'}
]);
require('./tasks/spec_acceptance')([
  {name: 'spec:acceptance', deps: ['build:app', 'serve'], specs: './spec/acceptance/**/*_spec.js', callback: browserSync.exit}
]);
gulp.task('spec', ['spec:unit', 'spec:acceptance']);

require('./tasks/build_html')([
  {name: 'build:app:html', file: './app/index.html', watch: false},
  {name: 'build:spec:html', file: './spec/unit/spec.html', watch: false},

  {name: 'watch:app:html', file: './app/index.html', watch: [browserSync.reload]},
  {name: 'watch:spec:html', file: './spec/unit/spec.html', watch: [browserSync.reload]}
]);
require('./tasks/build_css')([
  {name: 'build:app:css', file: './app/styles/app.css', watch: false},
  {name: 'build:spec:css', file: './spec/unit/spec.css', watch: false},

  {name: 'watch:app:css', file: './app/styles/app.css', watch: [browserSync.reload]},
  {name: 'watch:spec:css', file: './spec/unit/spec.css', watch: [browserSync.reload]}
]);
require('./tasks/build_js')([
  {name: 'build:app:js', file: './app/scripts/app.js', watch: false},
  {name: 'build:spec:js', file: './spec/unit/spec.js', watch: false},
  {name: 'build:spec:jasmine', file: './spec/unit/jasmine.js', watch: false},

  {name: 'watch:app:js', file: './app/scripts/app.js', watch: [browserSync.reload]},
  {name: 'watch:spec:js', file: './spec/unit/spec.js', watch: [browserSync.reload]},
  {name: 'watch:spec:jasmine', file: './spec/unit/jasmine.js', watch: [browserSync.reload]}
]);

gulp.task('build:app', ['build:app:html', 'build:app:css', 'build:app:js']);
gulp.task('build:spec', ['build:spec:html', 'build:spec:css', 'build:spec:js', 'build:spec:jasmine']);
gulp.task('build', ['build:app', 'build:spec']);

gulp.task('watch:app', ['watch:app:html', 'watch:app:css', 'watch:app:js']);
gulp.task('watch:spec', ['watch:spec:html', 'watch:spec:css', 'watch:spec:js', 'watch:spec:jasmine']);
gulp.task('watch', ['watch:app', 'watch:spec']);

gulp.task('serve', function() {
  browserSync({server: './dist', https: false, browser: []});
});

gulp.task('default', ['watch', 'serve']);


text:
package org.elasticsearch.search.functionscore;

import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.fieldValueFactorFunction;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;

/**
 * Tests for the {@code field_value_factor} function in a function_score query.
 */
public class FunctionScoreFieldValueIT extends ESIntegTestCase {

    @Test
    public void testFieldValueFactor() throws IOException {
        assertAcked(prepareCreate("test").addMapping(
                "type1",
                jsonBuilder()
                        .startObject()
                        .startObject("type1")
                        .startObject("properties")
                        .startObject("test")
                        .field("type", randomFrom(new String[]{"short", "float", "long", "integer", "double"}))
                        .endObject()
                        .startObject("body")
                        .field("type", "string")
                        .endObject()
                        .endObject()
                        .endObject()
                        .endObject()).get());
        ensureYellow();

        client().prepareIndex("test", "type1", "1").setSource("test", 5, "body", "foo").get();
        client().prepareIndex("test", "type1", "2").setSource("test", 17, "body", "foo").get();
        client().prepareIndex("test", "type1", "3").setSource("body", "bar").get();

        refresh();

        // document 2 scores higher because 17 > 5
        SearchResponse response = client().prepareSearch("test")
                .setExplain(randomBoolean())
                .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"), fieldValueFactorFunction("test")))
                .get();
        assertOrderedSearchHits(response, "2", "1");

        // try again, but this time explicitly use the do-nothing modifier
        response = client().prepareSearch("test")
                .setExplain(randomBoolean())
                .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
                        fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.NONE)))
                .get();
        assertOrderedSearchHits(response, "2", "1");

        // document 1 scores higher because 1/5 > 1/17
        response = client().prepareSearch("test")
                .setExplain(randomBoolean())
                .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
                        fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL)))
                .get();
        assertOrderedSearchHits(response, "1", "2");

        // doc 3 doesn't have a "test" field, so an exception will be thrown
        try {
            response = client().prepareSearch("test")
                    .setExplain(randomBoolean())
                    .setQuery(functionScoreQuery(matchAllQuery(), fieldValueFactorFunction("test")))
                    .get();
            assertFailures(response);
        } catch (SearchPhaseExecutionException e) {
            // We are expecting an exception, because 3 has no field
        }

        // doc 3 doesn't have a "test" field but we're defaulting it to 100 so it should be last
        response = client().prepareSearch("test")
                .setExplain(randomBoolean())
                .setQuery(functionScoreQuery(matchAllQuery(),
                        fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100)))
                .get();
        assertOrderedSearchHits(response, "1", "2", "3");

        // field is not mapped but we're defaulting it to 100 so all documents should have the same score
        response = client().prepareSearch("test")
                .setExplain(randomBoolean())
                .setQuery(functionScoreQuery(matchAllQuery(),
                        fieldValueFactorFunction("notmapped").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100)))
                .get();
        assertEquals(response.getHits().getAt(0).score(), response.getHits().getAt(2).score(), 0);

        // n divided by 0 is infinity, which should provoke an exception.
        try {
            response = client().prepareSearch("test")
                    .setExplain(randomBoolean())
                    .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"),
                            fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).factor(0)))
                    .get();
            assertFailures(response);
        } catch (SearchPhaseExecutionException e) {
            // This is fine, the query will throw an exception if executed
            // locally, instead of just having failures
        }

        // don't permit an array of factors
        try {
          String querySource = "{" +
            "\"query\": {" +
            "  \"function_score\": {" +
            "    \"query\": {" +
            "      \"match\": {\"name\": \"foo\"}" +
            "      }," +
            "      \"functions\": [" +
            "        {" +
            "          \"field_value_factor\": {" +
            "            \"field\": \"test\"," +
            "            \"factor\": [1.2,2]" +
            "          }" +
            "        }" +
            "      ]" +
            "    }" +
            "  }" +
            "}";
          response = client().prepareSearch("test")
          .setSource(querySource)
          .get();
          assertFailures(response);
        } catch (SearchPhaseExecutionException e) {
          // This is fine, the query will throw an exception if executed
          // locally, instead of just having failures
        }

    }
}