text:
<?php

namespace Hubzero\Filesystem;

use Hubzero\Base\Obj;
use Hubzero\Filesystem\Util\Icon;
use Hubzero\Error\Exception\BadMethodCallException;
use Hubzero\Error\Exception\RuntimeException;

/**
 * Filesystem entity
 */
class Entity extends Obj
{
	/**
	 * The filesystem adapter use for actually interacting with the entity
	 *
	 * @var  object
	 **/
	protected $adapter = null;

	/**
	 * Constructs the class
	 *
	 * @param   mixed  $properties  Either and associative array or another
	 *                              object to set the initial properties of the object.
	 */
	public function __construct($properties = null)
	{
		parent::__construct($properties);

		if (func_num_args() == 2)
		{
			$this->setAdapter(func_get_arg(1));
		}
	}

	/**
	 * Creates a new object using a path as our starting point
	 *
	 * Don't forget, paths are relative to the adapter root
	 *
	 * @param   string  $path     The path to use to build a new entity from
	 * @param   object  $adapter  The filesystem adapter to use for interaction with the entity
	 * @return  static
	 **/
	public static function fromPath($path, $adapter = null)
	{
		// If the entity exists, grab its metadata
		if (isset($adapter) && $adapter->has($path))
		{
			$metadata = $adapter->getMetadata($path);
		}
		else
		{
			// Otherwise, we'll make our best guess at the appropriate data
			$path = trim($path, '/');
			$bits = explode('/', $path);
			$end  = end($bits);

			// The minimum required data is a path and a type
			$metadata = [
				'type' => (strpos($end, '.') !== false) ? 'file' : 'dir',
				'path' => $path
			];
		}

		return self::getSpecialized($metadata, $adapter);
	}

	/**
	 * Creates a new object from metadata
	 *
	 * This is very similar to just creating a new object, except you could
	 * instantiate an entity and not even worry about whether its a dir
	 * or file at the time of creation.
	 *
	 * @param   array   $properties  The properties to use to build a new entity from
	 * @param   object  $adapter     The filesystem adapter to use for interaction with the entity
	 * @return  static
	 **/
	public static function fromMetadata($properties, $adapter = null)
	{
		return self::getSpecialized($properties, $adapter);
	}

	/**
	 * Gets the most specialized object for a given entity type
	 *
	 * @param   array   $properties  The properties to use to build a new entity from
	 * @param   object  $adapter     The filesystem adapter to use for interaction with the entity
	 * @return  static
	 **/
	protected static function getSpecialized($properties, $adapter)
	{
		// If it's a directory, stop there
		if ($properties['type'] == 'dir')
		{
			return new Directory($properties, $adapter);
		}

		if (!isset($properties['extension']))
		{
			$bits = explode('.', $properties['path']);
			if (count($bits) > 1)
			{
				$properties['extension'] = end($bits);
			}
			else
			{
				$properties['extension'] = '';
			}
		}

		// If it's a file, do we have a more specialized class?
		$file = __DIR__ . '/Type/' . ucfirst($properties['extension']) . '.php';
		if (file_exists($file))
		{
			$class = __NAMESPACE__ . '\\Type\\' . ucfirst($properties['extension']);
			return new $class($properties, $adapter);
		}

		return new File($properties, $adapter);
	}

	/**
	 * Calls undefined functions
	 *
	 * This is a compatibility helper. Basically, we're trying to map
	 * unnamed functions to their get* equivalent.
	 *
	 * @param   string  $name       The function name being called
	 * @param   array   $arguments  The arguments to be passed to the function
	 * @return  mixed
	 **/
	public function __call($name, $arguments)
	{
		static $methods = [];

		if (empty($methods))
		{
			$reflection = with(new \ReflectionClass($this))->getMethods(\ReflectionMethod::IS_PUBLIC);

			foreach ($reflection as $method)
			{
				$methods[] = $method->name;
			}
		}

		$alt = 'get' . ucfirst($name);

		if (in_array($alt, $methods))
		{
			return call_user_func_array([$this, $alt], $arguments);
		}

		throw new BadMethodCallException("'{$name}' method does not exist.", 500);
	}

	/**
	 * Sets the adapter on the entity
	 *
	 * @return  $this
	 **/
	public function setAdapter($adapter)
	{
		$this->adapter = $adapter;

		return $this;
	}

	/**
	 * Gets the filesystem adapter
	 *
	 * @return  object
	 **/
	public function getAdapter()
	{
		return $this->adapter;
	}

	/**
	 * Checks to see if entity is directory
	 *
	 * @return  bool
	 **/
	public function isDir()
	{
		$directory = __NAMESPACE__ . '\\Directory';
		return ($this instanceof $directory);
	}

	/**
	 * Checks to see if entity is a directory
	 *
	 * @return  bool
	 **/
	public function isDirectory()
	{
		return $this->isDir();
	}

	/**
	 * Checks to see if entity is a file
	 *
	 * @return  bool
	 **/
	public function isFile()
	{
		$file = __NAMESPACE__ . '\\File';
		return ($this instanceof $file);
	}

	/**
	 * Checks to see if entity is already on local filesystem
	 *
	 * @return  bool
	 **/
	public function isLocal()
	{
		$local = 'League\\Flysystem\\Adapter\\Local';
		return ($this->getAdapter()->getAdapter() instanceof $local);
	}

	/**
	 * Checks to see if the entity is virus free
	 *
	 * @param   bool  $remote  Whether or not to scan remote files
	 * @return  bool
	 **/
	public function isSafe($remote = false)
	{
		// Get the command
		// -i says we only want to hear about infected files
		// -r says scan recursively, this allows scanning a directory, rather than
		//    making multiple calls to scan individual files
		$command = App::get('config')->get('virus_scanner', 'clamscan -i -r --no-summary --block-encrypted');

		// Always scan local, and only scan remote if explicitly requested
		if ($this->isLocal() || (!$this->isLocal() && $remote))
		{
			if (!$this->isLocal())
			{
				// Copy to tmp
				$temp = Manager::getTempPath(uniqid(true) . '.tmp');
				$this->copy($temp);
				$path = $temp->getAbsolutePath();
			}
			else
			{
				$path = $this->getAbsolutePath();
			}

			// Build the command
			if (strstr($command, '%s'))
			{
				$command = sprintf($command, escapeshellarg($path));
			}
			else
			{
				$command .= ' ' . escapeshellarg($path);
			}

			// Execute the scan
			exec($command, $output, $status);

			// Get rid of the local copy if needed
			if (!$this->isLocal())
			{
				$temp->delete();
			}

			// Check the status, 1 means virus found, 2 means there was an error
			// (these definitions are for clamscan specifically)
			if ($status >= 1)
			{
				return false;
			}
		}

		return true;
	}

	/**
	 * Grabs the item name
	 *
	 * @return  string
	 **/
	public function getName()
	{
		if (isset($this->basename))
		{
			return $this->basename;
		}

		if (isset($this->filename))
		{
			return $this->filename;
		}

		if (isset($this->path))
		{
			$bits = explode('/', $this->path);
			return end($bits);
		}

		return '';
	}

	/**
	 * Grabs the item name
	 *
	 * @return  string
	 **/
	public function getDisplayName()
	{
		if (isset($this->filename))
		{
			// If it is a dotfile the filename is '' and the extension will be the rest of the filename
			if ($this->filename == '' && isset($this->extension))
			{
				return '.' . $this->extension;
			}
			return $this->filename;
		}

		if (isset($this->basename))
		{
			return $this->basename;
		}

		if (isset($this->path))
		{
			$bits = explode('/', $this->path);
			return end($bits);
		}

		return '';
	}

	/**
	 * Grabs the parent element, if applicable
	 *
	 * @param   bool  $raw  Whether or not to return raw string or applicable object
	 * @return  string|object
	 **/
	public function getParent($raw = true)
	{
		$return = '';

		if (isset($this->dirname))
		{
			$return = $this->dirname;
		}
		else if ($path = $this->getPath())
		{
			$bits = explode('/', $path);
			array_pop($bits);

			if (count($bits) > 0)
			{
				$return = implode('/', $bits);
			}
		}

		return $raw ? $return : self::fromPath($return, $this->getAdapter());
	}

	/**
	 * Grabs the timestamp
	 *
	 * @return  string
	 **/
	public function getTimestamp()
	{
		if (!isset($this->timestamp))
		{
			$this->timestamp = $this->hasAdapterOrFail()->adapter->getTimestamp($this->getPath());
		}

		return $this->timestamp;
	}

	/**
	 * Grabs the item ownership
	 *
	 * @return  int
	 **/
	public function getOwner()
	{
		return (isset($this->owner)) ? $this->owner : 0;
	}

	/**
	 * Grabs the full path to the entity
	 *
	 * @return  string
	 **/
	public function getPath()
	{
		return $this->path;
	}

	/**
	 * Computes the depth of the entity
	 *
	 * @return  int
	 */
	public function getDirLevel()
	{
		if (!trim($this->getPath()))
		{
			return 0;
		}

		$dirParts = explode('/', $this->getPath());

		return count($dirParts);
	}

	/**
	 * Grabs the absolute path to the entity (not relative to instance root)
	 *
	 * @return  string
	 **/
	public function getAbsolutePath()
	{
		// Don't let this confuse you...we're getting the actual filesystem adapter from
		// our adapter variable, which is really the filesystem class itself...words can be confusing.
		return $this->hasAdapterOrFail()->adapter->getAdapter()->applyPathPrefix($this->getPath());
	}

	/**
	 * Checks for a proper filesystem adapter being set
	 *
	 * @return  $this
	 **/
	public function hasAdapterOrFail()
	{
		if (!isset($this->adapter))
		{
			throw new \Exception('No adapter set', 500);
		}

		return $this;
	}

	/**
	 * Checks to see if entity exists on filesystem
	 *
	 * @return  bool
	 **/
	public function exists()
	{
		return $this->hasAdapterOrFail()->adapter->has($this->getPath());
	}

	/**
	 * Checks to see if entity exists on filesystem
	 *
	 * @return  bool
	 **/
	public function has()
	{
		return $this->exists();
	}

	/**
	 * Moves the entity
	 *
	 * @param   string  $to  Where to move the entity
	 * @return  bool
	 **/
	public function move($to)
	{
		$dest   = $to . '/' . $this->getDisplayName() . '.' . $this->getExtension();
		$return = $this->hasAdapterOrFail()->adapter->rename($this->getPath(), $dest);

		// Update the internal path
		if ($return)
		{
			$this->path = $dest;
		}

		return $return;
	}

	/**
	 * Renames the entity
	 *
	 * @param   string  $to  What to rename the entity to
	 * @return  bool
	 **/
	public function rename($to)
	{
		$dest   = $this->getParent() . '/' . $to;
		$return = $this->hasAdapterOrFail()->adapter->rename($this->getPath(), $dest);

		// Update the internal path
		if ($return)
		{
			$this->path = $dest;
		}

		return $return;
	}

	/**
	 * Copies the entity
	 *
	 * @param   string|object  $to  What/where to copy the entity to
	 * @return  bool
	 **/
	public function copy($to)
	{
		if (is_string($to))
		{
			return $this->hasAdapterOrFail()->adapter->copy($this->getPath(), $to);
		}
		else
		{
			return Manager::copy($this, $to);
		}
	}
}


text:
.. currentmodule:: tables

File manipulation class
=======================

.. _FileClassDescr:

The File Class
--------------
.. autoclass:: File

..  These are defined in the class docstring.
    This is necessary because attributes created in a class's
    __init__ method can't be documented with autoattribute.
    See Sphinx bug #904.
    https://bitbucket.org/birkenfeld/sphinx/issue/904

    Attributes
    ~~~~~~~~~~
    .. autoattribute:: File.filename
    .. autoattribute:: File.format_version
    .. autoattribute:: File.isopen
    .. autoattribute:: File.mode
    .. autoattribute:: File.root
    .. autoattribute:: File.root_uep

File properties
~~~~~~~~~~~~~~~
.. autoattribute:: File.title

.. autoattribute:: File.filters

.. autoattribute:: File.open_count

File methods - file handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automethod:: File.close

.. automethod:: File.copy_file

.. automethod:: File.flush

.. automethod:: File.fileno

.. automethod:: File.__enter__

.. automethod:: File.__exit__

.. automethod:: File.__str__

.. automethod:: File.__repr__

.. automethod:: File.get_file_image

.. automethod:: File.get_filesize

.. automethod:: File.get_userblock_size

File methods - hierarchy manipulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automethod:: File.copy_children

.. automethod:: File.copy_node

.. automethod:: File.create_array

.. automethod:: File.create_carray

.. automethod:: File.create_earray

.. automethod:: File.create_external_link

.. automethod:: File.create_group

.. automethod:: File.create_hard_link

.. automethod:: File.create_soft_link

.. automethod:: File.create_table

.. automethod:: File.create_vlarray

.. automethod:: File.move_node

.. automethod:: File.remove_node

.. automethod:: File.rename_node

File methods - tree traversal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automethod:: File.get_node

.. automethod:: File.is_visible_node

.. automethod:: File.iter_nodes

.. automethod:: File.list_nodes

.. automethod:: File.walk_groups

.. automethod:: File.walk_nodes

.. automethod:: File.__contains__

.. automethod:: File.__iter__

File methods - Undo/Redo support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automethod:: File.disable_undo

.. automethod:: File.enable_undo

.. automethod:: File.get_current_mark

.. automethod:: File.goto

.. automethod:: File.is_undo_enabled

.. automethod:: File.mark

.. automethod:: File.redo

.. automethod:: File.undo

File methods - attribute handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automethod:: File.copy_node_attrs

.. automethod:: File.del_node_attr

.. automethod:: File.get_node_attr

.. automethod:: File.set_node_attr

redpajama_set_name: RedPajamaGithub


text:
echo Starting UniGene Parser ...
java -Xmx512M -DentityExpansionLimit=5000000 -Djava.security.manager -Djava.security.policy=java.policy edu.wustl.geneconnect.parser.UniGeneParser %1 %2 %3 %4 %5 %6


text:
package dk.cwconsult.tempgres;

/**
 * An exception occurred while creating temporary database.
 */
public class TempgresException extends RuntimeException {

  public TempgresException(String message) {
    super(message);
  }

}


text:
<?php

class editarUsuario extends controllerExtends {

    public function main(\request $request) {
        try {
            $this->loadTableusuario();

            $usuario = new usuario();
            $usuario->setCedula($request->getParam('cedula'));
            $usuario->setNombre($request->getParam('nombre'));
            $usuario->setDireccion($request->getParam('direccion'));
            $usuario->setTelfijo($request->getParam('telfijo'));
            $usuario->setCelular($request->getParam('celular'));
            $usuario->setRol_id($request->getParam('rolid'));
            $usuario->setCorreo($request->getParam('correo'));
            $usuario->setId($request->getParam('id'));

            $usuarioDAO = new usuarioDAOExt($this->getConfig());
            $respuesta1 = $usuarioDAO->update($usuario);
            $respuesta2 = array(
                'code' => ($respuesta1 > 0) ? 200 : 500,
                'datos' => $respuesta1
            );

            $this->setParam('rsp', $respuesta2);
            $this->setView('imprimirJson');
        } catch (Exception $exc) {
            echo $exc->getMessage();
        }
    }

    private function loadTableusuario() {
        require $this->getConfig()->getPath() . 'model/table/table.usuario.php';
        require $this->getConfig()->getPath() . 'model/interface/interface.usuario.php';
        require $this->getConfig()->getPath() . 'model/DAO/class.usuarioDAO.php';
        require $this->getConfig()->getPath() . 'model/extended/class.usuarioDAOExt.php';
    }

}


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

<title>CrashReportPersister (acra 4.11 API)</title>
<meta name="date" content="2018-03-21">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.acra.file

Class CrashReportPersister

java.lang.Object

org.acra.file.CrashReportPersister

public final class CrashReportPersister
extends java.lang.Object

Stores a crash reports data with ReportField enum values as keys.
 This is basically the source of Properties adapted to extend an
 EnumMap instead of Hashtable and with a few tweaks to avoid losing crazy
 amounts of android time in the generation of a date comment when storing to
 file.

Constructor Summary

Constructors

Constructor and Description

CrashReportPersister()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

CrashReportData
load(java.io.File file)

Loads properties from the specified File.

void
store(CrashReportData crashData,
     java.io.File file)

Stores the mappings in this Properties to the specified OutputStream,
 putting the specified comment at the beginning.

Methods inherited from class java.lang.Object

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

Constructor Detail

CrashReportPersister

public CrashReportPersister()

Method Detail

load

@NonNull
public CrashReportData load(@NonNull
                                      java.io.File file)
                               throws java.io.IOException,
                                      org.json.JSONException

Loads properties from the specified File.

Parameters:

file - Report file from which to load the CrashData.

Returns:

CrashReportData read from the supplied File.

Throws:

java.io.IOException - if error occurs during reading from the File.

org.json.JSONException - if the stream cannot be parsed as a JSON object.

store

public void store(@NonNull
                  CrashReportData crashData,
                  @NonNull
                  java.io.File file)
           throws java.io.IOException

Stores the mappings in this Properties to the specified OutputStream,
 putting the specified comment at the beginning. The output from this
 method is suitable for being read by the load() method.

Parameters:

crashData - CrashReportData to save.

file - File into which to store the CrashReportData.

Throws:

java.io.IOException - if the CrashReportData could not be written to the OutputStream.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="urn:maven:assembly:1.1.0-SNAPSHOT">

  <id>assemble</id>

  <formats>
    <format>dir</format>
    <format>tar.gz</format>
  </formats>

  <includeBaseDirectory>false</includeBaseDirectory>

  <fileSets>
    <fileSet>
      <directory>target/jboss-as-${version.jboss.as}</directory>
      <outputDirectory></outputDirectory>
    </fileSet>
  </fileSets>

  <!-- ####################################################################################### -->
  <!-- WARNING: This file is currently not used, have a look at copy-distro profile in pom.xml -->
  <!-- ####################################################################################### -->
</assembly>


text:
* Sequelize http://docs.sequelizejs.com/en/latest/
* waterline https://github.com/balderdashy/waterline
* jugglingdb
* orm2 https://github.com/dresende/node-orm2

## Path | File
* glob
* fs-extra
* mz 将fs模块包装为Promise

## DOM
* cheerio

## NET
* request
* superagent

## MEMORY
* node-memwatch
* node-mtrace
* node-heapdump
* v8-profiler
* node-inspector

## HELPER
* underscore
* lodash


text:
from typing import Callable

import django
from django.http import HttpRequest

try:
    from django.utils.datastructures import CaseInsensitiveMapping
except ImportError:
    from .datastructures import CaseInsensitiveMapping

# HttpHeaders copypasted from django 3.0 codebase
class HttpHeaders(CaseInsensitiveMapping):
    HTTP_PREFIX = "HTTP_"
    # PEP 333 gives two headers which aren't prepended with HTTP_.
    UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"}

    def __init__(self, environ):
        headers = {}
        for header, value in environ.items():
            name = self.parse_header_name(header)
            if name:
                headers[name] = value
        super().__init__(headers)

    def __getitem__(self, key):
        """Allow header lookup using underscores in place of hyphens."""
        return super().__getitem__(key.replace("_", "-"))

    @classmethod
    def parse_header_name(cls, header):
        if header.startswith(cls.HTTP_PREFIX):
            start = len(cls.HTTP_PREFIX)
            header = header[start:]
        elif header not in cls.UNPREFIXED_HEADERS:
            return None
        return header.replace("_", "-").title()

def get_headers_old(request):
    return HttpHeaders(request.META)

def get_headers_v3(request):
    return request.headers

get_headers: Callable[[HttpRequest], HttpHeaders]

if django.VERSION[0] < 3:
    get_headers = get_headers_old
else:
    get_headers = get_headers_v3


text:
package com.guigarage.photonia.spring.services;

import com.guigarage.photonia.service.AsyncService;
import com.guigarage.photonia.service.PhotoniaService;
import com.guigarage.photonia.v2.ImageMetadata;
import com.guigarage.photonia.v2.PhotoniaAlbum;
import com.guigarage.photonia.v2.PhotoniaThumbnailCache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SpringPhotoniaService implements PhotoniaService {

    private PhotoniaThumbnailCache thumbnailCache;

    private List<PhotoniaAlbum> albums;

    @Inject
    private AsyncService asyncService;

    @Inject
    private ServletContext servletContext;

    @Value("${server.port:8080}")
    private int port;

    // @Inject
    // private DolphinEventBus eventBus;

    @PostConstruct
    public void init() {
        File thumbBaseFolder = new File("/Users/hendrikebbers/Desktop/photonia/thumbnails");
        thumbnailCache = new PhotoniaThumbnailCache(thumbBaseFolder, 400, id -> System.out.println(""));

        File dataFolder = new File("/Users/hendrikebbers/Desktop/photonia/albums");
        albums = new ArrayList<>();
        for (File albumFolder : dataFolder.listFiles()) {
            if (albumFolder.isDirectory()) {
                try {
                    PhotoniaAlbum album = new PhotoniaAlbum(albumFolder);
                    for(ImageMetadata imageMetadata : album.getMetadata().getImages()) {
                        if(!thumbnailCache.containsThumbnail(imageMetadata)) {
                            thumbnailCache.createThumbnail(imageMetadata, asyncService);
                        }
                    }
                    albums.add(album);
                } catch (Exception e) {
                    throw new RuntimeException("Can't create album for " + albumFolder, e);
                }
            }
        }
    }

    @Override
    public List<PhotoniaAlbum> getAllAlbums() {
        return albums;
    }

    @Override
    public PhotoniaAlbum getAlbumById(String albumId) {
        for (PhotoniaAlbum album : albums) {
            if (album.getMetadata().getUuid().equals(albumId)) {
                return album;
            }
        }
        return null;
    }

    @Override
    public PhotoniaThumbnailCache getThumbnailCache() {
        return thumbnailCache;
    }

    @Override
    public String getImageUrl(String id) {
        try {
            return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/" + servletContext.getContextPath() + "/images/get/" + id;
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getImageThumbnailUrl(String id) {
        try {
            return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + port + "/" + servletContext.getContextPath() + "/thumbs/get/" + id;
        } catch (UnknownHostException e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public ImageMetadata getImageById(String imageId) {
        for (PhotoniaAlbum album : albums) {
            for (ImageMetadata imageMetadata : album.getMetadata().getImages()) {
                if (imageMetadata.getUuid().equals(imageId)) {
                    return imageMetadata;
                }
            }
        }
        return null;
    }

    @Override
    public ImageMetadata getPrevImage(String imageId) {
        for (PhotoniaAlbum album : albums) {
            for(int i = 0; i < album.getMetadata().getImages().size(); i++) {
                if (album.getMetadata().getImages().get(i).getUuid().equals(imageId)) {
                    if(i > 0) {
                        return album.getMetadata().getImages().get(i-1);
                    } else {
                        return album.getMetadata().getImages().get(album.getMetadata().getImages().size() - 1);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public void delete(String id) {
        ImageMetadata metadata = getImageById(id);
        if(metadata != null) {
            metadata.delete();
        }
    }

    @Override
    public ImageMetadata getNextImage(String imageId) {
        for (PhotoniaAlbum album : albums) {
            for(int i = 0; i < album.getMetadata().getImages().size(); i++) {
                if (album.getMetadata().getImages().get(i).getUuid().equals(imageId)) {
                    if(i < album.getMetadata().getImages().size() - 1) {
                        return album.getMetadata().getImages().get(i+1);
                    } else {
                        return album.getMetadata().getImages().get(0);
                    }
                }
            }
        }
        return null;
    }
}


text:
Template[getTemplate('post_page')].helpers({
  post_item: function () {
    return getTemplate('post_item');
  },
  post_body: function () {
    return getTemplate('post_body');
  },
  comment_form: function () {
    return getTemplate('comment_form');
  },
  comment_list: function () {
    return getTemplate('comment_list');
  }
});

Template[getTemplate('post_page')].rendered = function(){
  $('body').scrollTop(0);
};


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateScheduleEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedule_events', function (Blueprint $table) {
            $table->increments('id')->unique();
            $table->string('description');
            $table->dateTime('event_date_time')->default('2000-01-01 23:59:00');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('schedule_events');
    }
}


text:
package org.qi4j.sample.dcicargo.sample_b.context.interaction.handling.registration.exception;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.qi4j.sample.dcicargo.sample_b.context.interaction.handling.parsing.dto.ParsedHandlingEventData;
import org.qi4j.sample.dcicargo.sample_b.data.structure.handling.HandlingEvent;

/**
 * If a {@link HandlingEvent} can't be created from a given set of parameters.
 *
 * It is a checked exception because it's not a programming error, but rather a
 * special case that the application is built to handle. It can occur during normal
 * program execution.
 */
public class CannotRegisterHandlingEventException extends Exception
{
    private ParsedHandlingEventData parsedHandlingEventData;

    protected String msg, id, time, type, unloc;
    protected String voy = "";

    public CannotRegisterHandlingEventException( ParsedHandlingEventData parsedHandlingEventData )
    {
        super();
        this.parsedHandlingEventData = parsedHandlingEventData;

        time = parseDate( parsedHandlingEventData.completionTime().get() );
        id = parse( parsedHandlingEventData.trackingIdString().get() );
        type = parse( parsedHandlingEventData.handlingEventType().get().name() );
        unloc = parse( parsedHandlingEventData.unLocodeString().get() );
        voy = parse( parsedHandlingEventData.voyageNumberString().get() );
    }

    public ParsedHandlingEventData getParsedHandlingEventData()
    {
        return parsedHandlingEventData;
    }

    private String parse( String str )
    {
        return str == null ? "null" : str;
    }

    private String parseDate( Date date )
    {
        return date == null ? "null" : new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( date );
    }
}


text:
#include "tensor.h"
#include "../util/exception.h"

napi_ref Tensor::constructor;

Tensor::Tensor(TF_DataType type, const int64_t* dims, int num_dims, void* data, size_t len) {
  // void (*deallocator)(void* data, size_t len, void* arg)
  this->tf_tensor = TF_NewTensor(type, dims,
    num_dims, data, len, &Deallocate, nullptr /* void* deallocator_arg */);
}

Tensor::~Tensor() { }

napi_value Tensor::Init(napi_env env) {
  napi_status status;

  napi_value cons;
  status = napi_define_class(env, "Tensor",
    Tensor::New, nullptr, 0, nullptr, &cons);
  assert(status == napi_ok);

  status = napi_create_reference(env, cons, 1, &constructor);
  assert(status == napi_ok);

  return cons;
}

napi_value Tensor::New(napi_env env, napi_callback_info info)
{
  napi_status status;

  // Invoked as constructor: `new Tensor(...)`
  size_t argc = 5;
  napi_value args[5];
  napi_value jsthis;
  status = napi_get_cb_info(env, info, &argc, args, &jsthis, nullptr);
  assert(status == napi_ok);

  if (argc < 5) {
    Exception::ThrowError(env, "5 arguments are needed!\n");
  }

  bool is_constructor;
  status = napi_is_construct_call(env, info, &is_constructor);
  assert(status == napi_ok);

  if (!is_constructor) {
    // Invoked as plain function `Operation(...)`, turn into construct call.
    return Tensor::NewInstance(env, info);
  }

  napi_valuetype valuetype;
  for (size_t i = 0; i < argc; i ++) {
    status = napi_typeof(env, args[0], &valuetype);
    assert(status == napi_ok && valuetype != napi_undefined);
  }

  TF_DataType type;
  status = napi_get_value_int32(env, args[0], (int *)&type);
  assert(status == napi_ok);

  int64_t dims;
  status = napi_get_value_int64(env, args[1], &dims);
  assert(status == napi_ok);

  int num_dims;
  // #ifdef __x86_64__
  // status = napi_get_value_int64(env, args[2], &num_dims);
  // #else // __i386__
  status = napi_get_value_int32(env, args[2], &num_dims);
  // #endif
  assert(status == napi_ok);

  size_t len = 0;
  status = napi_get_value_uint32(env, args[4], (uint32_t *)&len);
  assert(status == napi_ok);

  void* data = (void *)malloc(sizeof(char) * len);
  status = napi_get_buffer_info(env, args[3], &data, &len);
  assert(status == napi_ok);

  Tensor* tensor = new Tensor(type, &dims, num_dims, data, len);

  status = napi_wrap(env, jsthis,
    reinterpret_cast<void*>(tensor), Tensor::Destructor, nullptr, nullptr);
  assert(status == napi_ok);

  return jsthis;
}

napi_value Tensor::NewInstance(napi_env env, napi_callback_info info)
{
  napi_status status;

  size_t _argc = 5;
  napi_value args[5];
  status = napi_get_cb_info(env, info, &_argc, args, nullptr, nullptr);
  assert(status == napi_ok);

  const size_t argc = 5;
  napi_value argv[argc] = {args[0], args[1], args[2], args[3], args[4]};

  napi_value cons;
  status = napi_get_reference_value(env, constructor, &cons);
  assert(status == napi_ok);

  napi_value instance;
  status = napi_new_instance(env, cons, argc, argv, &instance);
  assert(status == napi_ok);

  return instance;
}

void Tensor::Destructor(napi_env env, void* instance_ptr, void* /*finalize_hint*/) {
  reinterpret_cast<Tensor*>(instance_ptr)->~Tensor();
}

void Tensor::Deallocate(void* data, size_t len, void* arg)
{
  // TODO dealloate the tensor data
}


text:
sudo yum -y install java
sudo yum -y install openssl
sudo yum -y install openssl-devel

# Elasticsearch
wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.6.0.tar.gz
tar xzvf elasticsearch-1.6.0.tar.gz
rm elasticsearch-1.6.0.tar.gz

# Ruby
git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
source ~/.bash_profile
rbnev install 2.2.2

# Redis
sudo yum -y install epel-release
sudo yum -y --enablerepo=epel install redis

# MySQL
sudo yum -y mysql

# Rust
curl -sf -L https://static.rust-lang.org/rustup.sh | sh
# thx. https://github.com/rust-lang/rust-installer/issues/30#issuecomment-100330002
sudo echo '/usr/local/lib' > /etc/ld.so.conf.d/local.conf
sudo ldconfig


text:
// PDFDocument.h
//
// Copyright (c) 2015 Iwe Labs
//
// 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.

#import <Foundation/Foundation.h>

/** PDFDocument represents a PDF document either loaded from file or disk. The class provides tools to reveal the structure, content and metadata of a PDF. PDFDocument serves as the model for PDFViewController to render an interactive PDF on a PDFView.
 */

@class PDFDictionary;
@class PDFFormContainer;

@interface PDFDocument : NSObject

/** The PDF file data.
 */
@property (nonatomic, strong) NSMutableData *documentData;

/** The form container holding the forms for the document.
 */
@property (nonatomic, readonly) PDFFormContainer *forms;

/** The path for the PDF document if it was loaded from file.
 @discussion If the document was loaded from memory, documentPath is nil.
 */
@property (nonatomic, readonly) NSString *documentPath;

/** The document catalog for the PDF.
 @discussion See 3.6.1 in 'PDF Reference Second Edition version 1.3, Adobe Systems Incorporated'.
 */
@property (nonatomic, readonly) PDFDictionary *catalog;

/** The document info dictionary
 */
@property (nonatomic, readonly) PDFDictionary *info;

/** An array containing PDFPage objects cooresponding in order and content to the pages of the document.
 */
@property (nonatomic, readonly) NSArray *pages;

/** The name of the PDF.
 */
@property (nonatomic, strong) NSString *pdfName;

/** The CGPDFDocument on top of which the class is built.
 */
@property (nonatomic, readonly) CGPDFDocumentRef document;

/**---------------------------------------------------------------------------------------
 * @name Creating a PDFDocument
 *  ---------------------------------------------------------------------------------------
 */

/** Creates a new instance of PDFDocument.

 @param data Content of the document.
 @return A new instance of PDFDocument initialized with data.
 */

- (instancetype)initWithData:(NSData *)data NS_DESIGNATED_INITIALIZER;

/** Creates a new instance of PDFDocument.

 @param name Resource to load.
 @return A new instance of PDFDocument initialized with a PDF resource named name.
 */
- (instancetype)initWithResource:(NSString *)name NS_DESIGNATED_INITIALIZER;

/** Creates a new instance of PDFDocument.

 @param path Points to PDF file to load.
 @return A new instance of PDFDocument initialized with a PDF located at path.
 */
- (instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER;

/**---------------------------------------------------------------------------------------
 * @name Finding Document Structure
 *  ---------------------------------------------------------------------------------------
 */
/** Returns the number of pages in the document.

 @return The page count.
 */
- (NSUInteger)numberOfPages;

/**---------------------------------------------------------------------------------------
 * @name Saving and Refreshing
 *  ---------------------------------------------------------------------------------------
 */

/** Reloads everything based on documentData.
 */
- (void)refresh;

/** Flattens the interactive elements, rendering the form values directly in the PDF.
 Useful for saving a PDF with forms that have been filled out.
 @return The data for the static flattened PDF.
 */
- (NSData *)savedStaticPDFData;

/**
 @param docToAppend
 @return The PDF data of the result when the passed document is appended to the receiver.
 */
- (NSData *)mergedDataWithDocument:(PDFDocument *)docToAppend;

/**
 Converts a PDF page to an image.
 @param page The page number. 1 is the first page.
 @param width The desired width of the returned image. The image will match the aspect ratio of the page.
 @return A UIImage representing the page.
 */

- (UIImage *)imageFromPage:(NSUInteger)page width:(NSUInteger)width;

/** Sets the background color for the PDF view.
 @return A string containing an xml representation of the forms of the document and their values. Used for submitting the form.
 */
- (NSString *)formXML;

@end


text:
module Shoulda
  module Matchers
    # @private
    VERSION = '3.1.2'.freeze
  end
end


text:
package org.mifos.reports.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.mifos.framework.business.service.BusinessService;
import org.mifos.framework.business.service.ServiceFactory;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.struts.action.BaseAction;
import org.mifos.framework.util.helpers.BusinessServiceName;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.reports.business.service.ReportsBusinessService;
import org.mifos.reports.persistence.ReportsPersistence;
import org.mifos.reports.util.helpers.ReportsConstants;
import org.mifos.security.util.ActionSecurity;
import org.mifos.security.util.SecurityConstants;

public class ReportsAction extends BaseAction {

    private static final Logger logger = LoggerFactory.getLogger(ReportsAction.class);

    private ReportsBusinessService reportsBusinessService;

    public ReportsAction() throws ServiceException {
        reportsBusinessService = (ReportsBusinessService) ServiceFactory.getInstance().getBusinessService(
                BusinessServiceName.ReportsService);
    }

    @Override
    protected BusinessService getService() {
        return reportsBusinessService;
    }

    public static ActionSecurity getSecurity() {
        ActionSecurity security = new ActionSecurity("reportsAction");
        security.allow("load", SecurityConstants.VIEW);
        security.allow("report_designer", SecurityConstants.CLIENTSDETAILVIEW);
        security.allow("product_history", SecurityConstants.CLIENTSPRODUCTHISTORY);

        security.allow("branch_performance", SecurityConstants.BRANCHPERFORMANCE);
        security.allow("area_performance", SecurityConstants.AREAPERFORMANCE);
        security.allow("collection_sheet", SecurityConstants.COLLECTIONSHEET);
        security.allow("loan_distribution", SecurityConstants.LOANDISTRIBUTION);
        security.allow("branch_disbursement", SecurityConstants.BRANCHDISBURSEMENT);
        security.allow("staffwise_report", SecurityConstants.STAFFWISEREPORT);
        security.allow("branchwise_report", SecurityConstants.BRANCHWISEREPORT);
        security.allow("analysis", SecurityConstants.ANALYSIS);
        security.allow("kendra_meeting", SecurityConstants.KENDRA_MEETING);
        security.allow("administerreports_path", SecurityConstants.ADMINISTER_REPORTS);
        security.allow("administerreportslist_path", SecurityConstants.ADMINISTER_REPORTS);
        return security;

    }

    /**
     * loads report page
     */
    public ActionForward load(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        logger.debug("In ReportsAction:load Method: ");
        StaticHibernateUtil.flushAndCloseSession();
        request.getSession().setAttribute(ReportsConstants.LISTOFREPORTS,
                new ReportsPersistence().getAllReportCategories());
        return mapping.findForward(Constants.LOAD_SUCCESS);
    }

    public ActionForward getReportPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        logger.debug("In ReportsAction:getReportPage Method: ");
        return mapping.findForward(request.getParameter("viewPath"));
    }

    public ActionForward getAdminReportPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        logger.debug("In ReportsAction:getAdminReportPage Method: ");
        return mapping.findForward("administerreports_path");
    }

    @Override
    protected boolean skipActionFormToBusinessObjectConversion(String method) {
        return true;
    }

}


text:
namespace scheduler {

WebViewSchedulerImpl::WebViewSchedulerImpl(
    blink::WebView* web_view,
    RendererSchedulerImpl* renderer_scheduler,
    bool disable_background_timer_throttling)
    : web_view_(web_view),
      renderer_scheduler_(renderer_scheduler),
      page_in_background_(false),
      disable_background_timer_throttling_(
          disable_background_timer_throttling) {}

WebViewSchedulerImpl::~WebViewSchedulerImpl() {
  // TODO(alexclarke): Find out why we can't rely on the web view outliving the
  // frame.
  for (WebFrameSchedulerImpl* frame_scheduler : frame_schedulers_) {
    frame_scheduler->DetachFromWebViewScheduler();
  }
}

void WebViewSchedulerImpl::setPageInBackground(bool page_in_background) {
  if (disable_background_timer_throttling_ ||
      page_in_background_ == page_in_background)
    return;

  page_in_background_ = page_in_background;

  for (WebFrameSchedulerImpl* frame_scheduler : frame_schedulers_) {
    frame_scheduler->SetPageInBackground(page_in_background_);
  }
}

scoped_ptr<WebFrameSchedulerImpl>
WebViewSchedulerImpl::createWebFrameSchedulerImpl() {
  scoped_ptr<WebFrameSchedulerImpl> frame_scheduler(
      new WebFrameSchedulerImpl(renderer_scheduler_, this));
  frame_scheduler->SetPageInBackground(page_in_background_);
  frame_schedulers_.insert(frame_scheduler.get());
  return frame_scheduler;
}

blink::WebPassOwnPtr<blink::WebFrameScheduler>
WebViewSchedulerImpl::createFrameScheduler() {
  return blink::adoptWebPtr(createWebFrameSchedulerImpl().release());
}

void WebViewSchedulerImpl::Unregister(WebFrameSchedulerImpl* frame_scheduler) {
  DCHECK(frame_schedulers_.find(frame_scheduler) != frame_schedulers_.end());
  frame_schedulers_.erase(frame_scheduler);
}

}  // namespace scheduler


text:
from pprint import pprint
from hpOneView.oneview_client import OneViewClient
from hpOneView.exceptions import HPOneViewException
from config_loader import try_load_from_file

config = {
    "ip": "172.16.102.59",
    "credentials": {
        "userName": "administrator",
        "password": ""
    }
}

# Try load config from a file (if there is a config file)
config = try_load_from_file(config)

oneview_client = OneViewClient(config)

# Create a new appliance backup
print("\n## Create a new appliance backup")
backup_details = oneview_client.backups.create()
pprint(backup_details)

filename = backup_details['id']

# Download the backup archive
print("\n## Download the previously created backup archive")
response = oneview_client.backups.download(backup_details['downloadUri'], filename)
print(response)

# Upload the backup archive
print("\n## Upload the previously downloaded backup archive")
backup_details = oneview_client.backups.upload(filename)
pprint(backup_details)

# Get by URI
print("\n## Find recently created backup by URI")
backup_by_uri = oneview_client.backups.get(backup_details['uri'])
pprint(backup_by_uri)

# Get all backups
print("\n## Get all backups")
backups = oneview_client.backups.get_all()
pprint(backups)

# Get the details of the backup configuration
print("\n## Get the details of the backup configuration for the remote server and automatic backup schedule")
config = oneview_client.backups.get_config()
pprint(config)

# Update the backup configuration
try:
    print("\n## Update the backup configuration")
    config['scheduleTime'] = '23:00'
    updated_config = oneview_client.backups.update_config(config)
    pprint(updated_config)
except HPOneViewException as e:
    print(e.msg)

# Save the backup file to a previously-configured remote location
try:
    print("\n## Save the backup file to a previously-configured remote location")
    backup_details = oneview_client.backups.update_remote_archive(backup_details['saveUri'])
    pprint(backup_details)
except HPOneViewException as e:
    print(e.msg)


text:
package util;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String a = "casa";
		String b = "casa";
		System.out.println(a==b);

	}

}


text:
#include<iostream>
using namespace std;
/*
 * g++ -E test.cpp  > sal.out
 * compile with that command and see how the compiler replace the constant
 */
#define PI 3.141516
#define MIN(a,b) (((a)<(b)) ? a : b)
int main(){
  cout << "The number PI is " << PI << endl;
  cout <<"The minimum is " << MIN(i, j) << endl;
  return 0;
}


text:
import java.sql.Connection;
import java.util.ArrayList;

public class populateAll{
	public static void main(String[] args){

		//create conntection to DB
		Connection connection = ConnectDB.Connect();

		//create an array to store every data to populate
		ArrayList<populate> population = new ArrayList<populate>();
		population.add(new populateBuilding());
		population.add(new populateStudent());
		population.add(new populateAS());

		for(populate x:population){
			x.populateData(connection);
		}

	}
}


text:
/* ************************************
  Server Config and Load
**************************************/
'use strict'

var restify = require('restify')
var hub = require('./lib/hub')
var srvConf = require('./lib/server')
var server = restify.createServer(srvConf)
require('./lib/router')(server)
var engine = require('./lib/engine')
var config = require('config')
var configChecker = require('./utils/envConfigChecker')
var logger = require('./utils/composrLogger')
var ComposrError = require('composr-core').ComposrError
var yn = require('yn')

/* ************************************
  Configuration check
**************************************/
configChecker.checkConfig()

/* ************************************
  Middlewares
**************************************/
logger.info('[App]', 'Loading Middlewares...')
require('./middlewares')(restify, server, config, logger)

/* ************************************
  Metrics
**************************************/
logger.info('[App]', 'Initializing metrics...')
require('./metrics')(restify, server, config, logger)

/* ************************************
  Error handlers
**************************************/

server.on('NotFound', function (req, res, err, next) {
  err = new ComposrError('error:not_found', err.message, 404)
  res.send(404, err)
  next() // Necesary for triggering request end
})

server.on('InternalServer', function (req, res, err, next) {
  logger.warn('[App]', 'Error caught by router InternalServer', req.path())
  err = new ComposrError('error:internal:server:error', err.message, 500)
  res.send(500, err)
  next() // Necesary for triggering request end
})

server.on('uncaughtException', function (req, res, route, err) {
  // uncaughtException errors doesn't emit a "server after" event
  if (res.headersSent) {
    return (false)
  }
  var status = err.statusCode || err.status || 500
  var body = err.message || err.errorDescription || err.body || err.data || err

  if (err instanceof ComposrError === false) {
    err = new ComposrError('error:internal:server:error', body, status)
  }

  logger.warn('[App]', 'Error caught by router uncaughtException', req.path())
  logger.error(status, body, route)

  res.send(status, err)
  hub.emit('http:end', req, res)
})

process.on('uncaughtException', function (err) {
  logger.warn('[App]', 'Error caught by uncaughtException')
  logger.error(err)
  if (!err || err.message !== "Can't set headers after they are sent.") {
    process.exit(1)
  }
})

/* ************************************
  Initialization
**************************************/

// Trigger the static routes creation
hub.emit('create:staticRoutes', server)

module.exports = function (serverID) {
  var localMode = config.get('execution.local')
  return engine.init(server, yn(localMode), serverID)
}


text:
/*
Package main provides a client used for benchmarking.  Before running the
client, the user would need to launch the grpc server.

To start the server before running the client, you can run look for the command
under the following file:

	benchmark/server/main.go

After starting the server, the client can be run.  An example of how to run this
command is:

go run benchmark/client/main.go -test_name=grpc_test

If the server is running on a different port than 50051, then use the port flag
for the client to hit the server on the correct port.
An example for how to run this command on a different port can be found here:

go run benchmark/client/main.go -test_name=grpc_test -port=8080
*/
package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"runtime"
	"runtime/pprof"
	"sync"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/benchmark"
	testpb "google.golang.org/grpc/benchmark/grpc_testing"
	"google.golang.org/grpc/benchmark/stats"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/internal/syscall"
)

var (
	port      = flag.String("port", "50051", "Localhost port to connect to.")
	numRPC    = flag.Int("r", 1, "The number of concurrent RPCs on each connection.")
	numConn   = flag.Int("c", 1, "The number of parallel connections.")
	warmupDur = flag.Int("w", 10, "Warm-up duration in seconds")
	duration  = flag.Int("d", 60, "Benchmark duration in seconds")
	rqSize    = flag.Int("req", 1, "Request message size in bytes.")
	rspSize   = flag.Int("resp", 1, "Response message size in bytes.")
	rpcType   = flag.String("rpc_type", "unary",
		`Configure different client rpc type. Valid options are:
		   unary;
		   streaming.`)
	testName = flag.String("test_name", "", "Name of the test used for creating profiles.")
	wg       sync.WaitGroup
	hopts    = stats.HistogramOptions{
		NumBuckets:   2495,
		GrowthFactor: .01,
	}
	mu    sync.Mutex
	hists []*stats.Histogram
)

func main() {
	flag.Parse()
	if *testName == "" {
		grpclog.Fatalf("test_name not set")
	}
	req := &testpb.SimpleRequest{
		ResponseType: testpb.PayloadType_COMPRESSABLE,
		ResponseSize: int32(*rspSize),
		Payload: &testpb.Payload{
			Type: testpb.PayloadType_COMPRESSABLE,
			Body: make([]byte, *rqSize),
		},
	}
	connectCtx, connectCancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
	defer connectCancel()
	ccs := buildConnections(connectCtx)
	warmDeadline := time.Now().Add(time.Duration(*warmupDur) * time.Second)
	endDeadline := warmDeadline.Add(time.Duration(*duration) * time.Second)
	cf, err := os.Create("/tmp/" + *testName + ".cpu")
	if err != nil {
		grpclog.Fatalf("Error creating file: %v", err)
	}
	defer cf.Close()
	pprof.StartCPUProfile(cf)
	cpuBeg := syscall.GetCPUTime()
	for _, cc := range ccs {
		runWithConn(cc, req, warmDeadline, endDeadline)
	}
	wg.Wait()
	cpu := time.Duration(syscall.GetCPUTime() - cpuBeg)
	pprof.StopCPUProfile()
	mf, err := os.Create("/tmp/" + *testName + ".mem")
	if err != nil {
		grpclog.Fatalf("Error creating file: %v", err)
	}
	defer mf.Close()
	runtime.GC() // materialize all statistics
	if err := pprof.WriteHeapProfile(mf); err != nil {
		grpclog.Fatalf("Error writing memory profile: %v", err)
	}
	hist := stats.NewHistogram(hopts)
	for _, h := range hists {
		hist.Merge(h)
	}
	parseHist(hist)
	fmt.Println("Client CPU utilization:", cpu)
	fmt.Println("Client CPU profile:", cf.Name())
	fmt.Println("Client Mem Profile:", mf.Name())
}

func buildConnections(ctx context.Context) []*grpc.ClientConn {
	ccs := make([]*grpc.ClientConn, *numConn)
	for i := range ccs {
		ccs[i] = benchmark.NewClientConnWithContext(ctx, "localhost:"+*port, grpc.WithInsecure(), grpc.WithBlock())
	}
	return ccs
}

func runWithConn(cc *grpc.ClientConn, req *testpb.SimpleRequest, warmDeadline, endDeadline time.Time) {
	for i := 0; i < *numRPC; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			caller := makeCaller(cc, req)
			hist := stats.NewHistogram(hopts)
			for {
				start := time.Now()
				if start.After(endDeadline) {
					mu.Lock()
					hists = append(hists, hist)
					mu.Unlock()
					return
				}
				caller()
				elapsed := time.Since(start)
				if start.After(warmDeadline) {
					hist.Add(elapsed.Nanoseconds())
				}
			}
		}()
	}
}

func makeCaller(cc *grpc.ClientConn, req *testpb.SimpleRequest) func() {
	client := testpb.NewBenchmarkServiceClient(cc)
	if *rpcType == "unary" {
		return func() {
			if _, err := client.UnaryCall(context.Background(), req); err != nil {
				grpclog.Fatalf("RPC failed: %v", err)
			}
		}
	}
	stream, err := client.StreamingCall(context.Background())
	if err != nil {
		grpclog.Fatalf("RPC failed: %v", err)
	}
	return func() {
		if err := stream.Send(req); err != nil {
			grpclog.Fatalf("Streaming RPC failed to send: %v", err)
		}
		if _, err := stream.Recv(); err != nil {
			grpclog.Fatalf("Streaming RPC failed to read: %v", err)
		}
	}
}

func parseHist(hist *stats.Histogram) {
	fmt.Println("qps:", float64(hist.Count)/float64(*duration))
	fmt.Printf("Latency: (50/90/99 %%ile): %v/%v/%v\n",
		time.Duration(median(.5, hist)),
		time.Duration(median(.9, hist)),
		time.Duration(median(.99, hist)))
}

func median(percentile float64, h *stats.Histogram) int64 {
	need := int64(float64(h.Count) * percentile)
	have := int64(0)
	for _, bucket := range h.Buckets {
		count := bucket.Count
		if have+count >= need {
			percent := float64(need-have) / float64(count)
			return int64((1.0-percent)*bucket.LowBound + percent*bucket.LowBound*(1.0+hopts.GrowthFactor))
		}
		have += bucket.Count
	}
	panic("should have found a bound")
}


text:
A QUARTS sheet for Roll20

The QUARTS Role-Playing Game can be found at the following link: https://sites.google.com/site/quartssrd/home


text:
if(!dojo._hasResource["dojox.dtl.filter.integers"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.dtl.filter.integers"] = true;
dojo.provide("dojox.dtl.filter.integers");

dojo.mixin(dojox.dtl.filter.integers, {
	add: function(value, arg){
		value = parseInt(value);
		arg = parseInt(arg);
		return isNaN(arg) ? value : value + arg;
	},
	get_digit: function(value, arg){
		// summary:
		//		Given a whole number, returns the 1-based requested digit of it
		// desciprtion:
		//		1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the
		//		original value for invalid input (if input or argument is not an integer,
		//		or if argument is less than 1). Otherwise, output is always an integer.
		value = parseInt(value);
		arg = parseInt(arg) - 1;
		if(arg >= 0){
			value += "";
			if(arg < value.length){
				value = parseInt(value.charAt(arg));
			}else{
				value = 0;
			}
		}
		return (isNaN(value) ? 0 : value);
	}
});

}


text:
<?php

namespace Sonata\AdminBundle\Tests\Form;

use PHPUnit\Framework\TestCase;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\BaseFieldDescription;
use Sonata\AdminBundle\Builder\FormContractorInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Model\ModelManagerInterface;
use Sonata\AdminBundle\Tests\Fixtures\Admin\CleanAdmin;
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\ResolvedFormTypeInterface;

class FormMapperTest extends TestCase
{
    /**
     * @var FormContractorInterface
     */
    protected $contractor;

    /**
     * @var AdminInterface
     */
    protected $admin;

    /**
     * @var ModelManagerInterface
     */
    protected $modelManager;

    /**
     * @var FormMapper
     */
    protected $formMapper;

    public function setUp()
    {
        $this->contractor = $this->getMockForAbstractClass(FormContractorInterface::class);

        $formFactory = $this->getMockForAbstractClass(FormFactoryInterface::class);
        $eventDispatcher = $this->getMockForAbstractClass(EventDispatcherInterface::class);

        $formBuilder = new FormBuilder('test', 'stdClass', $eventDispatcher, $formFactory);

        $this->admin = new CleanAdmin('code', 'class', 'controller');

        $this->modelManager = $this->getMockForAbstractClass(ModelManagerInterface::class);

        $this->modelManager->expects($this->any())
            ->method('getNewFieldDescriptionInstance')
            ->will($this->returnCallback(function ($class, $name, array $options = []) {
                $fieldDescription = $this->getFieldDescriptionMock();
                $fieldDescription->setName($name);
                $fieldDescription->setOptions($options);

                return $fieldDescription;
            }));

        $this->admin->setModelManager($this->modelManager);

        $labelTranslatorStrategy = $this->getMockForAbstractClass(LabelTranslatorStrategyInterface::class);
        $this->admin->setLabelTranslatorStrategy($labelTranslatorStrategy);

        $this->formMapper = new FormMapper(
            $this->contractor,
            $formBuilder,
            $this->admin
        );
    }

    public function testWithNoOptions()
    {
        $this->formMapper->with('foobar');

        $this->assertSame(['default' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'default',
            'translation_domain' => null,
            'name' => 'default',
            'box_class' => 'box box-primary',
            'auto_created' => true,
            'groups' => ['foobar'],
            'tab' => true,
        ]], $this->admin->getFormTabs());

        $this->assertSame(['foobar' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'foobar',
            'translation_domain' => null,
            'name' => 'foobar',
            'box_class' => 'box box-primary',
            'fields' => [],
        ]], $this->admin->getFormGroups());
    }

    public function testWithOptions()
    {
        $this->formMapper->with('foobar', [
            'translation_domain' => 'Foobar',
        ]);

        $this->assertSame(['foobar' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'foobar',
            'translation_domain' => 'Foobar',
            'name' => 'foobar',
            'box_class' => 'box box-primary',
            'fields' => [],
        ]], $this->admin->getFormGroups());

        $this->assertSame(['default' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'default',
            'translation_domain' => 'Foobar',
            'name' => 'default',
            'box_class' => 'box box-primary',
            'auto_created' => true,
            'groups' => ['foobar'],
            'tab' => true,
        ]], $this->admin->getFormTabs());
    }

    public function testWithFieldsCascadeTranslationDomain()
    {
        $this->contractor->expects($this->once())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper->with('foobar', [
                'translation_domain' => 'Foobar',
            ])
            ->add('foo', 'bar')
        ->end();

        $fieldDescription = $this->admin->getFormFieldDescription('foo');
        $this->assertSame('foo', $fieldDescription->getName());
        $this->assertSame('bar', $fieldDescription->getType());
        $this->assertSame('Foobar', $fieldDescription->getTranslationDomain());

        $this->assertTrue($this->formMapper->has('foo'));

        $this->assertSame(['default' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'default',
            'translation_domain' => 'Foobar',
            'name' => 'default',
            'box_class' => 'box box-primary',
            'auto_created' => true,
            'groups' => ['foobar'],
            'tab' => true,
        ]], $this->admin->getFormTabs());

        $this->assertSame(['foobar' => [
            'collapsed' => false,
            'class' => false,
            'description' => false,
            'label' => 'foobar',
            'translation_domain' => 'Foobar',
            'name' => 'foobar',
            'box_class' => 'box box-primary',
            'fields' => [
                'foo' => 'foo',
            ],
        ]], $this->admin->getFormGroups());
    }

    public function testRemoveCascadeRemoveFieldFromFormGroup()
    {
        $this->formMapper->with('foo');
        $this->formMapper->remove('foo');
    }

    public function testIfTrueApply()
    {
        $this->contractor->expects($this->once())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->ifTrue(true)
            ->add('foo', 'bar')
            ->ifEnd()
        ;

        $this->assertTrue($this->formMapper->has('foo'));
    }

    public function testIfTrueNotApply()
    {
        $this->formMapper
            ->ifTrue(false)
            ->add('foo', 'bar')
            ->ifEnd()
        ;

        $this->assertFalse($this->formMapper->has('foo'));
    }

    public function testIfTrueCombination()
    {
        $this->contractor->expects($this->once())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->ifTrue(false)
            ->add('foo', 'bar')
            ->ifEnd()
            ->add('baz', 'foobaz')
        ;

        $this->assertFalse($this->formMapper->has('foo'));
        $this->assertTrue($this->formMapper->has('baz'));
    }

    public function testIfFalseApply()
    {
        $this->contractor->expects($this->once())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->ifFalse(false)
            ->add('foo', 'bar')
            ->ifEnd()
        ;

        $this->assertTrue($this->formMapper->has('foo'));
    }

    public function testIfFalseNotApply()
    {
        $this->formMapper
            ->ifFalse(true)
            ->add('foo', 'bar')
            ->ifEnd()
        ;

        $this->assertFalse($this->formMapper->has('foo'));
    }

    public function testIfFalseCombination()
    {
        $this->contractor->expects($this->once())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->ifFalse(true)
            ->add('foo', 'bar')
            ->ifEnd()
            ->add('baz', 'foobaz')
        ;

        $this->assertFalse($this->formMapper->has('foo'));
        $this->assertTrue($this->formMapper->has('baz'));
    }

    public function testIfTrueNested()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifTrue(true);
        $this->formMapper->ifTrue(true);
    }

    public function testIfFalseNested()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifFalse(false);
        $this->formMapper->ifFalse(false);
    }

    public function testIfCombinationNested()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifTrue(true);
        $this->formMapper->ifFalse(false);
    }

    public function testIfFalseCombinationNested2()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifFalse(false);
        $this->formMapper->ifTrue(true);
    }

    public function testIfFalseCombinationNested3()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifFalse(true);
        $this->formMapper->ifTrue(false);
    }

    public function testIfFalseCombinationNested4()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Cannot nest ifTrue or ifFalse call');

        $this->formMapper->ifTrue(false);
        $this->formMapper->ifFalse(true);
    }

    public function testAddAcceptFormBuilder()
    {
        $formBuilder = $this
            ->getMockBuilder(FormBuilder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $formBuilder->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $formType = $this
            ->getMockBuilder(ResolvedFormTypeInterface::class)
            ->getMock();

        $innerType = $this
            ->getMockBuilder(FormType::class)
            ->getMock();

        $formType->expects($this->once())
            ->method('getInnerType')
            ->will($this->returnValue($innerType));

        $formBuilder->expects($this->once())
            ->method('getType')
            ->will($this->returnValue($formType));

        $this->formMapper->add($formBuilder);
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
    }

    public function testAddFormBuilderWithType()
    {
        $formBuilder = $this
            ->getMockBuilder(FormBuilder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $formBuilder->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $formBuilder->expects($this->never())
            ->method('getType');

        $this->formMapper->add($formBuilder, FormType::class);
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
    }

    public function testGroupRemovingWithoutTab()
    {
        $this->formMapper->with('foobar');

        $this->formMapper->removeGroup('foobar');

        $this->assertSame([], $this->admin->getFormGroups());
    }

    public function testGroupRemovingWithTab()
    {
        $this->formMapper->tab('mytab')->with('foobar');

        $this->formMapper->removeGroup('foobar', 'mytab');

        $this->assertSame([], $this->admin->getFormGroups());
    }

    public function testGroupRemovingWithoutTabAndWithTabRemoving()
    {
        $this->formMapper->with('foobar');

        $this->formMapper->removeGroup('foobar', 'default', true);

        $this->assertSame([], $this->admin->getFormGroups());
        $this->assertSame([], $this->admin->getFormTabs());
    }

    public function testGroupRemovingWithTabAndWithTabRemoving()
    {
        $this->formMapper->tab('mytab')->with('foobar');

        $this->formMapper->removeGroup('foobar', 'mytab', true);

        $this->assertSame([], $this->admin->getFormGroups());
        $this->assertSame([], $this->admin->getFormTabs());
    }

    public function testKeys()
    {
        $this->contractor->expects($this->any())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->add('foo', 'bar')
            ->add('baz', 'foobaz')
        ;

        $this->assertSame(['foo', 'baz'], $this->formMapper->keys());
    }

    public function testFieldNameIsSanitized()
    {
        $this->contractor->expects($this->any())
            ->method('getDefaultOptions')
            ->will($this->returnValue([]));

        $this->formMapper
            ->add('fo.o', 'bar')
            ->add('ba__z', 'foobaz')
        ;

        $this->assertSame(['fo__o', 'ba____z'], $this->formMapper->keys());
    }

    private function getFieldDescriptionMock($name = null, $label = null, $translationDomain = null)
    {
        $fieldDescription = $this->getMockForAbstractClass(BaseFieldDescription::class);

        if (null !== $name) {
            $fieldDescription->setName($name);
        }

        if (null !== $label) {
            $fieldDescription->setOption('label', $label);
        }

        if (null !== $translationDomain) {
            $fieldDescription->setOption('translation_domain', $translationDomain);
        }

        return $fieldDescription;
    }
}


text:
package org.gradle.api.internal.file;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import groovy.lang.Closure;
import org.apache.commons.lang.StringUtils;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.internal.file.collections.DirectoryFileTree;
import org.gradle.api.internal.file.collections.FileBackedDirectoryFileTree;
import org.gradle.api.internal.file.collections.FileCollectionResolveContext;
import org.gradle.api.internal.file.collections.ResolvableFileCollectionResolveContext;
import org.gradle.api.internal.tasks.TaskDependencyResolveContext;
import org.gradle.api.specs.Spec;
import org.gradle.api.specs.Specs;
import org.gradle.api.tasks.TaskDependency;
import org.gradle.util.CollectionUtils;
import org.gradle.util.GUtil;

import javax.annotation.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public abstract class AbstractFileCollection implements FileCollectionInternal {
    /**
     * Returns the display name of this file collection. Used in log and error messages.
     *
     * @return the display name
     */
    public abstract String getDisplayName();

    @Override
    public String toString() {
        return getDisplayName();
    }

    @Override
    public File getSingleFile() throws IllegalStateException {
        Iterator<File> iterator = iterator();
        if (!iterator.hasNext()) {
            throw new IllegalStateException(String.format("Expected %s to contain exactly one file, however, it contains no files.", getDisplayName()));
        }
        File singleFile = iterator.next();
        if (iterator.hasNext()) {
            throw new IllegalStateException(String.format("Expected %s to contain exactly one file, however, it contains more than one file.", getDisplayName()));
        }
        return singleFile;
    }

    @Override
    public Iterator<File> iterator() {
        return getFiles().iterator();
    }

    @Override
    public String getAsPath() {
        return GUtil.asPath(this);
    }

    @Override
    public boolean contains(File file) {
        return getFiles().contains(file);
    }

    @Override
    public FileCollection plus(FileCollection collection) {
        return new UnionFileCollection(this, collection);
    }

    @Override
    public FileCollection minus(final FileCollection collection) {
        return new AbstractFileCollection() {
            @Override
            public String getDisplayName() {
                return AbstractFileCollection.this.getDisplayName();
            }

            @Override
            public TaskDependency getBuildDependencies() {
                return AbstractFileCollection.this.getBuildDependencies();
            }

            @Override
            public Set<File> getFiles() {
                Set<File> files = new LinkedHashSet<File>(AbstractFileCollection.this.getFiles());
                files.removeAll(collection.getFiles());
                return files;
            }

            @Override
            public boolean contains(File file) {
                return AbstractFileCollection.this.contains(file) && !collection.contains(file);
            }
        };
    }

    @Override
    public void addToAntBuilder(Object builder, String nodeName, AntType type) {
        if (type == AntType.ResourceCollection) {
            addAsResourceCollection(builder, nodeName);
        } else if (type == AntType.FileSet) {
            addAsFileSet(builder, nodeName);
        } else {
            addAsMatchingTask(builder, nodeName);
        }
    }

    protected void addAsMatchingTask(Object builder, String nodeName) {
        new AntFileCollectionMatchingTaskBuilder(getAsFileTrees()).addToAntBuilder(builder, nodeName);
    }

    protected void addAsFileSet(Object builder, String nodeName) {
        new AntFileSetBuilder(getAsFileTrees()).addToAntBuilder(builder, nodeName);
    }

    protected void addAsResourceCollection(Object builder, String nodeName) {
        new AntFileCollectionBuilder(this).addToAntBuilder(builder, nodeName);
    }

    /**
     * Returns this collection as a set of {@link DirectoryFileTree} instances.
     */
    protected Collection<DirectoryFileTree> getAsFileTrees() {
        List<DirectoryFileTree> fileTrees = new ArrayList<DirectoryFileTree>();
        for (File file : this) {
            if (file.isFile()) {
                fileTrees.add(new FileBackedDirectoryFileTree(file));
            }
        }
        return fileTrees;
    }

    @Override
    public Object addToAntBuilder(Object node, String childNodeName) {
        addToAntBuilder(node, childNodeName, AntType.ResourceCollection);
        return this;
    }

    @Override
    public boolean isEmpty() {
        return getFiles().isEmpty();
    }

    @Override
    public FileTree getAsFileTree() {
        return new CompositeFileTree() {
            @Override
            public void visitContents(FileCollectionResolveContext context) {
                ResolvableFileCollectionResolveContext nested = context.newContext();
                nested.add(AbstractFileCollection.this);
                context.add(nested.resolveAsFileTrees());
            }

            @Override
            public void visitDependencies(TaskDependencyResolveContext context) {
                context.add(AbstractFileCollection.this);
            }

            @Override
            public String getDisplayName() {
                return AbstractFileCollection.this.getDisplayName();
            }
        };
    }

    @Override
    public FileCollection filter(Closure filterClosure) {
        return filter(Specs.convertClosureToSpec(filterClosure));
    }

    @Override
    public FileCollection filter(final Spec<? super File> filterSpec) {
        final Predicate<File> predicate = new Predicate<File>() {
            @Override
            public boolean apply(@Nullable File input) {
                return filterSpec.isSatisfiedBy(input);
            }
        };
        return new AbstractFileCollection() {
            @Override
            public String getDisplayName() {
                return AbstractFileCollection.this.getDisplayName();
            }

            @Override
            public TaskDependency getBuildDependencies() {
                return AbstractFileCollection.this.getBuildDependencies();
            }

            @Override
            public Set<File> getFiles() {
                return CollectionUtils.filter(AbstractFileCollection.this, new LinkedHashSet<File>(), filterSpec);
            }

            @Override
            public boolean contains(File file) {
                return AbstractFileCollection.this.contains(file) && predicate.apply(file);
            }

            @Override
            public Iterator<File> iterator() {
                return Iterators.filter(AbstractFileCollection.this.iterator(), predicate);
            }
        };
    }

    protected String getCapDisplayName() {
        return StringUtils.capitalize(getDisplayName());
    }

    @Override
    public void visitLeafCollections(FileCollectionLeafVisitor visitor) {
        visitor.visitCollection(this);
    }

    @Override
    public void registerWatchPoints(FileSystemSubset.Builder builder) {
        for (File file : this) {
            builder.add(file);
        }
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: chaosin
 * Date: 02.10.12
 * Time: 9:25
 * To change this template use File | Settings | File Templates.
 */
class ValidatorOldPassword extends sfValidatorSchema
{
    public function __construct($newpass, $oldpass, $options = array(), $messages = array())
    {
        $this->addOption('newpass', $newpass);
        $this->addOption('oldpass', $oldpass);

        $this->addOption('throw_global_error', false);

        parent::__construct(null, $options, $messages);
    }

    /**
     * @see sfValidatorBase
     */
    protected function doClean($values)
    {
        if (is_null($values))
        {
            $values = array();
        }

        if (!is_array($values))
        {
            throw new InvalidArgumentException('You must pass an array parameter to the clean() method');
        }

        $newpass = isset($values[$this->getOption('newpass')]) ? $values[$this->getOption('newpass')] : null;
        $oldpass = isset($values[$this->getOption('oldpass')]) ? $values[$this->getOption('oldpass')] : null;

        $valid = false;

        if( $newpass != '' && $newpass != null)
        {
            if ($oldpass != null && $oldpass != '')
            {
                $user = sfContext::getInstance()->getUser()->getGuardUser();
                if (!$user->checkPassword($oldpass))
                {
                    $error = new sfValidatorError($this, 'Invalid password', array('oldpass'  => $oldpass));

                    if ($this->getOption('throw_global_error'))
                    {
                        throw $error;
                    }

                    throw new sfValidatorErrorSchema($this, array($this->getOption('oldpass') => $error));
                }
            }
            else
            {
                $error = new sfValidatorError($this, 'Required', array('oldpass'  => $oldpass));

                if ($this->getOption('throw_global_error'))
                {
                    throw $error;
                }

                throw new sfValidatorErrorSchema($this, array($this->getOption('oldpass') => $error));
            }

        }
        return $values;
    }
}


text:
/*
 * terminal.h
 *
 *  Created on: Jan 15, 2013
 *      Author: peterryszkiewicz
 *
 *      Terminal interface. No implementation details.
 */

#ifndef TERMINAL_H_
#define TERMINAL_H_

#include <string>
#include <vector>

/* terminal_interface describes the interface the use has for the terminal.
 * The pure virtual functions must be implemented.
 */
class terminal_interface {
public:
	virtual ~terminal_interface() {}
	virtual bool string_push_back(const std::string&)=0;
	virtual bool print_terminal() const =0;
	virtual bool adjust_terminal_view(const int&)=0;
	virtual void adjust_terminal_position(const int&, const int&, const int&)=0;

};

// terminal_type implements terminal_interface
class terminal_type : public terminal_interface {
public:
	terminal_type(); // default constructor
	terminal_type(const int& size, const int& x, const int& y); // constructor taking terminal position and size
	~terminal_type(); // destructor
	bool string_push_back(const std::string&);
	bool print_terminal() const;
	bool adjust_terminal_view(const int& offset);
	void adjust_terminal_position(const int& size, const int& x, const int& y); // must call when display changes

private:
	typedef std::vector<std::string> content_t;
	typedef std::vector<std::string>::size_type content_index;
	content_t content;
	content_index top; // index of highest element to be shown in terminal
	content_index bottom; // index of lowest element + 1 to be shown in terminal
	int terminal_view_size;
	int terminal_view_X;
	int terminal_view_Y;
};

#endif /* TERMINAL_H_ */


text:
var express = require('express')
  , path = require('path')
  , app = express() // Web framework to handle routing requests
  , cons = require('consolidate') // Templating library adapter for Express
  , MongoClient = require('mongodb').MongoClient // Driver for connecting to MongoDB

  MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {
    "use strict";
    if(err) throw err;

    // Register our templating engine
    app.engine('html', cons.swig);
    app.set('view engine', 'html');
    app.set('views', __dirname + '/views');

    // Express middleware to populate 'req.cookies' so we can access cookies
    app.use(express.cookieParser());

    // Express middleware to populate 'req.body' so we can access POST variables
    app.use(express.bodyParser());

    app.use(express.static(path.join(__dirname, 'views')));

    // Application routes

    app.listen(8082);
    console.log('Express server listening on port 8082');
});


text:
namespace WindowsIoTDashboard.App.Pages
{
    public sealed partial class ProcessesPage : BasePage
    {
        public ProcessesPage()
        {
            this.InitializeComponent();
        }
    }
}


text:
module AudioFingerprint
	VERSION = "0.0.1"
end


text:
package de.dakror.vloxlands.ui;

import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;

import de.dakror.vloxlands.Vloxlands;
import de.dakror.vloxlands.game.world.Island;

/**
 * @author Dakror
 */
public class MinimapIsland extends Actor {
	Island island;
	boolean active;

	public MinimapIsland(Island island) {
		this.island = island;
	}

	@Override
	public Actor hit(float x, float y, boolean touchable) {
		if (touchable && getTouchable() != Touchable.enabled) return null;
		return x >= getWidth() / 4 && x < getWidth() / 4 * 3 && y >= 0 && y < getHeight() ? this : null;
	}

	@Override
	public void draw(Batch batch, float parentAlpha) {
		if (island.fbo != null) {
			if (active) {
				Drawable d = Vloxlands.skin.getDrawable("outline");
				d.draw(batch, (int) (getX() + getWidth() / 4), (int) getY(), (int) getWidth() / 2, (int) getHeight());
			}
			batch.draw(island.fbo.getColorBufferTexture(), getX(), getY(), getWidth(), getHeight(), 0, 0, island.fbo.getColorBufferTexture().getWidth(), island.fbo.getColorBufferTexture().getHeight(), false, true);
		}
	}
}


text:
author: slowe
categories: News
comments: true
date: 2008-03-17T12:40:24Z
slug: vmware-workstation-update
tags:
- Virtualization
- VMware
title: VMware Workstation Update
url: /2008/03/17/vmware-workstation-update/
wordpress_id: 661
---

Via Tarry at [Virtualization for Everyone](http://tarrysingh.blogspot.com/2008/03/vmware-workstation-603-released.html) (and numerous others), I saw that VMware has updated VMware Workstation to version 6.0.3, which is primarily an update release to address various security issues and add a few new features. More information is available [here](http://www.vmware.com/support/ws6/doc/releasenotes_ws6.html).


text:
module ThorTemplate::Help
  class << self
    def text(namespaced_command)
      path = namespaced_command.to_s.gsub(':','/')
      path = File.expand_path("../help/#{path}.md", __FILE__)
      IO.read(path) if File.exist?(path)
    end
  end
end


text:
/***************** MAXIMUM SINGLE-SELL PROFIT **************/

// Serial version: Dynamic programming
float max_profit_serial( const float *data, const size_t num_prices)
{
float profit = 0.0f;
float cheapest = data[0];
int i;
for(i=0 ; i<num_prices ; i++)
{
	cheapest = std::min(cheapest , data[i]);
	profit   = std::max(profit , data[i] - cheapest); // Updating the max profit
}
return profit;
}

// Muli-threaded version : OpenMP
float max_profit_omp (const float * const data, const int num_prices , const int nthreads)
{
  float maxes[nthreads];
  float mins [nthreads];
  float profit = 0.0f;

  for (int i=0; i<nthreads; i++)
  {
    mins [i] = FLT_MAX;
    maxes[i] = FLT_MIN;
  }

  /*
   * 1- Iterations of the parallel loop will be distributed in equal sized blocks
   *    to each thread in the team [schedule static].
   * 2- maxes and mins are shared among all threads.
   */
  #pragma omp parallel num_threads(nthreads) default(none) shared(mins, maxes) reduction(max:profit)
  {
      int index = omp_get_thread_num();
      float min = FLT_MAX, max = FLT_MIN;

      #pragma omp for schedule(static)	// In compile time
      for(int i=0; i < num_prices; i++)
      {
        if (data[i] < min) min=data[i];
        if (data[i] > max) max=data[i];
        if ((data[i] - min) > profit) profit = data[i] - min;
      }
      mins [index] = min;
      maxes[index] = max;
  }

  for (int i=0; i < nthreads-1; i++)
    for (int j=i+1; j < nthreads; j++)
        if ((maxes[j] - mins[i]) > profit) profit = maxes[j]-mins[i];

  return profit;
}


text:
package core.framework.cache;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;

/**
 * @author neo
 */
public interface Cache<T> {
    // loader must not return null, use wrapper class if it is necessary to cache null value
    // for performance reason, it does not copy the object returned by local cache, so it must not modify local cache object unless to put it back
    T get(String key, Function<String, T> loader);

    Map<String, T> getAll(Collection<String> keys, Function<String, T> loader);

    void put(String key, T value);

    void putAll(Map<String, T> values);

    void evict(String key);

    void evictAll(Collection<String> keys);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="contact">Têkilî</string>
  <string name="contactLichess">Bi Lichess ra bikeve têkiliyê</string>
  <string name="whatCanWeHelpYouWith">Em dikarin çawa alîkarîya we bikin?</string>
  <string name="iCantLogIn">Ez nikarim têkevim</string>
  <string name="forgotPassword">Min pêborînê bîr ve kir</string>
  <string name="forgotUsername">Min navê bikarhênerê bîr ve kir</string>
  <string name="wantCloseAccount">Ez dixwazim hesabê xwe bigirim</string>
  <string name="closeYourAccount">Tu dikarî hesabê xwe li vû rûpelê bigirî</string>
  <string name="doNotAskByEmail">Ji bo hesab girtinê ji me ra emaîl neşeynin, em ê nekin.</string>
  <string name="wantReopen">Ez dixwazim hesabê xwe ji nû ve vekim</string>
  <string name="reopenOnThisPage">Tu dikarî hesabê xwe li vê rûpelê ji nû ve vekî. Tenê carekî dikarî vê bikî.</string>
  <string name="doNotAskByEmailToReopen">Ji bo hesab ji nû ve vekirinê ji me ra emaîl neşeynin, em ê nekin.</string>
  <string name="wantChangeUsername">Ez dixwazim navê bikarhênerê biguherînim</string>
  <string name="changeUsernameCase">Ji bo guhertina navê bikarhênerê here vê rûpelê</string>
  <string name="orCloseAccount">Lê, tu dikarî hesabê xwe yê niha bigirî û hesabekî nû çê bikî.</string>
</resources>


text:
FOUNDATION_EXPORT NSNotificationName ABI42_0_0EXTestSuiteCompletedNotification;

typedef enum ABI42_0_0EXTestEnvironment {
  ABI42_0_0EXTestEnvironmentNone = 0,
  ABI42_0_0EXTestEnvironmentLocal = 1,
  ABI42_0_0EXTestEnvironmentCI = 2,
} ABI42_0_0EXTestEnvironment;

@interface ABI42_0_0EXTest : NSObject <ABI42_0_0RCTBridgeModule>

- (instancetype)initWithEnvironment:(ABI42_0_0EXTestEnvironment)environment NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;

+ (ABI42_0_0EXTestEnvironment)testEnvironmentFromString:(NSString *)testEnvironmentString;

@end


text:
<!DOCTYPE html>

    <title>Bootswatch: Default Bootstrap</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="../amelia/bootstrap.css" media="screen" id="stylesheet">
    <link rel="stylesheet" href="../bower_components/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../assets/css/bootswatch.min.css">

          Bootswatch
          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">

          </button>

              Themes

Default

Amelia

Cerulean

Cosmo

Cyborg

Flatly

Journal

Readable

Simplex

Slate

Spacelab

United

              Download

bootstrap.min.css

bootstrap.css

variables.less

bootswatch.less

              Help

              Blog

Amelia

Sweet and cheery

              <button type="button" class="btn btn-default">Default</button>
              <button type="button" class="btn btn-primary">Primary</button>
              <button type="button" class="btn btn-success">Success</button>
              <button type="button" class="btn btn-info">Info</button>
              <button type="button" class="btn btn-warning">Warning</button>
              <button type="button" class="btn btn-danger">Danger</button>


text:
#ifndef WorkerGlobalScopeProxy_h
#define WorkerGlobalScopeProxy_h

#if ENABLE(WORKERS)

#include "MessagePort.h"
#include "WorkerThread.h"
#include <wtf/Forward.h>
#include <wtf/PassOwnPtr.h>

namespace WebCore {

    class KURL;
    class Worker;

    // A proxy to talk to the worker context.
    class WorkerGlobalScopeProxy {
    public:
        static WorkerGlobalScopeProxy* create(Worker*);

        virtual ~WorkerGlobalScopeProxy() { }

        virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0;

        virtual void terminateWorkerGlobalScope() = 0;

        virtual void postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) = 0;

        virtual bool hasPendingActivity() const = 0;

        virtual void workerObjectDestroyed() = 0;

        virtual void notifyNetworkStateChange(bool isOnline) = 0;

#if ENABLE(INSPECTOR)
        class PageInspector {
        public:
            virtual ~PageInspector() { }
            virtual void dispatchMessageFromWorker(const String&) = 0;
        };
        virtual void connectToInspector(PageInspector*) { }
        virtual void disconnectFromInspector() { }
        virtual void sendMessageToInspector(const String&) { }
#endif
    };

} // namespace WebCore

#endif // ENABLE(WORKERS)

#endif // WorkerGlobalScopeProxy_h


text:
require 'spec_helper'

describe GeojsonModel::Feature do

  describe 'InstanceMethods' do

    describe 'type' do

      it 'is of type String' do
        expect(subject.type).to be_a(String)
      end

      it 'is set by default' do
        expect(subject.type).to eq('Feature')
      end
    end

    describe 'geometry' do

      it 'is of type GeojsonModel::Geometry' do
        subject.geometry = {}
        expect(subject.geometry).to be_a(GeojsonModel::Geometry)
      end
    end

    describe 'properties' do

      it 'is of type Hash' do
        expect(subject.properties).to be_a(Hash)
      end
    end

    describe 'to_geometry' do

      it 'is of type Geometry' do
        expect(subject.to_geometry).to be_a(GeojsonModel::Geometry)
      end
    end
  end
end