text:
<template name="tutorial.step_13.html">

           Improve this doc

 Previous

 Live Demo

 Code Diff

Next

Step 13 - Using and creating AngularJS filters

  <do-nothing class="col-md-12">
{{#markdown}}

Our next mission is to invite users to private parties.

We have subscribed to list of all users, but we can't invite everyone.
We can't invite the owner of the party and we can't invite users who are already invited, so why not filter them out of the view?

To do so we will use the powerful [filter feature](https://docs.angularjs.org/guide/filter) of AngularJS.

Filters can work on array as well as single values.
We can aggregate any number of filters on top of each other.

Here is the list of all of AngularJS built-in filters:
[https://docs.angularjs.org/api/ng/filter](https://docs.angularjs.org/api/ng/filter)

And here is a 3rd party library with many more filters:
[angular-filter](https://github.com/a8m/angular-filter)

Now let's create a custom filter that will filter out users that are the owners of a certain party and that are already invited to it.

Create a new folder named `filters` under the `client->parties` folder.

Under that folder create a new file named `uninvited.js` and place that code inside:

    angular.module('socially').filter('uninvited', function () {
      return function (users, party) {
        if (!party)
          return false;

        return _.filter(users, function (user) {
          if (user._id == party.owner ||
              _.contains(party.invited, user._id))
            return false;
          else
            return true;
        });
      }
    });

* First we define a filter to the 'socially' module (our app)
* The filter is named `uninvited`
* Filters always get at least one parameter and the first parameter is always the object or array that we are filtering (like the parties in the previous example)
Here we are filtering the users array, so that's the first parameter
* The second parameter is the party we want to check
* The first if statement is to make sure we passed the initializing phase of the party and it's not undefined

At this point we need to return the filtered array.

The great thing here is that thanks to Meteor we have access to the great [underscore](http://docs.meteor.com/#underscore) library.

So we use underscore's `filter` method to remove each user that either isn't the party's owner or that
is not already `_contains` (another underscore method) in the invited list.

So now let's use our new filter

Simply add the filter to the list of users and send the current party to the party parameter, inside `party-details.ng.html`:

      Users to invite:

{{dstache}} user.emails[0].address }}

Run the app and see the users in each party.

We still don't have invites but you can see that the filter already filters the party owners out of the list.

But some of the users don't have emails (maybe some of them may have signed in with Facebook). In that case we want to display their name and not the empty email field.

But it's only in the display so its perfect for a filter.

We want the list to simply look like this:

      Users to invite:

{{dstache}} user | displayName }}

and that the filter `displayName` will handle to logic and display the user's name in the best way possible.

So let's create another custom filter `displayName`.

Create a new file under the filters folder named `displayName.js` and place that code inside:

    angular.module('socially').filter('displayName', function () {
      return function (user) {
        if (!user)
          return;
        if (user.profile && user.profile.name)
          return user.profile.name;
        else if (user.emails)
          return user.emails[0].address;
        else
          return user;
      }
    });

Pretty simple logic but it's so much nicer to put it here and make the HTML shorter and more readable.

AngularJS can also display the return value of a function in the HTML.

To demonstrate let's add to each party in the parties list the creator's name:

Add this line to the parties list in `parties-list.ng.html`:

Posted by {{dstache}} creator(party) }}

so it will look like this:

      {{dstache}}party.name}}

{{dstache}}party.description}}

      <button ng-click="remove(party)">X</button>

Posted by {{dstache}} creator(party) }}

and define the creator scope function in the partiesListCtrl in `partiesList.js`:

    $scope.getUserById = function(userId){
      return Meteor.users.findOne(userId);
    };

    $scope.creator = function(party){
      if (!party)
        return;
      var owner = $scope.getUserById(party.owner);
      if (!owner)
        return 'nobody';

      if ($rootScope.currentUser)
        if ($rootScope.currentUser._id)
          if (owner._id === $rootScope.currentUser._id)
            return 'me';

      return owner;
    };

* Remember to add `$rootScope` to the controller's dependency injection

As you can see, we are using the `Meteor.users` collection here but we haven't made sure that we are subscribing to it
(If we visited the partyDetails controller before getting here, partyDetails controller would subscribe to the Meteor.users collection,
but if we weren't, we would get an empty array in Meteor.users).
So let's add a subscription to Meteor.users in the list controller as well:

    $scope.$meteorSubscribe('users');

Now we get the user object to the HTML. But we want his name, so let's put the displayName filter on that as well:

Posted by {{dstache}} creator(party) | displayName }}

# Summary

In this chapter we learned about AngularJS filters and how easy they are to use and to read from the HTML.

In the next step we will learn about Meteor methods, which enables us to run custom logic in the server, beyond the Mongo API and the allow/deny methods.

{{/markdown}}
    </do-nothing>

 Previous

 Live Demo

 Code Diff

Next

</template>


text:
const https = require('https');
const request = require('request');
const zlib = require('zlib');
const util = require('util');
const http = require('http');

var jQuery = require('jquery-deferred');
var postData = require('./credential.json');

console.log(postData);
console.log(postData[1]);
console.log(postData['password']);
console.log("Inspect\n", util.inspect(postData));
console.log(postData.length);
console.log(JSON.stringify(postData, null, 2));
console.log(Object.keys(postData));

return;
//postData=JSON.stringify(postData);

var options_request = {
    url: 'http://hapitas.jp/',
    headers:{
        "Connection": "keep-alive",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2",
        //"Referer": "https://hapitas.jp/auth/signin",
        "Accept-Encoding": "sdch",
        "Accept-Language": "ja,en-US;q=0.8,en;q=0.6",
        'Content-Type': 'text/plain;charset=utf-8',
        "Upgrade-Insecure-Requests": "1",

        //"Proxy-Connection": "keep-alive",
    },
//    proxy: 'http://myhost:8888',
//    strictSSL: false,
    jar: true
};

var post_options_request = {
    url: 'https://hapitas.jp/auth/signin',
    headers:{
        "Connection": "keep-alive",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2",
        "Referer": "https://hapitas.jp/",
        "Accept-Encoding": "sdch",//gzip,deflate,sdch",
        "Accept-Language": "ja,en-US;q=0.8,en;q=0.6",
        'Content-Type': 'application/x-www-form-urlencoded',
        "Upgrade-Insecure-Requests": "1",
        //"Content-Length": "108"//Buffer.byteLength(postData),
    },
/*//    form: {
            mail: 'mossom9@gmail.com',
            password: '0606060606060606',
            login_keep: 'on',
            signin: 'login'
    },//*/
    form: postData,
//    proxy: 'http://myhost:8888',
//    strictSSL: false,
    jar: true
};

//return null;
console.log(Buffer.byteLength(JSON.stringify(postData)+'\n'));
var Cookies;
var CookieHeaders = [];
var urlList;
//exports.handler = (event, context, callback) => {
//    console.log("recived event", event);
var delay = function(){
    var d = jQuery.Deferred();
    console.log('deffinition of d');
    setTimeout(function(){
    console.log('before resolve');
    d.resolve();
    console.log('after resolve');
    },1000);
    return d;
};
delay()
    .then(function(){
    console.log('delayed');
    })
    .then(function(){
    console.log('delayed2');
    })
    .fail(function(error){
    console.log('delayed error!!');
});

var dfdSingin = function (options) {
    var dfd = jQuery.Deferred();

    request.post(options, function (error, response, body) {
        if (!error) {
            var tmpCookie = response.headers["set-cookie"];
            console.log(tmpCookie);
            Cookies = tmpCookie[tmpCookie.length-1].match(/(\S+);/)[1];
            console.log(options);
            console.log(response.headers);
            dfd.resolve();
        }
        else {
            console.log(response.statusCode);
            console.log("Error happened", error);
            dfd.reject();
        }
    });
    return dfd.promise();
};

var dfdCandidateURL = function (options) {
    var dfd = jQuery.Deferred();

    request.get(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            //console.log(body);
            var result=body.match(/(clickget.recive.+top_clickget)/g);
            var setResult = new Set(result);
            urlList = [...setResult];

            console.log(response.headers);
            dfd.resolve();
        }
        else {
            console.log("Error happened", error);
            dfd.reject();
        }
    });
    return dfd.promise();
};

var dfdGetURL = function (options) {
    var dfd = jQuery.Deferred();

    request.get(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(options);
            console.log(response.headers);
            ///item/redirect/itemid/49694/p/0/click/2449/apn/top_clickget/linkid/782
            ///item/redirect/itemid/63079/p/0/click/2448/apn/top_clickget
            var result=body.match(/(item.redirect\S+)"\s/);
            if(result){
                options.url="http://hapitas.jp/"+result[1];
                options.headers["Cookie"] = Cookies;
                console.log(options);
                return dfdGetURL(options);
            }

            //console.log(body);
            dfd.resolve();
        }
        else {
            console.log("Error happened", error);
            dfd.reject();
        }
    });
    return dfd.promise();
};

/*
dfdSingin(post_options_request)
    .then(function(){
        console.log(Cookies);
    })
    .then(function(){
        options_request.url ="http://hapitas.jp/index/ajaxclickget";
        options_request.headers["Cookie"] = Cookies;
        return dfdCandidateURL(options_request);
    })
    .then(function(){
        console.log(urlList);
        urlList.forEach(function(each) {
            options_request.url ="http://hapitas.jp/" + each;
            console.log(options_request);
            return dfdGetURL(options_request);
        });
    })
    .fail(function(error){
        console.log('Main function delayed error!!');
});
*///

var set = [
  'clickget/recive/id/2436/apn/top_clickget',
  'clickget/recive/id/2437/apn/top_clickget',
  'clickget/recive/id/2438/apn/top_clickget',
  'clickget/recive/id/2439/apn/top_clickget',
  'clickget/recive/id/2442/apn/top_clickget',
  'clickget/recive/id/2443/apn/top_clickget',
  'clickget/recive/id/2444/apn/top_clickget',
  'clickget/recive/id/2445/apn/top_clickget',
  'clickget/recive/id/2446/apn/top_clickget' ];

//post_options_request.url = 'http://192.168.10.10/';

dfdSingin(post_options_request)
    .then(function(){
        console.log(Cookies);
    })
    .then(function(){
        options_request.url ="http://hapitas.jp/index/ajaxclickget";
        options_request.headers["Cookie"] = Cookies;
        return dfdCandidateURL(options_request);
    })
    .then(function(){
        console.log(urlList);
        urlList.forEach(function(each) {
        //var each=urlList[2];
            options_request.url ="http://hapitas.jp/" + each;
            options_request.headers["Cookie"] = Cookies;
            //console.log(options_request);
            return dfdGetURL(options_request);
        });
    })//*//
    .fail(function(error){
        console.log('Main function delayed error!!');
});

//*//

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: t_tls_dlopen.c,v 1.3 2012/01/17 20:34:57 joerg Exp $	*/
/*-
 * Copyright (c) 2011 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Joerg Sonnenberger.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: t_tls_dlopen.c,v 1.3 2012/01/17 20:34:57 joerg Exp $");

#include <atf-c.h>
#include <dlfcn.h>
#include <pthread.h>
#include <unistd.h>

#ifdef __NetBSD__
#include <sys/tls.h>
#endif

#ifdef __HAVE_NO___THREAD
#define	__thread
#endif

ATF_TC(t_tls_dlopen);

ATF_TC_HEAD(t_tls_dlopen, tc)
{
	atf_tc_set_md_var(tc, "descr",
	    "Test (un)initialized TLS variables and dlopen");
}

void (*testf_helper)(int, int);

__thread int var1 = 1;
__thread int var2;
__thread int *var3 = &optind;
int var4_helper;
__thread int *var4 = &var4_helper;

static void *
testf(void *dummy)
{
	ATF_CHECK_EQ(var1, 1);
	ATF_CHECK_EQ(var2, 0);
	ATF_CHECK_EQ(var3, &optind);
	ATF_CHECK_EQ(var4, &var4_helper);
	testf_helper(2, 2);
	ATF_CHECK_EQ(var1, 2);
	ATF_CHECK_EQ(var2, 2);
	testf_helper(3, 3);
	ATF_CHECK_EQ(var1, 3);
	ATF_CHECK_EQ(var2, 3);
	ATF_CHECK_EQ(var3, &optind);

	return NULL;
}

ATF_TC_BODY(t_tls_dlopen, tc)
{
	void *handle;
	pthread_t t;

#ifdef __HAVE_NO___THREAD
	atf_tc_skip("no TLS support on this platform");
#endif

	handle = dlopen("h_tls_dlopen.so", RTLD_NOW | RTLD_LOCAL);
	ATF_REQUIRE(handle != NULL);

	testf_helper = dlsym(handle, "testf_dso_helper");
	ATF_REQUIRE(testf_helper != NULL);

	testf(NULL);

	pthread_create(&t, 0, testf, 0);
	pthread_join(t, NULL);

	pthread_create(&t, 0, testf, 0);
	pthread_join(t, NULL);

	dlclose(handle);
}

ATF_TP_ADD_TCS(tp)
{
	ATF_TP_ADD_TC(tp, t_tls_dlopen);

	return atf_no_error();
}


text:
def center_idx(array):
    '''
    Get cetral idx of iterable.

    Parameters
    ----------
    array: Iterable
       An iterable object

    '''
    return int(round(len(array)/2.))


text:
By the end of the lesson, students will be able to use simple phrases to ask about and describe what they do on vacation.

## Content Skills
What do people do on vacation?
Are vacations meaningless?

## Key Expressions/Content:
- What do you do on vacation?
- While on vacation, I ________
- stay home
- go traveling
- go to the park
- hang out with friends
- visit family
- go to KTV
- go hiking
- go play basketball
- go to the movies
- sleep

## Materials:

## Presentation:
- Briefly present on what a vacation is and how people might spend it.

## Practice:
- Question and answer: One student will ask another student what they do on vacation. The other student will answer the question.

## Production:
- Vacation video clip
	- go over clip and answer questions.

## Debrief:

## Anticipated Problems/Activities:

## Back-up Plan/Activities:


text:
package br.com.urbano.exceptions;

import java.io.Serializable;

public class ConflictException extends Exception implements Serializable {
	private static final long serialVersionUID = -3095729621783577308L;

	public ConflictException() {
		// TODO Auto-generated constructor stub
		super();
	}

	public ConflictException(String message) {
		// TODO Auto-generated constructor stub
		super(message);
	}

	public ConflictException(String message, Throwable cause) {
		// TODO Auto-generated constructor stub
		super(message, cause);
	}

	public ConflictException(Throwable cause) {
		// TODO Auto-generated constructor stub
		super(cause.getMessage(), cause);
	}
}


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Sell extends StdCommand
{
	public Sell(){}

	private String[] access={"SELL"};
	public String[] getAccessWords(){return access;}
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
        Environmental shopkeeper=CMLib.english().parseShopkeeper(mob,commands,"Sell what to whom?");
		if(shopkeeper==null) return false;
		if(commands.size()==0)
		{
			mob.tell("Sell what?");
			return false;
		}

        int maxToDo=CMLib.english().calculateMaxToGive(mob,commands,true,mob,false);
        if(maxToDo<0) return false;

		String whatName=CMParms.combine(commands,0);
		Vector V=new Vector();
		boolean allFlag=((String)commands.elementAt(0)).equalsIgnoreCase("all");
		if(whatName.toUpperCase().startsWith("ALL.")){ allFlag=true; whatName="ALL "+whatName.substring(4);}
		if(whatName.toUpperCase().endsWith(".ALL")){ allFlag=true; whatName="ALL "+whatName.substring(0,whatName.length()-4);}
		int addendum=1;
		String addendumStr="";
		boolean doBugFix = true;
		while(doBugFix || ((allFlag)&&(addendum<=maxToDo)))
		{
			doBugFix=false;
			Item itemToDo=mob.fetchCarried(null,whatName+addendumStr);
			if(itemToDo==null) break;
			if((CMLib.flags().canBeSeenBy(itemToDo,mob))
			&&(!V.contains(itemToDo)))
				V.addElement(itemToDo);
			addendumStr="."+(++addendum);
		}

		if(V.size()==0)
			mob.tell("You don't seem to have '"+whatName+"'.");
		else
		for(int v=0;v<V.size();v++)
		{
			Item thisThang=(Item)V.elementAt(v);
			CMMsg newMsg=CMClass.getMsg(mob,shopkeeper,thisThang,CMMsg.MSG_SELL,"<S-NAME> sell(s) <O-NAME> to <T-NAMESELF>.");
			if(mob.location().okMessage(mob,newMsg))
				mob.location().send(mob,newMsg);
		}
		return false;
	}
    public double combatActionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCOMCMDTIME),100.0);}
    public double actionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCMDTIME),100.0);}
	public boolean canBeOrdered(){return false;}

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?php $this->load->view( 'header', $datos ); ?>

¿No recuerdas tu contraseña?

					<?php echo form_open('validar_recuperar_password', array( 'id' => 'form_login', 'name' => 'form_login', 'class' => 'form-horizontal', 'method' => 'POST', 'autocomplete' => 'off', 'role' => 'form' ) ); ?>

Danos tu email y te enviaremos un correo electrónico con tu contraseña

								<input type="email" class="form-control" id="email" name="email" placeholder="Correo Electrónico">

								<a href="<?php echo base_url(); ?>" class="btn btn-danger btn-block">CANCELAR

								<button type="submit" class="btn btn-primary btn-block">RECUPERAR</button>

					<?php echo form_close(); ?>

<?php $this->load->view( 'footer_login' ); ?>


text:
using Alachisoft.NCache.Common.Pooling.Lease;
using Alachisoft.NCache.Common.Pooling.Extension;

namespace Alachisoft.NCache.Common.Protobuf
{
    public partial class GetResponse : SimpleLease
    {
        #region ILeasable

        public override sealed void ResetLeasable()
        {
            data.Clear();
            flag = default(int);
            lockId = string.Empty;
            lockTime = default(long);
            version = default(ulong);
            commandID = default(int);
            requestId = default(long);
            itemType = CacheItemType.ItemType.CACHEITEM;
            extensionObject = default(ProtoBuf.IExtension);
        }

        public override sealed void ReturnLeasableToPool()
        {
            PoolManager.GetProtobufGetResponsePool()?.Return(this);
        }

        #endregion
    }
}


text:
Please send a pull request if you want to be added.

* [Fantomas](https://github.com/dungpa/fantomas)
* [fsharpx](https://github.com/fsharp/fsharpx)
* [FsPickler](https://github.com/nessos/FsPickler)
* [LinqOptimizer](https://github.com/nessos/LinqOptimizer)
* [Credit Suisse](http://www.credit-suisse.com)
* [BlueMountain Capital](https://github.com/bluemountaincapital)
* [Tachyus](http://tachyus.com/)
* [Fred](https://github.com/frankshearar/Fred/)
* [Digital Furnace Games](http://www.digitalfurnacegames.com/)
* [15below](http://15below.com/)
* [AntaniXml](http://giacomociti.github.io/AntaniXml/)
* [DoctestInteractive](https://github.com/tomakita/DoctestInteractive/)
* [Darklang](https://github.com/darklang/dark/)

## Academia

Yes, to my surprise people are writing academic papers about FsCheck. Well, at least one!

* Bernhard K. Aichernig and Richard Schumi. Property-based Testing with FsCheck by Deriving
Properties from Business Rule Models. In 2016 IEEE Ninth International Conference on Software
Testing, Verification, and Validation Workshops (ICSTW), 13th Workshop on Advances in Model
Based Testing (A-MOST 2016), IEEE,  2016. In press. [Link](http://truconf.ist.tugraz.at/index.php/2016/03/04/publication-at-a-most-2016/)


text:
package org.kie.api.event.kiebase;

import org.kie.api.definition.KiePackage;

public interface AfterKiePackageAddedEvent
    extends
    KieBaseEvent {

    public KiePackage getKiePackage();
}


text:
set -e

./config/linux/ubuntu_install_${project_name}.sh include-test;

./config/jenkins/linux/run_end_to_end_tests.sh $$1;


text:
//
//  KTBTaskQueue.m
//  KTBTaskQueue
//
//  Created by Kevin Barrett on 1/23/14.
//  Copyright (c) 2014 Little Spindle, LLC. All rights reserved.
//

#import "KTBTaskQueue.h"
#import "KTBTask.h"
#import <FMDB/FMDatabaseQueue.h>
#import <FMDB/FMDatabase.h>

void KTBDispatchSyncOnMainQueue(void (^block)(void)) {
    if ([NSThread isMainThread]) {
        block();
    }
    else {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

void KTBDispatchAsyncOnMainQueue(void (^block)(void)) {
    if ([NSThread isMainThread]) {
        block();
    }
    else {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

static dispatch_queue_t task_queue_processing_queue() {
    static dispatch_queue_t ktb_task_queue_processing_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ktb_task_queue_processing_queue = dispatch_queue_create("com.littlespindle.taskqueue.processing", DISPATCH_QUEUE_SERIAL);
    });

    return ktb_task_queue_processing_queue;
}

const NSTimeInterval KTBTaskQueueDefaultPollingInterval = 10;

@interface KTBTask (QueueAdditions)
- (NSString *)userInfoString;
- (NSNumber *)createdDateNumber;
- (NSNumber *)availableDateNumber;
- (NSDate *)nextAvailableDateWithBackoffInterval:(NSTimeInterval)backoffInterval;
@end

@interface KTBTaskQueue ()
@property (readwrite, nonatomic, strong) FMDatabaseQueue *databaseQueue;
@property (readwrite, nonatomic, copy) NSString *pathToDatabase;
@property (readwrite, nonatomic, strong) NSTimer *pollingTimer;
@property (readwrite, atomic, assign, getter = isProcessing) BOOL processing;
/**
 A valid queue has not been deleted with @c deleteQueue.
 Once a queue is deleted it is considered invalid and will no longer accept tasks.
 */
@property (readwrite, nonatomic, assign) BOOL valid;
@end

@implementation KTBTaskQueue

+ (instancetype)queueAtPath:(NSString *)filePath {
    return [self queueAtPath:filePath delegate:nil];
}

+ (instancetype)queueAtPath:(NSString *)filePath delegate:(id<KTBTaskQueueDelegate>)delegate {
    return [[self alloc] initWithPath:filePath delegate:delegate];
}

+ (instancetype)queueInMemory {
    return [self queueInMemoryWithDelegate:nil];
}

+ (instancetype)queueInMemoryWithDelegate:(id<KTBTaskQueueDelegate>)delegate {
    return [[self alloc] initWithPath:nil delegate:delegate];
}

- (instancetype)initWithPath:(NSString *)filePath delegate:(id<KTBTaskQueueDelegate>)delegate {
    self = [super init];
    if (self) {
        if (filePath) {
            NSURL *pathURL = [NSURL fileURLWithPath:filePath];
            if (![[pathURL pathExtension] length]) {
                filePath = [filePath stringByAppendingString:@".db"];
            }
        }

        [self setupDatabaseQueueAtPath:filePath];

        self.delegate = delegate;

        _suspended = NO;
        self.processing = NO;
        _prohibitsBackoff = NO;
        self.valid = YES;

        _backoffPollingInterval = KTBTaskQueueDefaultPollingInterval;
        [self startPollingTimer];
    }
    return self;
}

- (instancetype)init {
    return [self initWithPath:nil delegate:nil];
}

- (void)dealloc {
    _valid = NO;

    // Stop timer and close database
    [self stopPollingTimer];
    [self.databaseQueue close];
    _databaseQueue = nil;
}

#pragma mark - Control

- (void)setSuspended:(BOOL)suspended {
    _suspended = suspended;

    if (suspended) {
        [self stopPollingTimer];
    }
    else {
        [self dequeueNextTask];
    }
}

- (void)setProhibitsBackoff:(BOOL)prohibitsBackoff {
    _prohibitsBackoff = prohibitsBackoff;

    if (prohibitsBackoff) {
        if (self.pollingTimer) {
            [self stopPollingTimer];
        }
    }
    else if (self.valid) {
        [self dequeueNextTask];
    }
}

- (void)setBackoffPollingInterval:(NSTimeInterval)backoffPollingInterval {
    _backoffPollingInterval = backoffPollingInterval;

    // Reset polling timer
    if (self.pollingTimer) {
        [self stopPollingTimer];
        [self dequeueNextTask];
    }
}

#pragma mark - Adding Tasks

- (void)enqueueTaskWithName:(NSString *)name userInfo:(NSDictionary *)userInfo {
    [self enqueueTask:[KTBTask taskWithName:name userInfo:userInfo]];
}

- (void)enqueueTask:(KTBTask *)task {
    if (self.valid) {
        [self insertTask:task];
        [self dequeueNextTask];
    }
}

#pragma mark - Running Tasks and Timing

- (void)startPollingTimer {
    KTBDispatchSyncOnMainQueue(^{
        if (!self.pollingTimer && !self.suspended) {
            // The polling timer repeats until one or more tasks are available for dequeueing.
            // The tasks are dequeued serially. Once all available tasks have been dequeued, the timer is resumed.
            self.pollingTimer = [NSTimer scheduledTimerWithTimeInterval:self.backoffPollingInterval target:self selector:@selector(pollingTimerDidFire:) userInfo:nil repeats:YES];
            if ([self.pollingTimer respondsToSelector:@selector(setTolerance:)]) {
                // We can add a lot of tolerance because it's not terribly important when the timer fires.
                [self.pollingTimer setTolerance:self.backoffPollingInterval / 2];
            }
        }
    });
}

- (void)stopPollingTimer {
    KTBDispatchSyncOnMainQueue(^{
        [self.pollingTimer invalidate];
        self.pollingTimer = nil;
    });

}

- (void)pollingTimerDidFire:(NSTimer *)timer {
    [self dequeueNextTask];
}

- (void)dequeueNextTask {
    dispatch_async(task_queue_processing_queue(), ^{
        if (self.valid && !self.suspended && !self.processing && [self hasEligibleTasks]) {
            self.processing = YES;
            KTBTask *task = [self nextTask];
            if (task) {
                // Stop the timer
                [self stopPollingTimer];

                // Set completion block for responding to task results
                KTBTaskCompletionBlock completionBlock = ^(KTBTaskStatus result) {
                    // Respond to whatever the was to passed us
                    [self respondToResult:result forTask:task];

                    // We're no longer processing.
                    // Either there are more tasks and we should move to the next one,
                    // or we should go back to polling intermittently.
                    self.processing = NO;
                    if ([self hasEligibleTasks]) {
                        KTBDispatchAsyncOnMainQueue(^{
                            [self dequeueNextTask];
                        });
                    }
                    else {
                        [self startPollingTimer];
                    }
                };

                if (self.executionBlock) {
                    // Use our assigned execution block to process the task
                    self.executionBlock(task, completionBlock);
                }
                else if (self.delegate) {
                    // Ask the delegate to process the task
                    [self.delegate taskQueue:self executeTask:task completion:completionBlock];
                }
                else {
                    completionBlock(KTBTaskStatusFailure);
                }
            }
            else {
                // There are no available tasks. Go back to polling.
                self.processing = NO;
                [self startPollingTimer];
            }
        }
    });
}

- (void)respondToResult:(KTBTaskStatus)result forTask:(KTBTask *)task {
    if (result == KTBTaskStatusSuccess) {
        // Remove the job from the queue
        [self deleteTask:task];
    }
    else if (result == KTBTaskStatusFailure) {
        if ([task canBeRetried]) {
            [self setRetryDataForTask:task];
        }
        else {
            [self abandonTask:task];
        }
    }
    else if (result == KTBTaskStatusAbandon) {
        [self abandonTask:task];
    }
}

- (void)abandonTask:(KTBTask *)task {
    if ([self.delegate respondsToSelector:@selector(taskQueue:willAbandonTask:)]) {
        [self.delegate taskQueue:self willAbandonTask:task];
    }
    [self deleteTask:task];
}

#pragma mark - Querying the Queue

- (NSUInteger)count {
    return [self numberOfTasks];
}

- (BOOL)containsTaskWithName:(NSString *)name {
    return [self taskWithName:name] != nil;
}

- (BOOL)containsTask:(KTBTask *)task {
    return [self taskWithID:task.taskID] != nil;
}

#pragma mark - Cleanup

// This is typically only used for testing
- (void)deleteQueue {
    // Queue is no longer valid, stop accepting and processing tasks
    self.valid = NO;
    self.processing = NO;

    // Stop timer and close database
    [self stopPollingTimer];
    [self.databaseQueue close];
    self.databaseQueue = nil;

    // Remove database from disk
    NSFileManager *manager = [NSFileManager new];
    [manager removeItemAtPath:self.pathToDatabase error:NULL];
    self.pathToDatabase = nil;
}

#pragma mark - Database Operations

- (void)setupDatabaseQueueAtPath:(NSString *)filePath {
    self.pathToDatabase = filePath;
    self.databaseQueue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    // Create table
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:
         @"CREATE TABLE IF NOT EXISTS tasks ("
         @"    id               INTEGER PRIMARY KEY AUTOINCREMENT,"
         @"    name             TEXT NOT NULL DEFAULT '',"
         @"    userInfo         TEXT NOT NULL DEFAULT '{}',"
         @"    createdDate      INTEGER NOT NULL,"
         @"    availableDate    INTEGER NOT NULL,"
         @"    retryCount       INTEGER NOT NULL DEFAULT 0,"
         @"    maxRetries       INTEGER NOT NULL DEFAULT 10,"
         @"    retryWithBackoff INTEGER NOT NULL DEFAULT 1"
         @");"
         ];
        [self checkErrorForDatabase:db stepDescription:[NSString stringWithFormat:@"initializing task queue at %@", filePath]];
    }];
}

- (void)insertTask:(KTBTask *)task {
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:
         @"INSERT INTO tasks (name, userInfo, createdDate, availableDate, maxRetries, retryWithBackoff)"
         @"VALUES (?, ?, ?, ?, ?, ?)",
         task.name, [task userInfoString], [task createdDateNumber], [task availableDateNumber], @(task.maxRetries), @(!self.prohibitsBackoff && task.retryWithBackoff)];
        [self checkErrorForDatabase:db stepDescription:@"inserting task into task queue"];
    }];
}

- (BOOL)hasEligibleTasks {
    __block BOOL hasTasks = NO;

    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        NSNumber *availableNowDateNumber = @([[NSDate date] timeIntervalSince1970]);
        FMResultSet *resultSet = [db executeQuery:@"SELECT count(id) AS count FROM tasks WHERE availableDate <= ?", availableNowDateNumber];
        [self checkErrorForDatabase:db stepDescription:@"checking for eligible tasks"];

        if ([resultSet next]) {
            hasTasks = ([resultSet intForColumn:@"count"] > 0);
        }

        [resultSet close];
    }];

    return hasTasks;
}

- (KTBTask *)nextTask {
    __block KTBTask *task = nil;
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        NSNumber *availableNowDateNumber = @([[NSDate date] timeIntervalSince1970]);
        FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM tasks WHERE availableDate <= ? ORDER BY availableDate ASC LIMIT 1", availableNowDateNumber];
        [self checkErrorForDatabase:db stepDescription:@"selecting next eligible task"];

        if ([resultSet next]) {
            task = [KTBTask taskWithResultSet:resultSet];
        }

        [resultSet close];
    }];

    return task;
}

- (void)deleteTask:(KTBTask *)task {
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"DELETE FROM tasks WHERE id = ?", task.taskID];
        [self checkErrorForDatabase:db stepDescription:@"deleting task from task queue"];
    }];
}

- (void)setRetryDataForTask:(KTBTask *)task {
    NSDate *nextAvailableDate = [task nextAvailableDateWithBackoffInterval:self.backoffPollingInterval];
    if ([self.delegate respondsToSelector:@selector(taskQueue:willDelayRetryOfTask:untilDate:)]) {
        nextAvailableDate = [self.delegate taskQueue:self willDelayRetryOfTask:task untilDate:nextAvailableDate];
    }

    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        NSNumber *nextAvailableDateNumber = @([nextAvailableDate timeIntervalSince1970]);
        [db executeUpdate:@"UPDATE tasks SET retryCount = retryCount + 1, availableDate = ? WHERE id = ?", nextAvailableDateNumber, task.taskID];
        [self checkErrorForDatabase:db stepDescription:@"setting retry data for task"];
    }];
}

- (NSUInteger)numberOfTasks {
    __block NSUInteger count = 0;

    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"SELECT count(id) AS count FROM tasks"];
        [self checkErrorForDatabase:db stepDescription:@"getting number of tasks"];

        if ([resultSet next]) {
            count = (NSUInteger)[resultSet intForColumn:@"count"];
        }

        [resultSet close];
    }];

    return count;
}

- (KTBTask *)taskWithName:(NSString *)name {
    __block KTBTask *task = nil;
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM tasks WHERE name = ? LIMIT 1", name];
        [self checkErrorForDatabase:db stepDescription:@"searching for a task by name"];

        if ([resultSet next]) {
            task = [KTBTask taskWithResultSet:resultSet];
        }

        [resultSet close];
    }];

    return task;
}

- (KTBTask *)taskWithID:(NSNumber *)taskID {
    __block KTBTask *task = nil;
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM tasks WHERE id = ? LIMIT 1", taskID];
        [self checkErrorForDatabase:db stepDescription:@"searching for a task by ID"];

        if ([resultSet next]) {
            task = [KTBTask taskWithResultSet:resultSet];
        }

        [resultSet close];
    }];

    return task;
}

- (BOOL)checkErrorForDatabase:(FMDatabase *)db stepDescription:(NSString *)description {
    BOOL hadError = [db hadError];

    if (hadError) {
        if (!description) {
            description = @"doing something";
        }

        NSLog(@"Error %@: %@", description, [db lastError]);
    }

    return hadError;
}

- (NSString *)description {
    NSMutableString *description = [NSMutableString new];
    [description appendFormat:@"KTBTaskQueue (%ld tasks):\n", (long)[self numberOfTasks]];
    [self.databaseQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM tasks ORDER BY availableDate ASC"];
        [self checkErrorForDatabase:db stepDescription:@"dumping task list"];

        while ([resultSet next]) {
            KTBTask *task = [KTBTask taskWithResultSet:resultSet];
            [description appendString:[task description]];
            [description appendString:@"\n"];
        }

        [resultSet close];
    }];

    return description;
}

@end

#pragma mark - KTBTask (QueueAdditions)

@implementation KTBTask (QueueAdditions)

- (NSString *)userInfoString {
    return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self.userInfo options:0 error:NULL] encoding:NSUTF8StringEncoding];
}

- (NSNumber *)createdDateNumber {
    return @([self.createdDate timeIntervalSince1970]);
}

- (NSNumber *)availableDateNumber {
    return @([self.availableDate timeIntervalSince1970]);
}

- (NSDate *)nextAvailableDateWithBackoffInterval:(NSTimeInterval)backoffInterval {
    if (self.retryWithBackoff) {
        // 10 * 2^retryCount - 1
        // Subtract 1 so it catches next poll
        return [NSDate dateWithTimeIntervalSinceNow:(backoffInterval * pow(2, self.retryCount)) - 1];
    }
    else {
        return self.createdDate;
    }
}

@end


text:
package com.flipkart.lyrics.test.classes;

/**
 * Created by shrey.garg on 05/12/16.
 */
public class SuperClass {
}


text:
@interface JWTAlgorithmHS512 : NSObject <JWTAlgorithm>

@end


text:
@(goods: Seq[GoodsItemView], articlesNameAndTitle: Map[Long, Set[(String, String)]])(implicit request: RequestHeader)
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">

    @goods.map{ goodsItem =>
        <url>
            <loc>@{controllers.goods.routes.Goods.getGoodsItem(goodsItem.id.get).absoluteURL}</loc>
            @goodsItem.image.map{ imageName: String =>
                <image:image>
                    <image:loc>@{controllers.images.routes.Images.getImage(imageName).absoluteURL}</image:loc>
                </image:image>
            }
        </url>
    }

    @articlesNameAndTitle.map{ case (articleID: Long, namesAndTitle: Set[(String, String)]) =>
        <url>
            <loc>@{controllers.blog.routes.Blog.article(articleID).absoluteURL}</loc>
            @namesAndTitle.map{case (imageName, imageTitle) =>
                <image:image>
                    <image:loc>@{controllers.images.routes.Images.getImage(imageName).absoluteURL}</image:loc>
                    <image:title>@imageTitle</image:title>
                </image:image>
            }
        </url>
    }

</urlset>


text:
<?php

namespace App\Util;

use SeinopSys\RGBAColor;
use Illuminate\Support\Facades\App;

class Image {
	/**
	 * Preseving alpha
	 *
	 * @param resource $img
	 * @param int      $background
	 *
	 * @return resource
	 */
	public static function preserveAlpha($img, &$background = null) {
		$background = imagecolorallocatealpha($img, 0, 0, 0, 127);
		imagecolortransparent($img, $background);
		imagealphablending($img, false);
		imagesavealpha($img, true);
		return $img;
	}

	/**
	 * Transparent Image creator
	 *
	 * @param int      $width
	 * @param int|null $height
	 *
	 * @return resource
	 */
	public static function createTransparent($width, $height = null){
		if ($height === null)
			$height = $width;

		$png = Image::preserveAlpha(imagecreatetruecolor($width, $height), $transparency);
		imagefill($png, 0, 0, $transparency);
		return $png;
	}

	/**
	 * White Image creator
	 *
	 * @param int      $width
	 * @param int|null $height
	 *
	 * @return resource
	 */
	public static function createWhiteBG($width, $height = null){
		if ($height === null)
			$height = $width;

		$png = imagecreatetruecolor($width, $height);
		$white = imagecolorallocate($png, 255, 255, 255);
		imagefill($png, 0, 0, $white);
		return $png;
	}

	/**
	 * Draw a an (optionally filled) squre on an $image
	 *
	 * @param resource    $image
	 * @param int         $x
	 * @param int         $y
	 * @param mixed       $size
	 * @param string|null $fill
	 * @param string|int  $outline
	 */
	public static function drawSquare($image, $x, $y, $size, $fill, $outline){
		if (!empty($fill) && is_string($fill)){
			$fill = RGBAColor::parse($fill);
			$fill = imagecolorallocate($image, $fill->red, $fill->green, $fill->blue);
		}
		if (is_string($outline)){
			$outline = RGBAColor::parse($outline);
			$outline = imagecolorallocate($image, $outline->red, $outline->green, $outline->blue);
		}

		if (is_array($size)){
			/** @var $size int[] */
			$x2 = $x + $size[0];
			$y2 = $y + $size[1];
		}
		else {
			/** @var $size int */
			$x2 = $x + $size;
			$y2 = $y + $size;
		}

		$x2--; $y2--;

		if (isset($fill))
			imagefilledrectangle($image, $x, $y, $x2, $y2, $fill);
		if (isset($outline))
			imagerectangle($image, $x, $y, $x2, $y2, $outline);
	}

	/**
	 * Draw a an (optionally filled) circle on an $image
	 *
	 * @param resource    $image
	 * @param int         $x
	 * @param int         $y
	 * @param mixed       $size
	 * @param string|null $fill
	 * @param string|int  $outline
	 */
	public static function drawCircle($image, $x, $y, $size, $fill, $outline){
		if (!empty($fill) && is_string($fill)){
			$fill = RGBAColor::parse($fill);
			$fill = imagecolorallocate($image, $fill->red, $fill->green, $fill->blue);
		}
		if (is_string($outline)){
			$outline = RGBAColor::parse($outline);
			$outline = imagecolorallocate($image, $outline->red, $outline->green, $outline->blue);
		}

		if (is_array($size)){
			/** @var $size int[] */
			[$width,$height] = $size;
			$x2 = $x + $width;
			$y2 = $y + $height;
		}
		else {
			/** @var $size int */
			$x2 = $x + $size;
			$y2 = $y + $size;
			$width = $height = $size;
		}
		$cx = Core::average($x,$x2);
		$cy = Core::average($y,$y2);

		if (isset($fill))
			imagefilledellipse($image, $cx, $cy, $width, $height, $fill);
		imageellipse($image, $cx, $cy, $width, $height, $outline);
	}

	/**
	 * Writes on an image
	 *
	 * @param resource   $image
	 * @param string     $text
	 * @param int        $x
	 * @param int        $fontsize
	 * @param int        $fontcolor
	 * @param array|null $origin
	 * @param string     $FontFile
	 * @param array      $box
	 * @param int        $yOffset
	 *
	 * @return array
	 */
	public static function writeOn($image, $text, $x, $fontsize, $fontcolor, &$origin, $FontFile, $box = null, $yOffset = 0){
		if (is_string($fontcolor))
			$fontcolor = imagecolorallocate($image, 0, 0, 0);

		if (empty($box)){
			$box = self::saneGetTTFBox($fontsize, $FontFile, $text);
			$origin['y'] += $box['height'];
			$y = $origin['y'] - $box['bottom right']['y'];
		}
		else $y = $origin['y'] + $box['height'] - $box['bottom right']['y'];

		imagettftext($image, $fontsize, 0, $x, $y + $yOffset, $fontcolor, $FontFile, $text);

		return [$x, $y];
	}

	/**
	 * imagettfbbox wrapper with sane output
	 *
	 * @param int    $fontsize
	 * @param string $fontfile
	 * @param string $text
	 *
	 * @return array
	 */
	public static function saneGetTTFBox($fontsize, $fontfile, $text){
		/*
		    imagettfbbox returns (x,y):
		    6,7--4,5
		     |    |
		     |    |
		    0,1--2,3
		*/
		$box = imagettfbbox($fontsize, 0, $fontfile, $text);

		$return =  [
			'bottom left' => ['x' => $box[0], 'y' => $box[1]],
			'bottom right' => ['x' => $box[2], 'y' => $box[3]],
			'top right' => ['x' => $box[4], 'y' => $box[5]],
			'top left' => ['x' => $box[6], 'y' => $box[7]],
		];
		$return['width'] = abs($return['bottom right']['x'] - $return['top left']['x']);
		$return['height'] = abs($return['bottom right']['y'] - $return['top left']['y']);

		return $return;
	}

	/**
	 * Copies the source image to the destination image at the exact same positions
	 *
	 * @param resource $dest
	 * @param resource $source
	 * @param int      $x
	 * @param int      $y
	 * @param int      $w
	 * @param int      $h
	 */
	public static function copyExact($dest, $source, $x, $y, $w, $h){
		imagecopy($dest, $source, $x, $y, $x, $y, $w, $h);
	}

	/**
	 * Output png file to browser
	 *
	 * @param resource $resource
	 * @param string   $path
	 * @param string   $FileRelPath
	 */
	public static function outputPNG($resource, $path, $FileRelPath){
		self::_output($resource, $path, $FileRelPath, function($fp,$fd){ imagepng($fd, $fp, 9, PNG_NO_FILTER); }, 'png');
	}

	/**
	 * Output svg file to browser
	 *
	 * @param string|null $svgdata
	 * @param string      $path
	 * @param string      $FileRelPath
	 */
	public static function outputSVG($svgdata, $path, $FileRelPath){
		self::_output($svgdata, $path, $FileRelPath, function($fp,$fd){ File::put($fp, $fd); }, 'svg+xml');
	}

	/**
	 * @param resource|string $data
	 * @param string $path
	 * @param string $relpath
	 * @param callable $write_callback
	 * @param string $content_type
	 */
	private static function _output($data, $path, $relpath, $write_callback, $content_type){
		if ($data !== null){
			Core::CreateFoldersFor($path);
			$write_callback($path, $data);
			if (file_exists($path))
				File::chmod($path);
		}

		$filePortion = strtok($relpath,'?');
		$fpl = Core::Length($filePortion);
		$params = Core::Length($relpath) > $fpl ? '&'.Core::Substring($relpath, $fpl+1) : '';
		Core::FixPath("$filePortion?t=".filemtime($path).$params);
		header("Content-Type: image/$content_type");
		readfile($path);
		Core::exit();
	}

	/**
	 * Calculate and recreate the base image in case its size need to be increased
	 *
	 * @param int      $OutWidth
	 * @param int      $OutHeight
	 * @param int      $WidthIncrease
	 * @param int      $HeightIncrease
	 * @param resource $BaseImage
	 * @param array    $origin
	 */
	public static function calcRedraw(&$OutWidth, &$OutHeight, $WidthIncrease, $HeightIncrease, &$BaseImage, $origin){
		$Redraw = false;
		if ($origin['x']+$WidthIncrease > $OutWidth){
			$Redraw = true;
			$origin['x'] += $WidthIncrease;
		}
		if ($origin['y']+$HeightIncrease > $OutHeight){
			$Redraw = true;
			$origin['y'] += $HeightIncrease;
		}
		if ($Redraw){
			$NewWidth = max($origin['x'],$OutWidth);
			$NewHeight = max($origin['y'],$OutHeight);
			// Create new base image since height will increase, and copy contents of old one
			$NewBaseImage = Image::createTransparent($NewWidth, $NewHeight);
			Image::copyExact($NewBaseImage, $BaseImage, 0, 0, $OutWidth, $OutHeight);
			imagedestroy($BaseImage);
			$BaseImage = $NewBaseImage;
			$OutWidth = $NewWidth;
			$OutHeight = $NewHeight;
		}
	}
}


text:
package es.tid.cosmos.admin.command

import org.scalatest.FlatSpec
import org.scalatest.matchers.MustMatchers
import org.scalatest.mock.MockitoSugar
import org.mockito.BDDMockito._

import es.tid.cosmos.admin.cli.AdminArguments
import es.tid.cosmos.admin.cluster.{ClusterCommands, ClusterCommandsComponent}
import es.tid.cosmos.admin.groups.{GroupCommands, GroupCommandsComponent}
import es.tid.cosmos.admin.profile.{ProfileCommands, ProfileCommandsComponent}
import es.tid.cosmos.admin.storage.{PersistentStorageCommands, PersistentStorageCommandsComponent}
import es.tid.cosmos.api.profile.dao.mock.MockCosmosDataStoreComponent

class CommandRunnerTest extends FlatSpec with MustMatchers with MockitoSugar {

  class WithArguments(arguments: String*) extends CommandRunnerComponent
      with MockCosmosDataStoreComponent
      with ProfileCommandsComponent
      with GroupCommandsComponent
      with PersistentStorageCommandsComponent with ClusterCommandsComponent {
    override val persistentStorageCommands = mock[PersistentStorageCommands]
    override val profileCommands = mock[ProfileCommands]
    override val groupCommands = mock[GroupCommands]
    override val clusterCommands = mock[ClusterCommands]
    val runner = commandRunner(new AdminArguments(arguments.toSeq))
  }

  "A command runner" must "exit with non-zero status for invalid arguments" in
    new WithArguments() {
      runner.run().exitStatus must not be 0
    }

  it must "exit with non-zero status when setup fails" in new WithArguments("setup") {
    given(persistentStorageCommands.setup()).willReturn(CommandResult.error())
    runner.run().exitStatus must not be 0
  }

  it must "exit with zero status when everything goes OK" in new WithArguments("setup") {
    given(persistentStorageCommands.setup()).willReturn(CommandResult.success())
    runner.run().exitStatus must be (0)
  }

  it must "work with multi-subcommand arguments" in new WithArguments("persistent-storage", "setup") {
    given(persistentStorageCommands.setup()).willReturn(CommandResult.success())
    runner.run().exitStatus must be (0)
  }
}


text:
package internalversion

import (
	authorization "github.com/openshift/origin/pkg/authorization/apis/authorization"
	scheme "github.com/openshift/origin/pkg/authorization/generated/internalclientset/scheme"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
)

// RoleBindingRestrictionsGetter has a method to return a RoleBindingRestrictionInterface.
// A group's client should implement this interface.
type RoleBindingRestrictionsGetter interface {
	RoleBindingRestrictions(namespace string) RoleBindingRestrictionInterface
}

// RoleBindingRestrictionInterface has methods to work with RoleBindingRestriction resources.
type RoleBindingRestrictionInterface interface {
	Create(*authorization.RoleBindingRestriction) (*authorization.RoleBindingRestriction, error)
	Update(*authorization.RoleBindingRestriction) (*authorization.RoleBindingRestriction, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*authorization.RoleBindingRestriction, error)
	List(opts v1.ListOptions) (*authorization.RoleBindingRestrictionList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *authorization.RoleBindingRestriction, err error)
	RoleBindingRestrictionExpansion
}

// roleBindingRestrictions implements RoleBindingRestrictionInterface
type roleBindingRestrictions struct {
	client rest.Interface
	ns     string
}

// newRoleBindingRestrictions returns a RoleBindingRestrictions
func newRoleBindingRestrictions(c *AuthorizationClient, namespace string) *roleBindingRestrictions {
	return &roleBindingRestrictions{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the roleBindingRestriction, and returns the corresponding roleBindingRestriction object, and an error if there is any.
func (c *roleBindingRestrictions) Get(name string, options v1.GetOptions) (result *authorization.RoleBindingRestriction, err error) {
	result = &authorization.RoleBindingRestriction{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of RoleBindingRestrictions that match those selectors.
func (c *roleBindingRestrictions) List(opts v1.ListOptions) (result *authorization.RoleBindingRestrictionList, err error) {
	result = &authorization.RoleBindingRestrictionList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		VersionedParams(&opts, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested roleBindingRestrictions.
func (c *roleBindingRestrictions) Watch(opts v1.ListOptions) (watch.Interface, error) {
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		VersionedParams(&opts, scheme.ParameterCodec).
		Watch()
}

// Create takes the representation of a roleBindingRestriction and creates it.  Returns the server's representation of the roleBindingRestriction, and an error, if there is any.
func (c *roleBindingRestrictions) Create(roleBindingRestriction *authorization.RoleBindingRestriction) (result *authorization.RoleBindingRestriction, err error) {
	result = &authorization.RoleBindingRestriction{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		Body(roleBindingRestriction).
		Do().
		Into(result)
	return
}

// Update takes the representation of a roleBindingRestriction and updates it. Returns the server's representation of the roleBindingRestriction, and an error, if there is any.
func (c *roleBindingRestrictions) Update(roleBindingRestriction *authorization.RoleBindingRestriction) (result *authorization.RoleBindingRestriction, err error) {
	result = &authorization.RoleBindingRestriction{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		Name(roleBindingRestriction.Name).
		Body(roleBindingRestriction).
		Do().
		Into(result)
	return
}

// Delete takes name of the roleBindingRestriction and deletes it. Returns an error if one occurs.
func (c *roleBindingRestrictions) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *roleBindingRestrictions) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Body(options).
		Do().
		Error()
}

// Patch applies the patch and returns the patched roleBindingRestriction.
func (c *roleBindingRestrictions) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *authorization.RoleBindingRestriction, err error) {
	result = &authorization.RoleBindingRestriction{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("rolebindingrestrictions").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}


text:
@interface RCVideoCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray *attributesArray;
@property (nonatomic, assign) CGFloat itemAreaWidth;
@property (nonatomic, assign) CGFloat itemWidth;

@end

@implementation RCVideoCollectionViewLayout

//- (void)prepareLayout {
//    int itemCount = (int)[self.collectionView numberOfItemsInSection:0];
//    if (itemCount == 0) {
//        [super prepareLayout];
//        return;
//    }
//
//    NSMutableArray *attributesArrays = [NSMutableArray array];
//    CGFloat nowWidth = self.itemSize.width * [self.collectionView numberOfItemsInSection:0]+ (self.minimumInteritemSpacing * ([self.collectionView numberOfItemsInSection:0] - 1)) + _collectionViewContentInset.left  ;
//    for (NSInteger i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
//        //        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
//        UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes
//                                                        layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
//
//        attributes.frame = CGRectMake(nowWidth - self.itemSize.width,
//                                      _collectionViewContentInset.top, self.customItemSize.width, self.customItemSize.height);
//
//        [self.attributesArray addObject:attribute];
//        nowWidth = nowWidth - attribute.frame.size.width - self.minimumInteritemSpacing;
////        [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
//    }
//
////
////    CGRect frame = self.collectionView.bounds;
////    self.customItemSize = self.itemSize;
////
////    self.attributesArray = [[NSMutableArray alloc] init];
////    if (itemCount <= 8) {
////        CGFloat totalWidth = (self.itemSize.width + self.minimumInteritemSpacing) * itemCount;
//////        if (totalWidth < _collectionViewWidth) {
////            totalWidth = _collectionViewWidth;
//////        }
////        CGFloat nowWidth = self.collectionView.frame.size.width - _collectionViewContentInset.right + self.collectionView.contentOffset.x;
////
////
////
////        for (int i = 0; i < itemCount; i++) {
////            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes
////                                                            layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
////            attributes.frame = CGRectMake(nowWidth - (i + 1) * (_customItemSize.width) - (i) * self.minimumInteritemSpacing ,
////                                          _collectionViewContentInset.top, self.customItemSize.width, self.customItemSize.height);
////
//////            attributes.frame = CGRectMake(_collectionViewWidth - _contentInset.right - i * (self.minimumInteritemSpacing) - _customItemSize.width * (i + 1),
//////                                         _contentInset.top, self.customItemSize.width, self.customItemSize.height);
////
////            [self.attributesArray addObject:attributes];
////        }
//////        for (int i = itemCount-1; i >= 0; i--) {
//////            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes
//////                                                            layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
//////            attributes.frame = CGRectMake(_contentInset.left + i * (self.minimumInteritemSpacing + _customItemSize.width) * (i),
//////                                          _contentInset.top, self.customItemSize.width, self.customItemSize.height);
//////
//////            [self.attributesArray addObject:attributes];
//////        }
////
////    }
////
//    [super prepareLayout];
//}
- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.itemSize.width * [self.collectionView numberOfItemsInSection:0] +
                          (self.minimumInteritemSpacing * ([self.collectionView numberOfItemsInSection:0] - 1)) +
                          _collectionViewContentInset.left + _collectionViewContentInset.right,
                      0);
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path {
    UICollectionViewLayoutAttributes *attributes = [self.attributesArray objectAtIndex:[path row]];
    return attributes;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *layoutAttributes_t = [super layoutAttributesForElementsInRect:rect];
    NSArray *layoutAttributes = [[NSArray alloc] initWithArray:layoutAttributes_t copyItems:YES];

    NSMutableArray *attributesArrays = [NSMutableArray array];
    CGFloat nowWidth = self.itemSize.width * [self.collectionView numberOfItemsInSection:0] +
        (self.minimumInteritemSpacing * ([self.collectionView numberOfItemsInSection:0] - 1)) +
        _collectionViewContentInset.left;
    //    self.collectionView.contentOffset = CGPointMake(self.collectionView.frame.size.width, 0);
    if (nowWidth < self.collectionView.frame.size.width - _collectionViewContentInset.left) {
        nowWidth = self.collectionView.frame.size.width - _collectionViewContentInset.left;
    }
    for (NSInteger i = 0; i < layoutAttributes.count; i++) {
        //        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attribute = [layoutAttributes objectAtIndex:i];
        CGRect nowFrame = attribute.frame;
        nowFrame.origin.x = nowWidth - attribute.frame.size.width;
        attribute.frame = nowFrame;
        [attributesArrays addObject:attribute];
        nowWidth = nowWidth - attribute.frame.size.width - self.minimumInteritemSpacing;
        //        [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    self.attributesArray = attributesArrays;
    return attributesArrays;
}

@end


text:
<!DOCTYPE html>

	<title>Buku Tamu</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">

Daftar Buku Tamu

					<?php include "inti_list.php"; ?>

Daftar Buku Tamu

					<?php include "inti_list.php"; ?>

Daftar Buku Tamu

					<?php include "inti_list.php"; ?>

		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link href="css/bootstrap-theme.min.css" rel="stylesheet">


text:
@echo off
rem
rem    Licensed to the Apache Software Foundation (ASF) under one or more
rem    contributor license agreements.  See the NOTICE file distributed with
rem    this work for additional information regarding copyright ownership.
rem    The ASF licenses this file to You under the Apache License, Version 2.0
rem    (the "License"); you may not use this file except in compliance with
rem    the License.  You may obtain a copy of the License at
rem
rem       http://www.apache.org/licenses/LICENSE-2.0
rem
rem    Unless required by applicable law or agreed to in writing, software
rem    distributed under the License is distributed on an "AS IS" BASIS,
rem    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem    See the License for the specific language governing permissions and
rem    limitations under the License.
rem

rem Use JAVA_HOME if it's set; otherwise, just use java

if "%JAVA_HOME%" == "" goto noJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
set JAVA_EXE=%JAVA_HOME%\bin\java.exe
goto startConfig

:noJavaHome
echo The JAVA_HOME environment variable is not defined correctly.
echo Instead the PATH will be used to find the java executable.
echo.
set JAVA_EXE=java
goto startConfig

:startConfig
set LIB_DIR=%~dp0..\conf;%~dp0..\lib

set C2_SERVER_HOME=%~sdp0..\

SET JAVA_PARAMS=-cp %LIB_DIR%\* -Xms12m -Xmx24m %JAVA_ARGS% -Djava.net.preferIPv4Stack=true org.apache.nifi.minifi.c2.jetty.JettyServer

cmd.exe /C "%JAVA_EXE%" %JAVA_PARAMS% %*


text:
package com.github.nmorel.gwtjackson.rebind.property;

import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.thirdparty.guava.common.base.Optional;
import com.google.gwt.thirdparty.guava.common.base.Preconditions;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;

/**
 * @author Nicolas Morel
 */
public abstract class FieldAccessor {

    public static class Accessor {

        private final CodeBlock accessor;

        private final Optional<MethodSpec> additionalMethod;

        public Accessor( CodeBlock accessor ) {
            Preconditions.checkNotNull( accessor );
            this.accessor = accessor;
            this.additionalMethod = Optional.absent();
        }

        public Accessor( CodeBlock accessor, MethodSpec additionalMethod ) {
            Preconditions.checkNotNull( accessor );
            Preconditions.checkNotNull( additionalMethod );

            this.accessor = accessor;
            this.additionalMethod = Optional.of( additionalMethod );
        }

        public CodeBlock getAccessor() {
            return accessor;
        }

        public Optional<MethodSpec> getAdditionalMethod() {
            return additionalMethod;
        }
    }

    protected final String propertyName;

    private final boolean samePackage;

    protected final Optional<JField> field;

    protected final Optional<JMethod> method;

    private final boolean useMethod;

    protected FieldAccessor( String propertyName, boolean samePackage, boolean fieldAutoDetect, Optional<JField> field,
                             boolean methodAutoDetect, Optional<JMethod> method ) {
        Preconditions.checkNotNull( propertyName );
        Preconditions.checkArgument( field.isPresent() || method.isPresent(), "At least one of the field or method must be given" );

        this.propertyName = propertyName;
        this.samePackage = samePackage;
        this.field = field;
        this.method = method;

        // We first test if we can use the method
        if ( method.isPresent() && (methodAutoDetect || !fieldAutoDetect || !field.isPresent()) ) {
            useMethod = true;
        }
        // else use the field
        else {
            useMethod = false;
        }
    }

    public Optional<JField> getField() {
        return field;
    }

    public Optional<JMethod> getMethod() {
        return method;
    }

    public Accessor getAccessor( final String beanName, Object... params ) {
        final boolean useJsni;
        if ( useMethod ) {
            useJsni = method.get().isPrivate() || (!samePackage && !method.get().isPublic());
        }
        // else use the field
        else {
            useJsni = field.get().isPrivate() || (!samePackage && !field.get().isPublic());
        }
        return getAccessor( beanName, useMethod, useJsni, params );
    }

    protected abstract Accessor getAccessor( final String beanName, final boolean useMethod, final boolean useJsni, Object... params );
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bunjlabs.fuga.examples.i18n;

import com.bunjlabs.fuga.foundation.Controller;
import com.bunjlabs.fuga.foundation.Result;
import com.bunjlabs.fuga.views.ViewException;

public class I18nExampleController extends Controller {

    public Result language() {
        String langCode = ctx.lang();

        return redirect(ctx.urls().that(langCode));
    }

    public Result language(String langCode) {
        ctx.lang(langCode);
        return proceed();
    }

    public Result index() throws ViewException {
        return ok(view("i18n.html"));
    }
}


text:
<?php

use Illuminate\Database\Seeder;

class FeaturesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         DB::table("features")->insert([
            ["name" => "Air Conditioning"],
            ["name" => "Security Alarm"],
            ["name" => "Backyard"],
            ["name" => "Balcony"],
            ["name" => "Caretaker Service"],
            ["name" => "Central Heating"],
            ["name" => "Children Floor"],
            ["name" => "Ceramic/Tiled Floor"],
            ["name" => "Community Area"],
            ["name" => "Community Garage"],
            ["name" => "Community Pool"],
            ["name" => "Electric Heating"],
            ["name" => "Diesel Heating"],
            ["name" => "Close to Shopping"],
            ["name" => "Fitted Wardrobe"],
            ["name" => "Independent Kitchen"],
            ["name" => "Independent Toilet"],
            ["name" => "Lift"],
            ["name" => "Jacuzzi"],
            ["name" => "Private Pool"],
            ["name" => "Sports Area"],
            ["name" => "Warehouse"],
            ["name" => "Security Guards"],
            ["name" => "Packing Space"]
        ]);
    }
}


text:
package org.artifactory.version.converter.v160;

import org.apache.commons.lang.StringUtils;
import org.artifactory.descriptor.repo.RepoType;
import org.artifactory.version.converter.XmlConverter;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Gidi Shabat
 */
public class SuppressConsitencyConverter implements XmlConverter {
    private static final Logger log = LoggerFactory.getLogger(SingleRepoTypeConverter.class);

    @Override
    public void convert(Document doc) {
        log.info("Finished Converting repositories to a suppress consistency");

        Element rootElement = doc.getRootElement();
        Namespace namespace = rootElement.getNamespace();

        Element localRepos = rootElement.getChild("localRepositories", namespace);
        if (localRepos != null) {
            convertLocalRepos(localRepos.getChildren());
        }

        Element remoteRepos = rootElement.getChild("remoteRepositories", namespace);
        if (remoteRepos != null) {
            convertRemoteRepos(remoteRepos.getChildren());
        }

        log.info("Finished Converting repositories to a suppress consistency");
    }

    private void convertLocalRepos(List<Element> repos) {
        if (repos == null || repos.isEmpty()) {
            return;
        }

        for (Element repo : repos) {
            convertSuppressConsistency(repo);
        }
    }

    private void convertRemoteRepos(List<Element> repos) {
        if (repos == null || repos.isEmpty()) {
            return;
        }

        for (Element repo : repos) {
            convertSuppressConsistency(repo);
        }
    }

    private void convertSuppressConsistency(Element repo) {
        Element type = repo.getChild("type", repo.getNamespace());
        RepoType repoType = RepoType.fromType(type.getText());
        if (repoType.isMavenGroup()) {
            Element suppress= repo.getChild("suppressPomConsistencyChecks", repo.getNamespace());
            String pomConsistencyValue = repo.getChildText("suppressPomConsistencyChecks", repo.getNamespace());
            if (suppress==null ){
                suppress=new Element("suppressPomConsistencyChecks", repo.getNamespace());
                int lastLocation = findSuppressLocation(repo);
                repo.addContent(lastLocation + 1, new Text("\n            "));
                repo.addContent(lastLocation + 2, suppress);
            }
            if(StringUtils.isBlank(suppress.getText())) {
                pomConsistencyValue = "false";
            }
            suppress.setText(pomConsistencyValue);
        }
    }

    private int findSuppressLocation(Element repo) {
        return findLastLocation(repo, "maxUniqueSnapshots",
                        "handleSnapshots",
                        "handleReleases",
                        "blackedOut",
                        "dockerApiVersion",
                        "repoLayoutRef",
                        "excludesPattern",
                        "includesPattern",
                        "notes",
                        "description",
                        "type");
    }

    private int findLastLocation(Element parent, String... elements) {
        for (int i = 0; i < elements.length; i++) {
            Element child = parent.getChild(elements[i], parent.getNamespace());
            if (child != null) {
                return parent.indexOf(child);
            }
        }
        return -1;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c)2013 Prometheus Consulting

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
	>

	<description>Object Spring Configuration</description>

	<context:annotation-config/>

    <bean id="schema" class="org.springframework.core.io.ClassPathResource">
        <constructor-arg value="nz/co/senanque/schemaparser/SchemaParserTest.xsd"/>
    </bean>

</beans>


text:
package org.adligo.fabricate_tests.depot;

import org.adligo.fabricate.depot.ArtifactKey;
import org.adligo.tests4j.shared.asserts.common.ExpectedThrowable;
import org.adligo.tests4j.shared.asserts.common.I_Thrower;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_4mockito.MockitoSourceFileTrial;

@SourceFileScope (sourceClass=ArtifactKey.class, minCoverage=93.0)
public class ArtifactKeyTrial extends MockitoSourceFileTrial {

  @SuppressWarnings("unused")
  @Test
  public void testConstructorExceptions() {

    assertThrown(new ExpectedThrowable(new IllegalArgumentException("projectName")), new I_Thrower() {

      @Override
      public void run() throws Throwable {
        new ArtifactKey(null, "atA", "platA");
      }
    });

    assertThrown(new ExpectedThrowable(new IllegalArgumentException("artifactType")), new I_Thrower() {

      @Override
      public void run() throws Throwable {
        new ArtifactKey("pnA", null, "platA");
      }
    });

    assertThrown(new ExpectedThrowable(new IllegalArgumentException("platformName")), new I_Thrower() {

      @Override
      public void run() throws Throwable {
        new ArtifactKey("pnA", "atA", null);
      }
    });
  }

  @SuppressWarnings("boxing")
  @Test
  public void testConstructorEqualsHashCodeAndGets() {
    ArtifactKey aka = new ArtifactKey("pnA", "atA", "platA");
    ArtifactKey akaCopy = new ArtifactKey("pnA", "atA", "platA");
    ArtifactKey aka0 = new ArtifactKey("pnA0", "atA", "platA");
    ArtifactKey aka1 = new ArtifactKey("pnA", "atA1", "platA");
    ArtifactKey aka2 = new ArtifactKey("pnA", "atA", "platA2");

    assertEquals(aka.hashCode(), aka.hashCode());
    assertEquals(aka, aka);
    assertEquals("ArtifactKey [projectName=pnA, artifactType=atA, platformName=platA]", aka.toString());
    assertEquals("atA", aka.getArtifactType());
    assertEquals("platA", aka.getPlatformName());
    assertEquals("pnA", aka.getProjectName());

    assertEquals(akaCopy.hashCode(), akaCopy.hashCode());
    assertEquals(akaCopy, akaCopy);

    assertNotEquals(aka.hashCode(), aka0.hashCode());
    assertNotEquals(aka, aka0);
    assertNotEquals(aka.hashCode(), aka1.hashCode());
    assertNotEquals(aka, aka1);
    assertNotEquals(aka.hashCode(), aka2.hashCode());
    assertNotEquals(aka, aka2);
  }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>WebGL draw with uniform blocks conformance tests</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="example" width="100", height="100"></canvas>


text:
.class Landroid/view/VolumePanel$2;
.super Landroid/app/Dialog;
.source "VolumePanel.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/view/VolumePanel;-><init>(Landroid/content/Context;Landroid/media/AudioService;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/view/VolumePanel;

# direct methods
.method constructor <init>(Landroid/view/VolumePanel;Landroid/content/Context;I)V
    .locals 0
    .parameter
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 358
    iput-object p1, p0, Landroid/view/VolumePanel$2;->this$0:Landroid/view/VolumePanel;

    invoke-direct {p0, p2, p3}, Landroid/app/Dialog;-><init>(Landroid/content/Context;I)V

    return-void
.end method

# virtual methods
.method public onTouchEvent(Landroid/view/MotionEvent;)Z
    .locals 2
    .parameter "event"

    .prologue
    .line 360
    invoke-virtual {p0}, Landroid/view/VolumePanel$2;->isShowing()Z

    move-result v0

    if-eqz v0, :cond_0

    invoke-virtual {p1}, Landroid/view/MotionEvent;->getAction()I

    move-result v0

    const/4 v1, 0x4

    if-ne v0, v1, :cond_0

    .line 361
    iget-object v0, p0, Landroid/view/VolumePanel$2;->this$0:Landroid/view/VolumePanel;

    #calls: Landroid/view/VolumePanel;->forceTimeout()V
    invoke-static {v0}, Landroid/view/VolumePanel;->access$100(Landroid/view/VolumePanel;)V

    .line 362
    const/4 v0, 0x1

    .line 364
    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
package com.google.sps.servlets;

import com.google.sps.data.DatastoreScheduledInterviewDao;
import com.google.sps.data.ScheduledInterview;
import com.google.sps.data.ScheduledInterviewDao;
import com.google.sps.data.TimeRange;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.ZoneId;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

@WebServlet("/feedback")
public class FeedbackServlet extends HttpServlet {

  private ScheduledInterviewDao scheduledInterviewDao;

  @Override
  public void init() {
    init(new DatastoreScheduledInterviewDao());
  }

  public void init(ScheduledInterviewDao scheduledInterviewDao) {
    this.scheduledInterviewDao = scheduledInterviewDao;
  }

  // Opens the feedback form if the user's time is five minutes before the start of the interview.
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    long scheduledInterviewId = Long.parseLong(request.getParameter("interview"));
    String userTime = request.getParameter("userTime");
    String timeZone = request.getParameter("timeZone");
    String role = request.getParameter("role");
    boolean feedbackOpen = feedbackIsOpen(userTime, timeZone, scheduledInterviewId);
    request.setAttribute("feedbackOpen", feedbackOpen);
    request.setAttribute("role", role);
    RequestDispatcher rd = request.getRequestDispatcher("/feedback.jsp");
    try {
      rd.forward(request, response);
    } catch (ServletException e) {
      throw new RuntimeException(e);
    }
  }

  // Returns whether or not a scheduledInterviewId is found and the start time is at least five
  // minutes before the user's current time.
  private boolean feedbackIsOpen(
      String userTimeString, String timeZoneString, Long scheduledInterviewId) {
    ZoneId timeZoneId = ZoneId.of(timeZoneString);
    Instant userTime = Instant.parse(userTimeString);
    TimeRange scheduledInterviewRange =
        scheduledInterviewDao.get(scheduledInterviewId).map(ScheduledInterview::when).orElse(null);
    if (scheduledInterviewRange == null) {
      throw new NullPointerException("This scheduledInterviewId does not exist");
    }
    return scheduledInterviewRange.start().minus(5, ChronoUnit.MINUTES).isBefore(userTime);
  }
}


text:
package org.apache.lens.cube.error;

import static org.apache.lens.cube.error.LensCubeErrorCode.COLUMN_UNAVAILABLE_IN_TIME_RANGE;

import org.apache.lens.api.error.ErrorCollection;
import org.apache.lens.api.error.LensError;
import org.apache.lens.api.result.LensErrorTO;
import org.apache.lens.server.api.error.LensException;

import lombok.EqualsAndHashCode;
import lombok.NonNull;

@EqualsAndHashCode(callSuper = true)
public class ColUnAvailableInTimeRangeException extends LensException {

  private final ColUnAvailableInTimeRange colUnAvailableInTimeRange;

  public ColUnAvailableInTimeRangeException(@NonNull final ColUnAvailableInTimeRange colUnAvailableInTimeRange) {

    super(COLUMN_UNAVAILABLE_IN_TIME_RANGE.getLensErrorInfo());
    this.colUnAvailableInTimeRange = colUnAvailableInTimeRange;
  }

  @Override
  public String getFormattedErrorMsg(LensError lensError) {

    final String colName = colUnAvailableInTimeRange.getColumnName();
    final String availability = colUnAvailableInTimeRange.getAvailability();

    return lensError.getFormattedErrorMsg(colName, availability);
  }

  @Override
  protected LensErrorTO buildLensErrorTO(final ErrorCollection errorCollection, final String errorMsg,
      final String stackTrace) {

    return LensErrorTO.composedOf(COLUMN_UNAVAILABLE_IN_TIME_RANGE.getLensErrorInfo().getErrorCode(),
        errorMsg, stackTrace, colUnAvailableInTimeRange);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.sunshine.app">

    <uses-sdk
        android:maxSdkVersion="25"
        android:minSdkVersion="19"
        android:targetSdkVersion="24" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DetailedActivity"
                  android:label="@string/title_activity_detail"
                  android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.android.sunshine.app.MainActivity" />
        </activity>
        <activity android:name=".SettingsActivity"
            android:label="@string/title_settings_activity"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.android.sunshine.app.MainActivity" />
        </activity>
    </application>

</manifest>


text:
using System.ComponentModel.Design;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;

namespace System.ComponentModel
{
    public sealed partial class LicenseManager
    {
        // A private implementation of a LicenseContext used for instantiating
        // managed objects exposed to COM. It has memory for the license key
        // of a single Type.
        private class CLRLicenseContext : LicenseContext
        {
            private readonly Type _type;
            private string _key;

            private CLRLicenseContext(Type type, LicenseUsageMode mode)
            {
                UsageMode = mode;
                _type = type;
            }

            public static CLRLicenseContext CreateDesignContext(Type type)
            {
                return new CLRLicenseContext(type, LicenseUsageMode.Designtime);
            }

            public static CLRLicenseContext CreateRuntimeContext(Type type, string key)
            {
                var cxt = new CLRLicenseContext(type, LicenseUsageMode.Runtime);
                if (key != null)
                {
                    cxt.SetSavedLicenseKey(type, key);
                }

                return cxt;
            }

            public override LicenseUsageMode UsageMode { get; }

            public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly)
            {
                if (type == _type)
                {
                    return _key;
                }

                return null;
            }

            public override void SetSavedLicenseKey(Type type, string key)
            {
                if (type == _type)
                {
                    _key = key;
                }
            }
        }

        // Used from IClassFactory2 when retrieving LicInfo
        private class LicInfoHelperLicenseContext : LicenseContext
        {
            private readonly Hashtable _savedLicenseKeys = new Hashtable();

            public bool Contains(string assemblyName) => _savedLicenseKeys.Contains(assemblyName);

            public override LicenseUsageMode UsageMode => LicenseUsageMode.Designtime;

            public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) => null;

            public override void SetSavedLicenseKey(Type type, string key)
            {
                _savedLicenseKeys[type.AssemblyQualifiedName] = key;
            }
        }

        // This is a helper class that supports the CLR's IClassFactory2 marshaling
        // support.
        private class LicenseInteropHelper
        {
            // Used to validate a type and retrieve license details
            // when activating a managed COM server from an IClassFactory2 instance.
            public static bool ValidateAndRetrieveLicenseDetails(
                LicenseContext context,
                Type type,
                out License license,
                out string licenseKey)
            {
                if (context == null)
                {
                    context = LicenseManager.CurrentContext;
                }

                return LicenseManager.ValidateInternalRecursive(
                    context,
                    type,
                    instance: null,
                    allowExceptions: false,
                    out license,
                    out licenseKey);
            }

            // The CLR invokes this when instantiating an unmanaged COM
            // object. The purpose is to decide which IClassFactory method to
            // use.
            public static LicenseContext GetCurrentContextInfo(Type type, out bool isDesignTime, out string key)
            {
                LicenseContext licContext = LicenseManager.CurrentContext;
                isDesignTime = licContext.UsageMode == LicenseUsageMode.Designtime;
                key = null;
                if (!isDesignTime)
                {
                    key = licContext.GetSavedLicenseKey(type, resourceAssembly: null);
                }

                return licContext;
            }
        }
    }
}


text:
import styled, {keyframes} from 'styled-components';

const dayNight = keyframes`
  from {
    opacity: .95;
  }

  to {
    opacity: 0;
  }
`;

export default styled.div`
  position: fixed;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;

  background-color: black;

  animation: ${dayNight} 5s linear infinite alternate;

  z-index: 100;
`;