text:
ROOT = ../../../../..

DIR = Providers/ManagedSystem/UNIXProviders/ApplicationSystemHierarchy

include $(ROOT)/mak/config.mak

LIBRARY = UNIX_ApplicationSystemHierarchyProvider

EXTRA_INCLUDES += -I/usr/local/include -I./..

SOURCES = \
	../CIMHelper.cpp \
	UNIX_ApplicationSystemHierarchyMain.cpp \
	UNIX_ApplicationSystemHierarchy.cpp \
	UNIX_ApplicationSystemHierarchyProvider.cpp

ifeq ($(OS), aix)
	SOURCES += UNIX_ApplicationSystemHierarchy_AIX.cpp
endif
ifeq ($(OS), darwin)
	SOURCES += UNIX_ApplicationSystemHierarchy_DARWIN.cpp
endif
ifeq ($(OS), freebsd)
	SOURCES += UNIX_ApplicationSystemHierarchy_FREEBSD.cpp
endif
ifeq ($(OS), hpux)
	SOURCES += UNIX_ApplicationSystemHierarchy_HPUX.cpp
endif
ifeq ($(OS), linux)
	SOURCES += UNIX_ApplicationSystemHierarchy_LINUX.cpp
endif
ifeq ($(OS), solaris)
	SOURCES += UNIX_ApplicationSystemHierarchy_SOLARIS.cpp
endif
ifeq ($(OS), tru64)
	SOURCES += UNIX_ApplicationSystemHierarchy_TRU64.cpp
endif
ifeq ($(OS), vms)
	SOURCES += UNIX_ApplicationSystemHierarchy_VMS.cpp
endif
ifeq ($(OS), win32)
	SOURCES += UNIX_ApplicationSystemHierarchy_WIN32.cpp
endif
ifeq ($(OS), zos)
	SOURCES += UNIX_ApplicationSystemHierarchy_ZOS.cpp
endif
ifeq (, $(filter aix,darwin,freebsd,hpux,linux,solaris,tru64,vms,win32,zos $(OS)))

else
	SOURCES += UNIX_ApplicationSystemHierarchy_STUB.cpp
endif

LIBRARIES = \
	pegprovider \
	pegclient \
	pegcommon \
	pegquerycommon \
	pegqueryexpression \
	pegcql \
	pegwql

EXTRA_LIBRARIES = \
	-pthread \
	-lutil \
	-lgeom \
	-lkvm \
	-lcam

include $(ROOT)/mak/dynamic-library.mak


text:
@interface DLSSliderEditor ()

@property (assign, nonatomic) double min;
@property (assign, nonatomic) double max;

@end

@implementation DLSSliderEditor

+ (DLSSliderEditor*)zeroOneSlider {
    return [self sliderWithMin:0 max:1];
}

+ (DLSSliderEditor*)sliderWithMin:(double)min max:(double)max {
    DLSSliderEditor* description = [[DLSSliderEditor alloc] initWithMin:min max:max];
    return description;
}

- (id)initWithMin:(double)min max:(double)max {
    self = [super init];
    if(self != nil) {
        self.min = min;
        self.max = max;
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if(self != nil) {
        DLSDecodeDouble(aDecoder, min);
        DLSDecodeDouble(aDecoder, max);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    DLSEncodeDouble(aCoder, min);
    DLSEncodeDouble(aCoder, max);
}

@end

redpajama_set_name: RedPajamaGithub


text:
@class MPTChatMessage;

@interface MPTChatUser : NSManagedObject

@property (nonatomic, retain) NSNumber * isLocalUser;
@property (nonatomic, retain) NSString * username;
@property (nonatomic, retain) NSSet *messages;
@end

@interface MPTChatUser (CoreDataGeneratedAccessors)

- (void)addMessagesObject:(MPTChatMessage *)value;
- (void)removeMessagesObject:(MPTChatMessage *)value;
- (void)addMessages:(NSSet *)values;
- (void)removeMessages:(NSSet *)values;

@end


text:
<?php

namespace Melnik\BlogBundle\Tests\Twig\Extensions;

use Melnik\BlogBundle\Twig\Extensions\MelnikBlogExtension;

class MelnikBlogExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testCreatedAgo()
    {
        $blog = new MelnikBlogExtension();

        $this->assertEquals("0 seconds ago", $blog->createdAgo(new \DateTime()));
        $this->assertEquals("34 seconds ago", $blog->createdAgo($this->getDateTime(-34)));
        $this->assertEquals("1 minute ago", $blog->createdAgo($this->getDateTime(-60)));
        $this->assertEquals("2 minutes ago", $blog->createdAgo($this->getDateTime(-120)));
        $this->assertEquals("1 hour ago", $blog->createdAgo($this->getDateTime(-3600)));
        $this->assertEquals("1 hour ago", $blog->createdAgo($this->getDateTime(-3601)));
        $this->assertEquals("2 hours ago", $blog->createdAgo($this->getDateTime(-7200)));

        // Cannot create time in the future
        $this->setExpectedException('\InvalidArgumentException');
        $blog->createdAgo($this->getDateTime(60));
    }

    protected function getDateTime($delta)
    {
        return new \DateTime(date("Y-m-d H:i:s", time()+$delta));
    }
}


text:
package com.gs.tablasco.verify;

import com.gs.tablasco.VerifiableTable;

public interface SingleTableVerifier
{
    ResultTable verify(VerifiableTable actualData, VerifiableTable expectedData);
}


text:
{-# LANGUAGE ApplicativeDo #-}
module ShouldFail where

g :: IO ()
g = do
  x <- getChar
  'a' <- return (3::Int) -- type error
  return ()


text:
<!DOCTYPE html>

<TITLE>Manpage of fail2ban_selinux</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

fail2ban_selinux

Section: fail2ban SELinux Policy documentation (8)
Updated: fail2ban
Index
Return to Main Contents

NAME

fail2ban_selinux - Security Enhanced Linux Policy for the fail2ban processes

DESCRIPTION

SELinux Linux secures
fail2ban

(Update firewall filtering to ban IP addresses with too many password failures)
processes via flexible mandatory access
control.

FILE CONTEXTS

SELinux requires files to have an extended attribute to define the file type.

You can see the context of a file using the -Z option to lsP
Policy governs the access confined processes have to these files.
SELinux fail2ban policy is very flexible allowing users to setup their fail2ban processes in as secure a method as possible.

The following file types are defined for fail2ban:

fail2ban_exec_t

- Set files with the fail2ban_exec_t type, if you want to transition an executable to the fail2ban_t domain.

Paths:

/usr/bin/fail2ban-server, /usr/bin/fail2ban

fail2ban_initrc_exec_t

- Set files with the fail2ban_initrc_exec_t type, if you want to transition an executable to the fail2ban_initrc_t domain.

fail2ban_log_t

- Set files with the fail2ban_log_t type, if you want to treat the data as fail2ban log data, usually stored under the /var/log directory.

fail2ban_tmp_t

- Set files with the fail2ban_tmp_t type, if you want to store fail2ban temporary files in the /tmp directories.

fail2ban_var_lib_t

- Set files with the fail2ban_var_lib_t type, if you want to store the fail2ban files under the /var/lib directory.

fail2ban_var_run_t

- Set files with the fail2ban_var_run_t type, if you want to store the fail2ban files under the /run directory.

Note: File context can be temporarily modified with the chcon command.  If you want to permanently change the file context you need to use the
semanage fcontext

command.  This will modify the SELinux labeling database.  You will need to use
restorecon

to apply the labels.

PROCESS TYPES

SELinux defines process types (domains) for each process running on the system

You can see the context of a process using the -Z option to psP
Policy governs the access confined processes have to files.
SELinux fail2ban policy is very flexible allowing users to setup their fail2ban processes in as secure a method as possible.

The following process types are defined for fail2ban:

fail2ban_t

Note:
semanage permissive -a PROCESS_TYPE

can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated.

COMMANDS

semanage fcontext

can also be used to manipulate default file context mappings.

semanage permissive

can also be used to manipulate whether or not a process type is permissive.

semanage module

can also be used to enable/disable/install/remove policy modules.

system-config-selinux

is a GUI tool available to customize SELinux policy settings.

AUTHOR<TT>  </TT>

This manual page was autogenerated by genman.py.

SEE ALSO

selinux(8), fail2ban(8), semanage(8), restorecon(8), chcon(1)

Index

NAME

DESCRIPTION

FILE CONTEXTS

PROCESS TYPES

COMMANDS

AUTHOR<TT>  </TT>

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:25 GMT, December 24, 2015


text:
from itty import *

@get('/simple_post')
def simple_post(request):
    return open('examples/html/simple_post.html', 'r').read()

@post('/test_post')
def test_post(request):
    return "'foo' is: {}".format(request.POST.get('foo', 'not specified'))

@get('/complex_post')
def complex_post(request):
    return open('examples/html/complex_post.html', 'r').read()

@post('/test_complex_post')
def test_complex_post(request):
    html = """
    'foo' is: {}<br>
    'bar' is: {}
    """.format(request.POST.get('foo', 'not specified'),
            request.POST.get('bar', 'not specified'))
    return html

run_itty()


text:
package org.apache.camel.component.elasticsearch5;

public interface ElasticsearchConstants {

    String PARAM_OPERATION = "operation";
    String PARAM_INDEX_ID = "indexId";
    String PARAM_INDEX_NAME = "indexName";
    String PARAM_INDEX_TYPE = "indexType";
    String PARAM_WAIT_FOR_ACTIVE_SHARDS = "waitForActiveShards";
    String PARENT = "parent";
    String TRANSPORT_ADDRESSES = "transportAddresses";
    String PROTOCOL = "elasticsearch";
    String IP = "ip";
    String PORT = "port";
    int    DEFAULT_PORT = 9300;
    int    DEFAULT_FOR_WAIT_ACTIVE_SHARDS = 1; // Meaning only wait for the primary shard
    String TRANSPORT_ADDRESSES_SEPARATOR_REGEX = ",";
    String IP_PORT_SEPARATOR_REGEX = ":";
    String ES_QUERY_DSL_PREFIX = "query";
}


text:
import easeInOutQuad from './easing.js'

const jumper = () => {
  // private variable cache
  // no variables are created during a jump, preventing memory leaks

  let element         // element to scroll to                   (node)

  let start           // where scroll starts                    (px)
  let stop            // where scroll stops                     (px)

  let offset          // adjustment from the stop position      (px)
  let easing          // easing function                        (function)
  let a11y            // accessibility support flag             (boolean)

  let distance        // distance of scroll                     (px)
  let duration        // scroll duration                        (ms)

  let timeStart       // time scroll started                    (ms)
  let timeElapsed     // time spent scrolling thus far          (ms)

  let next            // next scroll position                   (px)

  let callback        // to call when done scrolling            (function)

  // scroll position helper

  function location () {
    return window.scrollY || window.pageYOffset
  }

  // element offset helper

  function top (element) {
    return element.getBoundingClientRect().top + start
  }

  // rAF loop helper

  function loop (timeCurrent) {
    // store time scroll started, if not started already
    if (!timeStart) {
      timeStart = timeCurrent
    }

    // determine time spent scrolling so far
    timeElapsed = timeCurrent - timeStart

    // calculate next scroll position
    next = easing(timeElapsed, start, distance, duration)

    // scroll to it
    window.scrollTo(0, next)

    // check progress
    timeElapsed < duration
      ? window.requestAnimationFrame(loop)       // continue scroll loop
      : done()                                   // scrolling is done
  }

  // scroll finished helper

  function done () {
    // account for rAF time rounding inaccuracies
    window.scrollTo(0, start + distance)

    // if scrolling to an element, and accessibility is enabled
    if (element && a11y) {
      // add tabindex indicating programmatic focus
      element.setAttribute('tabindex', '-1')

      // focus the element
      element.focus()
    }

    // if it exists, fire the callback
    if (typeof callback === 'function') {
      callback()
    }

    // reset time for next jump
    timeStart = false
  }

  // API

  function jump (target, options = {}) {
    // resolve options, or use defaults
    duration = options.duration || 1000
    offset = options.offset || 0
    callback = options.callback                       // "undefined" is a suitable default, and won't be called
    easing = options.easing || easeInOutQuad
    a11y = options.a11y || false

    // cache starting position
    start = location()

    // resolve target
    switch (typeof target) {
      // scroll from current position
      case 'number':
        element = undefined           // no element to scroll to
        a11y = false                  // make sure accessibility is off
        stop = start + target
        break

      // scroll to element (node)
      // bounding rect is relative to the viewport
      case 'object':
        element = target
        stop = top(element)
        break

      // scroll to element (selector)
      // bounding rect is relative to the viewport
      case 'string':
        element = document.querySelector(target)
        stop = top(element)
        break
    }

    // resolve scroll distance, accounting for offset
    distance = stop - start + offset

    // resolve duration
    switch (typeof options.duration) {
      // number in ms
      case 'number':
        duration = options.duration
        break

      // function passed the distance of the scroll
      case 'function':
        duration = options.duration(distance)
        break
    }

    // start the loop
    window.requestAnimationFrame(loop)
  }

  // expose only the jump method
  return jump
}

// export singleton

const singleton = jumper()

export default singleton


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Text;
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Text;

namespace Cake.Common.Text
{
    /// <summary>
    /// Provides functionality to perform simple text transformations
    /// from a Cake build script and save them to disc.
    /// </summary>
    /// <typeparam name="TTemplate">The text transformation template.</typeparam>
    public sealed class TextTransformation<TTemplate>
        where TTemplate : class, ITextTransformationTemplate
    {
        private readonly IFileSystem _fileSystem;
        private readonly ICakeEnvironment _environment;

        /// <summary>
        /// Gets the text transformation template.
        /// </summary>
        /// <value>The text transformation template.</value>
        public TTemplate Template { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TextTransformation{TTemplate}"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="template">The text template.</param>
        public TextTransformation(IFileSystem fileSystem,
            ICakeEnvironment environment, TTemplate template)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }
            _fileSystem = fileSystem;
            _environment = environment;
            Template = template;
        }

        /// <summary>
        /// Saves the text transformation to a file.
        /// </summary>
        /// <param name="path">The <see cref="FilePath"/> to save the text transformation to.</param>
        public void Save(FilePath path)
        {
            Save(path, new UTF8Encoding(false));
        }

        /// <summary>
        /// Saves the text transformation to a file.
        /// </summary>
        /// <param name="path">The <see cref="FilePath"/> to save the text transformation to.</param>
        /// <param name="encoding">The text encoding.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Stream writer leaves stream open.")]
        public void Save(FilePath path, Encoding encoding)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            // Make the path absolute if necessary.
            path = path.IsRelative ? path.MakeAbsolute(_environment) : path;

            // Render the content to the file.
            var file = _fileSystem.GetFile(path);
            using (var stream = file.OpenWrite())
            using (var writer = new StreamWriter(stream, encoding, 1024, true))
            {
                writer.Write(Template.Render());
            }
        }

        /// <summary>
        /// Returns a string containing the rendered template.
        /// </summary>
        /// <returns>A string containing the rendered template.</returns>
        public override string ToString()
        {
            return Template.Render();
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>F (Play! API)</title>
<meta name="date" content="2015-12-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

play.libs

Class F

java.lang.Object

play.libs.F

public class F
extends java.lang.Object

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static interface
F.Action<T>

static interface
F.Action0

static class
F.ArchivedEventStream<T>

static class
F.E2<A,B>

static class
F.E3<A,B,C>

static class
F.E4<A,B,C,D>

static class
F.E5<A,B,C,D,E>

static class
F.Either<A,B>

static class
F.EventStream<T>

static class
F.IndexedEvent<M>

static class
F.Matcher<T,R>

static class
F.None<T>

static class
F.Option<T>

static class
F.Promise<V>

static class
F.Some<T>

static class
F.T2<A,B>

static class
F.T3<A,B,C>

static class
F.T4<A,B,C,D>

static class
F.T5<A,B,C,D,E>

static class
F.Timeout

static class
F.Tuple<A,B>

Field Summary

Fields

Modifier and Type
Field and Description

static F.None<java.lang.Object>
None

Constructor Summary

Constructors

Constructor and Description

F()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static <A> F.Some<A>
Some(A a)

static <A,B> F.T2<A,B>
T2(A a,
  B b)

static <A,B,C> F.T3<A,B,C>
T3(A a,
  B b,
  C c)

static <A,B,C,D> F.T4<A,B,C,D>
T4(A a,
  B b,
  C c,
  D d)

static <A,B,C,D,E>
F.T5<A,B,C,D,E>
T5(A a,
  B b,
  C c,
  D d,
  E e)

static F.Timeout
Timeout(long delay)

static F.Timeout
Timeout(java.lang.String delay)

static F.Timeout
Timeout(java.lang.String token,
       long delay)

static F.Timeout
Timeout(java.lang.String token,
       java.lang.String delay)

static <A,B> F.Tuple<A,B>
Tuple(A a,
     B b)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

None

public static F.None<java.lang.Object> None

Constructor Detail

F

public F()

Method Detail

Timeout

public static F.Timeout Timeout(java.lang.String delay)

Timeout

public static F.Timeout Timeout(java.lang.String token,
                                java.lang.String delay)

Timeout

public static F.Timeout Timeout(long delay)

Timeout

public static F.Timeout Timeout(java.lang.String token,
                                long delay)

Some

public static <A> F.Some<A> Some(A a)

Tuple

public static <A,B> F.Tuple<A,B> Tuple(A a,
                                       B b)

T2

public static <A,B> F.T2<A,B> T2(A a,
                                 B b)

T3

public static <A,B,C> F.T3<A,B,C> T3(A a,
                                     B b,
                                     C c)

T4

public static <A,B,C,D> F.T4<A,B,C,D> T4(A a,
                                         B b,
                                         C c,
                                         D d)

T5

public static <A,B,C,D,E> F.T5<A,B,C,D,E> T5(A a,
                                             B b,
                                             C c,
                                             D d,
                                             E e)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
class Hash
  def should_be_ok(files_count = 1)
    self.size.should == files_count
    self.errors_count.should == 0
  end

  def ok_count
    self.values.count{ |res| !res[:error] }
  end

  def errors_count
    self.size - self.ok_count
  end

  def only_value
    if self.size == 1
      self.values.first
    else
      raise "request for 1 value, but there is more: #{self.size}"
    end
  end

  def only_match(pattern)
    keys = self.keys.grep(pattern)
    if keys.size == 1
      key = keys.first
      self[key]
    else
      raise "incorrect pattern: matched #{keys.size} with #{pattern} (expected only 1)"
    end
  end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Filibuster</title> <link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">

Results for "war_explosivemedium"

Index

landmine

ICBM

ICBM

bomb

ICMS

booby-trap

ICMS

landmine

rocket

ICMS

bomb

landmine

rocket

ICBM

rocket

rocket

ICBM

landmine

rocket

ICMS


text:
package com.wt.dms.service.impl;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wt.dms.dao.SuggestionBoxDao;
import com.wt.dms.model.SuggestionBox;
import com.wt.dms.service.SuggestionBoxService;

/**
 * <pre>
 * 业务名:
 * 功能说明:
 * 编写日期:
 * 作者:	HEA IDE
 *
 * 历史记录
 * 1、修改日期:
 *    修改人:
 *    修改内容:
 * </pre>
 */
@Service(value = "SuggestionBoxService")
@Transactional
public class SuggestionBoxServiceImpl implements SuggestionBoxService
{
	@Resource
	private SuggestionBoxDao dao;

	public List<SuggestionBox> getAllSuggestionBox()
	{
		List<SuggestionBox> allList = dao.findAll();

		return allList;
	}

	public int getAllSuggestionBoxCount()
	{

		return dao.findAll().size();
	}

	public boolean updateSuggestionBox(SuggestionBox o)
	{
		return dao.update(o) != null;
	}

	public void deleteSuggestionBox(SuggestionBox o)
	{
		dao.delete(o);
	}

	public List<SuggestionBox> findByExample(SuggestionBox o){
		return dao.findByExample(o);
	}

	public List<SuggestionBox> getSuggestionBoxByMap(Map<String, String> propertyMap, Map<String, ?> searchMap, int firstResult, int maxResults){
		return dao.getEntitiesByMap(propertyMap, null, searchMap, firstResult, maxResults);
	}

	public int getSuggestionBoxByMapCount(Map<String, String> propertyMap,
			Map<String, ?> searchMap){
			return dao.getEntitiesCountByMap(propertyMap, searchMap);
	}
}


text:
package com.floreysoft.jmte;

import com.floreysoft.jmte.token.AnnotationToken;

/**
 * Processor for an annotation, like ${@type String simple}.
 *
 * @param <T>
 *            what the processor produces
 */
public interface AnnotationProcessor<T> {

	String getType();
	/**
	 * Processes the annotation and possible returns a value.
	 *
	 * @param token
	 *            the annotation token triggering this processor
	 *
	 * @param context
	 *            current context during template evaluation
	 * @return the produced value
	 */
	T eval(AnnotationToken token, TemplateContext context);

}


text:
<?php if ( !isset( $_SESSION ) ) session_start(); header( "(anti-spam-content-type:) image/png" );

$enc_num = rand( 0, 9999 );
$key_num = rand( 0, 24 );
$hash_string = substr( md5( $enc_num ), $key_num, 5 ); // Length of String
$hash_md5 = md5( $hash_string );

$_SESSION['jigowatt']['ajax-extended-form']['verify'] = $hash_md5;

// Verification Image Background Selection
$dir = dirname( dirname( __FILE__ ) ) . '/assets/';
$bgs = array(
	$dir . 'img/verify/1.png',
	$dir . 'img/verify/2.png',
	$dir . 'img/verify/3.png'
);
$background = array_rand( $bgs, 1 );

// Verification Image Variables
$img_handle = imagecreatefrompng( $bgs[$background] );
$text_colour = imagecolorallocate( $img_handle, 108, 127, 6 );
$font_size = 5;

$size_array = getimagesize( $bgs[$background] );
$img_w = $size_array[0];
$img_h = $size_array[1];

$horiz = round( ( $img_w/2 )-( ( strlen( $hash_string )*imagefontwidth( 5 ) )/2 ), 1 );
$vert = round( ( $img_h/2 )-( imagefontheight( $font_size )/2 ) );

// Make the Verification Image
imagestring( $img_handle, $font_size, $horiz, $vert, $hash_string, $text_colour );
imagepng( $img_handle );

// Destroy the Image to keep Server Space
imagedestroy( $img_handle );


text: export * from './TableFooter';


text:
package verdad.retrosync;

import android.util.Log;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by bqmackay on 8/17/15.
 */
public class RetroSyncCallback implements Callback<SyncModel> {

    SyncModel model;
    private PendingObject pendingObject;
    Callback<SyncModel> serverCallback;

    public RetroSyncCallback(SyncModel model, PendingObject pendingObject, Callback<SyncModel> serverCallback) {
        this.model = model;
        this.pendingObject = pendingObject;
        this.serverCallback = serverCallback;
    }

    public RetroSyncCallback(SyncModel model, PendingObject pendingObject) {
        this.model = model;
        this.pendingObject = pendingObject;
    }

    @Override
    public void success(SyncModel syncModel, Response response) {
        Log.i("RetroSync", "Deleting pending object");
        pendingObject.delete();
        if (serverCallback != null) serverCallback.success(syncModel, response);
    }

    @Override
    public void failure(RetrofitError error) {
        pendingObject.save();
        Log.i("RetroSync", "Failed calls");
        if (serverCallback != null) serverCallback.failure(error);
    }
}


text:
package analyzer

import (
	"net/http"
	base "webcrawler/base"
)

// 被用于解析HTTP响应的函数类型。
type ParseResponse func(httpResp *http.Response, respDepth uint32) ([]base.Data, []error)


text:
using Microsoft.AspNetCore.Mvc;

namespace Sir.HttpServer.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Json(new { status = "Sir.HttpServer is alive." });
        }
    }
}


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

namespace PitFortressTests.Correctness
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class CorrectnessSetMine : BaseTestClass
    {
        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithNonExistingPlayer_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.SetMine("Mr.MMS", 0, 1, 50);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithNegativeCoordinate_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", -20, 1, 50);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithInvalidCoordinate_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", 2000000, 1, 50);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithNegativeDelay_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", 0, -1, 50);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithIncorrectDelay_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", 0, 20000, 50);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithNegativeDamage_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", 0, 5, -5);
        }

        [TestCategory("Correctness")]
        [ExpectedException(typeof(ArgumentException))]
        [TestMethod]
        public void CorrectnessSetMine_WithInvalidDamage_ShouldThrowCorrectException()
        {
            this.PitFortressCollection.AddPlayer("Mr.MMs", 10);
            this.PitFortressCollection.SetMine("Mr.MMS", 0, 5, 101);
        }

        [TestCategory("Correctness")]
        [TestMethod]
        public void CorrectnessSetMine_WithValidMine_ShouldIncreaseMinesCount()
        {
            this.PitFortressCollection.AddPlayer("Jichkata", 10);
            this.PitFortressCollection.SetMine("Jichkata", 13, 5, 89);

            Assert.AreEqual(this.PitFortressCollection.MinesCount,1,"Mines Count did not match!");

        }

        [TestCategory("Correctness")]
        [TestMethod]
        public void CorrectnessSetMine_WithExistingMines_ShouldIncreaseMinesCountCorrectly()
        {
            this.PitFortressCollection.AddPlayer("Jichkata", 5);
            this.PitFortressCollection.AddPlayer("Pesho", 10);

            this.PitFortressCollection.SetMine("Pesho", 13, 1, 20);
            this.PitFortressCollection.SetMine("Jichkata", 1, 1, 15);
            this.PitFortressCollection.SetMine("Pesho", 20, 2, 25);
            this.PitFortressCollection.SetMine("Pesho", 25, 3, 40);

            Assert.AreEqual(this.PitFortressCollection.MinesCount, 4, "Mines Count did not match!");

            this.PitFortressCollection.SetMine("Jichkata", 117, 13, 99);

            Assert.AreEqual(this.PitFortressCollection.MinesCount, 5, "Mines Count did not match!");

        }

        [TestCategory("Correctness")]
        [TestMethod]
        public void CorrectnessSetMine_WithValidMine_ShouldAddCorrectMine()
        {
            this.PitFortressCollection.AddPlayer("Jichkata", 10);
            this.PitFortressCollection.SetMine("Jichkata", 13, 5, 89);

            var mines = this.PitFortressCollection.GetMines().ToList();

            Assert.AreEqual(mines[0].Id, 1, "Mine Id did not match!");
            Assert.AreEqual(mines[0].XCoordinate, 13, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[0].Delay, 5, "Mine Delay did not match!");
            Assert.AreEqual(mines[0].Damage, 89, "Mine Damage did not match!");
            Assert.AreEqual(mines[0].Player.Name, "Jichkata", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[0].Player.Radius, 10, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[0].Player.Score, 0, "Mine's Player's Score did not match!");
        }

        [TestCategory("Correctness")]
        [TestMethod]
        public void CorrectnessSetMine_MultipleMinesWithMultiplePlayers_ShouldAddCorrectMines()
        {
            this.PitFortressCollection.AddPlayer("Pencho", 1);
            this.PitFortressCollection.AddPlayer("Oncho", 2);
            this.PitFortressCollection.AddPlayer("Gencho", 3);

            this.PitFortressCollection.SetMine("Gencho", 999996, 96, 96);
            this.PitFortressCollection.SetMine("Pencho", 999997, 97, 97);
            this.PitFortressCollection.SetMine("Gencho", 999998, 98, 98);
            this.PitFortressCollection.SetMine("Pencho", 999999, 99, 99);
            this.PitFortressCollection.SetMine("Oncho", 1000000, 100, 100);

            var mines = this.PitFortressCollection.GetMines().ToList();

            Assert.AreEqual(mines[0].Id, 1, "Mine Id did not match!");
            Assert.AreEqual(mines[0].XCoordinate, 999996, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[0].Delay, 96, "Mine Delay did not match!");
            Assert.AreEqual(mines[0].Damage, 96, "Mine Damage did not match!");
            Assert.AreEqual(mines[0].Player.Name, "Gencho", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[0].Player.Radius, 3, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[0].Player.Score, 0, "Mine's Player's Score did not match!");

            Assert.AreEqual(mines[1].Id, 2, "Mine Id did not match!");
            Assert.AreEqual(mines[1].XCoordinate, 999997, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[1].Delay, 97, "Mine Delay did not match!");
            Assert.AreEqual(mines[1].Damage, 97, "Mine Damage did not match!");
            Assert.AreEqual(mines[1].Player.Name, "Pencho", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[1].Player.Radius, 1, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[1].Player.Score, 0, "Mine's Player's Score did not match!");

            Assert.AreEqual(mines[2].Id, 3, "Mine Id did not match!");
            Assert.AreEqual(mines[2].XCoordinate, 999998, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[2].Delay, 98, "Mine Delay did not match!");
            Assert.AreEqual(mines[2].Damage, 98, "Mine Damage did not match!");
            Assert.AreEqual(mines[2].Player.Name, "Gencho", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[2].Player.Radius, 3, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[2].Player.Score, 0, "Mine's Player's Score did not match!");

            Assert.AreEqual(mines[3].Id, 4, "Mine Id did not match!");
            Assert.AreEqual(mines[3].XCoordinate, 999999, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[3].Delay, 99, "Mine Delay did not match!");
            Assert.AreEqual(mines[3].Damage, 99, "Mine Damage did not match!");
            Assert.AreEqual(mines[3].Player.Name, "Pencho", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[3].Player.Radius, 1, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[3].Player.Score, 0, "Mine's Player's Score did not match!");

            Assert.AreEqual(mines[4].Id, 5, "Mine Id did not match!");
            Assert.AreEqual(mines[4].XCoordinate, 1000000, "Mine Coordinate did not match!");
            Assert.AreEqual(mines[4].Delay, 100, "Mine Delay did not match!");
            Assert.AreEqual(mines[4].Damage, 100, "Mine Damage did not match!");
            Assert.AreEqual(mines[4].Player.Name, "Oncho", "Mine's Player's Name did not match!");
            Assert.AreEqual(mines[4].Player.Radius, 2, "Mine's Player's Radius did not match!");
            Assert.AreEqual(mines[4].Player.Score, 0, "Mine's Player's Score did not match!");
        }
    }
}


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

namespace AdysTech.InfluxDB.Client.Net
{
    public class ServiceUnavailableException:InvalidOperationException
    {
        public ServiceUnavailableException():base("InfluxDB service is not available")
        {

        }
    }
}


text:
require 'spec_helper'

describe Employee do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package challenge37

import (
	"crypto/rand"
	"crypto/sha256"
	"fmt"
	"math/big"
)

func Login() bool {
	server, client := Start([]byte("test@test.com"), []byte("tomato"))

	// client generates private key
	aBytes := make([]byte, 128)
	_, err := rand.Read(aBytes)
	if err != nil {
		panic(err)
	}
	a := new(big.Int)
	a.SetBytes(aBytes)

	// server generates private key
	bBytes := make([]byte, 128)
	_, err = rand.Read(bBytes)
	if err != nil {
		panic(err)
	}
	b := new(big.Int)
	b.SetBytes(bBytes)

	var clientPayload [][]byte
	// client sends up email and public key
	clientPayload = GetClientEmailPayload(&client, a, []byte("test@test.com"))

	// server sends salt and public key
	serverPayload := GetServerSaltPayload(&server, b)

	// server receives what client sent and generates a session key
	// recEmail := clientPayload[0]
	recA := new(big.Int)
	recA.SetBytes(clientPayload[1])
	server.GetSession(recA, b)

	// client receives what server sent and generates a session key
	recSalt := new(big.Int)
	recSalt.SetBytes(serverPayload[0])
	client.SetSalt(recSalt)

	recB := new(big.Int)
	recB.SetBytes(serverPayload[1])
	client.GetSession(recB, a, []byte("tomato"))

	// to confirm authentication, client sends HMAC(key, salt) to server
	// server also computes HMAC(key, salt) and if they match, return success
	clientAuthPayload := GetClientAuthPayload(&client)

	verified := ServerCheckAuth(&server, clientAuthPayload[0])

	return verified
}

func LoginZero() bool {
	server, client := Start([]byte("test@test.com"), []byte("tomato"))

	// client generates private key
	aBytes := make([]byte, 128)
	_, err := rand.Read(aBytes)
	if err != nil {
		panic(err)
	}
	a := new(big.Int)
	a.SetBytes(aBytes)

	// server generates private key
	bBytes := make([]byte, 128)
	_, err = rand.Read(bBytes)
	if err != nil {
		panic(err)
	}
	b := new(big.Int)
	b.SetBytes(bBytes)

	var clientPayload [][]byte
	// instead of sending the normal payload, send a 0 as A
	clientPayload = [][]byte{
		[]byte("test@test.com"),
		big.NewInt(0).Bytes(),
	}

	// server sends salt and public key
	serverPayload := GetServerSaltPayload(&server, b)

	// server receives what client sent and generates a session key
	// recEmail := clientPayload[0]
	recA := new(big.Int)
	recA.SetBytes(clientPayload[1])
	server.GetSession(recA, b)

	// now the server should have generated a session key of 0, so we don't
	// need to do the math
	recSalt := new(big.Int)
	recSalt.SetBytes(serverPayload[0])
	client.SetSalt(recSalt)
	client.S = big.NewInt(0)
	client.K = sha256.Sum256(client.S.Bytes())

	// to confirm authentication, client sends HMAC(key, salt) to server
	// server also computes HMAC(key, salt) and if they match, return success
	clientAuthPayload := GetClientAuthPayload(&client)

	verified := ServerCheckAuth(&server, clientAuthPayload[0])

	return verified
}

func LoginN() bool {
	server, client := Start([]byte("test@test.com"), []byte("tomato"))

	// client generates private key
	aBytes := make([]byte, 128)
	_, err := rand.Read(aBytes)
	if err != nil {
		panic(err)
	}
	a := new(big.Int)
	a.SetBytes(aBytes)

	// server generates private key
	bBytes := make([]byte, 128)
	_, err = rand.Read(bBytes)
	if err != nil {
		panic(err)
	}
	b := new(big.Int)
	b.SetBytes(bBytes)

	var clientPayload [][]byte
	// instead of sending the normal payload, send a N as A
	clientPayload = [][]byte{
		[]byte("test@test.com"),
		client.N.Bytes(),
	}

	// server sends salt and public key
	serverPayload := GetServerSaltPayload(&server, b)

	// server receives what client sent and generates a session key
	// recEmail := clientPayload[0]
	recA := new(big.Int)
	recA.SetBytes(clientPayload[1])
	server.GetSession(recA, b)

	fmt.Println(server.S)

	// now the server should have generated a session key of 0, so we don't
	// need to do the math
	recSalt := new(big.Int)
	recSalt.SetBytes(serverPayload[0])
	client.SetSalt(recSalt)
	client.S = big.NewInt(0)
	client.K = sha256.Sum256(client.S.Bytes())

	// to confirm authentication, client sends HMAC(key, salt) to server
	// server also computes HMAC(key, salt) and if they match, return success
	clientAuthPayload := GetClientAuthPayload(&client)

	verified := ServerCheckAuth(&server, clientAuthPayload[0])

	return verified
}


text:
@interface WMFWelcomeIntroductionViewController : UIViewController

@end


text:
from app import app, cache
from flask import request, render_template, Response, make_response

import random

@app.route('/')
def index():
    return render_template('main.html', title="Utils")

@app.route('/raw/ip')
def ip():
    addr = request.remote_addr
    if addr.startswith('::ffff:'):
        addr = addr.split(':')[-1]
    return Response(addr, mimetype="text/plain")

@app.route('/raw/user-agent')
def user_agent():
    return Response(request.user_agent.string, mimetype="text/plain")

@app.route('/raw/request-body', methods=['GET', 'POST'])
def request_body():
    return Response(request.environ['body_copy'], mimetype="text/plain")

@app.route('/raw/request-headers', methods=['GET', 'POST'])
def request_headers():
    return Response(str(request.headers), mimetype="text/plain")

@app.route('/raw/fortune')
def fortune():
    options = {
        'all': ('fortune_count', 'fortune_%d'),
        'off': ('offensive_fortune_count', 'offensive_fortune_%d'),
        'tame': ('tame_fortune_count', 'tame_fortune_%d')
    }

    intersection = set(request.values.keys()) & set(options.keys())
    if intersection:
        selection = intersection.pop()
    else:
        selection = 'tame'

    count, key = options[selection]

    fortune_number = random.randrange(0, cache.get(count))
    fortune = cache.get(key % fortune_number)

    return Response(fortune.strip(), mimetype="text/plain")

@app.route('/amionline')
@app.route('/amionline/<string:foo>', methods=['GET', 'POST'])
def amionline(foo=None):
    if foo is None:
        res = "Usage: GET /amionline/RANDOM_STRING"
    else:
        res = foo

    return Response(res, mimetype="text/plain")

@app.route('/random-name')
def random_name():
    return render_template('random-name.html')

@app.route('/timer')
def timer():
    return render_template('timer.html')

@app.route('/robots.txt')
def robots_txt():
    resp = make_response(render_template('robots.txt'))
    resp.mimetype = "text/plain"
    return resp


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf8">
<TITLE>
app
</TITLE>

<META NAME="date" CONTENT="2014-01-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

app

Classes

TestAssassin

TestBarbare

TestConsole

TestEquipement

TestEquipements

TestIHM

TestKnight

TestMineur

TestNinja

TestPersonnage

TestServeur

TestTroll


text:
var oServiceCall = function()
{
    this.name = 'ServiceCall';
    this.viewCallCreate = false;
}

oServiceCall.prototype.destroy = function()
{
    $('#main').empty();
    return true;
}

oServiceCall.prototype.load = function()
{
    $('#main').empty();

    $('#main').append( API.render('ServiceCall/ServiceCall', {}));

    var ServiceCallView = $('div.ServiceCall');

    ServiceCallView.find('div.buttons-options button')
        .filter('button.new-call').button().click(function(evt){
            Module.newCall();
        }).end()
        .filter('button.schedule-downtime').button().click(function(evt){

        }).end();

    ServiceCallView.find('#outfitter').chosen();
    /*
    * Data Temporario
    */
    var data = [{id: 1, isAvaliable: true, gitec: 'Gitec', sr: 'Sr', loterico: 'Mr. Coutinho', number: 'HDO321654987', startDate: '23/10/2012', scheduleDate: '23/10/2012', category: 'Hardware', type: 'ADSL', ocurrence: 'Erro ao utilizar'} ,{id: 1, isAvaliable: true, gitec: 'Gitec', sr: 'Sr', loterico: 'Mr. Coutinho', number: 'HDO321654987', startDate: '23/10/2012', scheduleDate: '23/10/2012', category: 'Hardware', type: 'ADSL', ocurrence: 'Erro ao utilizar'}];

    ServiceCallView.find('#table-call').jqGrid({
        data: data,
        datatype: "local",
        height: 180,
        rowNum: 10,
        colNames:['id', 'isAvaliable',  'Código Gitec', 'Código SR', 'Código Lotérico', 'Número Chamado', 'Data de Abertura', 'Data de Agendamento', 'Categoria', 'Tipo', 'Ocorrência', 'Ações'],
        colModel:[
            {name:'id',index:'id',hidden:true},
            {name:'isAvaliable',index:'isAvaliable', hidden:true},

            {name:'gitec',index:'gitec', resizable: false, align: 'center', width:80 /*,hidden:(Profile.name == Profile.names.lottery || Profile.name == Profile.names.gitec || Profile.name == Profile.names.sr)*/},
            {name:'sr',index:'sr', resizable: false, align: 'center', width:80/*, hidden:(Profile.name == Profile.names.lottery || Profile.name == Profile.names.gitec || Profile.name == Profile.names.sr)*/},
            {name:'loterico',index:'loterico', resizable: false, align: 'center', width:100/*, hidden:(Profile.name == Profile.names.lottery)*/},

            {name:'number',index:'number', resizable: false, align: 'center', width:100},
            {name:'startDate',index:'startDate', resizable: false, align: 'center', width: 100},
            {name:'scheduleDate',index:'scheduleDate', resizable: false, align: 'center', width: 100},
            {name:'category',index:'category', resizable: false, align: 'center', width: 100},
            {name:'type',index:'type', resizable: false, align: 'center', width: 100},
            {name:'ocurrence',index:'ocurrence', resizable: false, align: 'center', width: 100},
            {name:'buttons', sortable:false, selectable:false, resizable: false, align: 'center', width:70}
        ],
        gridComplete: function(){
            var tb = $('#table-call');
            var data =  tb.jqGrid('getRowData');
            for(var i=0;i < data.length;i++){
                var button = "";
                button += data[i].isAvaliable != "false" ? "" : "";
                tb.jqGrid('setRowData',data[i].id,{buttons:button});
            }

            tb.find('span.icon-select').button({
                icons: {
                    primary: "ui-icon-search"
                },
                text: false
            }).click(function(evt){
                    serviceCallDetail($(this).attr('class').match(/[0-9]+/g)[0]);
                });

            tb.find('span.icon-clipboard').button({
                icons: {
                    primary: "ui-icon-clipboard"
                },
                text: false
            }).click(function(evt){
                    evaluateTreatment($(this).attr('class').match(/[0-9]+/g)[0]);
                });
        },
        pager: '#plist-call',
        autowidth: true
    });
}

oServiceCall.prototype.newCall = function(id){
    var call = id;

    var html = API.render('ServiceCall/NewCall', {});

        Module.viewCallCreate = $('#new-call-view').append('

').find('.new-call.active').html(html).dialog({
            resizable: false,
            modal:true,
            autoOpen: false,
            width:655,
            dialogClass: 'custom-dialog ServiceCall',
            position: 'center',
            close: function(event, ui) {

            }
    });

    this.viewCallCreate.dialog('open');

    this.viewCallCreate.qtip({
        content: {
            style: {
                classes: 'new-call-helpers-qtip'
            },
            text: API.render('ServiceCall/NewCallHelpers'),
            title: {
                text: 'Ajuda',
                button: true
            }
        },
        position: {
            my: 'left center', // Use the corner...
            at: 'right center' // ...and opposite corner
        },
        show: {
            event: false, // Don't specify a show event...
            ready: true // ... but show the tooltip when ready
        },
        hide: false, // Don't specify a hide event either!
        style: {
            classes: 'ui-tooltip-shadow ui-tooltip-bootstrap'
        }
    });

}

Module = new oServiceCall();


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef MOOST_ALGORITHM_KETAMA_PARTITIONER_HPP__
#define MOOST_ALGORITHM_KETAMA_PARTITIONER_HPP__

#include <boost/random/mersenne_twister.hpp>

#include "partitioner.hpp"

#include <vector>
#include <algorithm>
#include <limits>

namespace moost { namespace algorithm {

/// @brief ketama_partitioner implements consistent hashing, such that the addition or removal of buckets does not
/// significantly change the mapping of keys to buckets.  By using consistent hashing, only K/n keys need to be
/// remapped on average, where K is the number of keys, and n is the number of buckets.
template<typename T>
class ketama_partitioner: public partitioner<T>
{
private:

  /* erikf raised a concern about boost::mt19937 potentially changing and thus
   * included a copy of mersenne_twister.hpp in moost. Not only is this ugly,
   * it has also been the source of link-level errors with recent versions of
   * boost due to refactoring of the implementation.
   *
   * The algorithm itself is well-defined and extremely unlikely to ever be
   * changed. The only thing that's slightly more probable to change (even
   * though I don't think it ever will) is the default seed, which is why we
   * keep a copy of the "original" seed here and explicitly seed the RNGs.
   */
  static uint32_t default_seed()
  {
     return 5489u;
  }

  struct bucket_hash
  {
    bucket_hash(size_t bucket_, size_t hash_) :
      bucket(bucket_), hash(hash_)
    {
    }
    size_t bucket;
    size_t hash;
    bool operator <(const bucket_hash & other) const
    {
      return hash < other.hash;
    }
  };

  std::vector<bucket_hash> m_bhashes;

  // stolen from http://isthe.com/chongo/tech/comp/fnv/
  unsigned int fnv_hash(const void *key, size_t len) const
  {
    const unsigned char *p = (const unsigned char*) key;
    unsigned int h = 2166136261UL;

    for (size_t i = 0; i != len; i++)
      h = (h * 16777619) ^ p[i];

    return h;
  }

public:

  ketama_partitioner(size_t num_buckets, size_t num_hashes = 4096)
  : partitioner<T> (num_buckets)
  {
    boost::mt19937 gen(default_seed());

    // for each bucket
    for (size_t i = 0; i != num_buckets; ++i)
    {
      // for each hash
      for (size_t j = 0; j != num_hashes; ++j)
      {
        // add it to the ring
        m_bhashes.push_back(bucket_hash(i, gen()));
      }
    }

    // now sort the whole darn thing
    std::sort(m_bhashes.begin(), m_bhashes.end());
  }

  template <typename Y>
  ketama_partitioner( const std::vector<Y>& buckets, size_t num_hashes = 4096)
  : partitioner<T>( buckets.size() )
  {
     boost::mt19937 gen(default_seed());
     typename std::vector<Y>::const_iterator it;
     // for each bucket
     size_t i = 0;
     for ( it = buckets.begin(); it != buckets.end(); ++it, ++i )
     {
        gen.seed( fnv_hash( &(*it), sizeof(Y)) );
        // for each hash
        for (size_t j = 0; j != num_hashes; ++j)
        {
           // add it to the ring
           m_bhashes.push_back(bucket_hash(i, gen()));
        }
     }

     // now sort the whole darn thing
     std::sort(m_bhashes.begin(), m_bhashes.end());
  }

  /// Specialization for bucket of strings
  ketama_partitioner( const std::vector<std::string>& buckets, size_t num_hashes = 4096)
     : partitioner<T>( buckets.size() )
  {
     boost::mt19937 gen(default_seed());
     std::vector<std::string>::const_iterator it;
     // for each bucket
     size_t i = 0;
     for ( it = buckets.begin(); it != buckets.end(); ++it, ++i )
     {
        gen.seed( fnv_hash(it->c_str(), it->length()) );
        // for each hash
        for (size_t j = 0; j != num_hashes; ++j)
        {
           // add it to the ring
           m_bhashes.push_back(bucket_hash(i, gen()));
        }
     }

     // now sort the whole darn thing
     std::sort(m_bhashes.begin(), m_bhashes.end());
  }

  size_t partition(const T & key) const
  {
    typename std::vector<bucket_hash>::const_iterator it = std::lower_bound(m_bhashes.begin(), m_bhashes.end(),
        bucket_hash(0, fnv_hash(&key, sizeof(T))));
    if (it == m_bhashes.end())
      it = m_bhashes.begin();
    return it->bucket;
  }
};

/// Specialization for string key
template <>
inline size_t ketama_partitioner<std::string>::partition(const std::string& key) const
{
   std::vector<bucket_hash>::const_iterator it = std::lower_bound(m_bhashes.begin(), m_bhashes.end(),
      bucket_hash(0, fnv_hash(key.c_str(), key.length())));
   if (it == m_bhashes.end())
      it = m_bhashes.begin();
   return it->bucket;
}

}} // moost::algorithm

#endif // MOOST_ALGORITHM_KETAMA_PARTITIONER_HPP__


text:
/*
 * @(#)JMDIDesktopPane.java
 *
 * Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
 * contributors. All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with the copyright holders. For details
 * see accompanying license terms.
 */

package org.scijava.ui.swing.mdi;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.beans.PropertyVetoException;

import javax.swing.DefaultDesktopManager;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;

import org.scijava.ui.Arrangeable;
import org.scijava.ui.Desktop;

/**
 * An extension of JDesktopPane that supports often used MDI functionality. This
 * class also handles setting scroll bars for when windows move too far to the left or
 * bottom, providing the JMDIDesktopPane is in a ScrollPane.
 * Note by dnoyeb: I dont know why the container does not fire frame close events when the frames
 * are removed from the container with remove as opposed to simply closed with the
 * "x".  so if you say removeAll from container you wont be notified.  No biggie.
 *
 * @author Werner Randelshofer
 * Original version by
 * Wolfram Kaiser (adapted from an article in JavaWorld),
 * C.L.Gilbert (dnoyeb@users.sourceforge.net)
 */
public class JMDIDesktopPane extends JDesktopPane implements  Desktop {
    private MDIDesktopManager manager;

    public JMDIDesktopPane() {
        manager = new MDIDesktopManager(this);
        setDesktopManager(manager);
        setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        setAlignmentX(Component.LEFT_ALIGNMENT);
    }

    @Override
    public void setArrangement(Arrangeable.Arrangement newValue) {
        Arrangeable.Arrangement oldValue = getArrangement();
        switch (newValue) {
            case CASCADE :
                arrangeFramesCascading();
                break;
            case HORIZONTAL :
                arrangeFramesHorizontally();
                break;
            case VERTICAL :
                arrangeFramesVertically();
                break;
        }
        firePropertyChange("arrangement", oldValue, newValue);
    }

    @Override
    public Arrangeable.Arrangement getArrangement() {
        // FIXME Check for the arrangement of the JInternalFrames here
        // and return the true value
        return Arrangeable.Arrangement.CASCADE;
    }
    /**
     * Cascade all internal frames
     */
    private void arrangeFramesCascading() {
        JInternalFrame[] allFrames = getAllFrames();

        // do nothing if no frames to work with
        if (allFrames.length == 0) {
            return;
        }

        manager.setNormalSize();
        Insets insets = getInsets();
        int x = insets.left;
        int y = insets.top;
        int frameOffset=0;
        for (int i = allFrames.length - 1; i >= 0; i--) {
            Point p=SwingUtilities.convertPoint(allFrames[i].getContentPane(),0,0,allFrames[i]);
            frameOffset=Math.max(frameOffset,Math.max(p.x,p.y));
        }
        int frameHeight = (getBounds().height-insets.top-insets.bottom) - allFrames.length * frameOffset;
        int frameWidth = (getBounds().width-insets.left-insets.right) - allFrames.length * frameOffset;
        for (int i = allFrames.length - 1; i >= 0; i--) {
            try {
                allFrames[i].setMaximum(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            allFrames[i].setBounds(x, y, frameWidth, frameHeight);
            x = x + frameOffset;
            y = y + frameOffset;
        }

        checkDesktopSize();
    }

    public void tileFramesHorizontally() {
        Component[] allFrames = getAllFrames();

        // do nothing if no frames to work with
        if (allFrames.length == 0) {
            return;
        }

        manager.setNormalSize();

        int frameHeight = getBounds().height/allFrames.length;
        int y = 0;
        for (int i = 0; i < allFrames.length; i++) {
            try {
                ((JInternalFrame)allFrames[i]).setMaximum(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            allFrames[i].setBounds(0, y, getBounds().width,frameHeight);
            y = y + frameHeight;
        }

        checkDesktopSize();
    }

    public void tileFramesVertically() {
        Component[] allFrames = getAllFrames();

        // do nothing if no frames to work with
        if (allFrames.length == 0) {
            return;
        }
        manager.setNormalSize();

        int frameWidth = getBounds().width/allFrames.length;
        int x = 0;
        for (int i = 0; i < allFrames.length; i++) {
            try {
                ((JInternalFrame)allFrames[i]).setMaximum(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            allFrames[i].setBounds(x, 0, frameWidth, getBounds().height);
            x = x + frameWidth;
        }

        checkDesktopSize();
    }

    /**
     * Arranges the frames as efficiently as possibly with preference for
     * keeping vertical size maximal.

     *
     */
    public void arrangeFramesVertically() {
        Component[] allFrames = getAllFrames();
        // do nothing if no frames to work with
        if (allFrames.length == 0) {
            return;
        }

        manager.setNormalSize();

        int vertFrames = (int)Math.floor(Math.sqrt(allFrames.length));
        int horFrames = (int)Math.ceil(Math.sqrt(allFrames.length));

        // first arrange the windows that have equal size
        int frameWidth = getBounds().width / horFrames;
        int frameHeight = getBounds().height / vertFrames;
        int x = 0;
        int y = 0;
        int frameIdx = 0;
        for (int horCnt = 0; horCnt < horFrames-1; horCnt++) {
            y = 0;
            for (int vertCnt = 0; vertCnt < vertFrames; vertCnt++) {
                try {
                    ((JInternalFrame)allFrames[frameIdx]).setMaximum(false);
                } catch (PropertyVetoException e) {
                    e.printStackTrace();
                }

                allFrames[frameIdx].setBounds(x, y, frameWidth, frameHeight);
                frameIdx++;
                y = y + frameHeight;
            }
            x = x + frameWidth;
        }

        // the rest of the frames are tiled down on the last column with equal
        // height
        frameHeight = getBounds().height / (allFrames.length - frameIdx);
        y = 0;
        for (; frameIdx < allFrames.length; frameIdx++) {
            try {
                ((JInternalFrame)allFrames[frameIdx]).setMaximum(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            allFrames[frameIdx].setBounds(x, y, frameWidth, frameHeight);
            y = y + frameHeight;
        }

        checkDesktopSize();
    }

    /**
     * Arranges the frames as efficiently as possibly with preference for
     * keeping horizontal size maximal.

     *
     */
    public void arrangeFramesHorizontally() {
        Component[] allFrames = getAllFrames();
        // do nothing if no frames to work with
        if (allFrames.length == 0) {
            return;
        }

        manager.setNormalSize();

        int vertFrames = (int)Math.ceil(Math.sqrt(allFrames.length));
        int horFrames = (int)Math.floor(Math.sqrt(allFrames.length));

        // first arrange the windows that have equal size
        int frameWidth = getBounds().width / horFrames;
        int frameHeight = getBounds().height / vertFrames;
        int x = 0;
        int y = 0;
        int frameIdx = 0;
        for (int vertCnt = 0; vertCnt < vertFrames-1; vertCnt++) {
            x = 0;
            for (int horCnt = 0; horCnt < horFrames; horCnt++) {
                try {
                    ((JInternalFrame)allFrames[frameIdx]).setMaximum(false);
                } catch (PropertyVetoException e) {
                    e.printStackTrace();
                }

                allFrames[frameIdx].setBounds(x, y, frameWidth, frameHeight);
                frameIdx++;
                x = x + frameWidth;
            }
            y = y + frameHeight;
        }

        // the rest of the frames are tiled down on the last column with equal
        // height
        frameWidth = getBounds().width / (allFrames.length - frameIdx);
        x = 0;
        for (; frameIdx < allFrames.length; frameIdx++) {
            try {
                ((JInternalFrame)allFrames[frameIdx]).setMaximum(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            allFrames[frameIdx].setBounds(x, y, frameWidth, frameHeight);
            x = x + frameWidth;
        }

        checkDesktopSize();
    }

    /**
     * Sets all component size properties ( maximum, minimum, preferred)
     * to the given dimension.
     */
    public void setAllSize(Dimension d) {
        setMinimumSize(d);
        setMaximumSize(d);
        setPreferredSize(d);
        setBounds(0, 0, d.width, d.height);
    }

    /**
     * Sets all component size properties ( maximum, minimum, preferred)
     * to the given width and height.
     */
    public void setAllSize(int width, int height) {
        setAllSize(new Dimension(width,height));
    }

    private void checkDesktopSize() {
        if ((getParent() != null) && isVisible()) {
            manager.resizeDesktop();
        }
    }

}
/**
 * Private class used to replace the standard DesktopManager for JDesktopPane.
 * Used to provide scrollbar functionality.
 */
class MDIDesktopManager extends DefaultDesktopManager {
    private JMDIDesktopPane desktop;

    public MDIDesktopManager(JMDIDesktopPane newDesktop) {
        this.desktop = newDesktop;
    }

    @Override
    public void endResizingFrame(JComponent f) {
        super.endResizingFrame(f);
        resizeDesktop();
    }

    @Override
    public void endDraggingFrame(JComponent f) {
        super.endDraggingFrame(f);
        resizeDesktop();
    }

    public void setNormalSize() {
        JScrollPane scrollPane = getScrollPane();
        Insets scrollInsets = getScrollPaneInsets();

        if (scrollPane != null) {
            Dimension d = scrollPane.getVisibleRect().getSize();
            if (scrollPane.getBorder() != null) {
                d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right,
                        d.getHeight() - scrollInsets.top - scrollInsets.bottom);
            }

            d.setSize(d.getWidth() - 20, d.getHeight() - 20);
            desktop.setAllSize(d);
            scrollPane.invalidate();
            scrollPane.validate();
        }
    }

    private Insets getScrollPaneInsets() {
        JScrollPane scrollPane = getScrollPane();
        if ((scrollPane == null) || (getScrollPane().getBorder() == null)) {
            return new Insets(0, 0, 0, 0);
        }
        return getScrollPane().getBorder().getBorderInsets(scrollPane);
    }

    public JScrollPane getScrollPane() {
        if (desktop.getParent() instanceof JViewport) {
            JViewport viewPort = (JViewport)desktop.getParent();
            if (viewPort.getParent() instanceof JScrollPane)
                return (JScrollPane)viewPort.getParent();
        }
        return null;
    }

    protected void resizeDesktop() {
        int x = 0;
        int y = 0;
        JScrollPane scrollPane = getScrollPane();
        Insets scrollInsets = getScrollPaneInsets();

        if (scrollPane != null) {
            JInternalFrame allFrames[] = desktop.getAllFrames();
            for (int i = 0; i < allFrames.length; i++) {
                if (allFrames[i].getX() + allFrames[i].getWidth() > x) {
                    x = allFrames[i].getX() + allFrames[i].getWidth();
                }
                if (allFrames[i].getY() + allFrames[i].getHeight() > y) {
                    y = allFrames[i].getY() + allFrames[i].getHeight();
                }
            }
            Dimension d=scrollPane.getVisibleRect().getSize();
            if (scrollPane.getBorder() != null) {
                d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right,
                        d.getHeight() - scrollInsets.top - scrollInsets.bottom);
            }

            if (x <= d.getWidth()) {
                x = ((int)d.getWidth()) - 20;
            }
            if (y <= d.getHeight()) {
                y = ((int)d.getHeight()) - 20;
            }
            desktop.setAllSize(x,y);
            scrollPane.invalidate();
            scrollPane.validate();
        }
    }
}


text:
__author__       = "Vivek <vivek.balasubramanian@rutgers.edu>"
__copyright__    = "Copyright 2014, http://radical.rutgers.edu"
__license__      = "MIT"
__example_name__ = "Multiple Simulations Instances, Single Analysis Instance Example (MSSA)"

import sys
import os
import json

from radical.ensemblemd import Kernel
from radical.ensemblemd import SimulationAnalysisLoop
from radical.ensemblemd import EnsemblemdError
from radical.ensemblemd import SingleClusterEnvironment

# ------------------------------------------------------------------------------
# Set default verbosity

if os.environ.get('RADICAL_ENMD_VERBOSE') == None:
    os.environ['RADICAL_ENMD_VERBOSE'] = 'REPORT'

# ------------------------------------------------------------------------------
#
class MSSA(SimulationAnalysisLoop):
    """MSMA exemplifies how the MSMA (Multiple-Simulations / Multiple-Analsysis)
       scheme can be implemented with the SimulationAnalysisLoop pattern.
    """
    def __init__(self, iterations, simulation_instances, analysis_instances):
        SimulationAnalysisLoop.__init__(self, iterations, simulation_instances, analysis_instances)

    def simulation_step(self, iteration, instance):
        """In the simulation step we
        """
        k = Kernel(name="misc.mkfile")
        k.arguments = ["--size=1000", "--filename=asciifile.dat"]
        return [k]

    def analysis_step(self, iteration, instance):
        """In the analysis step we use the ``$PREV_SIMULATION`` data reference
           to refer to the previous simulation. The same
           instance is picked implicitly, i.e., if this is instance 5, the
           previous simulation with instance 5 is referenced.
        """
        link_input_data = []
        for i in range(1, self.simlation_instances+1):
            link_input_data.append("$PREV_SIMULATION_INSTANCE_{instance}/asciifile.dat > asciifile-{instance}.dat".format(instance=i))

        k = Kernel(name="misc.ccount")
        k.arguments            = ["--inputfile=asciifile-*.dat", "--outputfile=cfreqs.dat"]
        k.link_input_data      = link_input_data
        k.download_output_data = "cfreqs.dat > cfreqs-{iteration}.dat".format(iteration=iteration)
        return [k]

# ------------------------------------------------------------------------------
#
if __name__ == "__main__":

    try:

        # Create a new static execution context with one resource and a fixed
        # number of cores and runtime.
        cluster = SingleClusterEnvironment(
                        resource=resource,
                        cores=1,
                        walltime=15,
                        #username=None,

                        #project=None,
                        #queue = None,

                        #database_url=None,
                        #database_name=None,
        )

        # Allocate the resources.
        cluster.allocate()

        # We set both the the simulation and the analysis step 'instances' to 16.
        # If they
        mssa = MSSA(iterations=4, simulation_instances=16, analysis_instances=1)

        cluster.run(mssa)

        cluster.deallocate()

    except EnsemblemdError, er:

        print "Ensemble MD Toolkit Error: {0}".format(str(er))
        raise # Just raise the execption again to get the backtrace


text:
{% load laundryapptags scheduletags %}
{% load tz %}

    {% for slot in slots %}

      {{ slot.start|time:"G:i" }}
      {% if addable %}
      {% laundryapp_create_event_url calendar slot.start %}
      {% endif %}

    {% if slot.occurrences %}

      {% for occ in slot.occurrences %}
            <button type="button"  class="btn {% if occ.cancelled %} btn-danger {%else%} btn-primary {% endif %}" data-toggle="modal" data-target="#{% hash_occurrence occ %}">
                  {% options occ %}
                  {% title occ %}
            </button>
      {% include 'schedule/_detail.html' with occurrence=occ %}
      {% endfor %}

    {% else %}

    {% endif %}

    {% endfor %}


text:
extern alias from_nuget;
extern alias from_project;
using BenchmarkDotNet.Attributes;

namespace Stashbox.Benchmarks
{
    [MemoryDiagnoser]
    public class NullableBenchmarks
    {
        private readonly from_nuget::Stashbox.IStashboxContainer oldContainer =
            new from_nuget::Stashbox.StashboxContainer();

        private readonly from_project::Stashbox.IStashboxContainer newContainer =
            new from_project::Stashbox.StashboxContainer();

        [Benchmark(Baseline = true)]
        public object Old()
        {
            return this.oldContainer.ResolveOrDefault(typeof(object));
        }

        [Benchmark]
        public object New()
        {
            return this.newContainer.ResolveOrDefault(typeof(object));
        }
    }
}


text:
//Image.h
//
//Class representing an image
//  original by Wagner Correa, 1999
//  turned to C++ by Robert Osada, 2000
//  updated by Stephen J. Guy, 2017

#ifndef IMAGE_INCLUDED
#define IMAGE_INCLUDED

#include <assert.h>
#include <stdio.h>
#include "pixel.h"

#include "stb_image.h"
#include "stb_image_write.h"

/**
 * constants
 **/
enum {
    IMAGE_SAMPLING_POINT,
    IMAGE_SAMPLING_BILINEAR,
    IMAGE_SAMPLING_GAUSSIAN,
    IMAGE_N_SAMPLING_METHODS
};

enum {
    IMAGE_CHANNEL_RED,
    IMAGE_CHANNEL_GREEN,
    IMAGE_CHANNEL_BLUE,
    IMAGE_CHANNEL_ALPHA,
    IMAGE_N_CHANNELS
};

/**
 * Image
 **/
class Image
{
public:
    union PixelData{
       Pixel *pixels;
       uint8_t *raw;
    };

    PixelData data;
    //PixelInfo *pixels; //pixel array
    //uint8_t *pixelData;
    int width, height, num_pixels;
    int sampling_method;
	//BMP* bmpImg;

public:
    // Creates a blank image with the given dimensions
    Image (int width, int height);

    // Copy iamage
    Image (const Image& src);

	// Make image from file
	Image(char *fname);

    // Destructor
    ~Image ();

    // Pixel access
    int ValidCoord (int x, int y)  const { return x>=0 && x<width && y>=0 && y<height; }
    Pixel& GetPixel (int x, int y) const { assert(ValidCoord(x,y));  return data.pixels[y*width + x]; }
    void SetPixel (int x, int y, Pixel p) const { assert(ValidCoord(x,y));  data.pixels[y*width + x] = p; }

    // Dimension access
    int Width     () const { return width; }
    int Height    () const { return height; }
    int NumPixels () const { return num_pixels; }

	// Make file from image
	void Write( char *fname );

    // Adds noise to an image.  The amount of noise is given by the factor
    // in the range [0.0..1.0].  0.0 adds no noise.  1.0 adds a lot of noise.
    void AddNoise (double factor);

    // Brightens the image by multiplying each pixel component by the factor.
    void Brighten (double factor);

    /**
     * Changes the contrast of an image by interpolating between the image
     * and a constant gray image with the average luminance.
     * Interpolation reduces constrast, extrapolation boosts constrast,
     * and negative factors generate inverted images.
     **/
    void ChangeContrast (double factor);

    /**
     * Changes the saturation of an image by interpolating between the
     * image and a gray level version of the image.  Interpolation
     * decreases saturation, extrapolation increases it, negative factors
     * presrve luminance but invert the hue of the input image.
     **/
    void ChangeSaturation (double factor);

    /**
     * Extracts a sub image from the image, at position (x, y), width w,
     * and height h.
     **/
    Image* Crop(int x, int y, int w, int h);

    /**
     * Extracts a channel of an image.  Leaves the specified channel
     * intact.  Sets all other ones to zero.
     **/
    void ExtractChannel(int channel);

    /**
     * Quantizes an image with "nbits" bits per channel.
     **/
    void Quantize (int nbits);

    // Converts and image to nbits per channel using random dither.
    void RandomDither(int nbits);

    // Blurs an image with an n x n Gaussian filter.
    void Blur(int n);

	// Sharpens an image by blurring with an n x n Gaussian filter and then extrapolating
    void Sharpen(int n);

    // Detects edges in an image.
    void EdgeDetect();

    /**
     * Converts an image to nbits per channel using ordered dither, with a
     * 4x4 Bayer's pattern matrix.
     **/
    void OrderedDither(int nbits);

    /**
     * Converts an image to nbits per channel using Floyd-Steinberg dither
     * with error diffusion.
     **/
    void FloydSteinbergDither(int nbits);

    // Scales an image in x by sx, and y by sy.
    Image* Scale(double sx, double sy);

    // Rotates an image by the given angle.
    Image* Rotate(double angle);

    // Warps an image using a creative filter of your choice.
    void Fun();

    // Sets the sampling method.
    void SetSamplingMethod(int method);

    // Sample image using current sampling method.
    Pixel Sample(double u, double v);

    // nonphotorealism effect added by Pei Xu
    void Watercolor();
};

#endif


text:
<?php

namespace Film\Bundle\DataFixtures\ORM;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Film\Bundle\Entity\Category;
use Film\Bundle\Entity\Actor;
use Film\Bundle\Entity\Film;
use Film\Bundle\Entity\Genre;

class LoadFilmsData implements FixtureInterface, ContainerAwareInterface
{
    protected $categoryManager;
    protected $actorManager;
    protected $genreManager;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->categoryManager = $container->get('category.repository');
        $this->actorManager = $container->get('actor.repository');
        $this->genreManager = $container->get('genre.repository');
    }

    public function load(ObjectManager $manager)
    {
        $this->loadCategories($manager);
        $this->loadActors($manager);
        $this->loadGenres($manager);
        $this->loadFilms($manager);
    }

    protected function loadCategories($manager)
    {
        $categories = array(
            'Документальный',
            'Мультфильм',
            'Сериал',
            'Художественный',
            'Мультсериал',
            'Телепрограмма',
            'Спорт',
            'Музыка',
        );

        foreach ($categories as $title) {
            $category = new Category();
            $category->setTitle($title);
            $manager->persist($category);
        }

        $manager->flush();
    }

    protected function loadGenres($manager)
    {
        $genres = array(
            'Боевик',
            'Вестерн',
            'Детектив',
            'Драма',
            'Комедия',
            'Мелодрама',
            'Триллер',
            'Ужасы',
            'Фантастика',
            'Фентези',
        );

        foreach ($genres as $title) {
            $genre = new Genre();
            $genre->setTitle($title);
            $manager->persist($genre);
        }

        $manager->flush();
    }

    protected function loadActors($manager)
    {
        $actor = new Actor();
        $actor->setName('Джейми Фокс');
        $actor->setBirthDate(new \DateTime('2008-11-13'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Том Круз');
        $actor->setBirthDate(new \DateTime('1962-06-02'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Квентин Тарантино');
        $actor->setBirthDate(new \DateTime('1963-05-12'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Мартин Фриман');
        $actor->setBirthDate(new \DateTime('1971-09-10'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Джейсон Стэйтем');
        $actor->setBirthDate(new \DateTime('1967-09-12'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Дэниэл Крэйг');
        $actor->setBirthDate(new \DateTime('1968-03-02'));
        $manager->persist($actor);

        $actor = new Actor();
        $actor->setName('Дженнифер Гарнер');
        $actor->setBirthDate(new \DateTime('1972-04-17'));
        $manager->persist($actor);

        $manager->flush();
    }

    protected function loadFilms($manager)
    {
        $film = new Film();
        $film->setTitle('Джек Ричер');
        $film->setReleaseWorldAt(new \DateTime('2013-04-20'));
        $film->setDescription('По роману «Выстрел» британского писателя Ли Чайлда. Снайпер убивает пять случайных прохожих, но все улики указывают на человека, заключенного под стражу. На допросе подозреваемый умоляет об одном - найти Джека Ричера.');
        $film->setCategory($this->categoryManager->findOneBy(array('id' => 1)));

        $actor = $this->actorManager->findOneBy(array('id' => 1));
        $film->getActors()->add($actor);

        $genre = $this->genreManager->findOneBy(array('id' => 1));
        $film->getGenres()->add($genre);

        $manager->persist($film);

        $manager->flush();
    }
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors:  Alan Knowles <alan@akbkhome.com>                           |
// +----------------------------------------------------------------------+
//
// $Id: SmartyConvertor.php 162576 2004-07-03 03:46:43Z alan_k $
//
//  Smarty Conversion compiler
//  takes a smarty template, and converts it to a flexy one.
//  then does a standard flexy compile.
//
//  anything that is not supported gets changed to HTML comments

/* Usage:
a simple script: 'convertsmarty.php'

#!/usr/bin/php
   $file = $_SERVER['argv'][1];
   $x = new HTML_Template_Flexy(array(
                    'compileDir'    =>  dirname(__FILE__) ,      // where do you want to write to..
                    'templateDir'   =>  $dir ,     // where are your templates
                    'locale'        => 'en',    // works with gettext
                    'forceCompile'  =>  true,  // only suggested for debugging
                    'debug'         => false,   // prints a few errors
                    'nonHTML'       => false,  // dont parse HTML tags (eg. email templates)
                    'allowPHP'      => false,   // allow PHP in template
                    'compiler'      => 'SmartyConvertor', // which compiler to use.
                    'compileToString' => true,    // returns the converted template (rather than actually
                                                   // converting to PHP.
                    'filters'       => array(),    // used by regex compiler..
                    'numberFormat'  => ",2,'.',','",  // default number format  = eg. 1,200.00 ( {xxx:n} )
                    'flexyIgnore'   => 0        // turn on/off the tag to element code
                ));

    echo $x->compile(basename($file));

then run it at the command line:
php convertsmarty.php /path/to/a/smarty/template.tpl > /path/to/the/flexy/templates.html
*/

require_once 'HTML/Template/Flexy/Compiler.php';

/**
* The Smarty Converter implementation.
* designed primarily to be used as above, to convert from one to another.
* however it could be used inline to convert simple smarty templates into
* flexy ones - then compile them on the fly.
*
* @version    $Id: SmartyConvertor.php 162576 2004-07-03 03:46:43Z alan_k $
*/
class HTML_Template_Flexy_Compiler_SmartyConvertor extends HTML_Template_Flexy_Compiler {

    /**
    * compile implementation
    *
    * see HTML_Template_Flexy_Compiler::compile()
    *
    * @param   object    The core flexy object.
    * @param   string    optionally a string to compile.
    *
    * @return   true | string   string when compiling to String.
    * @access   public
    */

    function compile(&$flexy,$string=false)
    {
        $data = $string;
        if ($string === false) {
            $data = file_get_contents($flexy->currentTemplate);
        }

        $data = $this->convertToFlexy($data);

        if ($flexy->options['compileToString']) {
            return $data;
        }

        require_once 'HTML/Template/Flexy/Compiler/Standard.php';
        $flexyCompiler = new HTML_Template_Flexy_Compiler_Standard;
        $flexyCompiler->compile($flexy,$data);
        return true;
    }

    /**
    * The core work of parsing a smarty template and converting it into flexy.
    *
    * @param   string       the contents of the smarty template
    *
    * @return   string         the flexy version of the template.
    * @access   public|private
    * @see      see also methods.....
    */
    function convertToFlexy($data)
    {

        $leftq = preg_quote('{', '!');
        $rightq = preg_quote('}', '!');

        preg_match_all("!" . $leftq . "\s*(.*?)\s*" . $rightq . "!s", $data, $matches);
        $tags = $matches[1];
        // find all the tags/text...
        $text = preg_split("!" . $leftq . ".*?" . $rightq . "!s", $data);

        $max_text = count($text);
        $max_tags = count($tags);

        for ($i = 0 ; $i < $max_tags ; $i++) {
            $compiled_tags[] = $this->_compileTag($tags[$i]);
        }
        // error handling for closing tags.

        $data = '';
        for ($i = 0; $i < $max_tags; $i++) {
            $data .= $text[$i].$compiled_tags[$i];
        }
        $data .= $text[$i];
        return $data;

    }

    /**
    * stack for conditional and closers.
    *
    * @var array
    * @access public
    */
    var $stack = array(
            'if' => 0,
        );

    /**
    * compile a smarty { tag } into a flexy one.
    *
    * @param   string           the tag
    *
    * @return   string      the converted version
    * @access   private
    */
    function _compileTag($str)
    {
        // skip comments
        if (($str{0} == '*') && (substr($str,-1,1) == '*')) {
            return '';
        }

        switch($str{0}) {
            case '$':
                // its a var
                return $this->_convertVar($str);
            case '#':
                // its a config var
                return $this->_convertConfigVar($str);
            case '%':
                // wtf does this do
                return "<!-- what is this? $str -->";
        }

        // this is where it gets messy
        // this is very slow - but what the hell
        //   - its only done once
        //   - its alot more readable than a long regext.
        //   - it doesnt infringe on copyright...
        switch(true) {
            case (preg_match('/^config_load\s/', $str)):
                // convert to $t->TemplateConfigLoad()
                $args = $this->convertAttributesToKeyVal(substr($str,strpos( $str,' ')));
                return '{plugin(#smartyConfigLoad#,#'.$args['file'].'#,#'.$args['section'].'#)}';

            case (preg_match('/^include\s/', $str)):
                // convert to $t->TemplateConfigLoad()
                $args = $this->convertAttributesToKeyVal(substr($str,strpos( $str,' ')));

                return '{plugin(#smartyInclude#,#'.$args['file'].'#)}';

            case ($str == 'ldelim'):
                return '{';
            case ($str == 'rdelim'):
                return '}';

            case (preg_match('/^if \$(\S+)$/', $str,$matches)):
            case (preg_match('/^if \$(\S+)\seq\s""$/', $str,$matches)):
                // simple if variable..
                // convert to : {if:sssssss}
                $this->stack['if']++;
                $var =  $this->_convertVar('$'.$matches[1]);
                return '{if:'.substr($var,1);

            case (preg_match('/^if #(\S+)#$/', $str,$matches)):
            case (preg_match('/^if #(\S+)#\sne\s""$/', $str,$matches)):
                // simple if variable..
                // convert to : {if:sssssss}
                $this->stack['if']++;
                $var =  $this->_convertConfigVar('#'.$matches[1].'#');
                return '{if:'.substr($var,1);

            // negative matches
            case (preg_match('/^if\s!\s\$(\S+)$/', $str,$matches)):
            case (preg_match('/^if \$(\S+)\seq\s""$/', $str,$matches)):
                // simple if variable..
                // convert to : {if:sssssss}
                $this->stack['if']++;
                $var =  $this->_convertVar('$'.$matches[1]);
                return '{if:!'.substr($var,1);

             case ($str == 'else'):
                if (!$this->stack['if']) {
                    break;
                }
                return '{else:}';

            case ($str == '/if'):
                if (!$this->stack['if']) {
                    break;
                }
                $this->stack['if']--;
                return '{end:}';

        }

        return "<!--   UNSUPPORTED TAG: $str FOUND -->";

    }

    /**
    * convert a smarty var into a flexy one.
    *
    * @param   string       the inside of the smart tag
    *
    * @return   string      a flexy version of it.
    * @access   private
    */

    function _convertVar($str)
    {
        // look for modfiers first.
        $mods = explode('|', $str);
        $var = array_shift($mods);
        $var = substr($var,1); // strip $

        // various formats :
        // aaaa.bbbb.cccc => aaaa[bbbb][cccc]
        // aaaa[bbbb] => aaa[bbbb]
        // aaaa->bbbb => aaaa.bbbb

        $bits = explode('.',$var);
        $var = array_shift($bits);
        foreach($bits as $k) {
            $var.= '['.$k .']';
        }
        $bits = explode('->',$var);
        $var = implode('.',$bits);
        $mods = implode('|',$mods);

        if (strlen($mods)) {
            return '{plugin(#smartyModifiers#,'.$var.',#'.$mods.'#):h}';
        }
        return '{'.$var .'}' . $mods;
    }
    /**
    * convert a smarty key="value" string into a key value array
    * cheap and cheerfull - doesnt handle spaces inside the strings...
    *
    * @param   string       the key value part of the tag..
    *
    * @return   array      key value array
    * @access   private
    */
    function convertAttributesToKeyVal($str)
    {
        $atts = explode(' ', $str);
        $ret = array();
        foreach($atts as $bit) {
            $bits = explode('=',$bit);
            // loose stuff!!!
            if (count($bits) != 2) {
                continue;
            }
            $ret[$bits[0]] = ($bits[1]{0} == '"') ? substr($bits[1],1,-1) : $bits[1];
        }
        return $ret;
    }
     /**
    * convert a smarty config var into a flexy one.
    *
    * @param   string       the inside of the smart tag
    *
    * @return   string      a flexy version of it.
    * @access   private
    */

    function _convertConfigVar($str)
    {
        $mods = explode('|', $str);
        $var = array_shift($mods);
        $var = substr($var,1,-1); // strip #'s
        $mods = implode('|',$mods);
        if (strlen($mods)) {
            $mods = "<!-- UNSUPPORTED MODIFIERS: $mods -->";
        }
        return '{configVars.'.$var .'}' . $mods;
    }
}


text:
package io.cattle.platform.lb.instance.dao;

import io.cattle.platform.core.model.LoadBalancerHostMap;

import java.util.List;

public interface LoadBalancerInstanceDao {

    List<? extends LoadBalancerHostMap> getLoadBalancerHostMaps(long lbId);

}


text:
import logging

from framework import basehandlers
from internals import notifier

class StarsAPI(basehandlers.APIHandler):
  """Users can star a feature by clicking a star icon.  The client-side has
  logic to toggle the star icon.  When a user has starred a feature, they
  will be sent notification emails about changes to that feature."""

  def do_get(self, **kwargs):
    """Return a list of all starred feature IDs for the signed-in user."""
    user = self.get_current_user()
    if user:
      feature_ids = notifier.FeatureStar.get_user_stars(user.email())
    else:
      feature_ids = []  # Anon users cannot star features.

    data = {
        'featureIds': feature_ids,
        }
    return data

  def do_post(self, **kwargs):
    """Set or clear a star on the specified feature."""
    feature = self.get_specified_feature()
    starred = self.get_bool_param('starred', default=True)
    user = self.get_current_user(required=True)

    notifier.FeatureStar.set_star(
        user.email(), feature.key.integer_id(), starred)
    # Callers don't use the JSON response for this API call.
    return {'message': 'Done'}


text:
package uva.tomo7;

/*Uva 750*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class EightQueensChessProblemDFS { /* 8 Queens Chess Problem */
	// NO FUNCIONA, la forma en la que explora el espacio no va con el codigo,
	// se queda con la una columna llenada y trata con todas las filas, pero eso
	// deberia ser diferente, primero el coge una columna y una fila, y de ahi
	// hace lo mismo en profundidad revisando no dañar los estados anteriores

	static BufferedReader input;

	static StringTokenizer _stk;

	static String readln() throws IOException {
		String l = input.readLine();
		if (l != null)
			_stk = new StringTokenizer(l, " ");
		return l;
	}

	static String next() {
		return _stk.nextToken();
	}

	static int nextInt() {
		return Integer.parseInt(next());
	}

	static void dbg(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}

	public static void main(String[] args) throws IOException {
		Locale.setDefault(Locale.US);
		// input=new BufferedReader(new InputStreamReader(System.in));
		input = new BufferedReader(new FileReader("EightQueensChessProblem"));
		readln();
		TC = nextInt();
		while (TC-- > 0) {
			readln();
			readln();
			a = nextInt();
			b = nextInt();
			for (int i = 0; i < 9; i++)
				row[i] = 0;
			lineCounter = 0;
			System.out.printf("SOLN       COLUMN\n");
			System.out.printf(" #      1 2 3 4 5 6 7 8\n\n");
			backtrack(1); // generate all possible 8! candidate solutions
			if (TC > 0)
				System.out.printf("\n");
		}
	}

	private static int[] row = new int[9];
	private static int TC, a, b, lineCounter; // it is ok to use global
												// variables in competitive
												// programming

	private static boolean place(int col, int tryrow) {
		for (int prev = 1; prev < col; prev++)
			// check previously placed queens
			if (row[prev] == tryrow
					|| (Math.abs(row[prev] - tryrow) == Math.abs(prev - col)))
				return false; // an infeasible solution if share same row or
								// same diagonal
		return true;
	}

	private static void backtrack(int col) {

		LinkedList<Integer> busq = new LinkedList<Integer>();
		busq.add(col);
		// dbg(AdjList);
		while (!busq.isEmpty()) {
			col = busq.removeFirst();
			// dbg(busq);
			for (int tryrow = 1; tryrow <= 4; tryrow++) {
				dbg("a", a, "b", b, "place", place(col, tryrow), "row", tryrow,
						"col", col, "row", row);
				// if (col == b && tryrow != a)
				// continue;
				// try all possible row
				if (place(col, tryrow)) { // if can place a queen at this col
											// and
											// row...
					row[col] = tryrow; // put this queen in this col and row
					if (col == 8) { // a candidate solution & (a, b)
									// has 1 queen
						System.out.printf("%2d      %d", ++lineCounter, row[1]);
						for (int j = 2; j <= 8; j++)
							System.out.printf(" %d", row[j]);
						System.out.printf("\n");

					} else {
						busq.addFirst(col + 1);
						dbg(busq);
					}
				}
			}
		}

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/material_indigo_500" />
</shape>