text:
/**
 * \file
 * \brief Capability invocations specific to the monitors
 */

/*
 * Copyright (c) 2007-2016, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstr 6, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef MONITOR_INVOCATIONS_ARCH_H
#define MONITOR_INVOCATIONS_ARCH_H

#include <barrelfish/syscall_arch.h>
#include <barrelfish/caddr.h>
#include <barrelfish/invocations_arch.h>

static inline errval_t
invoke_monitor_create_cap(uint64_t *raw, capaddr_t caddr, int level, capaddr_t slot, coreid_t owner)
{
    assert(sizeof(struct capability) <= 3*sizeof(uint64_t));
    return cap_invoke8(cap_kernel, KernelCmd_Create_cap,
                       raw[0], raw[1], raw[2],
                       caddr, level, slot, owner).error;
}

static inline errval_t
invoke_monitor_remote_cap_retype(capaddr_t src_root, capaddr_t src, gensize_t offset,
                                 enum objtype newtype, gensize_t objsize, size_t count,
                                 capaddr_t to_cspace,  capaddr_t to, capaddr_t slot,
                                 int level) {
    return cap_invoke9(cap_kernel, KernelCmd_Retype,
                       ((uint64_t)src_root << 32) | (uint64_t)src,
                       offset, newtype, objsize, count,
                       ((uint64_t)to_cspace << 32) | (uint64_t)to,
                       slot, level).error;
}

static inline errval_t
invoke_monitor_copy_existing(uint64_t *raw, capaddr_t croot_addr, capaddr_t cn_addr,
                             int cn_level, cslot_t slot)
{
    assert(sizeof(struct capability) <= 3*sizeof(uint64_t));
    return cap_invoke8(cap_kernel, KernelCmd_Copy_existing,
                       raw[0], raw[1], raw[2],
                       croot_addr, cn_addr, cn_level, slot).error;
}

/**
 * \brief Set up tracing in the kernel
 *
 */
static inline errval_t
invoke_trace_setup(struct capref cap)
{
    return cap_invoke2(cap_kernel, KernelCmd_Setup_trace,
                       get_cap_addr(cap)).error;
}

static inline errval_t
invoke_domain_id(struct capref cap, domainid_t domain_id)
{
    return cap_invoke3(cap_kernel, KernelCmd_Domain_Id, get_cap_addr(cap),
                       domain_id).error;
}

static inline errval_t invoke_monitor_sync_timer(uint64_t synctime)
{
    return cap_invoke2(cap_kernel, KernelCmd_Sync_timer, synctime).error;
}

static inline errval_t
invoke_monitor_revoke_mark_relations(uint64_t *raw_base)
{
    assert(sizeof(struct capability) <= 3*sizeof(uint64_t));
    return cap_invoke4(cap_kernel, KernelCmd_Revoke_mark_relations,
                       raw_base[0], raw_base[1], raw_base[2]).error;
}

static inline errval_t
invoke_monitor_has_descendants(uint64_t *raw, bool *res)
{
    assert(sizeof(struct capability) <= 3*sizeof(uint64_t));
    struct sysret sysret;
    sysret = cap_invoke4(cap_kernel, KernelCmd_Has_descendants,
                         raw[0], raw[1], raw[2]);
    if (err_is_ok(sysret.error)) {
        *res = sysret.value;
    }
    return sysret.error;
}

static inline errval_t
invoke_monitor_is_retypeable(uint64_t *raw, gensize_t offset,
                             gensize_t objsize, size_t count)
{
    assert(sizeof(struct capability) <= 3*sizeof(uint64_t));
    return cap_invoke7(cap_kernel, KernelCmd_Is_retypeable,
                       raw[0], raw[1], raw[2], offset, objsize, count).error;
}

#endif


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stallone.api.datasequence;

import java.io.IOException;
import java.util.List;

/**
 *
 * Interface for loaders that retrieve DataSequences (e.g. trajectories)
 * from file systems or data bases. Shields the usage of this data from the
 * file / database access in order to efficiently deal with slow loading times,
 * while at the same time keeping the memory and file handle usage low.
 *
 * @author noe
 */
public interface IDataSequenceLoader extends IDataInput
{
    //public void setLoader(IDataReader loader);

    /**
     * Adds a link to a file or data base entry of a data sequence
     * @param link filename or URL
     */
    //public void addSource(String link);

    /**
     * Scans all files or data base entries.
     * This method needs to be called before any of the info methods (size, memorySize...) can be called.
     * Scan will also check the file consistency, make sure that all source files have the same dimensionality
     * and can be successfully read.
     * It is not necessary to scan before using one of the iterables below, but in this case there is
     * no guarantee that the iterable won't crash at a file inconsistency.
     */
    public void scan()
            throws IOException;

    /**
     * Memory requirement for the given sequence. Need to scan() first before calling this method.
     */
    public long memorySizeOfSingleSequence(int index);

    /**
     * Memory requirement for the largest single sequence. Need to scan() first before calling this method.
     */
    public long memorySizeOfLargestSequence();

    /**
     * The entire subset, as given by the index set is loaded and returned. Need to scan() first before calling this method.
     * @param indexes nx2 array with trajectory and within-trajectory indexes
     * @return
     */
    //public IDataSequences loadSubset(IIntArray indexes)
    //        throws IOException;

    /**
     * Memory requirement for everything. Need to scan() first before calling this method.
     */
    public long memorySizeTotal();

    /**
     * Load a single data sequence. Does not require scan() to be called.
     * @param sequenceIndex
     * @return
     * @throws IOException
     */
    public IDataSequence loadSequence(int sequenceIndex);

    /**
     * Loads everything into memory. Does not require scan() to be called.
     * @return
     */
    public IDataInput loadAll();
}

redpajama_set_name: RedPajamaGithub


text:
namespace bp = boost::python;

void register_vector_less__osgUtil_scope_Hit__greater__class(){

    { //::std::vector< osgUtil::Hit >
        typedef bp::class_< std::vector< osgUtil::Hit > > vector_less__osgUtil_scope_Hit__greater__exposer_t;
        vector_less__osgUtil_scope_Hit__greater__exposer_t vector_less__osgUtil_scope_Hit__greater__exposer = vector_less__osgUtil_scope_Hit__greater__exposer_t( "vector_less__osgUtil_scope_Hit__greater_" );
        bp::scope vector_less__osgUtil_scope_Hit__greater__scope( vector_less__osgUtil_scope_Hit__greater__exposer );
        vector_less__osgUtil_scope_Hit__greater__exposer.def( bp::indexing::vector_suite< std::vector< osgUtil::Hit > >() );
    }

}


text:
package org.bib.tbase.domain.user;

import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.querydsl.core.types.Predicate;

public class RolePredicates {
// Constructors

// Public Methods
	/**
	 * Role name matches one of the argument role names.
	 * @param roleNames Strings representing role names
	 * @return A Predicate instance, never null
	 */
	public static Predicate roleNameIn(String ... roleNames) {
		return QRole.role.name.toUpperCase().in(Collections2.transform(Arrays.asList(roleNames), new Function<String, String>() {
			@Override
			public String apply(String input) {
				return StringUtils.upperCase(input);
			}

		}));
	}

	/**
	 * Role name equals argument roleName (ignore case)
	 * @param roleName The role name, may be empty/null
	 * @return A Predicate
	 */
	public static Predicate roleNameEq(String roleName) {
		return QRole.role.name.equalsIgnoreCase(roleName);
	}

// Getters & Setters

// Attributes
	/**
	 * Serialziation
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Logger
	 */
	private static final Logger logger = LogManager.getLogger(RolePredicates.class);
}


text:
<?php

namespace Roots\Sage\Setup;

use Roots\Sage\Assets;

/**
 * Theme setup
 */
function setup() {
  // Enable features from Soil when plugin is activated
  // https://roots.io/plugins/soil/
  add_theme_support('soil-clean-up');
  add_theme_support('soil-nav-walker');
  add_theme_support('soil-nice-search');
  add_theme_support('soil-jquery-cdn');
  add_theme_support('soil-relative-urls');

  // Make theme available for translation
  // Community translations can be found at https://github.com/roots/sage-translations
  load_theme_textdomain('sage', get_template_directory() . '/lang');

  // Enable plugins to manage the document title
  // http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag
  add_theme_support('title-tag');

  // Register wp_nav_menu() menus
  // http://codex.wordpress.org/Function_Reference/register_nav_menus
  register_nav_menus([
    'primary_navigation' => __('Navigation principale', 'cdrm')
  ]);
  register_nav_menus([
    'link' => __('Liens utiles', 'cdrm')
  ]);

  // Enable post thumbnails
  // http://codex.wordpress.org/Post_Thumbnails
  // http://codex.wordpress.org/Function_Reference/set_post_thumbnail_size
  // http://codex.wordpress.org/Function_Reference/add_image_size
  add_theme_support('post-thumbnails');
  add_image_size( 'event', 400, 300, true );

  // Enable post formats
  // http://codex.wordpress.org/Post_Formats
  //add_theme_support('post-formats', ['aside', 'gallery', 'link', 'image', 'quote', 'video', 'audio']);

  // Enable HTML5 markup support
  // http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5
  //add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);

  // Use main stylesheet for visual editor
  // To add custom styles edit /assets/styles/layouts/_tinymce.scss
  add_editor_style(Assets\asset_path('styles/main.css'));
}
add_action('after_setup_theme', __NAMESPACE__ . '\\setup');

/**
 * Register sidebars
 */
function widgets_init() {
  register_sidebar([
    'name'          => 'Sidebar agenda',
    'id'            => 'sidebar-event',
    'before_widget' => '
',
    'after_widget'  => '

',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);

  register_sidebar([
    'name'          => 'Sidebar actualités',
    'id'            => 'sidebar-post',
    'before_widget' => '
',
    'after_widget'  => '

',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);

  register_sidebar([
    'name'          => __('Footer', 'sage'),
    'id'            => 'sidebar-footer',
    'before_widget' => '
',
    'after_widget'  => '
',
    'before_title'  => '
',
    'after_title'   => '
'
  ]);
}
add_action('widgets_init', __NAMESPACE__ . '\\widgets_init');

/**
 * Determine which pages should NOT display the sidebar
 */
function display_sidebar() {
  static $display;

  isset($display) || $display = !in_array(true, [
    // The sidebar will NOT be displayed if ANY of the following return true.
    // @link https://codex.wordpress.org/Conditional_Tags
    is_404(),
    is_front_page(),
    is_page() && !is_page_template('page-archives.php'),
    is_page_template('template-custom.php'),

  ]);

  return apply_filters('sage/display_sidebar', $display);
}

/**
 * Theme assets
 */
function assets() {
  wp_enqueue_style('sage/css', Assets\asset_path('styles/main.css'), false, null);

  if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
  }

  wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), ['jquery'], null, true);
  wp_enqueue_script('menu/js', Assets\asset_path('scripts/menu.js'), array(), null, true);
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100);


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import userListComponent from './userList.component';

let userListModule = angular.module('userList', [
  uiRouter
])

.component('userList', userListComponent)

.name;

export default userListModule;


text:
package server

import (
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	log "github.com/Sirupsen/logrus"
)

// StartPluginAtPath starts an HTTP server listening on a unix socket at the specified path.
// Returns a channel to signal stop when closed, a channel to block on stopping, and an error if occurs.
func StartPluginAtPath(socketPath string, endpoint http.Handler) (chan<- struct{}, <-chan error, error) {
	log.Infoln("Listening at:", socketPath)

	engineStop, engineStopped, err := runHTTP(socketPath, &http.Server{Handler: endpoint, Addr: socketPath})
	if err != nil {
		return nil, nil, err
	}

	shutdownTasks := []func() error{}

	shutdownTasks = append(shutdownTasks, func() error {
		// close channels that others may block on for shutdown
		close(engineStop)
		err := <-engineStopped
		return err
	})

	// Triggers to start shutdown sequence
	fromKernel := make(chan os.Signal, 1)

	// kill -9 is SIGKILL and is uncatchable.
	signal.Notify(fromKernel, syscall.SIGHUP)  // 1
	signal.Notify(fromKernel, syscall.SIGINT)  // 2
	signal.Notify(fromKernel, syscall.SIGQUIT) // 3
	signal.Notify(fromKernel, syscall.SIGABRT) // 6
	signal.Notify(fromKernel, syscall.SIGTERM) // 15

	fromUser := make(chan struct{})
	stopped := make(chan error)
	go func(tasks []func() error) {
		defer close(stopped)

		select {
		case <-fromKernel:
		case <-fromUser:
		}
		for _, task := range tasks {
			if err := task(); err != nil {
				stopped <- err
				return
			}
		}
		return
	}(shutdownTasks)

	return fromUser, stopped, nil
}

// Runs the http server.  This server offers more control than the standard go's default http server.
// When the returned stop channel is closed, a clean shutdown and shutdown tasks are executed.
// The return value is a channel that can be used to block on.  An error is received if server shuts
// down in error; or a nil is received on a clean signalled shutdown.
func runHTTP(socketPath string, server *http.Server) (chan<- struct{}, <-chan error, error) {
	listener, err := net.Listen("unix", socketPath)

	if err != nil {
		return nil, nil, err
	}

	if _, err = os.Lstat(socketPath); err == nil {
		// Update socket filename permission
		if err := os.Chmod(server.Addr, 0777); err != nil {
			return nil, nil, err
		}
	} else {
		return nil, nil, err
	}

	stop := make(chan struct{})
	stopped := make(chan error)

	userInitiated := new(bool)
	go func() {
		<-stop
		*userInitiated = true
		listener.Close()
	}()

	go func() {
		// Serve will block until an error (e.g. from shutdown, closed connection) occurs.
		err := server.Serve(listener)

		defer close(stopped)

		switch {
		case !*userInitiated && err != nil:
			panic(err)
		case *userInitiated:
			stopped <- nil
		default:
			stopped <- err
		}
	}()
	return stop, stopped, nil
}


text:
<?php

namespace Page;

use Behat\Behat\Context\Context;

class Comment implements Context
{
    public static $docPath = '/cftree/doc/';
    public static $commentFilePath = '/salt/case/export_comment/';

    protected string $filename;
    protected string $CfDocComment;
    protected string $CfItemComment;

    protected \AcceptanceTester $I;

    public function __construct(\AcceptanceTester $I)
    {
        $this->I = $I;
    }

    /**
     * @When /^I see the Export Comment button$/
     */
    public function iSeeExportCommentButton(): void
    {
        $I = $this->I;
        $I->see('Export Comments');
    }

    /**
     * @Given /^I added comments on DocItem$/
     */
    public function iAddedCommentsOnDocItem(): void
    {
        $I = $this->I;
        $this->CfDocComment = 'acceptance doc comment '.sq($I->getItemId());
        $I->waitForElementNotVisible('#modalSpinner', 120);
        $I->createAComment($this->CfDocComment);
        $I->waitForJS('return $.active == 0;', 2);
        $I->see($this->CfDocComment, '.comment-wrapper .wrapper .content');
    }

    /**
     * @Given I added comments on CFItem
     */
    public function iAddedCommentsOnCFItem(): void
    {
        $I = $this->I;
        $this->CfItemComment = 'acceptance item comment '.sq($I->getItemId());
        $I->createAComment($this->CfItemComment);
        $I->waitForJS('return $.active == 0;', 2);
        $I->see($this->CfItemComment, '.comment-wrapper .wrapper .content');
    }

    /**
     * @Given /^I download the comment report CSV$/
     */
    public function iDownloadTheCSV(): void
    {
        $I = $this->I;
        $url = self::$commentFilePath.'document/'.$I->getDocId().'/comment.csv';
        $this->filename = $I->download($url);
    }

    /**
     * @Then /^I can see the comment data in the CSV matches the data in the comment section$/
     */
    public function iCheckTheCSV(): void
    {
        $I = $this->I;
        $csvFile = file_get_contents($this->filename);
        $I->assertNotEmpty($csvFile, 'CSV file is empty');
        $comment = explode("\n", $csvFile);
        $I->assertGreaterThanOrEqual(1, sizeof($comment));
        $I->assertStringContainsString($this->CfDocComment, $csvFile, 'Exported Doc Comments');
        $I->assertStringContainsString($this->CfItemComment, $csvFile, 'Exported Item Comments');
    }
}


text:
/**
 * Auto configuration for the {@literal selectors} module of Genie web.
 *
 * @author tgianos
 * @since 4.0.0
 */
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.selectors;

import javax.annotation.ParametersAreNonnullByDefault;


text:
<?php

namespace Oro\Bundle\EntityBundle\ORM;

use Doctrine\Common\Cache\Cache;
use Oro\Bundle\EntityBundle\Exception\EntityAliasNotFoundException;
use Oro\Bundle\EntityBundle\Exception\InvalidEntityAliasException;
use Oro\Bundle\EntityBundle\Model\EntityAlias;
use Oro\Bundle\EntityBundle\Provider\EntityAliasLoader;
use Oro\Bundle\EntityBundle\Provider\EntityAliasStorage;
use Oro\Component\Config\Cache\ClearableConfigCacheInterface;
use Oro\Component\Config\Cache\ConfigCacheStateInterface;
use Oro\Component\Config\Cache\WarmableConfigCacheInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides functionality to get singular and plural aliases for an entity class
 * and resolve entity class by any of these aliases.
 */
class EntityAliasResolver implements WarmableConfigCacheInterface, ClearableConfigCacheInterface
{
    private const CACHE_KEY = 'entity_aliases';

    /** @var EntityAliasLoader */
    private $loader;

    /** @var Cache */
    private $cache;

    /** @var LoggerInterface */
    private $logger;

    /** @var ConfigCacheStateInterface */
    private $configCacheState;

    /** @var EntityAliasStorage|null */
    private $storage;

    /**
     * @param EntityAliasLoader $loader
     * @param Cache             $cache
     * @param LoggerInterface   $logger
     */
    public function __construct(EntityAliasLoader $loader, Cache $cache, LoggerInterface $logger)
    {
        $this->loader = $loader;
        $this->cache = $cache;
        $this->logger = $logger;
    }

    /**
     * Sets an object that should be used to check if entity alias cache is fresh or should be rebuilt.
     *
     * @param ConfigCacheStateInterface $configCacheState
     */
    public function setConfigCacheState(ConfigCacheStateInterface $configCacheState): void
    {
        $this->configCacheState = $configCacheState;
    }

    /**
     * Checks whether the given entity class has an alias.
     *
     * @param string $entityClass The FQCN of an entity
     *
     * @return bool
     */
    public function hasAlias($entityClass)
    {
        $this->ensureAllAliasesLoaded();

        return null !== $this->storage->getEntityAlias($entityClass);
    }

    /**
     * Returns the alias for the given entity class.
     *
     * @param string $entityClass The FQCN of an entity
     *
     * @return string The alias for the requested entity
     *
     * @throws EntityAliasNotFoundException if an alias not found
     */
    public function getAlias($entityClass)
    {
        $this->ensureAllAliasesLoaded();

        $entityAlias = $this->storage->getEntityAlias($entityClass);
        if (null === $entityAlias) {
            throw new EntityAliasNotFoundException(
                sprintf('An alias for "%s" entity not found.', $entityClass)
            );
        }

        return $entityAlias->getAlias();
    }

    /**
     * Returns the plural alias for the given entity class.
     *
     * @param string $entityClass The FQCN of an entity
     *
     * @return string The plural alias for the requested entity
     *
     * @throws EntityAliasNotFoundException if an alias not found
     */
    public function getPluralAlias($entityClass)
    {
        $this->ensureAllAliasesLoaded();

        $entityAlias = $this->storage->getEntityAlias($entityClass);
        if (null === $entityAlias) {
            throw new EntityAliasNotFoundException(
                sprintf('A plural alias for "%s" entity not found.', $entityClass)
            );
        }

        return $entityAlias->getPluralAlias();
    }

    /**
     * Returns the entity class by the given alias.
     *
     * @param string $alias The alias of an entity
     *
     * @return string The FQCN of an entity
     *
     * @throws EntityAliasNotFoundException if the given alias is not associated with any entity class
     */
    public function getClassByAlias($alias)
    {
        $this->ensureAllAliasesLoaded();

        $entityClass = $this->storage->getClassByAlias($alias);
        if (!$entityClass) {
            throw new EntityAliasNotFoundException(
                sprintf('The alias "%s" is not associated with any entity class.', $alias)
            );
        }

        return $entityClass;
    }

    /**
     * Returns the entity class by the given plural alias.
     *
     * @param string $pluralAlias The plural alias of an entity
     *
     * @return string The FQCN of an entity
     *
     * @throws EntityAliasNotFoundException if the given plural alias is not associated with any entity class
     */
    public function getClassByPluralAlias($pluralAlias)
    {
        $this->ensureAllAliasesLoaded();

        $entityClass = $this->storage->getClassByPluralAlias($pluralAlias);
        if (!$entityClass) {
            throw new EntityAliasNotFoundException(
                sprintf('The plural alias "%s" is not associated with any entity class.', $pluralAlias)
            );
        }

        return $entityClass;
    }

    /**
     * Returns all entity aliases.
     *
     * @return EntityAlias[]
     */
    public function getAll()
    {
        $this->ensureAllAliasesLoaded();

        return $this->storage->getAll();
    }

    /**
     * {@inheritdoc}
     */
    public function warmUpCache(): void
    {
        $this->clearCache();
        $this->ensureAllAliasesLoaded();
    }

    /**
     * {@inheritdoc}
     */
    public function clearCache(): void
    {
        $this->cache->delete(self::CACHE_KEY);
        $this->storage = null;
    }

    /**
     * Creates a new instance of EntityAliasStorage.
     *
     * @return EntityAliasStorage
     */
    protected function createStorage()
    {
        return new EntityAliasStorage();
    }

    /**
     * Makes sure that aliases for all entities are loaded.
     */
    private function ensureAllAliasesLoaded()
    {
        if (null === $this->storage) {
            $storage = $this->fetchAliasesFromCache();
            if (null === $storage) {
                $storage = $this->loadAliases();
                if (null !== $storage) {
                    $this->saveAliasesToCache($storage);
                }
            }
            $this->storage = $storage;
        }
    }

    /**
     * @return EntityAliasStorage|null
     */
    private function fetchAliasesFromCache(): ?EntityAliasStorage
    {
        $storage = null;
        $cachedData = $this->cache->fetch(self::CACHE_KEY);
        if (false !== $cachedData) {
            list($timestamp, $value) = $cachedData;
            if (null === $this->configCacheState || $this->configCacheState->isCacheFresh($timestamp)) {
                $storage = $value;
            }
        }

        return $storage;
    }

    /**
     * @param EntityAliasStorage $storage
     */
    private function saveAliasesToCache(EntityAliasStorage $storage): void
    {
        $timestamp = null === $this->configCacheState
            ? null
            : $this->configCacheState->getCacheTimestamp();
        $this->cache->save(self::CACHE_KEY, [$timestamp, $storage]);
    }

    /**
     * @return EntityAliasStorage
     */
    private function loadAliases(): ?EntityAliasStorage
    {
        $storage = $this->createStorage();
        try {
            $this->loader->load($storage);
        } catch (InvalidEntityAliasException $e) {
            throw $e;
        } catch (\Exception $e) {
            $storage = null;
            $this->logger->error('Loading of entity aliases failed', ['exception' => $e]);
        }

        return $storage;
    }
}


text:
var microjungle=function(e){function f(h,b){for(var e=h.length,g=0;g<e;g++){var a=h[g];if(a)if(typeof a=='string')b.innerHTML+=a;else if(typeof a[0]=='string'){var j=i.createElement(a.shift()),c={}.toString.call(a[0])==='[object Object]'&&a.shift(),d;if(c)for(d in c)c[d]&&j.setAttribute(d,c[d]);b.appendChild(f(a,j));}else a.nodeType===11?b.appendChild(a):f(a,b);}return b;}var i=document;return f(e,i.createDocumentFragment());};

// Panel Constructor

function appendPanel(options) {

	var body = document.body,
		panel = document.createElement('div'),
		button = document.createElement('button'),
		yepList = [], nopeList = [],
		maybeFeatures = options.features.slice(0, options.features.length - 1),
		nopeFeatures = [], yepFeatures = [],
		nopeDesc = 'Your browser doesn’t support all required features',
		yepDesc = 'Success! Your browser supports all required features!';

	for(var i=0, l=maybeFeatures.length; i<l; i++) {
		var feature = maybeFeatures[i];
		if(Modernizr[feature.name]) {
			yepFeatures.push(feature);
		} else {
			nopeFeatures.push(feature);
		}
	}

	var tags = ['p', {'class': 'sd-tags'}];

	for(var i=0, l=options.tags.length; i<l; i++) {
		var tag = options.tags[i];
		tags.push(['a', {'href': '/'+ tag + '/'}, tag]);
	}

	var nopes = nopeFeatures.length,
		yeps = yepFeatures.length;

	function createFeatures(features, list) {
		for(var i=0, l=features.length; i<l; i++) {
			var feature = features[i];
			list.push(['li',
				['a', {'href': feature.link}, feature.title]
			]);
		}
	}

	if(nopes) {
		nopeList = ['ul', {'class': 'sd-list sd-list-nope'}];
		createFeatures(nopeFeatures, nopeList);
		panel.classList.add('sd-panel-on');
	}

	if(yeps) {
		yepList = ['ul', {'class': 'sd-list sd-list-yep'}];
		createFeatures(yepFeatures, yepList);
	}

	var desc = nopes ? nopeDesc : yepDesc,
		descName = nopes ? 'sd-features-nope' : 'sd-features-yep';

	var content = microjungle([
		['div', {'class': 'sd-description'},
			['div', {'class': 'sd-title'},
				['p',
					['a', {'href': '/'}, 'SD']
				],
				['h1', options.title]
			],
			['p', {'class': 'sd-legend'}, options.legend],
			tags
		],
		['div', {'class': 'sd-features ' + descName},
			['p', desc],
			nopeList,
			yepList
		]
	]);

	panel.classList.add('sd-panel');

	button.classList.add('sd-button');
	button.addEventListener('click', function(){
		panel.classList.toggle('sd-panel-on');
	}, false);

	panel.appendChild(content);
	panel.appendChild(button);
	body.appendChild(panel);

}

// Google Analytics

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-17110734-4']);
_gaq.push(['_trackPageview']);

(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


text:
package io.gravitee.repository.management.api;

import java.util.Set;

import io.gravitee.repository.exceptions.TechnicalException;
import io.gravitee.repository.management.model.Environment;

/**
 * @author Florent CHAMFROY (florent.chamfroy at graviteesource.com)
 * @author GraviteeSource Team
 */
public interface EnvironmentRepository extends CrudRepository<Environment, String>{
    Set<Environment> findAll() throws TechnicalException;

    Set<Environment> findByOrganization(String organizationId) throws TechnicalException;

    Set<Environment> findByOrganizationsAndHrids(Set<String> organizationsHrids, Set<String> hrids) throws TechnicalException;
}


text:
CUM_RETVALS = 0

#=============
# IMPORTS

import collections
import logging
import logging.handlers
import math
import multiprocessing
import os
import shutil
import subprocess
import sys
import time
import traceback

try:
    from Bio import SeqIO
except ImportError:
    print "Biopython required for script, but not found (exiting)"
    sys.exit(1)
from optparse import OptionParser

try:
    import rpy2.robjects as robjects
    rpy2_import = True
except ImportError:
    print "Could not import rpy2: graphical output " +\
        "and TETRA method not available"
    rpy2_import = False

#=============
# FUNCTIONS

# Parse command-line
def parse_cmdline(args):
    """ Parse command-line arguments for the script
    """
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--outdir", dest="outdirname",
                      action="store", default=None,
                      help="Output directory")
    parser.add_option("-i", "--indir", dest="indirname",
                      action="store", default=None,
                      help="Input directory name")
    parser.add_option("-v", "--verbose", dest="verbose",
                      action="store_true", default=False,
                      help="Give verbose output")
    parser.add_option("-f", "--force", dest="force",
                      action="store_true", default=False,
                      help="Force file overwriting")
    parser.add_option("-s", "--fragsize", dest="fragsize",
                      action="store_const", default=1020,
                      help="Sequence fragment size for ANIb")
    parser.add_option("-l", "--logfile", dest="logfile",
                      action="store", default=None,
                      help="Logfile location")
    parser.add_option("--skip_nucmer", dest="skip_nucmer",
                      action="store_true", default=False,
                      help="Skip NUCmer runs, for testing " +
                      "(e.g. if output already present)")
    parser.add_option("--skip_blast", dest="skip_blast",
                      action="store_true", default=False,
                      help="Skip BLAST runs, for testing " +
                      "(e.g. if output already present)")
    parser.add_option("--noclobber", dest="noclobber",
                      action="store_true", default=False,
                      help="Don't nuke existing files")
    parser.add_option("-g", "--graphics", dest="graphics",
                      action="store_true", default=False,
                      help="Generate heatmap of ANI")
    parser.add_option("--format", dest="gformat",
                      action="store", default="pdf",
                      help="Graphics output format [pdf|png|jpg]")
    parser.add_option("-m", "--method", dest="method",
                      action="store", default="ANIm",
                      help="ANI method [ANIm|ANIb|TETRA]")
    parser.add_option("--maxmatch", dest="maxmatch",
                      action="store_true", default=False,
                      help="Override MUMmer to allow all NUCmer matches")
    parser.add_option("--nucmer_exe", dest="nucmer_exe",
                      action="store", default="nucmer",
                      help="Path to NUCmer executable")
    parser.add_option("--blast_exe", dest="blast_exe",
                      action="store", default="blastn",
                      help="Path to BLASTN+ executable")
    parser.add_option("--makeblastdb_exe", dest="makeblastdb_exe",
                      action="store", default="makeblastdb",
                      help="Path to BLAST+ makeblastdb executable")
    return parser.parse_args()

# Report last exception as string
def last_exception():
    """ Returns last exception as a string, or use in logging.
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    return ''.join(traceback.format_exception(exc_type, exc_value,
                                              exc_traceback))

# METHOD: ANIm
# This method uses NUCmer to calculate pairwise alignments for the input
# organisms, without chopping sequences into fragments. We follow the method
# of Richter et al. (2009)
def calculate_anim():
    """ Calculate ANI by the ANIm method, as described in Richter et al (2009)
        Proc Natl Acad Sci USA 106: 19126-19131 doi:10.1073/pnas.0906412106.

        All FASTA format files (selected by suffix) in the input directory
        are compared against each other, pairwise, using NUCmer (which must
        be in the path). NUCmer output is stored in the output directory.

        The NUCmer .delta file output is parsed to obtain an alignment length
        and similarity error count for every unique region alignment between
        the two organisms, as represented by the sequences in the FASTA files.

        These are processed to give matrices of aligned sequence lengths,
        similarity error counts, average nucleotide identity (ANI) percentages,
        and minimum aligned percentage (of whole genome) for each pairwise
        comparison.

        The matrices are written to file in a plain text tab-separated format.
    """
    logger.info("Running ANIm method")
    infiles = get_fasta_files(options.indirname)
    org_lengths = get_org_lengths()
    pairwise_nucmer(infiles)
    lengths, sim_errors, perc_ids, perc_aln = process_delta(org_lengths)
    # Sanity check print for organisms of same species
    #for k, v in sorted(perc_ids.items()):
    #    if v > 0.95:
    #        print k, v
    # Write output to file
    write_table('aln_lengths.tab', org_lengths.keys(), lengths,
                "Aligment lengths")
    write_table('sim_errors.tab', org_lengths.keys(), sim_errors,
                "Similarity errors")
    write_table('perc_ids.tab', org_lengths.keys(), perc_ids,
                "ANIm", "float")
    write_table('perc_aln.tab', org_lengths.keys(), perc_aln,
                "Minimum % aligned nt", "float")

# METHOD: ANIb
# This method uses BLAST to calculate pairwise alignments for input organisms,
# fragmented into consecutive 1020bp fragments, as described in Goris et al.
# (2007).
def calculate_anib():
    """ Calculate ANI by the ANIb method, as described in Goris et al. (2007)
        Int J Syst Evol Micr 57: 81-91. doi:10.1099/ijs.0.64483-0.

        All FASTA format files (selected by suffix) in the input directory are
        used to construct BLAST databases, placed in the output directory.
        Each file's contents are also split into sequence fragments of length
        options.fragsize, and the multiple FASTA file that results written to
        the output directory. These are BLASTNed, pairwise, against the
        databases.

        The BLAST output is interrogated for all fragment matches that cover
        at least 70% of the query sequence, with at least 30% nucleotide
        identity over the full length of the query sequence. This is an odd
        choice and doesn't correspond to the twilight zone limit as implied by
        Goris et al. We persist with their definition, however.  Only these
        qualifying matches contribute to the total aligned length, and total
        aligned sequence identity used to calculate ANI.

        The results are processed to give matrices of aligned sequence length
        (aln_lengths.tab), similarity error counts (sim_errors.tab), ANIs
        (perc_ids.tab), and minimum aligned percentage (perc_aln.tab) of
        each genome, for each pairwise comparison. These are written to the
        output directory in plain text tab-separated format.
    """
    logger.info("Running ANIb method")
    fragment_input_files()
    org_lengths = get_org_lengths()
    make_blast_dbs()
    pairwise_blast(get_input_files(options.outdirname, '.fasta'))
    lengths, sim_errors, perc_ids, perc_aln = process_blast(org_lengths)
    # Sanity check print for organisms of same species
    for k, v in sorted(perc_ids.items()):
        if v > 0.95:
            print k, v
    # Write output to file
    write_table('aln_lengths.tab', org_lengths.keys(), lengths,
                "Aligment lengths")
    write_table('sim_errors.tab', org_lengths.keys(), sim_errors,
                "Similarity errors")
    write_table('perc_ids.tab', org_lengths.keys(), perc_ids,
                "ANIb", "float")
    write_table('perc_aln.tab', org_lengths.keys(), perc_aln,
                "Minimum % aligned nt", "float")

# METHOD: TETRA
# This method calculates tetranucleotide frequencies for the input organisms,
# as used by JSpecies, and described in Richter et al (2009) and Teeling et
# al. (2004) and Teeling et al. (2004)
def calculate_tetra():
    """ Calculate tetranucleotide frequencies for each input sequence, and
        their Pearson correlation, as described in Teeling et al. (2004a)
        Env. Micro. 6 938-947 doi:10.1111/j.1462-2920.2004.00624.x;
        Teeling et al. (2004b) BMC Bioinf. 5 163 doi:10.1186/1471-2105-5-163;
        and Richter & Rossello-Mora (2009) PNAS 106 19126-19131
        doi:10.1073/pnas.0906412106.

        FASTA format files (selected by suffix) in the input directory are used
        to construct frequency tables of tetranucleotide occurrence. These
        frequencies are converted into Z-scores, and tabulated
        (rows=tetranucleotides, columns=input sequences, written as
        tetra_z_scores.tab). The Pearson correlation between Z-scores for
        input sequences is then used as a measure of sequence similarity and
        written to tetra_corr.tab.
    """
    logger.info("Running TETRA method")
    tetra_z = calc_org_tetra()   # Calculate Z-scores for tetranucleotides
    write_tetraz('tetra_z_scores.tab', tetra_z)
    corr_z = calc_tetra_corr(tetra_z)  # Calculate Pearson correlation
    write_table('tetra_corr.tab', tetra_z.keys(), corr_z, "TETRA", "float")

# SUPPORT FUNCTIONS
# Write the set of tetranucleotide frequency Z scores to a plain text
# tab-separated table, in the output directory
def write_tetraz(filename, tetra_z):
    """ Writes the Z score for each tetranucleotide to a plain text
        tab-separated table with one row for each tetranucleotide, and one
        column for each input sequence.

        - filename is the location of the file to which the tetranucleotide
              Z-scores should be written

        - tetra_z is a dictionary containing the tetranucleotide Z-scores
              for each input sequence
    """
    try:
        fh = open(os.path.join(options.outdirname, filename), 'w')
        logger.info("Writing Z-scores to %s" % fh.name)
    except:
        logger.error("Could not open %s for writing (exiting)")
        sys.exit(1)
    orgs = sorted(tetra_z.keys())
    tets = sorted(tetra_z.values()[0].keys())
    # Write headers
    print >> fh, "# calculate_ani.py %s" % time.asctime()
    print >> fh, "# tetranucleotide frequency Z-scores"
    print >> fh, '\t' + '\t'.join(orgs)
    for tet in tets:
        outstr = [tet] + ["%.2f" % tetra_z[org][tet] for org in orgs]
        print >> fh, '\t'.join(outstr)
    fh.close()

# Calculate Pearson's correlation coefficient from the Z-scores for each
# tetranucleotide. If we're forcing rpy2, might as well use that, though...
def calc_tetra_corr(tetra_z):
    """ Calculate Pearson correlation coefficient from Z scores for each
        tetranucleotide. This is done longhand here, which is fast enough,
        but for robustness we might want to just hand this over to R,
        as it is a dependency for this method anyway (TODO).

        Note that we report a correlation by this method, rather than a
        percentage identity.

        - tetra_z is a dictionary of tetranucleotide Z-scores, for each
              input sequence
    """
    corrs = {}
    orgs = sorted(tetra_z.keys())
    for idx, o1 in enumerate(orgs[:-1]):
        for o2 in orgs[idx+1:]:
            assert sorted(tetra_z[o1].keys()) == sorted(tetra_z[o2].keys())
            tets = sorted(tetra_z[o1].keys())
            z1 = [tetra_z[o1][t] for t in tets]
            z2 = [tetra_z[o2][t] for t in tets]
            z1_mean = sum(z1) / len(z1)
            z2_mean = sum(z2) / len(z2)
            z1diffs = [z - z1_mean for z in z1]
            z2diffs = [z - z2_mean for z in z2]
            diffprods = sum([z1diffs[i] * z2diffs[i] for i in
                             range(len(z1diffs))])
            z1diffs2 = sum([z * z for z in z1diffs])
            z2diffs2 = sum([z * z for z in z2diffs])
            corrs[(o1, o2)] = diffprods/math.sqrt(z1diffs2 * z2diffs2)
    return corrs

# Calculate tetranucleotide values for each input sequence
def calc_org_tetra():
    """ We calculate the mono-, di-, tri- and tetranucleotide frequencies
        for each sequence, on each strand, and follow Teeling et al. (2004)
        in calculating a corresponding Z-score for each observed
        tetranucleotide frequency, dependent on the mono-, di- and tri-
        nucleotide frequencies for that input sequence.
    """
    org_tetraz = {}
    for fn in get_fasta_files(options.indirname):
        org = os.path.splitext(os.path.split(fn)[-1])[0]
        logger.info("Calculating tetranucleotide frequencies for %s" % fn)
        # For the Teeling et al. method, the Z-scores require us to count
        # mono, di, tri and tetranucleotide sequences
        monocnt, dicnt, tricnt, tetracnt = (collections.defaultdict(int),
                                            collections.defaultdict(int),
                                            collections.defaultdict(int),
                                            collections.defaultdict(int))
        for rec in SeqIO.parse(fn, 'fasta'):
            for s in [str(rec.seq).upper(),
                      str(rec.seq.reverse_complement()).upper()]:
                # Since the Teeling et al. algorithm requires us to consider
                # both strand orientations, monocounts are easy
                monocnt['G'] += s.count('G')
                monocnt['C'] += s.count('C')
                monocnt['T'] += s.count('T')
                monocnt['A'] += s.count('A')
                # For di, tri and tetranucleotide counts, we loop over the
                # sequence and its reverse complement, until near the end:
                for i in range(len(s[:-4])):
                    di, tri, tetra = s[i:i+2], s[i:i+3], s[i:i+4]
                    dicnt[str(di)] += 1
                    tricnt[str(tri)] += 1
                    tetracnt[str(tetra)] += 1
                # We clean up the straggling bit at the end:
                tricnt[str(s[-4:-1])] += 1
                tricnt[str(s[-3:])] += 1
                dicnt[str(s[-4:-2])] += 1
                dicnt[str(s[-3:-1])] += 1
                dicnt[str(s[-2:])] += 1
        logger.info("%d mono, %d di, %d tri, %d tetranucleotides found" %
                    (len(monocnt), len(dicnt), len(tricnt), len(tetracnt)))
        # Following Teeling (2004), we calculate expected frequencies for each
        # tetranucleotide; we ignore ambiguity symbols
        tetra_exp = {}
        for t in [tet for tet in tetracnt if tet_clean(tet)]:
            tetra_exp[t] = 1.*tricnt[t[:3]]*tricnt[t[1:]]/dicnt[t[1:3]]
        logger.info("%d non-ambiguous tetranucleotides" % len(tetra_exp))
        # Following Teeling (2004) we approximate the std dev of each
        # tetranucleotide
        tetra_sd = {}
        for t, exp in tetra_exp.items():
            den = dicnt[t[1:3]]
            tetra_sd[t] = math.sqrt(exp * (den - tricnt[t[:3]]) *
                                    (den - tricnt[t[1:]]) / (den * den))
        # Following Teeling (2004) we calculate the Z-score for each
        # tetranucleotide
        tetra_z = {}
        for t, exp in tetra_exp.items():
            try:
                tetra_z[t] = (tetracnt[t] - exp)/tetra_sd[t]
            except ZeroDivisionError:
                # We hit a zero in the estimation of variance
                zeroes = [k for k, v in tetra_sd.items() if v == 0]
                logger.warning("Zero variance for tetranucleotides %s" %
                               zeroes)
                tetra_z[t] = 1 / (dicnt[t[1:3]] * dicnt[t[1:3]])
        #print len(tetra_z), sorted(tetra_z.items())
        #for tet in sorted(tetra_exp.keys()):
        #    print tet, tetracnt[tet], tetra_exp[tet], tetra_sd[tet], \
        #        tetra_z[tet]
        org_tetraz[org] = tetra_z
    return org_tetraz

# Returns true if the passed string contains only A, C, G or T
def tet_clean(s):
    """ Checks that a passed string contains only unambiguous IUPAC nucleotide
        symbols. We are assuming that a low frequency of IUPAC ambiguity
        symbols doesn't affect our calculation.
    """
    if not len(set(s) - set('ACGT')):
        return True
    return False

# Divide the input FASTA sequences into fragments, and place multiple sequence
# FASTA files into the output directory
def fragment_input_files():
    """ Takes every sequence from every FASTA file in the input directory,
        splits them into consecutive fragments of length options.fragsize,
        (with any trailing sequences being included, even if shorter), and
        writes the resulting set of sequences to a file with the same name
        in the output directory. All fragments are named consecutively and
        uniquely as fragNNNNN.
    """
    logger.info("Fragmenting input FASTA files")
    for fn in get_fasta_files(options.indirname):
        logger.info("Processing %s" % fn)
        ostem = os.path.splitext(os.path.split(fn)[-1])[0]
        ofn = os.path.join(options.outdirname, ostem) + '.fasta'
        logger.info("Writing fragments to %s" % ofn)
        outseqs = []
        i, count = 0, 0
        for s in SeqIO.parse(fn, 'fasta'):
            while i < len(s):
                count += 1
                newseq = s[i:i+options.fragsize]
                newseq.id = "frag%05d" % count
                outseqs.append(newseq)
                i += options.fragsize
        SeqIO.write(outseqs, ofn, 'fasta')

# Make BLAST databases for each of the fragmented input files
def make_blast_dbs():
    """ Use local makeblastdb to build BLAST a nucleotide database for each
        input sequence.

        For ANIb, the input sequence has been split into consecutive fragments.
    """
    global CUM_RETVALS
    logger.info("Making BLAST databases for fragment files")
    cmdlines = []
    for fn in get_fasta_files(options.indirname):
        cmdlines.append(make_makeblastdb_cmd(fn))
    logger.info("BLAST makeblastdb command lines:\n\t%s" %
                '\n\t'.join(cmdlines))
    multiprocessing_run(cmdlines)
    if 0 < CUM_RETVALS:           # At least one error
        logger.error("At least one BLAST database creation step had a " +
                     "nonzero return value. ANIb may fail.")
        CUM_RETVALS = 0           # Reset error

# Get the list of FASTA files from the input directory
def get_fasta_files(dirname=None):
    """ Return a list of FASTA files in the input directory
    """
    infiles = get_input_files(dirname,  # '.fna')
                              '.fasta', '.fas', '.fa', '.fna')
    logger.info("Input files:\n\t%s" % '\n\t'.join(infiles))
    return infiles

# Get lengths of sequence for each organism
def get_org_lengths():
    """ Returns a dictionary of total input sequence lengths, keyed by
        organism.

        Biopython's SeqIO module is used to parse all sequences in the FASTA
        file corresponding to each organism, and the total base count in each
        is obtained.

        NOTE: ambiguity symbols are not discounted.
    """
    logger.info("Processing input organism sequence lengths")
    tot_lengths = {}
    for fn in get_fasta_files(options.indirname):
        tot_lengths[os.path.splitext(os.path.split(fn)[-1])[0]] = \
            sum([len(s) for s in SeqIO.parse(fn, 'fasta')])
    return tot_lengths

# Write a table of values to file, organised as a square matrix with row/col
# headers, in tab-separated format
def write_table(filename, org_names, values, comment='', fmt=None):
    """ Writes a tab-separated plain text square matrix file, with row and
        column headers, describing the passed data.

        - filename is the full path for the output file

        - org_names describes the row and column headers, as a list of strings

        - values describes the values in each cell, as a dictionary keyed by
             (row, col) tuple, with identifiers from org_names

        - comment is an optional comment string for the output file
    """
    # Open file and write file header
    fname = os.path.join(options.outdirname, filename)
    try:
        logger.info("Opening %s for writing" % fname)
        fh = open(fname, 'w')
        print >> fh, "# calculate_ani.py %s" % time.asctime()
        if len(comment):
            print >> fh, "# %s" % comment
    except:
        logger.error("Could not open file %s for output (exiting)" % fname)
        logger.error(last_exception())
        sys.exit(1)
    names = sorted(list(set(org_names)))  # Set name order
    print >> fh, '\t'.join([''] + names)
    for n1 in names:
        outrow = [n1]
        for n2 in names:
            if n1 == n2:
                outrow.append('NA')
                continue
            try:
                val = values[(n1, n2)]
            except KeyError:  # This error is not thrown for a square matrix
                val = values[(n2, n1)]
            if fmt == "float":
                outrow.append("%.4f" % val)
            else:
                outrow.append(str(val))
        print >> fh, '\t'.join(outrow)
    logger.info("Wrote data to %s" % fname)

# Parse NUCmer delta output to store alignment total length, sim_error,
# and percentage identity, for each pairwise comparison
def process_delta(org_lengths):
    """ Returns a tuple containing a list and four dictionaries. The list
        describes the names of all organisms (derived from their filenames).
        The dictionaries describe results for pairwise comparisons: total
        aligned lengths; similarity errors in those alignments; the percentage
        of aligned length that matches (ANIm); and the percentage of the
        pairwise comparison that is aligned.

        For the total aligned length, similarity error, and ANIm dictionaries,
        as these are triangular/symmetrical matrices we only key them by
        (query, subject), but as the percentage aligned measure depends on the
        sequence we calculate it against, we report (query, subject) and
        (subject, query) values.

        - org_lengths is a dictionary of total sequence lengths for each
              input sequence
    """
    global CUM_RETVALS
    infiles = get_input_files(options.outdirname, '.delta')
    logger.info("Delta files:\n\t%s" % '\n\t'.join(infiles))
    logger.info("Processing .delta files")
    # We store pairwise comparison lengths in dictionaries, keyed by organism
    # ID pair tuples:
    # perc_aln is useful, as it is a matrix of the minimum percentage of an
    # organism's genome involved in a pairwise alignment
    lengths, sim_errors, perc_ids, perc_aln = {}, {}, {}, {}
    for dname in infiles:
        logger.info("Processing %s" % dname)
        qname, sname = \
            os.path.splitext(os.path.split(dname)[-1])[0].split('_vs_')
        logger.info("Query organism: %s; Subject organism: %s" %
                    (qname, sname))
        tot_length, tot_sim_error = parse_delta(dname)
        try:
            perc_id = 1 - 1. * tot_sim_error/tot_length
        except ZeroDivisionError:
            # If this is thrown, the proximate cause is an empty NUCmer output
            # The root cause may be a failed NUCmer run (when CUM_RETVALS>0)
            # or that one or more of the sequences is too distant for NUCmer
            # to identify a similarity.
            logger.error("One or more of the NUCmer output files contains " +
                         "no useable output.")
            if 0 < CUM_RETVALS:
                logger.error("One or more NUCmer runs failed. " +
                             "Please investigate.")
                logger.error("Please retry the NUCmer comparison for " +
                             "%s vs %s manually" % (qname, sname))
            else:
                logger.error("The NUCmer comparison between %s and %s " %
                             (qname, sname) +
                             "has no usable output. The comparison may be " +
                             "too distant for use. Consider using --maxmatch.")
            logger.error(last_exception())
        lengths[(qname, sname)] = tot_length
        sim_errors[(qname, sname)] = tot_sim_error
        perc_ids[(qname, sname)] = perc_id
        perc_aln[(qname, sname)] = 1.*tot_length/org_lengths[qname]
        perc_aln[(sname, qname)] = 1.*tot_length/org_lengths[sname]
    return lengths, sim_errors, perc_ids, perc_aln

# Parse BLAST tabular output and store total alignment length, similarity
# counts and percentage identity for each pairwise comparison
def process_blast(org_lengths):
    """ Read in the BLASTN comparison output files, and calculate alignment
        lengths, similarity errors, and percentage identity and alignment
        coverage for each input sequence comparison.

        - org_lengths is a dictionary of total sequence lengths for each
              input sequence.
    """
    infiles = get_input_files(options.outdirname, '.blast_tab')
    logger.info("BLAST files:\n\t%s" % '\n\t'.join(infiles))
    logger.info("Processing .blast_tab files")
    lengths, sim_errors, perc_ids, perc_aln = {}, {}, {}, {}
    org_names = set()
    for tname in infiles:
        logger.info("Processing %s" % tname)
        qname, sname = \
            os.path.splitext(os.path.split(tname)[-1])[0].split('_vs_')
        org_names.add(qname)
        org_names.add(sname)
        logger.info("Query organism: %s; Subject organism: %s" %
                    (qname, sname))
        tot_length, tot_sim_error = parse_blast(tname)
        if tot_length:
            perc_id = 1 - 1. * tot_sim_error/tot_length
        else:
            perc_id = 0
        lengths[(qname, sname)] = tot_length
        sim_errors[(qname, sname)] = tot_sim_error
        perc_ids[(qname, sname)] = perc_id
        perc_aln[(qname, sname)] = 1.*tot_length/org_lengths[qname]
        perc_aln[(sname, qname)] = 1.*tot_length/org_lengths[sname]
    return lengths, sim_errors, perc_ids, perc_aln

# Parse NUCmer delta file to get total alignment length and total sim_errors
def parse_delta(filename):
    """ Reads a NUCmer output .delta file, extracting the aligned length and
        number of similarity errors for each aligned uniquely-matched region,
        and returns the cumulative total for each as a tuple.

        - filename is the path to the input .delta file
    """
    aln_length, sim_errors = 0, 0
    for line in [l.strip().split() for l in open(filename, 'rU').readlines()]:
        if line[0] == 'NUCMER' or line[0].startswith('>'):  # Skip headers
            continue
        # We only want lines with seven columns:
        if len(line) == 7:
            aln_length += abs(int(line[1]) - int(line[0]))
            sim_errors += int(line[4])
    return aln_length, sim_errors

# Parse custom BLASTN output to get total alignment length and mismatches
def parse_blast(filename):
    """ Calculate the alignment length and total number of similarity errors
        for the passed BLASTN alignment file generated by comparing fragmented
        input sequences.

        - filename is the location of the BLASTN output for a pairwise
              comparison between input sequences
    """
    aln_length, sim_errors = 0, 0,
    qname, sname = \
        os.path.splitext(os.path.split(filename)[-1])[0].split('_vs_')
    qalnlen, qnumid, qlen, qerr = (collections.defaultdict(float),
                                   collections.defaultdict(float),
                                   collections.defaultdict(float),
                                   collections.defaultdict(float))
    seen = set()  # IDs of queries that have been processed
    for line in [l.strip().split() for l in open(filename, 'rU').readlines()
                 if len(l) and not l.startswith('#')]:
        # We need to collate matches by query ID, to determine whether the
        # match has > 30% identity and > 70% coverage.
        # Following Goris et al (2007) we only use matches that contribute to
        # a total match identity of at least 30% and a total match coverage
        # of at least 70% of either query or reference length
        # As of BLASTN 2.2.29+, the max_target_seqs/num_alignments still
        # will not restrict to the best hit. We rely on BLAST output giving
        # the best hit for any query first in the table, and check whether we
        # have seen it before. If not, we carry on processing the data.
        qid = line[0]
        if qid in seen:
            continue
        seen.add(qid)
        qalnlen[qid] += int(line[2])
        qnumid[qid] += int(line[5])
        qlen[qid] = int(line[6])
        qerr[qid] += int(line[3])
    for qid, ql in qlen.items():
        if 1.*qalnlen[qid]/ql > 0.7 and 1.*qnumid[qid]/ql > 0.3:
            aln_length += int(qalnlen[qid])
            sim_errors += int(qerr[qid])
    return aln_length, sim_errors

# Run BLASTN pairwise on input files, using multiprocessing
def pairwise_blast(filenames):
    """ Run BLASTN for each pairwise comparison of fragmented input sequences,
        using multiprocessing to take advantage of multiple cores where
        possible, and writing results to the nominated output directory.

        - filenames is an iterable of locations of input FASTA files, from
              which BLASTN command lines are constructed.

        We loop over all FASTA files in the input directory, generating
        BLASTN command line for each pairwise comparison, and then pass those
        command lines to be run using multiprocessing.
    """
    global CUM_RETVALS
    logger.info("Running pairwise BLASTN to generate *.blast_tab")
    cmdlines = []
    for idx, f1 in enumerate(filenames[:-1]):
        cmdlines.extend([make_blast_cmd(f1, f2)
                         for f2 in filenames[idx+1:]])
    logger.info("BLASTN command lines:\n\t%s" % '\n\t'.join(cmdlines))
    if not options.skip_blast:
        multiprocessing_run(cmdlines)
        if 0 < CUM_RETVALS:
            logger.error("At least one BLAST comparison returned a nonzero " +
                         "value. ANIb may fail.")
    else:
        logger.warning("BLASTN run skipped!")

# Run NUCmer pairwise on the input files, using multiprocessing
def pairwise_nucmer(filenames):
    """ Run NUCmer to generate pairwise alignment data for each of the
        input FASTA files.

        - filenames is a list of input FASTA filenames, from which NUCmer
              command lines are constructed

        We loop over all FASTA files in the input directory, generating NUCmer
        command lines for each pairwise comparison, and then pass those
        command lines to be run using multiprocessing.
    """
    global CUM_RETVALS
    logger.info("Running pairwise NUCmer comparison to generate *.delta")
    cmdlines = []
    for idx, f1 in enumerate(filenames[:-1]):
        cmdlines.extend([make_nucmer_cmd(f1, f2)
                         for f2 in filenames[idx+1:]])
    logger.info("NUCmer command lines:\n\t%s" % '\n\t'.join(cmdlines))
    if not options.skip_nucmer:
        multiprocessing_run(cmdlines)
        if 0 < CUM_RETVALS:
            logger.error("At least one NUCmer comparison failed. ANIm " +
                         "may fail.")
    else:
        logger.warning("NUCmer run skipped!")

# Run a set of command lines using multiprocessing
def multiprocessing_run(cmdlines):
    """ Distributes the passed command-line jobs using multiprocessing.

        - cmdlines is an iterable of command line strings
    """
    logger.info("Running %d jobs with multiprocessing" % len(cmdlines))
    pool = multiprocessing.Pool()
    completed = []
    if options.verbose:
        callback_fn = logger_callback
    else:
        callback_fn = completed.append
    pool_outputs = [pool.apply_async(subprocess.call,
                                     (str(cline), ),
                                     {'stderr': subprocess.PIPE,
                                      'shell': sys.platform != "win32"},
                                     callback=callback_fn)
                    for cline in cmdlines]
    pool.close()        # Run jobs
    pool.join()         # Collect output
    logger.info("Multiprocessing jobs completed:\n%s" % completed)

# Multiprocessing callback to logger
def logger_callback(val):
    """ Basic callback for multiprocessing just to log status of each job

        - val is an integer returned by multiprocessing, describing the run
             status
    """
    global CUM_RETVALS
    logger.info("Multiprocessing run completed with status: %s" % val)
    # Keep track of returned values, as these help diagnose problems
    # for ANIm analyses
    CUM_RETVALS += val

# Construct a command-line for NUCmer
def make_nucmer_cmd(f1, f2):
    """ Construct a command-line for NUCmer pairwise comparison, and return as
        a string

        - f1, f2 are the locations of two input FASTA files for analysis

        We use the -mum option so that we consider matches that are unique in
        both the reference and the query. -mumreference gives us matches
        unique only in the reference and -maxmatch gives us matches to all
        regions, regardless of uniqueness. We may want to make this an option.
    """
    prefix = os.path.join(options.outdirname, "%s_vs_%s" %
                          (os.path.splitext(os.path.split(f1)[-1])[0],
                           os.path.splitext(os.path.split(f2)[-1])[0]))
    # Do we use the --maxmatch option?
    if options.maxmatch:
        mode = "-maxmatch"
    else:
        mode = "-mum"
    cmd = "%s %s -p %s %s %s" % (options.nucmer_exe, mode, prefix, f1, f2)
    return cmd

# Construct a command-line for BLASTN
def make_blast_cmd(f1, f2):
    """ Construct a BLASTN command line to conduct sequence comparison between
        two fragmented input sequences, for ANIb.

        - f1, f2 are the locations of two input FASTA files for analysis
    """
    prefix = os.path.join(options.outdirname, "%s_vs_%s" %
                          (os.path.splitext(os.path.split(f1)[-1])[0],
                           os.path.splitext(os.path.split(f2)[-1])[0]))
    blastdb = os.path.splitext(f2)[0]
    cmd = "%s -out %s.blast_tab -query %s -db %s " % \
        (options.blast_exe, prefix, f1, blastdb) + \
        "-xdrop_gap_final 150 -dust no -evalue 1e-15 " +\
        "-max_target_seqs 1 -outfmt '6 qseqid sseqid length mismatch " +\
        "pident nident qlen slen qstart qend sstart send positive " +\
        "ppos gaps' -task blastn"
    return cmd

# Construct a command line for BLAST makeblastdb
def make_makeblastdb_cmd(filename):
    """ Construct a makeblastdb command line to make a BLAST nucleotide
        database from the passed fragmented input sequence FASTA file.

        - filename is the location of the fragmented input FASTA sequence
              file, for constructing the database
    """
    db_prefix = os.path.join(options.outdirname,
                             os.path.split(os.path.splitext(filename)[0])[-1])
    cmd = "%s -out %s -dbtype nucl -in %s" % (options.makeblastdb_exe,
                                              db_prefix, filename)
    return cmd

# Get list of FASTA files in a directory
def get_input_files(dir, *ext):
    """ Returns a list of files in the input directory with the passed
        extension

        - dir is the location of the directory containing the input files

        - *ext is a list of arguments describing permissible file extensions
    """
    filelist = [f for f in os.listdir(dir)
                if os.path.splitext(f)[-1] in ext]
    return [os.path.join(dir, f) for f in filelist]

# Create output directory if it doesn't exist
def make_outdir():
    """ Make the output directory, if required.

        This is a little involved.  If the output directory already exists,
        we take the safe option by default, and stop with an error.  We can,
        however, choose to force the program to go on, in which case we can
        either clobber or not the existing directory.  The options turn out
        as the following, if the directory exists:

        DEFAULT: stop
        FORCE: continue, and remove the existing output directory
        NOCLOBBER+FORCE: continue, but do not remove the existing output
    """
    if os.path.exists(options.outdirname):
        if not options.force:
            logger.error("Output directory %s would " % options.outdirname +
                         "overwrite existing files (exiting)")
            sys.exit(1)
        else:
            logger.info("Removing directory %s and everything below it" %
                        options.outdirname)
            if options.noclobber:
                logger.warning("NOCLOBBER: not actually deleting directory")
            else:
                shutil.rmtree(options.outdirname)
    logger.info("Creating directory %s" % options.outdirname)
    try:
        os.makedirs(options.outdirname)   # We make the directory recursively
    except OSError:
        # This gets thrown if the directory exists. If we've forced overwrite/
        # delete and we're not clobbering, we let things slide
        if options.noclobber and options.force:
            logger.info("NOCLOBBER+FORCE: not creating directory")
        else:
            logger.error(last_exception)
            sys.exit(1)

#=============
# SCRIPT

if __name__ == '__main__':

    # Parse command-line
    # options are all options - no arguments
    options, args = parse_cmdline(sys.argv)

    # We set up logging, and modify loglevel according to whether we need
    # verbosity or not
    # err_handler points to sys.stderr
    # err_handler_file points to a logfile, if named
    logger = logging.getLogger('calculate_ani.py')
    logger.setLevel(logging.DEBUG)
    err_handler = logging.StreamHandler(sys.stderr)
    err_formatter = logging.Formatter('%(levelname)s: %(message)s')
    err_handler.setFormatter(err_formatter)
    if options.logfile is not None:
        try:
            logstream = open(options.logfile, 'w')
            err_handler_file = logging.StreamHandler(logstream)
            err_handler_file.setFormatter(err_formatter)
            err_handler_file.setLevel(logging.INFO)
            logger.addHandler(err_handler_file)
        except:
            logger.error("Could not open %s for logging" %
                         options.logfile)
            sys.exit(1)
    if options.verbose:
        err_handler.setLevel(logging.INFO)
    else:
        err_handler.setLevel(logging.WARNING)
    logger.addHandler(err_handler)
    logger.info('# calculate_ani.py logfile')
    logger.info('# Run: %s' % time.asctime())

    # Report arguments, if verbose
    logger.info(options)
    logger.info(args)

    # Report that this script is deprecated
    logger.warning("THIS SCRIPT IS DEPRECATED.")
    logger.warning("PLEASE USE THE PYANI MODULE INSTEAD.")
    logger.warning("https://github.com/widdowquinn/pyani")

    # Have we got an input and output directory? If not, exit.
    if options.indirname is None:
        logger.error("No input directory name (exiting)")
        sys.exit(1)
    logger.info("Input directory: %s" % options.indirname)
    if options.outdirname is None:
        logger.error("No output directory name (exiting)")
        sys.exit(1)
    make_outdir()
    logger.info("Output directory: %s" % options.outdirname)

    # Have we got a valid method choice?
    methods = {"ANIm": calculate_anim,
               "ANIb": calculate_anib,
               "TETRA": calculate_tetra}
    if options.method not in methods:
        logger.error("ANI method %s not recognised (exiting)" % options.method)
        logger.error("Valid methods are: %s" % methods.keys())
        sys.exit(1)
    logger.info("Using ANI method: %s" % options.method)

    # Run method on the contents of the input directory, writing out
    # to the named output directory
    methods[options.method]()

    # If graphics have been selected, use R to generate a heatmap of the ANI
    # scores from the perc_id.tab output
    if options.graphics:
        logger.info("Rendering heatmap with R")
        if options.method == "TETRA":
            filename = "tetra_corr.tab"
        else:
            filename = "perc_ids.tab"
        if options.gformat.lower() not in ('pdf', 'png', 'jpg'):
            options.gformat = 'pdf'
        if not rpy2_import:
            logger.error("No rpy2 module: graphics are unavailable")
        else:
            rstr = ["library(gplots)",
                    "ani <- read.table('%s', " %
                    os.path.join(options.outdirname, filename) +
                    "header=T, sep='\\t', " +
                    "row.names=1)",
                    "ani[] <- lapply(ani, " +
                    "function(x){replace(x, x == 0, NA)})",
                    "%s('%s')" %
                    (options.gformat.lower(),
                     os.path.join(options.outdirname, '%s.%s' %
                                  (options.method,
                                   options.gformat.lower()))),
                    "heatmap.2(as.matrix(ani), col=bluered, " +
                    "breaks=seq(min(0.9, " +
                    "max(ani[!is.na(ani)]))-0.01,1,0.001), " +
                    "margins=c(15,12), " +
                    "cexCol=1/log10(ncol(ani)), " +
                    "cexRow=1/log10(nrow(ani)), main='%s')" % options.method,
                    "dev.off()"]
            rstr = '\n'.join(rstr)
            logger.info("R command:\n%s" % rstr)
            robjects.r(rstr)


text:
//
//  Mine.m
//  LoginDemo
//
//  Created by lichq on 6/26/15.
//  Copyright (c) 2015 ciyouzen. All rights reserved.
//

#import "Mine.h"

#ifdef USE_CommonFMDBUtil
    #import "FirstFMDBFileManager.h"
#else
    #import "AccountSqliteUtil.h"
#endif

@interface Mine ()

@end

@implementation Mine

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    if ([LoginHelper isLogin]) {
        NSString *uid = [LoginHelper loginUID];
#ifdef USE_CommonFMDBUtil
        AccountInfo *info = [FirstFMDBFileManager selectAccountInfoWhereUID:uid];
#else
        AccountInfo *info = [AccountSqliteUtil selectInfoWhereUID:uid];
#endif
        [self.btn setTitle:info.name forState:UIControlStateNormal];

    }else{
        [self.btn setTitle:NSLocalizedString(@"立即登录", nil) forState:UIControlStateNormal];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = NSLocalizedString(@"我的", nil);

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    //CFShow((__bridge CFTypeRef)(infoDictionary));
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //NSString *version = [infoDictionary objectForKey:(NSString *)kCFBundleVersionKey];
    //app_Version = @"3.1.1";
    self.labVersion.text = [NSString stringWithFormat:@"V%@", app_Version];

    //通过api获取当前最新版,如果当前版本与最新版相等,显示"已是最新版"
    //.....
}

/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    self.navigationController.navigationBarHidden = NO;
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Belmar-Farmingdale, NJ</location>
	<station_id>KBLM</station_id>
	<latitude>40.18333</latitude>
	<longitude>-74.13333</longitude>
	<observation_time>Last Updated on Jan 4 2016, 9:55 pm EST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 21:55:00 -0500</observation_time_rfc822>
	<weather>A Few Clouds</weather>
	<temperature_string>16.0 F (-9.0 C)</temperature_string>
	<temp_f>16.0</temp_f>
	<temp_c>-9.0</temp_c>
	<relative_humidity>41</relative_humidity>
	<wind_string>from the Northwest at 17.3 gusting to 24.2 MPH (15 gusting to 21 KT)</wind_string>
	<wind_dir>Northwest</wind_dir>
	<wind_degrees>330</wind_degrees>
	<wind_mph>17.3</wind_mph>
	<wind_gust_mph>24.2</wind_gust_mph>
	<wind_kt>15</wind_kt>
	<wind_gust_kt>21</wind_gust_kt>
	<pressure_in>30.29</pressure_in>
	<dewpoint_string>-4.0 F (-20.0 C)</dewpoint_string>
	<dewpoint_f>-4.0</dewpoint_f>
	<dewpoint_c>-20.0</dewpoint_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KBLM.html</two_day_history_url>
	<icon_url_name>nfew.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KBLM.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
//#define __STDC_CONSTANT_MACROS
#include <boost/thread/detail/config.hpp>
#include <boost/thread/once.hpp>
#include <boost/thread/pthread/pthread_mutex_scoped_lock.hpp>
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/atomic.hpp>
#include <boost/memory_order.hpp>
#include <pthread.h>

namespace boost
{
  namespace thread_detail
  {

    enum flag_states
    {
      uninitialized, in_progress, initialized
    };

#ifndef BOOST_THREAD_PROVIDES_ONCE_CXX11
    BOOST_STATIC_ASSERT_MSG(sizeof(atomic_int_type) == sizeof(atomic_type), "Boost.Thread: unsupported platform");
#endif

    static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
    static pthread_cond_t once_cv = PTHREAD_COND_INITIALIZER;

    BOOST_THREAD_DECL bool enter_once_region(once_flag& flag) BOOST_NOEXCEPT
    {
      atomic_type& f = get_atomic_storage(flag);
      if (f.load(memory_order_acquire) != initialized)
      {
        pthread::pthread_mutex_scoped_lock lk(&once_mutex);
        if (f.load(memory_order_acquire) != initialized)
        {
          while (true)
          {
            atomic_int_type expected = uninitialized;
            if (f.compare_exchange_strong(expected, in_progress, memory_order_acq_rel, memory_order_acquire))
            {
              // We have set the flag to in_progress
              return true;
            }
            else if (expected == initialized)
            {
              // Another thread managed to complete the initialization
              return false;
            }
            else
            {
              // Wait until the initialization is complete
              //pthread::pthread_mutex_scoped_lock lk(&once_mutex);
              BOOST_VERIFY(!pthread_cond_wait(&once_cv, &once_mutex));
            }
          }
        }
      }
      return false;
    }

    BOOST_THREAD_DECL void commit_once_region(once_flag& flag) BOOST_NOEXCEPT
    {
      atomic_type& f = get_atomic_storage(flag);
      {
        pthread::pthread_mutex_scoped_lock lk(&once_mutex);
        f.store(initialized, memory_order_release);
      }
      BOOST_VERIFY(!pthread_cond_broadcast(&once_cv));
    }

    BOOST_THREAD_DECL void rollback_once_region(once_flag& flag) BOOST_NOEXCEPT
    {
      atomic_type& f = get_atomic_storage(flag);
      {
        pthread::pthread_mutex_scoped_lock lk(&once_mutex);
        f.store(uninitialized, memory_order_release);
      }
      BOOST_VERIFY(!pthread_cond_broadcast(&once_cv));
    }

  } // namespace thread_detail

} // namespace boost


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- | Copyright 2017 Adobe Systems Incorporated | | Licensed under the Apache
	License, Version 2.0 (the "License"); | you may not use this file except
	in compliance with the License. | You may obtain a copy of the License at
	| | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable
	law or agreed to in writing, software | distributed under the License is
	distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY
	KIND, either express or implied. | See the License for the specific language
	governing permissions and | limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.citraining</groupId>
		<artifactId>citraining</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>citraining.core</artifactId>
	<packaging>bundle</packaging>
	<name>citraining - Core</name>
	<description>Core bundle for citraining</description>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.sling</groupId>
				<artifactId>maven-sling-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<!-- Import any version of javax.inject, to allow running on multiple
							versions of AEM -->
						<Import-Package>javax.inject;version=0.0.0,*</Import-Package>
						<Bundle-SymbolicName>com.citraining.core</Bundle-SymbolicName>
						<_plugin>org.apache.sling.bnd.models.ModelsScannerPlugin</_plugin>
					</instructions>
				</configuration>
				<dependencies>
					<dependency>
						<groupId>org.apache.sling</groupId>
						<artifactId>org.apache.sling.bnd.models</artifactId>
						<version>1.0.0</version>
					</dependency>
				</dependencies>
			</plugin>
			<plugin>
				<groupId>org.apache.sling</groupId>
				<artifactId>maven-sling-plugin</artifactId>
				<!-- <configuration> <slingUrl>http://${crx.host}:${crx.port}/apps/citraining/install</slingUrl>
					<usePut>true</usePut> </configuration> -->
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<!-- OSGi Dependencies -->
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>osgi.core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>osgi.cmpn</artifactId>
		</dependency>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>osgi.annotation</artifactId>
		</dependency>
		<!-- Other Dependencies -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.jcr</groupId>
			<artifactId>jcr</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
		</dependency>
		<dependency>
			<groupId>junit-addons</groupId>
			<artifactId>junit-addons</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.scr.annotations</artifactId>
		</dependency>
		<dependency>
			<groupId>com.day.commons.osgi.wrapper</groupId>
			<artifactId>com.day.commons.osgi.wrapper.commons-email</artifactId>
		</dependency>
		<dependency>
			<groupId>com.adobe.cq</groupId>
			<artifactId>core.wcm.components.core</artifactId>
		</dependency>
		<dependency>
			<groupId>com.day.commons</groupId>
			<artifactId>day.commons.datasource.poolservice</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.fragment.xml</artifactId>
		</dependency>
		<dependency>
			<groupId>com.day.commons.osgi.wrapper</groupId>
			<artifactId>com.day.commons.osgi.wrapper.commons-lang2</artifactId>
		</dependency>
		<dependency>
			<groupId>com.day.jcr.vault</groupId>
			<artifactId>com.day.jcr.vault</artifactId>
		</dependency>
		<!-- Solr Dependencies -->
		<dependency>
			<groupId>org.apache.servicemix.bundles</groupId>
			<artifactId>org.apache.servicemix.bundles.solr-solrj</artifactId>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
		<dependency>
			<groupId>org.noggit</groupId>
			<artifactId>noggit</artifactId>
			<version>0.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.5</version>
		</dependency>
		<!-- Solr Dependencies -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>com.adobe.aem</groupId>
			<artifactId>uber-jar</artifactId>
			<classifier>apis</classifier>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.models.api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.geronimo.specs</groupId>
			<artifactId>geronimo-atinject_1.0_spec</artifactId>
		</dependency>
		<dependency>
			<artifactId>gson</artifactId>
			<groupId>com.google.code.gson</groupId>
			<version>2.6.2</version>
		</dependency>
		<dependency>
			<artifactId>citraining.soap.weather</artifactId>
			<groupId>com.citraining</groupId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.apache.sling</groupId>
			<artifactId>org.apache.sling.fragment.ws</artifactId>
		</dependency>
	</dependencies>
</project>


text:
const fs = require('fs');

class FileSystem {

    move (oldPath, newPath, callback) {

        fs.rename(oldPath, newPath, function (err) {
            if (err) {
                if (err.code === 'EXDEV') {
                    copy();
                } else {
                    callback(err);
                }
                return;
            }
            callback();
        });

        function copy() {

            var readStream = fs.createReadStream(oldPath);
            var writeStream = fs.createWriteStream(newPath);

            readStream.on("error", callback);
            writeStream.on("error", callback);

            readStream.on("close", function () {
                fs.unlink(oldPath, callback);
            });

            readStream.pipe(writeStream);
        }
    }
}

module.exports = new FileSystem();


text:
namespace BulletAnimatSim
{
	namespace Environment
	{

		class BULLET_PORT BlConstraintRelaxation : public AnimatSim::Environment::ConstraintRelaxation
		{
		protected:
            btAnimatGeneric6DofConstraint *m_lpConstraint;

            //Pointer to the bullet joint
            BlJoint *m_lpBlJoint;

            /// The maximum amount that this relaxation is allowed to move.
			float m_fltMaxLimit;

            /// The minimum amount that this relaxation is allowed to move.
			float m_fltMinLimit;

            /// The equilibrium position of the spring that controls this relaxation.
			float m_fltEqPos;

            //Keeps the inverse damping constant to actually use.
            float m_fltInvDamping;

            //For joints like hinge and prismatic I am allowing them to set a spring in the direction of the joint motion (Z axis). However, the joint
            //itself needs to be the one to determine when to enable/disable the spring because it has to control the motor as well. This flag tells
            // the relaxation that it should not directly set the spring enabled/disabled, that it should allow the joint to do that itself.
            bool m_bDisallowSpringEnable;

			virtual void SetRelaxationProperties();

		public:
			BlConstraintRelaxation();
			virtual ~BlConstraintRelaxation();

			virtual float MinLimit();
			virtual void MinLimit(float fltVal, bool bUseScaling = true);

			virtual float MaxLimit();
			virtual void MaxLimit(float fltVal, bool bUseScaling = true);

			virtual float EqPos();
			virtual void EqPos(float fltVal, bool bUseScaling = true);

			virtual void Damping(float fltVal, bool bUseScaling = true);

            virtual bool DisallowSpringEnable();
            virtual void DisallowSpringEnable(bool bVal);

            virtual void Initialize();

			virtual void CreateDefaultUnits();
			virtual bool SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError = true);
			virtual void QueryProperties(CStdPtrArray<TypeProperty> &aryProperties);

			virtual void Load(CStdXml &oXml);
		};

	}			// Visualization
}				//BulletAnimatSim


text:
package io.druid.java.util.common.parsers;

import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

/**
 */
public class ToLowerCaseParser implements Parser<String, Object>
{
  private final Parser baseParser;

  public ToLowerCaseParser(Parser baseParser)
  {
    this.baseParser = baseParser;
  }

  @Override
  public Map parse(String input)
  {
    Map<String, Object> line = baseParser.parse(input);
    Map<String, Object> retVal = Maps.newLinkedHashMap();
    for (Map.Entry<String, Object> entry : line.entrySet()) {
      String k = entry.getKey().toLowerCase();

      if(retVal.containsKey(k)) {
        // Duplicate key, case-insensitively
        throw new ParseException("Unparseable row. Duplicate key found : [%s]", k);
      }

      retVal.put(k, entry.getValue());
    }
    return retVal;
  }

  @Override
  public void startFileFromBeginning()
  {
    baseParser.startFileFromBeginning();
  }

  @Override
  public void setFieldNames(Iterable<String> fieldNames)
  {
    baseParser.setFieldNames(fieldNames);
  }

  @Override
  public List<String> getFieldNames()
  {
    return baseParser.getFieldNames();
  }
}