text:
package org.ovirt.engine.core.bll.gluster;

import java.util.Collections;
import java.util.List;

import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.LockMessagesMatchUtil;
import org.ovirt.engine.core.bll.utils.ClusterUtils;
import org.ovirt.engine.core.bll.utils.GlusterUtil;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerInfo;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.gluster.GlusterAuditLogUtil;
import org.ovirt.engine.core.dao.ClusterDao;
import org.ovirt.engine.core.dao.StepDao;
import org.ovirt.engine.core.dao.VdsDao;
import org.ovirt.engine.core.dao.VdsDynamicDao;
import org.ovirt.engine.core.dao.VdsStaticDao;
import org.ovirt.engine.core.dao.VdsStatisticsDao;
import org.ovirt.engine.core.dao.gluster.GlusterBrickDao;
import org.ovirt.engine.core.dao.gluster.GlusterClusterServiceDao;
import org.ovirt.engine.core.dao.gluster.GlusterGeoRepDao;
import org.ovirt.engine.core.dao.gluster.GlusterHooksDao;
import org.ovirt.engine.core.dao.gluster.GlusterOptionDao;
import org.ovirt.engine.core.dao.gluster.GlusterServerDao;
import org.ovirt.engine.core.dao.gluster.GlusterServerServiceDao;
import org.ovirt.engine.core.dao.gluster.GlusterServiceDao;
import org.ovirt.engine.core.dao.gluster.GlusterVolumeDao;
import org.ovirt.engine.core.dao.gluster.StorageDeviceDao;
import org.ovirt.engine.core.dao.network.InterfaceDao;
import org.ovirt.engine.core.dao.network.NetworkDao;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.lock.LockManager;
import org.ovirt.engine.core.utils.lock.LockManagerFactory;

public abstract class GlusterJob {

    private final LockManager lockManager = LockManagerFactory.getLockManager();
    protected GlusterAuditLogUtil logUtil = GlusterAuditLogUtil.getInstance();

    /**
     * Required so that the log util can be mocked in the JUnit test
     */
    protected void setLogUtil(GlusterAuditLogUtil logUtil) {
        this.logUtil = logUtil;
    }

    @SuppressWarnings("unchecked")
    protected List<GlusterServerInfo> fetchServers(VDS upServer) {
        VDSReturnValue result = runVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServer.getId()));

        return result.getSucceeded() ? (List<GlusterServerInfo>) result.getReturnValue() : null;
    }

    protected VDSReturnValue runVdsCommand(VDSCommandType commandType, VDSParametersBase params) {
        return Backend.getInstance().getResourceManager().runVdsCommand(commandType, params);
    }

    protected ClusterUtils getClusterUtils() {
        return ClusterUtils.getInstance();
    }

    protected VdsStatisticsDao getVdsStatisticsDao() {
        return DbFacade.getInstance().getVdsStatisticsDao();
    }

    protected VdsStaticDao getVdsStaticDao() {
        return DbFacade.getInstance().getVdsStaticDao();
    }

    protected VdsDynamicDao getVdsDynamicDao() {
        return DbFacade.getInstance().getVdsDynamicDao();
    }

    protected InterfaceDao getInterfaceDao() {
        return DbFacade.getInstance().getInterfaceDao();
    }

    protected ClusterDao getClusterDao() {
        return DbFacade.getInstance().getClusterDao();
    }

    protected VdsDao getVdsDao() {
        return DbFacade.getInstance().getVdsDao();
    }

    protected GlusterVolumeDao getVolumeDao() {
        return DbFacade.getInstance().getGlusterVolumeDao();
    }

    protected GlusterOptionDao getOptionDao() {
        return DbFacade.getInstance().getGlusterOptionDao();
    }

    protected GlusterBrickDao getBrickDao() {
        return DbFacade.getInstance().getGlusterBrickDao();
    }

    protected GlusterHooksDao getHooksDao() {
        return DbFacade.getInstance().getGlusterHooksDao();
    }

    protected GlusterServiceDao getGlusterServiceDao() {
        return DbFacade.getInstance().getGlusterServiceDao();
    }

    protected GlusterServerServiceDao getGlusterServerServiceDao() {
        return DbFacade.getInstance().getGlusterServerServiceDao();
    }

    protected GlusterClusterServiceDao getGlusterClusterServiceDao() {
        return DbFacade.getInstance().getGlusterClusterServiceDao();
    }

    protected GlusterServerDao getGlusterServerDao() {
        return DbFacade.getInstance().getGlusterServerDao();
    }

    protected StepDao getStepDao() {
        return DbFacade.getInstance().getStepDao();
    }

    protected GlusterGeoRepDao getGeoRepDao() {
        return DbFacade.getInstance().getGlusterGeoRepDao();
    }

    protected StorageDeviceDao getStorageDeviceDao() {
        return DbFacade.getInstance().getStorageDeviceDao();
    }

    protected NetworkDao getNetworkDao() {
        return DbFacade.getInstance().getNetworkDao();
    }

    /**
     * Acquires a lock on the cluster with given id and locking group {@link LockingGroup#GLUSTER}
     *
     * @param clusterId
     *            ID of the cluster on which the lock is to be acquired
     */
    protected void acquireLock(Guid clusterId) {
        lockManager.acquireLockWait(getEngineLock(clusterId));
    }

    /**
     * Releases the lock held on the cluster having given id and locking group {@link LockingGroup#GLUSTER}
     *
     * @param clusterId
     *            ID of the cluster on which the lock is to be released
     */
    protected void releaseLock(Guid clusterId) {
        lockManager.releaseLock(getEngineLock(clusterId));
    }

    /**
     * Returns an {@link EngineLock} instance that represents a lock on a cluster with given id and the locking group
     * {@link LockingGroup#GLUSTER}
     */
    private EngineLock getEngineLock(Guid clusterId) {
        return new EngineLock(Collections.singletonMap(clusterId.toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER, EngineMessage.ACTION_TYPE_FAILED_GLUSTER_OPERATION_INPROGRESS)), null);
    }

    protected EngineLock acquireGeoRepSessionLock(Guid id) {
        EngineLock lock = new EngineLock(Collections.singletonMap(id.toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER_GEOREP,
                        EngineMessage.ACTION_TYPE_FAILED_GEOREP_SESSION_LOCKED)), null);
        LockManagerFactory.getLockManager().acquireLockWait(lock);
        return lock;
    }

    protected EngineLock acquireVolumeSnapshotLock(Guid id) {
        EngineLock lock = new EngineLock(Collections.singletonMap(id.toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER_SNAPSHOT,
                        EngineMessage.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_LOCKED)), null);
        LockManagerFactory.getLockManager().acquireLockWait(lock);
        return lock;
    }

    protected GlusterUtil getGlusterUtil() {
        return GlusterUtil.getInstance();
    }
}


text:
using PdfSharp.Pdf.IO;
using System;
using System.IO;

namespace OutlookOkan.Models
{
    public sealed class PdfTools
    {
        internal bool CheckPdfIsEncrypted(string filePath)
        {
            //リンクとして添付の場合、実ファイルが存在しない場合がある。
            if (!File.Exists(filePath)) return false;

            try
            {
                PdfReader.Open(filePath, PdfDocumentOpenMode.ReadOnly).Dispose();
            }
            catch (PdfReaderException)
            {
                return true;
            }
            catch (Exception)
            {
                return false;
            }

            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
![Logo](https://github.com/EastPoint/CroMagVersion/raw/master/logo-128.png)

# CroMagVersion

CroMag helps to version all of the projects within a solution via a single file convention, and will bump build and version numbers of your project automatically during the build based on a date and version number scheme AND a build number variable that can originate from a build server like [Jenkins](http://jenkins-ci.org/).  Furthermore, DVCS changeset hashes also make their way into built assemblies.

## Requirements

* Nuget
* Package restore via [PepitaGet](http://code.google.com/p/pepita/) (or Nuget) highly recommended
* MSBuild 4 or higher (uses static property functions)
* To have the current short SHA1 hash added to AssemblyConfiguration, you must be using Mercurial or Git

## What does it do?

CroMagVersion allows projects to share the following assembly attributes:

* [AssemblyCompany](http://msdn.microsoft.com/en-us/library/system.reflection.assemblycompanyattribute.aspx) - Uses $(VersionCompany) and $(VersionCompanyUrl) from ```version.props```
* [AssemblyCopyright](http://msdn.microsoft.com/en-us/library/system.reflection.assemblycopyrightattribute.aspx) - Copyright $(Year) $(VersionCompany) from ```version.props```
* [AssemblyConfiguration](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyconfigurationattribute.aspx) - Annotated with build Configuration (i.e. Debug, Release) and the SHA1 hash of the current source version

* [AssemblyVersion](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.aspx) - Calculates date convention based version
* [AssemblyFileVersion](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyfileversionattribute.aspx) - Calculates date convention based version by default, but the layout can be customized (see below)
* [AssemblyInformationalVersion](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyinformationalversionattribute.aspx) - Calculates date convention based version, but the layout can be customized (see below)

## How does it work?

* During the package installation ```SharedAssemblyInfo.cs``` is added to the project file as a **linked file** that is generated by a **linked** T4 template -
```CroMagVersion.tt```.  This file will be shared amongst all projects that install the package, and is not actually copied into any projects.

  **NOTE: This isn't quite a *standard* T4 template.  There is no dependency on
  Visual Studio or any special MSBuild tasks or other cruft that make this
  difficult to share with other developers or use on a build server.  The T4
  generator from MonoDevelop is called via an Exec task right before the compile.
  The T4 template results *may* be refreshed in Visual Studio by running the
  ```Run Custom Tool``` command.  However, since the T4 template has no access
  to the real MSBuild ```$(SolutionDir)``` or ```$(Configuration)``` variables,
  the generated file does not have the same contents that it would otherwise
  have during a build (and will further be regenerated on the next build /
  rebuild cycle).**

* The constant ```CROMAG``` is added to any project configurations that DOES NOT
have the ```DEBUG``` constant defined.  Use this constant to restrict the
generation of versioning information for local developer builds.  Given the
nature of metadata versioning it is impossible to support [incremental builds](http://msdn.microsoft.com/en-us/library/ms171483.aspx).
For large projects, its vital to define the ```CROMAG``` constant on only the
build configuration used by the build server.

* A new file called ```version.props``` is copied to the solution folder if it doesn't exist - this is where user modifications such as major and minor version should be made.  These values are configurable and should always be modified by hand as needed.  If following semantic guidelines, there's no easy way to identify what things are breaking changes - this requires a human of at least average intelligence.

```xml
<MajorVersion>0</MajorVersion>
<MinorVersion>1</MinorVersion>
<VersionCompany></VersionCompany>
<VersionCompanyUrl></VersionCompanyUrl>
<!-- Typically this value will be supplied by a build server like Jenkins -->
<!--
<BUILD_NUMBER>0</BUILD_NUMBER>
-->
```
**NOTE: While this looks like an MSBuild file, it is not.  It is a standard XML
file**

* ```version.props``` is shared at the solution level, but projects must opt-in.
That is, they must install the CroMagVersion NuGet package to take advantage of
automatic versioning.

* A ```CroMagVersion``` msbuild target is injected into the project and it is
set to run before CoreCompile (the CSharp target typically responsible for
running the csc compiler).  In prior versions, this was done with the [Import](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx)
of a ```CroMagVersion.targets``` file, but this caused a chicken/egg scenario
in package restore scenarios, so the ```SharedAssemblyInfo.cs``` generation is
now performed by a T4 template instead, which doesn't prevent projects from
loading if it hasn't been restored from Nuget yet.

* Before the build goes down, ```SharedAssemblyInfo.cs``` file is updated with the major / minor version from ```version.props``` and has date based version information added in the following format:
$(MajorVersion).$(MinorVersion).$(YearMonth).$(DayNumber)$(Build)

    * ```YearMonth``` is a 2 digit year, 2 digit month - for instance 1203
    * ```DayNumber``` is a 2 digit day - for instance 03 or 31
    * ```$(Build)``` is 0 by default, or ```BUILD_NUMBER``` environment variable as supplied by Jenkins or via an override in ```version.props```.  Only the last 3 digits of this number can be used, as each fragment of the build number has a maximum of 65536.

Is this the best way to date tag a build?  Not necessarily, but it's a pretty reasonable solution that results in something human readable after the fact.

**NOTE: This system cannot accomodate multiple version changes in a day if there
is no build server providing a ```BUILD_NUMBER``` environment variable.**

## Customizing The Layout

```AssemblyFileVersion``` and ```AssemblyInformationalVersion``` can have customized layouts by enabling ```AssemblyFileVersionLayout``` or ```AssemblyInformationalVersionLayout``` in ```version.props``` .  This may be necessary to deal with wacky installers (like MSI) that don't consider a bump to the 4th number significant enough to upgrade an existing product install.  Sigh...

The following is pretty self-explanatory:

```xml
<!-- Available variables for a custom layout are:
  $(MajorVersion) - from this file
  $(MinorVersion) - from this file
  $(BUILD_NUMBER) - original number from build server / environment variable if available, otherwise 0, unless overriden in this file
  $(Build) - BUILD_NUMBER truncated to last 3 digits
  $(YearMonth) - yyMM
  $(DayNumber) - dd
  $(Year) - yyyy

  $(BuildVersion) - $(YearMonth)
  $(RevisionVersion) - $(DayNumber)$(Build)

  $(VersionNumber) - $(MajorVersion).$(MinorVersion).$(BuildVersion).$(RevisionVersion)

  Note that these are NOT proper MSBuild variables, and therefore
  arbitrary variables will not resolve.  Only these whitelisted
  variables will do anything.  All other strings, valid or not,
  will be treated as plaintext.
-->

<!--
<AssemblyFileVersionLayout>$(MajorVersion).$(MinorVersion).$(BuildVersion).$(RevisionVersion)</AssemblyFileVersionLayout>
<AssemblyInformationalVersionLayout>$(MajorVersion).$(MinorVersion).$(BuildVersion).$(RevisionVersion)</AssemblyInformationalVersionLayout>
-->
```

## A note about naming conventions for version pieces

This project follows the standard .NET style naming convention specified by [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) of Major.Minor.Build.Revision, where the 3rd and 4th numbers are Build and Revision.

Other systems tend to use different schemes:

* Major.Minor.Revision.Build - common many places, including, Java
* Major.Minor.Patch - for instance [SemVer](http://semver.org/)
* Major.Minor.Build, for instance MSI [ProductVersion](http://msdn.microsoft.com/en-us/library/windows/desktop/aa370859\(v=vs.85\).aspx).

The names for the slots aren't important so much as the semantics.

## Similar Projects

* [SemVerHarvester](https://github.com/jennings/SemVerHarvester) - MSBuild task library that harvests version numbers from tags in source control versions.  It appears to work with both Git and Mercurial.

## Future Improvements / Known Issues

* Until proper MSBuild inputs / outputs are figured out, there might be issues
in VS 2012 with parallel builds enabled.  File locking may occur, due to a race
condition with generation of SharedAssemblyInfo.cs.
* Ensure Mono works properly
* In Visual Studio, CroMagVersion.tt doesn't initially show under Properties,
even though it exists in the csproj on disk. This appears to be a VS bug.

## Release Notes

#### 0.3.5.0 - minor bugfix

* When hg or git was not in PATH, builds could generate spurious exceptions like
`System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified`

#### 0.3.4.0 - minor bugfix

* Deleting README-CroMagVersion.txt during install
* This file is used to ensure install.ps1 is kicked off, but thats it!

#### 0.3.2.0 - minor bugfix

* An initial DEBUG build would fail after the first package restore, until a RELEASE build
was executed first.  Now shipping an empty version file to work around this issue.

#### 0.3.1.0 - minor bugfixes

* If a project path contained spaces, TextTransform.exe would fail to handle the SolutionDir
properly.  There was an interesting issue with Mono.Options that made it more difficult than
it should have been to quote variables at the command line.
* Non-standard Git and Mercurial locations are OK, as long as git.exe or hg.exe is in the PATH.
* Uninstall no longer opens the AssemblyInfo.cs files modified during installation.  This is
because there is no way to differentiate a package update from a full on removal.

#### 0.3.0.0 - major rewrite of codegen procedure

* File generation is now provided through a T4 template instead of via an imported MSBuild target.
This was necessary to better support package restore, and should be a transparent under-the-hood change.
* Includes MonoDevelops TextTransform.exe to codegen instead of relying on anything that ships
with Visual Studio
* Adds a new CROMAG variable that must be defined to generate versioning code - by default this
is enabled for any non-DEBUG builds
* Breaking change - no longer emits MSBuild variables $(VersionNumber) $(Changeset) $(BuildVersion)
or $(RevisionVersion)

#### 0.2.5.0

* Removed MSBuild-y ness from version.props since its extraneous and confuses things (breaking change)
* Added ability to override FileVersion and AssemblyInformationalVersion versions with a custom layout given a few well known variables
* Able to find AssemblyInfo.cs in locations other than Properties folder
* Using BeforeTargets="CoreCompile" instead of BeforeTargets="Build"
* Renamed Lines ItemGroup internally to AssemblyInfoLines to prevent possible collisions with other global MSBuild variables
* Renamed Version target to CroMagVersion target to prevent possible MSBuild collisions
* CroMagVersion now registered as a dependency via BuildDependsOn and RebuildDependsOn

## Contributing

Fork the code, and submit a pull request!

Any useful changes are welcomed.  If you have an idea you'd like to see implemented that strays far from the simple spirit of the application, ping us first so that we're on the same page.

## Credits

* [MonoDevelop TextTemplating Add-In](https://github.com/mono/monodevelop/tree/master/main/src/addins/TextTemplating) - provides the
T4 templating engine used
* [Git-Last-Commit Gist](https://gist.github.com/966148) - inline msbuild task for grabbing Git command line output
* [StackOverlow - How can I auto increment the C# assembly version via our CI platform (Hudson)?](http://stackoverflow.com/questions/1126880/how-can-i-auto-increment-the-c-assembly-version-via-our-ci-platform-hudson)
* [Mercurial Revision No to Version your AssemblyInfo - MsBuild Series](http://markkemper1.blogspot.com/2010/10/mercurial-revision-no-to-version-your.html)
* The logo is from the [Dino Icon Pack](http://www.fasticon.com/freeware/dino-icons/) produced by FastIcon.
* [MSBuild.Mercurial](http://msbuildhg.codeplex.com/) - tasks for retrieving info from a hg repo - no longer used, but provided initial inspiration for changeset
retrieval


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK
#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK

#include "gmock/gmock.h"
#include "application_manager/application.h"
#include "application_manager/hmi_state.h"
#include "application_manager/state_controller.h"
#include "application_manager/application_manager.h"
#include "interfaces/MOBILE_API.h"

namespace state_controller_test {
namespace am = application_manager;

class StateControllerMock :public am::StateController {
 public:
  MOCK_METHOD2(SetRegularState, void (
      am::ApplicationSharedPtr, const mobile_apis::AudioStreamingState::eType));
  MOCK_METHOD2(SetRegularState, void (
      am::ApplicationSharedPtr, const mobile_apis::SystemContext::eType));
  MOCK_METHOD3(OnStateChanged, void (
      am::ApplicationSharedPtr, am::HmiStatePtr, am::HmiStatePtr));
  MOCK_METHOD1(ApplyStatesForApp, void (am::ApplicationSharedPtr));
  MOCK_METHOD0(OnNaviStreamingStarted, void ());
  MOCK_METHOD0(OnNaviStreamingStopped, void ());
};

}
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK


text:
'use strict';

function ComplexBuilderZero() {

}

ComplexBuilderZero.construct = function (theArguments) {

    return {re: 0, im: 0};
};

module.exports = ComplexBuilderZero;


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 83: 48 (2002)

#### Original name
Glabrocyphella stercoraria Barrasa, Esteve-Rav. & Sánchez Nieto, 1998

### Remarks
null


text:
<?php
namespace PHPCrystal\PHPCrystalTest;

use PHPCrystal\PHPCrystal\Service\Event as Event;

/**
 * @backupGlobals disabled
 */
class TestCaseDummy extends TestCase
{
	public function setUp()
	{
		$autoloader = require (__DIR__ . '/../../vendor/autoload.php');

		$this->appPkg = Application::create($autoloader)
			->addExtension(__DIR__ . '/../..')
			->bootstrap(Event\Type\Dummy::create())
		;
	}
}


text:
/*
the jQuery dataTables plugin is documented at
http://datatables.net/reference/api/

instantiated on eventsBrowserPageView as:

this.eventsSearchObserverCollection = new SearchObserverCollection({

    // overwriting to call timestamp instead of "@timestamp"
    addRange: function() {
        return '?timestamp__range={"gte":' + this.gte + ',"lte":' + this.epochNow + '}';
    },

    urlBase: '/core/events/',
    skipFetch: true
});

this.eventsBrowserView = new ChartSet({

    // overwrite processListeners
    processListeners: function() {
        var self = this;

        // registers 'sync' event so view 'watches' collection for data update
        if (this.collection) {
            this.listenTo(this.collection, 'sync', this.update);
            this.listenTo(this.collection, 'error', this.dataErrorMessage);
        }

        this.listenTo(this, 'lookbackSelectorChanged', function() {
            self.showSpinner();
            self.collection.triggerDataTableFetch();
        });
    },

    chartTitle: goldstone.contextTranslate('Event Search', 'eventsbrowser'),
    collection: this.eventsSearchObserverCollection,
    el: '#events-histogram-visualization',
    marginLeft: 60,
    width: $('#events-histogram-visualization').width(),
    yAxisLabel: goldstone.contextTranslate('Number of Events', 'eventsbrowser')
});

*/

var EventsBrowserDataTableView = DataTableBaseView.extend({

    instanceSpecificInit: function() {
        EventsBrowserDataTableView.__super__.instanceSpecificInit.apply(this, arguments);
        this.processListenersForServerSide();
        this.renderFreshTable();
        this.initializeSearchTableServerSide('#reports-result-table');
    },

    update: function() {
        this.oTable.ajax.reload();
    },

    oTableParamGeneratorBase: function() {
        var self = this;
        var standardAjaxOptions = {

            // corresponds to 'show xx entries' selector
            "iDisplayLength": self.cachedPageSize,

            // corresponds to 'showing x to y of z entries' display
            // and affects which pagination selector is active
            "iDisplayStart": self.cachedPaginationStart,
            "lengthChange": true,

            // populate search input box with string, if present
            "oSearch": {
                sSearch: self.cachedSearch
            },
            "ordering": true,
            "processing": false,
            "paging": true,
            "scrollX": true,
            "searching": true,
            "serverSide": true,
            "ajax": {
                beforeSend: function(obj, settings) {
                    self.hideSpinner();

                    // having the results of the last render that fit the
                    // current heading structure will allow to return it to
                    // the table that is about to be destroyed and overwritten.
                    // just returning an empty set will cause a disorienting
                    // flash when the table is destroyed, prior to the next
                    // one being constructed.
                    self.mockForAjaxReturn = self.cachedResults;

                    // store the browser page height to restore it post-render
                    self.currentTop = $(document).scrollTop();
                    self.currentScrollLeft = $('.dataTables_scrollBody').scrollLeft();

                    // call the url generation function that will
                    // create the url string to replace the
                    // datatables native url generation
                    self.collectionMixin.urlGenerator();

                    // extraction methods defined on dataTableBaseView
                    // for the dataTables generated url string that will
                    //  be replaced by self.collectionMixin.url after
                    // the required components are parsed out of it
                    var pageSize = self.getPageSize(settings.url);
                    var searchQuery = self.getSearchQuery(settings.url);
                    var paginationStart = self.getPaginationStart(settings.url);
                    var computeStartPage = Math.floor(paginationStart / pageSize) + 1;
                    var sortByColumnNumber = self.getSortByColumnNumber(settings.url);
                    var sortAscDesc = self.getSortAscDesc(settings.url);

                    // cache values for next serverside deferred rendering
                    self.cachedSearch = searchQuery;

                    // convert strings to numbers for both
                    self.cachedPageSize = parseInt(pageSize, 10);
                    self.cachedPaginationStart = parseInt(paginationStart, 10);

                    // cache ordering column and direction to highlight the
                    // selected column upon next table rendering
                    self.cachedSortAscDesc = sortAscDesc;
                    self.cachedSortByColumnNumber = parseInt(sortByColumnNumber, 10);

                    // the url that will be fetched is now about to be
                    // replaced with the urlGen'd url before adding on
                    // the parsed components
                    settings.url = self.collectionMixin.url + "&page_size=" + pageSize +
                        "&page=" + computeStartPage;

                    // here begins the combiation of additional params
                    // to construct the final url for the dataTable fetch
                    if (searchQuery) {
                        settings.url += "&_all__regexp=.*" +
                            searchQuery + ".*";
                    }

                    // ordering by column

                    /*
                    columnLabelHash is now being dynamically generated
                    before this standardAjaxOptions is returned.

                    var columnLabelHash = {
                        0: 'timestamp',
                        1: 'eventType',
                        ... dynamically constructed
                    };
                    */

                    var ascDec = {
                        asc: '',
                        'desc': '-'
                    };

                    if (this.columnLabelHash[sortByColumnNumber]) {

                        var nameToStore = this.columnLabelHash[sortByColumnNumber];
                        // correct for vagaries in ES results
                        if (nameToStore === 'eventTime') {
                            nameToStore = 'timestamp';
                        }

                        // store the columnHeadingByName of the actual sort column that was clicked
                        self.cachedColumnHeadingByName = this.columnLabelHash[sortByColumnNumber];

                        settings.url = settings.url + "&ordering=" + ascDec[sortAscDesc] + nameToStore;
                    }

                },
                dataSrc: "results",
                dataFilter: function(data) {
                    data = JSON.parse(data);

                    // eventViz will handle rendering of aggregations
                    self.sendAggregationsToViz(data);

                    data = self.serverSideDataPrep(data);

                    // add to JavaScript engine event loop to be handled
                    // after the function returns and the table
                    // renders the 'throw-away' version of the table
                    setTimeout(function() {
                        self.createNewDataTableFromResults(self.cachedTableHeadings, self.cachedResults);

                    }, 0);

                    // make the 'throw-away' version identical to the
                    // currently rendered table for better UX
                    if (self.mockForAjaxReturn) {
                        return JSON.stringify(
                            self.mockForAjaxReturn
                        );
                    } else {

                        // upon instantiation, just render empty dataTable
                        return JSON.stringify({
                            results: []
                        });
                    }
                },
            }
        }; // end standardAjaxOptions

        // in the case of their being cached data from the last call,
        // deferLoading will skip the ajax call and use the
        // data already present in the dom
        if (self.cachedResults) {

            // sets 'z' in 'showing x to y of z records'
            standardAjaxOptions.deferLoading = self.cachedResults.recordsTotal;
        }

        // standardAjaxOptions.ajax.columnLabelHash = {
        //     0: 'timestamp',
        //     1: 'eventType',
        //    ...
        // };

        // set up the dynamic column label ordering scheme
        standardAjaxOptions.ajax.columnLabelHash = self.createHashFromArray(self.cachedHeadingArray);

        // set up the proper column heading ordering arrow
        if ((this.cachedSortByColumnNumber !== undefined) && this.cachedSortAscDesc) {

            // find the clicked column label in the hash
            var newIndexOfSortColumn = _.findKey(standardAjaxOptions.ajax.columnLabelHash, function(item) {
                return item === self.cachedColumnHeadingByName;
            });

            // if the sort column is no longer existent, don't
            // impose a sort order on the table
            if (newIndexOfSortColumn !== undefined) {
                standardAjaxOptions.order = [
                    [newIndexOfSortColumn, this.cachedSortAscDesc]
                ];
            }
        }

        // will be used as the 'options' when instantiating dataTable
        return standardAjaxOptions;
    },

    createHashFromArray: function(arr) {
        var result = {};

        if (!arr) {
            return {
                0: 'eventTime'
            };
        }

        _.each(arr, function(item, key) {
            result[key] = item;
        });

        return result;
    },

    prepDataForViz: function(data) {
        // initialize container for formatted results
        var finalResult = [];

        // for each array index in the 'data' key
        _.each(data.aggregations.per_interval.buckets, function(item) {
            var tempObj = {};
            tempObj.time = item.key;
            tempObj.count = item.doc_count;
            finalResult.push(tempObj);
        });

        return finalResult;
    },

    sendAggregationsToViz: function(data) {

        // send data to collection to be rendered via eventBrowserView
        // when the 'sync' event is triggered
        this.collectionMixin.reset();
        this.collectionMixin.add(this.prepDataForViz(data));
        this.collectionMixin.trigger('sync');
    },

    createNewDataTableFromResults: function(headings, results) {

        // at least one  required or else dataTables will error
        headings = headings || '	';

        // removes dataTable handling of table (sorting/searching/pagination)
        // but visible data remaions in DOM
        this.oTableApi.fnDestroy();

        // cache updated headings
        this.serverSideTableHeadings = headings;
        this.renderFreshTable();

        // construct table html from results matrix
        var constructedResults = '';
        _.each(results.results, function(line) {
            constructedResults += '
';
            constructedResults += line.join('	');
            constructedResults += '
';
        });

        // insert constructed table html into DOM target
        this.$el.find('.data-table-body').html(constructedResults);

        // 'turn on' dataTables handling of table in DOM.
        this.initializeSearchTableServerSide('#reports-result-table');

    },

    serverSideDataPrep: function(data) {
        var result = {

            // run results through pre-processing step
            results: this.extractUniqAndDataSet(data.results),
            recordsTotal: data.count,
            recordsFiltered: data.count
        };
        this.cachedResults = result;
        result = JSON.stringify(result);
        return result;
    },

    // just an empty  element for initial render.
    serverSideTableHeadings: '' +
        '	',

    extractUniqAndDataSet: function(data) {
        var self = this;

        // strip object down to things in 'traits' and then
        // flatten object before returning it to the dataPrep function
        var result = data.map(function(record) {
            return record._source.traits;
        });

        var uniqueObjectKeys = _.uniq(_.flatten(result.map(function(record) {
            return _.keys(record);
        })));

        // START SORT

        // sort uniqueHeadings to favor order defined
        // by the hash in this.headingsToPin

        // if there is a unique key with "name" somewhere in it,
        // reorder the keys so that it is first
        var keysWithName = [];
        for (var i = 0; i < uniqueObjectKeys.length; i++) {
            var item = uniqueObjectKeys[i];
            if (this.isPinnedHeading(item)) {
                var spliced = uniqueObjectKeys.splice(i, 1);
                keysWithName[this.headingsToPin[item]] = spliced;
                i--;
            } else {
                continue;
            }
        }

        // keysWithName have been pulled out, now remove artifacts
        keysWithName = this.pruneUndefinedValues(keysWithName);

        // and sort remaining uniqueObjectKeys (sans keysWithName)
        uniqueObjectKeys = this.sortRemainingKeys(uniqueObjectKeys);

        // now put the keysWithName back at the beginning of the
        // uniqueObjectKeys array
        _.each(keysWithName, function(item) {
            uniqueObjectKeys.unshift(item[0]);
        });

        // store the sorted list so it can be used to create a map for
        // the column that is clicked for sorting
        self.cachedHeadingArray = uniqueObjectKeys;

        // END SORT

        // now use the uniqueObjectKeys to construct the table header
        // for the upcoming render
        var headerResult = '';
        _.each(uniqueObjectKeys, function(heading) {
            headerResult += '' + heading + '	';
        });

        // and store for later
        self.cachedTableHeadings = headerResult;

        // make nested arrays of the final data to return
        // any undefined values will be replaced with empty string
        var finalResult = result.map(function(unit) {
            return _.map(uniqueObjectKeys, function(heading) {
                return unit[heading] || '';
            });
        });

        return finalResult;
    },

    // keys will be pinned in ascending value order of key:value pair
    headingsToPin: {
        'eventTime': 0,
        'eventType': 1,
        'id': 2,
        'action': 3,
        'outcome': 4
    },

    // main template with placeholder for table
    template: _.template(
        '

' +
        '

'
    ),

    // table to be used with dataTables
    // dynamic headers to be inserted in the 'data-table-header-container'
    dataTableTemplate: _.template(
        '
' +
        '
' +
        '
' +

        //  elements will be dynamically inserted
        '
' +
        '
' +
        '

' +
        '
'
    ),

    renderFreshTable: function() {

        // the main table template only needs to be added once, to avoid
        // poor UX from erasing and re-rendering entire table.
        if (!$('.data-table-body').length) {
            $(this.el).find('.refreshed-report-container').html(this.dataTableTemplate());
        }

        // add the default or generated table headings
        $(this.el).find('.data-table-header-container').html(this.serverSideTableHeadings);

        return this;
    },

    initializeSearchTableServerSide: function(location) {
        // params will include "deferLoading" after initial table rendering
        // in order for table to be able to recursively spawn itself
        // without infinite loop
        var oTableParams = this.oTableParamGeneratorBase();

        // initialize dataTable
        this.oTable = $(location).DataTable(oTableParams);

        // set reference to dataTable api to be used for fnDestroy();
        this.oTableApi = $(location).dataTable();

        // bring focus to search box
        if ($('input.form-control').val() !== undefined) {
            $('input.form-control').focus();

            // firefox puts the cursor at the beginning of the search box
            // after re-focus. Use the native 'input' element method
            // setSelectionRange to force cursor position to end of input box
            if ($('input')[0].setSelectionRange) {
                var len = $('input.form-control').val().length * 2; // ensure end
                $('input.form-control')[0].setSelectionRange(len, len);
            } else {

                // IE hack, replace input with itself, hopefully to
                // end up with cursor at end of input element
                $('input.form-control').val($('input.form-control').val());
            }

            // in case input element is a text field
            $('input.form-control').scrollTop = 1e6;
        }

        // reposition page to pre-refresh height
        if (this.currentTop !== undefined) {
            $(document).scrollTop(this.currentTop);
        }
        if (this.currentScrollLeft !== undefined) {
            $('.dataTables_scrollBody').scrollLeft(this.currentScrollLeft);
        }
    }
});


text:
package org.apache.guacamole.net.auth;

import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.GuacamoleTunnel;
import org.apache.guacamole.protocol.GuacamoleClientInformation;

/**
 * An object which Guacamole can connect to.
 */
public interface Connectable {

    /**
     * Establishes a connection to guacd using the information associated with
     * this object. The connection will be provided the given client
     * information.
     *
     * @param info
     *     Information associated with the connecting client.
     *
     * @return
     *     A fully-established GuacamoleTunnel.
     *
     * @throws GuacamoleException
     *     If an error occurs while connecting to guacd, or if permission to
     *     connect is denied.
     */
    public GuacamoleTunnel connect(GuacamoleClientInformation info)
            throws GuacamoleException;

    /**
     * Returns the number of active connections associated with this object.
     * Implementations may simply return 0 if this value is not tracked.
     *
     * @return
     *     The number of active connections associated with this object.
     */
    public int getActiveConnections();

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Iconogr. Mycol. 18: 878 (1931)

#### Original name
Coprinus atramentarius var. squamosus Bres.

### Remarks
null


text:
package io.opencensus.exporter.stats.signalfx;

import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.opencensus.common.Duration;
import java.net.URI;
import java.net.URISyntaxException;
import javax.annotation.concurrent.Immutable;

/**
 * Configurations for {@link SignalFxStatsExporter}.
 *
 * @since 0.11
 */
@AutoValue
@Immutable
public abstract class SignalFxStatsConfiguration {

  /**
   * The default SignalFx ingest API URL.
   *
   * @since 0.11
   */
  public static final URI DEFAULT_SIGNALFX_ENDPOINT;

  static {
    try {
      DEFAULT_SIGNALFX_ENDPOINT = new URI("https://ingest.signalfx.com");
    } catch (URISyntaxException e) {
      // This shouldn't happen if DEFAULT_SIGNALFX_ENDPOINT was typed in correctly.
      throw new IllegalStateException(e);
    }
  }

  /**
   * The default stats export interval.
   *
   * @since 0.11
   */
  public static final Duration DEFAULT_EXPORT_INTERVAL = Duration.create(1, 0);

  private static final Duration ZERO = Duration.create(0, 0);

  SignalFxStatsConfiguration() {}

  /**
   * Returns the SignalFx ingest API URL.
   *
   * @return the SignalFx ingest API URL.
   * @since 0.11
   */
  public abstract URI getIngestEndpoint();

  /**
   * Returns the authentication token.
   *
   * @return the authentication token.
   * @since 0.11
   */
  public abstract String getToken();

  /**
   * Returns the export interval between pushes to SignalFx.
   *
   * @return the export interval.
   * @since 0.11
   */
  public abstract Duration getExportInterval();

  /**
   * Returns a new {@link Builder}.
   *
   * @return a {@code Builder}.
   * @since 0.11
   */
  public static Builder builder() {
    return new AutoValue_SignalFxStatsConfiguration.Builder()
        .setIngestEndpoint(DEFAULT_SIGNALFX_ENDPOINT)
        .setExportInterval(DEFAULT_EXPORT_INTERVAL);
  }

  /**
   * Builder for {@link SignalFxStatsConfiguration}.
   *
   * @since 0.11
   */
  @AutoValue.Builder
  public abstract static class Builder {

    Builder() {}

    /**
     * Sets the given SignalFx ingest API URL.
     *
     * @param url the SignalFx ingest API URL.
     * @return this.
     * @since 0.11
     */
    public abstract Builder setIngestEndpoint(URI url);

    /**
     * Sets the given authentication token.
     *
     * @param token the authentication token.
     * @return this.
     * @since 0.11
     */
    public abstract Builder setToken(String token);

    /**
     * Sets the export interval.
     *
     * @param exportInterval the export interval between pushes to SignalFx.
     * @return this.
     * @since 0.11
     */
    public abstract Builder setExportInterval(Duration exportInterval);

    abstract SignalFxStatsConfiguration autoBuild();

    /**
     * Builds a new {@link SignalFxStatsConfiguration} with current settings.
     *
     * @return a {@code SignalFxStatsConfiguration}.
     * @since 0.11
     */
    public SignalFxStatsConfiguration build() {
      SignalFxStatsConfiguration config = autoBuild();
      Preconditions.checkArgument(
          !Strings.isNullOrEmpty(config.getToken()), "Invalid SignalFx token");
      Preconditions.checkArgument(
          config.getExportInterval().compareTo(ZERO) > 0, "Interval duration must be positive");
      return config;
    }
  }
}


text:
void ComputeQuantiles(const vector<vector<string>* >& buffer,
  const string& min_string, const string& max_string,
  int num_quantiles, int64 tot_elems, vector<string>* quantiles);

// Simple struct that stores a single entry of quantile summary.
// It is a triple (string, int64, int64) that stores the value
// along with some bookkeeping vars (g_value, delta). See the
// paper above for details.

struct SummaryTuple {
  string value;  // Sample value from stream of input elements

  // Difference between the minimum rank of this element
  // and the previous one. See paper for details.
  int64 g_value;

  // Difference between the minimum and maximum rank of this
  // element.
  int64 delta;

  // Simple constructor. Simply copies the values that
  // are input into appropriate struct vars.
  SummaryTuple(const string& in_value,
               int64 in_g_value, int64 in_delta)
    : value(in_value), g_value(in_g_value), delta(in_delta)  { }
};

REGISTER_SZL_TAB_WRITER(quantile, SzlQuantile);

// We compute the "smallest possible k" satisfying two inequalities:
//    1)   (b - 2) * (2 ^ (b - 2)) + 0.5 <= epsilon * MAX_TOT_ELEMS
//    2)   k * (2 ^ (b - 1)) \geq MAX_TOT_ELEMS
//
// For an explanation of these inequalities, please read the Munro-Paterson or
// the Manku-Rajagopalan-Linday papers.
int64 SzlQuantile::SzlQuantileEntry::ComputeK() {
  const double epsilon = 1.0 / (num_quantiles_ - 1);
  int b = 2;
  while ((b - 2) * (0x1LL << (b - 2)) + 0.5 <= epsilon * MAX_TOT_ELEMS) {
    ++b;
  }
  const int64 k = MAX_TOT_ELEMS / (0x1LL << (b - 1));
  VLOG(2) << StringPrintf(
      "ComputeK(): returning k = %lld for num_quantiles_ = %d (epsilon = %f)",
      k, num_quantiles_, epsilon);
  return k;
}

// If buffer_[level] already exists, do nothing.
// Else create a new buffer_[level] that is empty.
int SzlQuantile::SzlQuantileEntry::EnsureBuffer(const int level) {
  int extra_memory = 0;
  if (buffer_.size() < level + 1) {
    size_t old_capacity = buffer_.capacity();
    buffer_.resize(level + 1, NULL);
    extra_memory +=
        (buffer_.capacity() - old_capacity) * sizeof(vector<string>*);
  }
  if (buffer_[level] == NULL) {
    VLOG(2) << StringPrintf("Creating buffer_[%d] ...", level);
    buffer_[level] = new vector<string>();
    extra_memory += sizeof(*(buffer_[level]));
  }
  return extra_memory;
}

// Estimate the amount of memory being used.
// This is an expensive call since it iterates over all members of
// all buffers in "buffer_".
int SzlQuantile::SzlQuantileEntry::Memory() {
  // capacity() returns the number of elements for which memory has
  // been allocated. capacity() is always greater than or equal to size().
  int memory = sizeof(SzlQuantileEntry) + min_.size() + max_.size()
      + sizeof(vector<string> *) * buffer_.capacity();

  for (vector<vector<string>* >::const_iterator iter = buffer_.begin();
      iter != buffer_.end(); ++iter) {
    if (*iter == NULL)
      continue;
    // Account for the memory taken by the current buffer.
    memory += sizeof(**iter) + (*iter)->capacity() * sizeof(string);
    for (vector<string>::const_iterator member = (*iter)->begin();
        member != (*iter)->end(); ++member) {
      memory += member->size();
    }
  }
  return memory;
}

// For Collapse(), both "a" and "b" should be vectors of length "k_".
// Conceptually, Collapse() combines "a" and "b" into a single vector, sorts
// this vector and then chooses every other member of this vector.
// The result is stored in "output".
//
// The return value is the change is memory requirements. What causes
// increase/decrease in memory?  (i) "output" is populated and (ii) just before
// returning, both "a" and "b" are cleared.
int SzlQuantile::SzlQuantileEntry::Collapse(vector<string> *const a,
                                            vector<string> *const b,
                                            vector<string> *const output) {
  CHECK_EQ(a->size(), k_);
  CHECK_EQ(b->size(), k_);
  CHECK_EQ(output->size(), 0);

  int memory_delta = 0;
  int index_a = 0;
  int index_b = 0;
  int count = 0;
  const string* smaller;

  while (index_a < k_ || index_b < k_) {
    if (index_a >= k_ || (index_b < k_ && a->at(index_a) >= b->at(index_b))) {
      smaller = &(b->at(index_b++));
    } else {
      smaller = &(a->at(index_a++));
    }

    if ((count++ % 2) == 0) {  // remember "smallest"
      output->push_back(*smaller);
    } else {  // forget "smallest"
      memory_delta -= smaller->size();
    }
  }

  // Account for the memory taken by output and a & b.
  memory_delta += (output->capacity() - a->capacity() - b->capacity())
      * sizeof(string);

  // Make sure we completely deallocate the memory taken by a & b.
  {
    vector<string> tmp;
    a->swap(tmp);
  }
  {
    vector<string> tmp;
    b->swap(tmp);
  }

  return memory_delta;
}

// Algorithm for RecursiveCollapse():
//
// 1. Let "merged" denote the output of Collapse("buf", "buffer_[level]")
//
// 2. If "buffer_[level + 1]" is full (i.e., already exists)
//      Collapse("merged", "buffer_[level + 1]")
//    else
//      "buffer_[level + 1]"  <-- "merged"
//
// The return value is the difference in memory usage.
int SzlQuantile::SzlQuantileEntry::RecursiveCollapse(vector<string> *buf,
                                                     const int level) {
  VLOG(2) << StringPrintf("RecursiveCollapse() invoked with level = %d", level);

  CHECK_EQ(buf->size(), k_);
  CHECK_GE(level, 1);
  CHECK_GE(buffer_.size(), level + 1);
  CHECK(buffer_[level] != NULL);
  CHECK_EQ(buffer_[level]->size(), k_);

  int memory_delta = EnsureBuffer(level + 1);

  vector<string> *merged;
  if (buffer_[level + 1]->size() == 0) {  // buffer_[level + 1] is empty
    merged = buffer_[level + 1];
  } else {                                // buffer_[level + 1] is full
    merged = new vector<string>;
    // merged is going to be filled with k_ elements we might as well
    // reserve the space now.
    merged->reserve(k_);
  }
  // We account for the memory taken by merged even if it's a
  // temporary vector, since in this case it will be passed to
  // RecursiveCollapse, which will substract the memory it takes.
  memory_delta += Collapse(buffer_[level], buf, merged);
  if (buffer_[level + 1] == merged) {
    return memory_delta;
  }
  memory_delta += RecursiveCollapse(merged, level + 1);
  delete merged;
  return memory_delta;
}

// Goal: Add a new element ("elem" is a SzlEncoded value).
// Return value: "diff in memory usage".
//
// Algorithm:
//   if (buffer_[0] is not full (i.e., has less than k_ elements)) {
//       insert "elem" into buffer_[0]
//   } else if buffer_[1] is not full (i.e., has less than k_ elements) {
//       insert "elem" into "buffer_[1]"
//   } else {
//       Sort buffer_[0] and buffer_[1]
//       RecursiveCollapse(buffer_[0], buffer_[1])
//       Insert into buffer_[0]
//   }
int SzlQuantile::SzlQuantileEntry::AddElem(const string& elem) {
  int memory_delta = 0;

  // Update min_ and max_.
  if ((tot_elems_ == 0) || (elem < min_)) {
    memory_delta += elem.size() - min_.size();
    min_ = elem;
    VLOG(3) << "AddElem(" << elem << "): min_ updated to " << min_;
  }
  if ((tot_elems_ == 0) || (max_ < elem)) {
    memory_delta += elem.size() - max_.size();
    max_ = elem;
    VLOG(3) << "AddElem(" << elem << "): max_ updated to " << max_;
  }

  // First, test if both buffer_[0] and buffer_[1] are full.
  // This is equivalent to testing
  //    (tot_elems_ > 0)    &&   (tot_elems_ % (2 * k_) == 0).
  // If so, sort buffer_[0] and buffer_[1] and invoke RecursiveCollapse().
  // When RecursiveCollapse() returns, both buffer_[0] and buffer_[1] would be
  // "empty" (i.e., with zero elements in them).
  if ((tot_elems_ > 0) && (tot_elems_ % (2 * k_) == 0)) {
    CHECK(buffer_[0] != NULL);
    CHECK(buffer_[1] != NULL);
    CHECK_EQ(buffer_[0]->size(), k_);
    CHECK_EQ(buffer_[1]->size(), k_);
    VLOG(2) << "AddElem(" << elem << "): Sorting buffer_[0] ...";
    sort(buffer_[0]->begin(), buffer_[0]->end());
    VLOG(2) << "AddElem(" << elem << "): Sorting buffer_[1] ...";
    sort(buffer_[1]->begin(), buffer_[1]->end());
    const int level = 1;
    // RecursiveCollapse will start with Collapse(buffer_[0], buffer_[level]).
    memory_delta += RecursiveCollapse(buffer_[0], level);
  }

  // At this point, we are sure that either buffer_[0] or buffer_[1] can
  // accommodate "elem".
  memory_delta += EnsureBuffer(0);
  memory_delta += EnsureBuffer(1);
  CHECK((buffer_[0]->size(), k_) || (buffer_[1]->size(), k_));
  int index = (buffer_[0]->size() < k_) ? 0 : 1;
  VLOG(3) << "AddElem(" << elem << "): Inserting into buffer_[" << index << "]";
  int old_capacity = buffer_[index]->capacity();
  buffer_[index]->push_back(elem);
  memory_delta += elem.size()
      + (buffer_[index]->capacity() - old_capacity) * sizeof(string);
  ++tot_elems_;
  VLOG(3) << StringPrintf("AddElem(%s): returning with tot_elems_ = %lld",
                          elem.c_str(), tot_elems_);
  return memory_delta;
}

// Flush the state to "output".
void SzlQuantile::SzlQuantileEntry::Flush(string* output) {
  SzlEncoder enc;

  // We emit "dummy_epsilon == 0.0" for historyical reasons.
  double dummy_epsilon = 0.0;
  enc.PutInt(tot_elems_);
  enc.PutInt(num_quantiles_);
  enc.PutFloat(dummy_epsilon);
  enc.PutInt(k_);
  enc.PutInt(buffer_.size());

  if (tot_elems_ > 0) {
    // Encode "min_" and "max_".
    enc.AppendEncoding(min_.data(), min_.size());
    enc.AppendEncoding(max_.data(), max_.size());

    // Encode each member of "buffer_[]".
    for (vector<vector<string>* >::const_iterator iter = buffer_.begin();
         iter != buffer_.end(); ++iter) {
      if (*iter == NULL) {
        enc.PutInt(0);
      } else {
        enc.PutInt((*iter)->size());
        for (vector<string>::const_iterator member = (*iter)->begin();
             member != (*iter)->end(); ++member) {
          enc.AppendEncoding(member->data(), member->size());
        }
      }
    }
  }
  enc.Swap(output);
  Clear();
  VLOG(2) << StringPrintf("Flush() succeeded. tot_elems_ = %lld", tot_elems_);
}

void SzlQuantile::SzlQuantileEntry::FlushForDisplay(vector<string>* output) {
  output->clear();
  if (tot_elems_ == 0) {
    output->push_back("");
    return;
  }

  // We display the quantiles, not the raw output.
  ComputeQuantiles(buffer_, min_, max_, num_quantiles_, tot_elems_, output);
}

// Simple helper function to extract a value from "dec" by using "ops()".
// Returns true on success, false on failure.
bool SzlQuantile::SzlQuantileEntry::EncodingToString(SzlDecoder *const dec,
                                        string *const output) {
  // Record the starting position of the next value.
  unsigned const char* p1 = dec->position();
  // Skip past it
  if (!element_ops().Skip(dec)) {
    return false;
  }
  // Now we know the end of the encoded value.
  // Record the new position
  unsigned const char* p2 = dec->position();
  output->assign(reinterpret_cast<const char*>(p1), p2 - p1);
  return true;
}

// Goal: Merge "val" with the existing state stored in SzlQuantileEntry.
//
// Recap:
//   Please read the short description of Munro-Paterson algorithm at the very
//   top of this file. Then, recall that SzlQuantileEntry::Flush() simply dumps
//   all non-empty buffers (in the binary tree of buffers).
//
// Algorithm:
//   We have to merge two "trees of buffers".
SzlTabEntry::MergeStatus SzlQuantile::SzlQuantileEntry::Merge(
                                      const string& val) {
  SzlDecoder dec(val.data(), val.size());
  int64 tot_elems, num_quantiles, k, num_buffers;

  double dummy_epsilon = 0.0;
  if (!val.empty()) {
    // Format errors and sanity checks
    if ((!dec.GetInt(&tot_elems)) || (tot_elems < 0)
        || (!dec.GetInt(&num_quantiles)) || (num_quantiles != num_quantiles_)
        || (!dec.GetFloat(&dummy_epsilon))) {
      LOG(ERROR) << "Failed to parse header in Merge()";
      return MergeError;
    }
  }

  if (val.empty() || dummy_epsilon > 0.0) {
    return MergeError;
  }
  if ((!dec.GetInt(&k)) || (k != k_) || (!dec.GetInt(&num_buffers))) {
    LOG(ERROR) << "Failed to parse header in Merge()";
    return MergeError;
  }
  if (tot_elems == 0) {
    VLOG(2) << "Merge() encountered tot_elems = 0";
    return MergeOk;
  }
  VLOG(2) << StringPrintf("Merge(): tot_elems=%lld num_buffers=%lld",
                          tot_elems, num_buffers);

  // Update min_ and max_
  string min_string, max_string;
  if (!EncodingToString(&dec, &min_string)
      || !EncodingToString(&dec, &max_string)) {
    return MergeError;
  }
  if ((tot_elems_ == 0) || (min_string < min_)) {
    min_ = min_string;
    VLOG(2) << StringPrintf("Merge(): min_ updated to %s", min_.c_str());
  }
  if ((tot_elems_ == 0) || (max_ < max_string)) {
    max_ = max_string;
    VLOG(2) << StringPrintf("Merge(): max_ updated to %s", max_.c_str());
  }

  // Now comes the complex part of this method.
  //
  // We start de-serializing the buffers in "dec".
  // The first two buffers correspond to the leaf nodes in the "binary tree of
  // buffers".  The contents of these buffers are simply
  for (int level = 0; level < num_buffers; ++level) {
    int64 count;
    if (!dec.GetInt(&count) || (count < 0)) {
      return MergeError;
    }
    // Buffers at level >= 2 are either empty (of size 0) or full (of size k_)
    CHECK(level < 2 || count == 0 || count == k_);
    if (count == 0) {  // this is an "empty" buffer (with no elements).
      continue;        // so we do nothing.
    }

    VLOG(2) << StringPrintf("Merge(): About to de-serialize buffer at level %d"
                            " with %lld elements.", level, count);
    EnsureBuffer(level);

    // If buffer_[level] is "empty" (with size 0)
    //    newbuffer <-- buffer_[level]
    // else
    //    newbuffer <-- "a newly allocated buffer"
    vector<string> *newbuffer;
    if (buffer_[level]->size() == 0) {
      newbuffer = buffer_[level];
    } else {
      newbuffer = new vector<string>;
      newbuffer->reserve(k_);
    }

    // De-serialize the buffer at this level into "newbuffer".
    while (count-- > 0) {
      newbuffer->push_back("");
      if (!EncodingToString(&dec, & (newbuffer->back()))) {
        if (newbuffer != buffer_[level]) {
          delete newbuffer;
        }
        return MergeError;
      }
    }

    // The first two buffers in "buffer_" (corresponding to level == 0,1) are
    // actually the leaf buffers in the "tree of buffers" in the Munro-Paterson
    // algorithm.  So only if (level >= 2) does the buffer correspond to an
    // internal node in the tree.
    //
    // If (level >= 2) {
    //    If (newbuffer != buffer_[level]) {
    //       RecursiveCollapse(newbuffer, level)
    //     }
    // } else {
    //    If (newbuffer != buffer_[level]) {
    //       AddElem() for every member of "newbuffer"
    //    }
    // }
    if (level >= 2) {
      tot_elems_ += k_ * (0x1LL << (level - 1));
      if (newbuffer != buffer_[level]) {
        RecursiveCollapse(newbuffer, level);
        delete newbuffer;
        newbuffer = NULL;
      }
    } else if (newbuffer != buffer_[level]) {
      for (vector<string>::const_iterator iter = newbuffer->begin();
          iter != newbuffer->end(); ++iter) {
        AddElem(*iter);
      }
      delete newbuffer;
      newbuffer = NULL;
    } else {
      tot_elems_ += newbuffer->size();
    }
  }

  VLOG(2) << StringPrintf("Merge() succeeded. tot_elems_ = %lld", tot_elems_);
  return MergeOk;
}


text:
A golang RESource conCATenator

## Purpose, History and Goals

The general purpose of go-rescat is to provide a go implementation of [perlbal's enable_concatenate_get](http://search.cpan.org/~dormando/Perlbal-1.80/lib/Perlbal/Manual/WebServer.pod#enable_concatenate_get) and [mod_concat](https://code.google.com/p/modconcat/). mod_concat is an Apache2 module to provide perlbal's enable_concatenate_get option.

### Purpose

The above modules improve website performance and web development efficiency by allowing independent developement of individual JS and CSS resources by different teams in different files, but then effectively serving them in a single request per resource type -- JS and CSS.

Given an example where mobile developers work in `http://example.com/css/mobile.css`, and desktop developers work in `http://example.com/css/default.css` and `http://example.com/css/admin.css` and all teams are building their work on a common CSS framework `http://example.com/css/framework/main.css`. One can effectively optimize the CSS loaded into a page into a single request -- optimized per page [note the per page optimization would still be manual unless automated by some build process].

For public facing pages, one might use the following resource URL `http://example.com/css/??framwork/main.css,default.css,mobile.css` rather than three individual stylesheet links. Further, for admin pages one might use ``http://example.com/css/??framwork/main.css,default.css,mobile.css,admin.css`. Similar optimizations might happen for JS, `http://example.com/js/??jquery.js,jqueryui.js,default.js`.

NB: The double `??` denoted to perlbal and mod_concat that they should implement concatenation behavior for this URL. The the order of the comma seperated resources is important in that it is the order in which the concatenation of resources.

### History

TODO: Add some copy about the history of: perbal, mod_concat, Steve Souders [Rule 1](http://stevesouders.com/hpws/rule-min-http.php) from [High Performance Web Sites](http://stevesouders.com/hpws/rules.php) and why rescat exists...

### Goals

While this software may be moot with the advent and widespread adoption of SPDY or HTTP 2.0, it may still prove useful for some period of time until all agents support SPDY or HTTP 2.0. Additionally it serves as a well know problem with a (roughly) fixed scope, as well as sufficient complexity to leverage and learn a significant set of features in Go.

This package is a library which implements an [http.Handle](http://golang.org/pkg/net/http/#Handle) or [http.HandleFunc](http://golang.org/pkg/net/http/#HandleFunc) with configurable providers usable within any generic web framework as well as provide examples of such integration.

Additionally, it provides an http server implementation which allows configuring multiple domains with multiple providers and handlers.

## Definitions

### Handlers

Handlers are [http.Handle](http://golang.org/pkg/net/http/#Handle) functions with can be used in a [ServeMux](http://golang.org/pkg/net/http/#ServeMux).

### Providers

TODO: elaborate

Ideas for providers include:

  - filesystem provider: retrieve the requested resources on the filesystem at the configured document root/base path
  - http provider: retrieve the requested resources via http requests from the configured base URL
  - S3 provider: retrieve the requested resources via http requests from the configured bucket
  - groupcache or memcache provider: ...

Ideas for server options/optimizations:
  - gzip compression
  - minification
  - cache/expiration header configuration
  - memoization
  - group cache/memcache/redis integration

<small>Copyright © 2013 Reed O'Brien. All rights reserved.</small>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorPrimary">#ff6464</color>
  <color name="colorPrimaryDark">#303f9f</color>
  <color name="colorAccent">#3a3a3a</color>

  <color name="black_overlay">#66000000</color>

</resources>


text:
<?php

$ot=$this->object_title;

$cameraUsername = $this->getProperty('cameraUsername');
$cameraPassword = $this->getProperty('cameraPassword');

$body = '';
$streamURL = '';

if ($this->getProperty('snapshotURL')) {
    $streamURL = $this->getProperty('snapshotURL');
} elseif ($this->getProperty('streamURL_HQ')) {
    $streamURL = $this->getProperty('streamURL_HQ');
} elseif ($this->getProperty('streamURL')) {
    $streamURL = $this->getProperty('streamURL');
}
$thumb_params='';
$thumb_params.= 'username="' . $cameraUsername . '" password="' . $cameraPassword . '"';
$thumb_params.= ' url="' . $streamURL . '"';
$streamTransport = $this->getProperty('streamTransport');
if ($streamTransport!='auto' && $streamTransport!='') {
    $thumb_params.= ' transport="'.$streamTransport.'"';
}

$body = '[#module name="thumb" '. $thumb_params. '#]';
$body = processTitle($body, $this);
if (preg_match('/img src="(.+?)"/is',$body,$m)) {
    $snapshotPreviewURL=$m[1];
    $snapshotPreviewURL = preg_replace('/&w=(\d+?)/','', $snapshotPreviewURL);
    $snapshotPreviewURL = preg_replace('/&h=(\d+?)/','', $snapshotPreviewURL);
} else {
    $snapshotPreviewURL='';
}
$image_url=BASE_URL.$snapshotPreviewURL;

$new_width = 500;
$new_height = 500;
$gif_delay = 100; // 1/100 sec

$images=array();
for($i=0;$i<5;$i++) {
    $image_data=getURL($image_url);
    $lst = getimagesizefromstring($image_data);
    $image_width=$lst[0];
    $image_height=$lst[1];
    $image_format=$lst[2];
    if ($image_width>0 && $image_height>0) {
        if (($new_width!=0) && ($new_width<$image_width)) {
            $image_height=(int)($image_height*($new_width/$image_width));
            $image_width=$new_width;
        }
        if (($new_height!=0) && ($new_height<$image_height)) {
            $image_width=(int)($image_width*($new_height/$image_height));
            $image_height=$new_height;
        }
        $old_image=imagecreatefromstring($image_data);
        $new_image=imageCreateTrueColor($image_width, $image_height);
        $white = ImageColorAllocate($new_image, 255, 255, 255);
        ImageFill($new_image, 0, 0, $white);
        imagecopyresampled( $new_image, $old_image, 0, 0, 0, 0, $image_width, $image_height, imageSX($old_image), imageSY($old_image));
        $images[]=$new_image;
    }
}

$total=count($images);
if ($total>0) {
    $durations=array();
    for($i=0;$i<$total;$i++) {
        $durations[]=$gif_delay;
    }
    include_once(ROOT.'lib/utils/AnimGif.php');
    $gif_filename = ROOT.'cached/'.$ot.'_'.date('Y-m-d_H-i-s').'.gif';

    $anim = new GifCreator\AnimGif();
    if ($anim->create($images,$durations)) {
        $anim->save($gif_filename);
        $this->setProperty('series',$gif_filename);
        unlink($gif_filename);
    } else {
        $this->setProperty('series','');
    }
} else {
    $this->setProperty('series','');
}
$value = $this->getProperty('series');
if ($value) {
    $value=ROOT.'cms/images/'.$value;
}

return $value;


text:
<!DOCTYPE html>

	<title>Default viewport demo</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../../../codebase/dhtmlx.css"/>

		for such init type the following css is required

html, body {
	width: 100%;
	height: 100%;
	margin: 0px;
	overflow: hidden;
}

		The Dead Zone is a 1983 horror film/Thriller film based on the Stephen King novel of the same name. Directed by David Cronenberg, the film stars Christopher Walken, Tom Skerritt, Herbert Lom, Brooke Adams, and Colleen Dewhurst. The plot revolves around a schoolteacher, Johnny Smith (Walken), who awakens from a coma to find he has psychic powers.

		Johnny Smith (Walken) is a young New England schoolteacher in love with his colleague Sarah (Adams) when he is involved in a serious car accident that sends him into a coma. He awakes under the care of neurologist Dr. Weizak (Lom) and counts himself fortunate when he notes no casts, bandages or visible signs of injuries on his body. However, the awakening turns rude when he is told that five years have passed since he last knew consciousness: his girlfriend has long since married and had a child.

		Johnny's transition back to life is made rougher when he discovers that he has the ability to learn a person's secrets (past, present, future) through making physical contact with the person.

		After reluctantly using his ability to help a local sheriff (Skerritt) solve a series of brutal rape-murders, Johnny attempts to resume his profession, as a private tutor. However, his ability continues to haunt him, especially when he foresees that a rising local political star, Greg Stillson (Sheen), will someday be elected President of the United States, with disastrous consequences - in John's vision, Stillson starts a nuclear holocaust, presumably destroying all of civilization.

		Johnny decides to avert this possible future by shooting Stillson at a meeting. He misses and winds up mortally wounded, but he has nonetheless accomplished his mission. During the shooting, the terrified Stillson grabbed a baby to use as a human shield. A photographer covering the meeting got a picture of this cowardly act and ran out before Stillson's security could stop him. Stillson goes to the dying Johnny, demanding to know who sent him. Johnny touches Stillson, and receives one final vision -- that of a haggard Stillson, ruined as a result of the scandal, killing himself. "You're finished," he tells the politician.


text:
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'>
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="cleartype" content="on">


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommandLine.Tests.Fakes;

using FluentAssertions;

using Xunit;

namespace CommandLine.Tests.Unit.Attributes
{
    public class OptionListAttributeFixture
    {

        [Fact]
        public void Should_use_property_name_as_long_name_if_omitted()
        {
            // Given
            var options = new OptionsWithImplicitLongName();
            var parser = new CommandLine.Parser();
            var arguments = new[] {
                "--segments", "header.txt:body.txt:footer.txt"
            };

            // When
            var result = parser.ParseArguments(arguments, options);

            // Than
            result.Should().Be(true);
            options.Segments.Should().HaveCount(c => c == 3);
            options.Segments.Should().ContainInOrder(new[] { "header.txt", "body.txt", "footer.txt" });
        }
    }
}


text:
using System;
using System.Globalization;
using System.Collections.Generic;

using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Types;

namespace Sasoma.Microdata.Properties
{
	/// <summary>
	/// The media objects that encode this creative work. This property is a synonym for encodings.
	/// </summary>
	public class AssociatedMedia_Core : PropertyCore
	{
		public AssociatedMedia_Core()
		{
			this._PropertyId = 18;
			this._Id = "associatedMedia";
			string label = "";
			GetLabel(out label, "AssociatedMedia", typeof(AssociatedMedia_Core));
			this._Label = label;
			this._Domains = new int[]{78};
			this._Ranges = new int[]{161};
		}
	}
}


text:
{-# LANGUAGE CPP #-}

#if SHOULD_PASS
message :: String
message = "Hello!"
#endif

main :: IO ()
main = putStrLn message


text:
.class Lcom/android/gallery3d/ui/ActionModeHandler$2;
.super Ljava/lang/Object;
.source "ActionModeHandler.java"

# interfaces
.implements Landroid/widget/ShareActionProvider$OnShareTargetSelectedListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/gallery3d/ui/ActionModeHandler;->onCreateActionMode(Landroid/view/ActionMode;Landroid/view/Menu;)Z
.end annotation

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

# instance fields
.field final synthetic this$0:Lcom/android/gallery3d/ui/ActionModeHandler;

# direct methods
.method constructor <init>(Lcom/android/gallery3d/ui/ActionModeHandler;)V
    .locals 0
    .parameter

    .prologue
    .line 189
    iput-object p1, p0, Lcom/android/gallery3d/ui/ActionModeHandler$2;->this$0:Lcom/android/gallery3d/ui/ActionModeHandler;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onShareTargetSelected(Landroid/widget/ShareActionProvider;Landroid/content/Intent;)Z
    .locals 4
    .parameter "source"
    .parameter "intent"

    .prologue
    const/4 v0, 0x0

    .line 191
    iget-object v1, p0, Lcom/android/gallery3d/ui/ActionModeHandler$2;->this$0:Lcom/android/gallery3d/ui/ActionModeHandler;

    #getter for: Lcom/android/gallery3d/ui/ActionModeHandler;->mSelectionManager:Lcom/android/gallery3d/ui/SelectionManager;
    invoke-static {v1}, Lcom/android/gallery3d/ui/ActionModeHandler;->access$000(Lcom/android/gallery3d/ui/ActionModeHandler;)Lcom/android/gallery3d/ui/SelectionManager;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/gallery3d/ui/SelectionManager;->leaveSelectionMode()V

    .line 199
    const-string v1, "ActionModeHandler"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "onShareTargetSelected:intent="

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Lcom/android/gallery3d/ui/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 200
    invoke-static {}, Lcom/android/gallery3d/ui/ActionModeHandler;->access$100()Z

    move-result v1

    if-eqz v1, :cond_0

    invoke-virtual {p2}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

    move-result-object v1

    if-eqz v1, :cond_0

    invoke-virtual {p2}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

    move-result-object v1

    const-string v2, "includedSteroImage"

    invoke-virtual {v1, v2, v0}, Landroid/os/Bundle;->getBoolean(Ljava/lang/String;Z)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 203
    iget-object v0, p0, Lcom/android/gallery3d/ui/ActionModeHandler$2;->this$0:Lcom/android/gallery3d/ui/ActionModeHandler;

    #calls: Lcom/android/gallery3d/ui/ActionModeHandler;->checkStereoIntent(Landroid/content/Intent;)V
    invoke-static {v0, p2}, Lcom/android/gallery3d/ui/ActionModeHandler;->access$200(Lcom/android/gallery3d/ui/ActionModeHandler;Landroid/content/Intent;)V

    .line 204
    invoke-static {p2}, Lcom/mediatek/gallery3d/stereo/StereoHelper;->makeShareProviderIgnorAction(Landroid/content/Intent;)V

    .line 205
    const/4 v0, 0x1

    .line 208
    :cond_0
    return v0
.end method


text:
namespace apps {
class ExtensionAppsEnableFlow;
}

// This class is responsible for receiving AppController events from Ash, and
// implementing their effects.
//
// See LacrosExtensionAppsPublisher for the class responsible for sending events
// to Ash.
class LacrosExtensionAppsController : public crosapi::mojom::AppController {
 public:
  LacrosExtensionAppsController();
  ~LacrosExtensionAppsController() override;

  LacrosExtensionAppsController(const LacrosExtensionAppsController&) = delete;
  LacrosExtensionAppsController& operator=(
      const LacrosExtensionAppsController&) = delete;

  // This class does not receive events from ash until Initialize is called.
  // Tests may construct this class without using Initialize if the tests
  // directly call the AppController methods.
  void Initialize(mojo::Remote<crosapi::mojom::AppPublisher>& publisher);

  // crosapi::mojom::AppController
  // Public for testing.
  void Uninstall(const std::string& app_id,
                 apps::mojom::UninstallSource uninstall_source,
                 bool clear_site_data,
                 bool report_abuse) override;
  void PauseApp(const std::string& app_id) override;
  void UnpauseApp(const std::string& app_id) override;
  void GetMenuModel(const std::string& app_id,
                    GetMenuModelCallback callback) override;
  void LoadIcon(const std::string& app_id,
                apps::IconKeyPtr icon_key,
                apps::IconType icon_type,
                int32_t size_hint_in_dip,
                LoadIconCallback callback) override;
  void OpenNativeSettings(const std::string& app_id) override;
  void SetWindowMode(const std::string& app_id,
                     apps::WindowMode window_mode) override;
  void Launch(crosapi::mojom::LaunchParamsPtr launch_params,
              LaunchCallback callback) override;
  void ExecuteContextMenuCommand(
      const std::string& app_id,
      const std::string& id,
      ExecuteContextMenuCommandCallback callback) override;
  void StopApp(const std::string& app_id) override;
  void SetPermission(const std::string& app_id,
                     apps::PermissionPtr permission) override;

 private:
  // Called when the enable flow has finished. |success| indicates whether the
  // extension was enabled.
  void FinishedEnableFlow(crosapi::mojom::LaunchParamsPtr launch_params,
                          LaunchCallback callback,
                          void* key,
                          bool success);

  // Tracks instances of ExtensionAppsEnableFlow. This class constructs one
  // instance of ExtensionAppsEnableFlow for each attempt to launch a disabled
  // application. There is no deduplication by app_id -- that means that if ash
  // attempts to launch the same disabled app multiple times, there will be
  // multiple instances of ExtensionAppsEnableFlow, and eventually each one will
  // result in a callback to FinishedEnableFlow.
  // The key is the raw pointer to the ExtensionAppsEnableFlow.
  std::map<void*, std::unique_ptr<apps::ExtensionAppsEnableFlow>> enable_flows_;

  // Mojo endpoint that's responsible for receiving messages from Ash.
  mojo::Receiver<crosapi::mojom::AppController> controller_;

  base::WeakPtrFactory<LacrosExtensionAppsController> weak_factory_{this};
};

#endif  // CHROME_BROWSER_LACROS_LACROS_EXTENSION_APPS_CONTROLLER_H_


text:
require_relative 'database'
require_relative 'toilet_doc'
require_relative 'toilet_details'

class AppDoc

  def self.get_settings
    get_collection.find_one(settings_criteria, fields: {counts: 0})
  end

  def self.save_all_fields(options = {})
    filters = {}
    counts = Hash.new(0)

    doc = get_settings
    if doc && doc['filters']
      filters = doc['filters']
    end

    docs = ToiletDoc.all
    docs.each do |doc|
      keys = doc.keys - ignored_keys
      keys_hash = keys.inject({}) {|result, key| result.merge(key => nil)}
      filters = keys_hash.merge(filters)
      keys.each do |key|
        counts[key] += 1
      end
    end

    activate_filters(filters, counts)

    require 'pp'
    pp filters

    update_doc = {filters: filters}
    if options[:save_count]
      update_doc[:counts] = Hash[counts.sort_by {|key, count| count}]
    end
    puts get_collection.update(settings_criteria, {"$set" => update_doc}, upsert: true)
  end

  protected

    def self.activate_filters(filters, counts)
      filters.each do |key, value|
        filters[key] = value || (counts[key] >= 100 && key != 'location')
        if filters[key]
          distinct_values = ToiletDoc.get_collection.distinct(key)
          update_doc = {key => distinct_values}
          get_collection.update(values_criteria, {"$set" => update_doc}, upsert: true)
          filters[key] = control_type(distinct_values)
        else
          filters.delete(key)
        end
      end
    end

    def self.control_type(values)
      if values.all? {|value| ["Ja", "Nein"].include?(value)}
        "checkbox"
      elsif values.all? {|value| value.to_i != 0}
        "number"
      else
        "select"
      end
    end

    def self.settings_criteria
      {_id: 'settings'}
    end

    def self.values_criteria
      {_id: 'values'}
    end

    def self.ignored_keys
      ['_id'] + ToiletDetails.basic_keys.map(&:to_s)
    end

    def self.get_collection
      Database.new.collection('app_data')
    end

end


text:
<?php

Class Infrastructuremodel extends MY_Model {

    /**
     * Default constructor
     */
    function __construct()
    {
        parent::__construct();
        $this->table_id = 'upgrade_id';
        $this->table = 'upgrade_orders';
    }

    /**
     * Get this planet's upgrade order if any exists
     */
    function get_by_planet($planet_id)
    {
        return $this->db->query('SELECT * FROM upgrade_orders WHERE planet_id='.$planet_id)->row();
    }

    /**
     * Get all upgrade orders in a game
     */
    function get_by_game($game_id)
    {
        return $this->db->query('SELECT * FROM upgrade_orders'
                . ' JOIN planets ON planets.planet_id=upgrade_orders.planet_id'
                . ' JOIN games ON games.game_id=planets.game_id'
                . ' WHERE planets.game_id='.$game_id)->result();
    }

}


text:
layout: page
title: About
permalink: /about/
---

Tom Brown is a software developer and beer league hockey player...


text:
import psycopg2
import random
import requests
import json

postgres = psycopg2.connect(database = 'pmp', host = 'localhost', user = 'ashutosh', password = '123')
cursor = postgres.cursor()

#   generate simulation module for users{relation} here user_id is unique and
#   it will be used for the purpose of mapping from user_description{relation} and
#   this relation will have the information of user details like which device is
#   used recently and corresponding to that it will send the push notifications
#   In user_description relation we will create a primary key user_id and on the
#   basis of this very primary key we will map to the users and after mapping we
#   will send the push notification to the concerned device with the appropriate
#   server i.e. {use apns for apple, gcm for android etc}.

 ######################################################################################
 ######################################################################################
 #                               CHECK FOR TABLE USERS                                #
 ######################################################################################
 ######################################################################################

cursor.execute("""
   select exists(select 0 from pg_class where relname = 'users')
""")
# it returns true if there is at least row in database and it will be a tuple
presence = cursor.fetchone()[0]
print(presence)

 ######################################################################################
 ######################################################################################
 #                               DELETE TABLE USERS IF EXISTS                         #
 ######################################################################################
 ######################################################################################

if presence:
    print('users table exists, deleting here')
    cursor.execute("""
        drop table users
    """)

 ######################################################################################
 ######################################################################################
 #                               CREATE TABLE USERS                                   #
 ######################################################################################
 ######################################################################################
cursor.execute("""
    create table users(
        userid bigserial,
        username text,
        name text,
        email text
    )
""")
######################################################################################
######################################################################################
#                       COMMIT AND ROLLBACK IF EXCEPTION                             #
######################################################################################
######################################################################################

try:
    postgres.commit()
except Exception as e:
    postgres.rollback()
    print(e)

 ######################################################################################
 ######################################################################################
 #                               CHECK FOR TABLE USERSDESCRIPTION                     #
 ######################################################################################
 ######################################################################################

cursor.execute("""
   select exists(select 0 from pg_class where relname = 'usersdescription')
""")
# it returns true if there is at least row in database and it will be a tuple
presence = cursor.fetchone()[0]
print(presence)

 ######################################################################################
 ######################################################################################
 #                       DELETE USERSDESCRIPTION IF EXISTS                            #
 ######################################################################################
 ######################################################################################

if presence:
    print('usersdescription table exists, deleting here')
    cursor.execute("""
        drop table usersdescription
    """)

 ######################################################################################
 ######################################################################################
 #                       CREATE TABLE USERSDESCRIPTION                                #
 ######################################################################################
 ######################################################################################

cursor.execute("""
    create table usersdescription(
            userid bigint,
            deviceid text,
            platform text
            -- CONSTRAINT userdescription_pk PRIMARY KEY (userid)
    )
""")
try:
    postgres.commit()
except Exception as e:
    postgres.rollback()
    print(e)


text:
package net.sf.kerner.utils.concurrent;

import java.util.concurrent.RunnableFuture;

public interface FactoryRunnableFuture<T> {

    RunnableFuture<T> create(Runnable runnable, T value);

}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Tools.Common.Issues;

namespace Tools.Common.Loggers
{
    /// <summary>
    /// Abstract class to implement the report logging structure
    /// </summary>
    public class AnalysisLogger
    {
        string _baseDirectory;
        string _exceptionsDirectory;
        private static string _defaultLogName;
        private static Dictionary<string, AnalysisLogger> _logDictionary;

        private log4net.ILog Log4NetLogger { get; set; }

        private static Dictionary<string, AnalysisLogger> LogDictionary
        {
            get
            {
                if(_logDictionary == null)
                {
                    _logDictionary = new Dictionary<string, AnalysisLogger>();
                }

                return _logDictionary;
            }
        }

        /// <summary>
        /// Factory to get logger
        /// </summary>
        /// <param name="loggerName">Name of logger that was either created earlier or needs to be created</param>
        /// <returns>AnalysisLogger</returns>
        private static AnalysisLogger GetLogger(string loggerName)
        {
            //TODO: Once logger is simplified throughout application, factory method can be enabled
            AnalysisLogger log;
            if (!string.IsNullOrEmpty(loggerName))
            {
                if (!LogDictionary.TryGetValue(loggerName, out log))
                {
                    _defaultLogName = loggerName;
                    log = new AnalysisLogger(Assembly.GetEntryAssembly().Location);
                    LogDictionary.Add(loggerName, log);
                }
            }
            else
            {
                LogDictionary.TryGetValue(_defaultLogName, out log);
            }

            return log;
        }

        /// <summary>
        /// Create an analysis logger that will write reports to the given directory
        /// </summary>
        /// <param name="baseDirectory">The base directory for reports</param>
        /// <param name="exceptionsDirectory">The directory containing exceptions form static analysis rules.</param>
        public AnalysisLogger(string baseDirectory, string exceptionsDirectory)
        {
            _baseDirectory = baseDirectory;
            _exceptionsDirectory = exceptionsDirectory;
            var assembly = Assembly.GetExecutingAssembly();
            var assemblyType = assembly.GetType();
            _defaultLogName = assembly.GetName().Name;
#if !NETSTANDARD
            Log4NetLogger = log4net.LogManager.GetLogger(_defaultLogName);
#else
            Log4NetLogger = log4net.LogManager.GetLogger(assemblyType);
#endif
        }

        /// <summary>
        /// Create an analysis logger without exceptions
        /// </summary>
        /// <param name="baseDirectory">The base directory for reports</param>
        public AnalysisLogger(string baseDirectory) : this(baseDirectory, null)
        { }

        IList<ReportLogger> _loggers = new List<ReportLogger>();
        protected virtual IList<ReportLogger> Loggers { get { return _loggers; } }

        /// <summary>
        /// Write a report file to the given file, using the given file contents.
        /// </summary>
        /// <param name="name">The path to the file</param>
        /// <param name="contents">The contents of the report</param>
        public virtual void WriteReport(string name, string contents)
        {
            File.WriteAllText(name, contents);
        }

        /// <summary>
        /// Create a logger for a particular report
        /// </summary>
        /// <typeparam name="T">The type of records written to the log</typeparam>
        /// <param name="fileName">The filename (without file path) where the report will be written</param>
        /// <returns>The given logger.  Analyzer may write records to this logger and they will be written to
        /// the report file.</returns>
        public virtual ReportLogger<T> CreateLogger<T>(string fileName) where T : class, IReportRecord, new()
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            var filePath = Path.Combine(_baseDirectory, fileName);
            ReportLogger<T> logger;
            if (_exceptionsDirectory != null && Directory.Exists(_exceptionsDirectory))
            {
                var exceptionsPath = Path.Combine(_exceptionsDirectory, fileName);
                WriteWarning("Using exceptions file {0}", exceptionsPath);
                logger = new ReportLogger<T>(filePath, exceptionsPath, this);
            }
            else
            {
                WriteWarning("Using no exceptions file.");
                logger = new ReportLogger<T>(filePath, this);
            }

            Loggers.Add(logger);
            return logger;
        }

        public ReportLogger GetReportLogger(string loggerFileName)
        {
            return Loggers.Where<ReportLogger>((log) => Path.GetFileName(log.FileName).Equals(loggerFileName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault<ReportLogger>();
        }

        /// <summary>
        /// Write out the report files for each of the added report loggers.
        /// </summary>
        public void WriteReports()
        {
            foreach (var logger in Loggers.Where(l => l.Records.Any()))
            {
                StringBuilder reportText = new StringBuilder();
                reportText.AppendLine(logger.Records.First().PrintHeaders());
                foreach (var reportRecord in logger.Records)
                {
                    reportText.AppendLine(reportRecord.FormatRecord());
                }

                WriteReport(logger.FileName, reportText.ToString());
            }
        }

        public void CheckForIssues(int maxSeverity)
        {
            var hasErrors = false;
            foreach (var logger in Loggers.Where(l => l.Records.Any(r => r.Severity < maxSeverity)))
            {
                hasErrors = true;
                StringBuilder errorText = new StringBuilder();
                errorText.AppendLine(logger.Records.First().PrintHeaders());
                foreach (var reportRecord in logger.Records)
                {
                    errorText.AppendLine(reportRecord.FormatRecord());
                }

                WriteError("{0} Errors", logger.FileName);
                WriteError(errorText.ToString());
                WriteError("");
            }

            if (hasErrors)
            {
                throw new InvalidOperationException(string.Format("One or more errors occurred in validation. " +
                                                                  "See the analysis reports at {0} for details",
                    _baseDirectory));
            }
        }

        #region Write Methods
        /// <summary>
        /// Write an error report.
        /// </summary>
        /// <param name="error">The message to write</param>
        public virtual void WriteError(string error)
        {
            Error(error);
        }

        public virtual void WriteError(string format, params object[] args)
        {
            WriteError(string.Format(format, args));
        }

        /// <summary>
        /// Write an informational message.
        /// </summary>
        /// <param name="message">The message to write</param>
        public virtual void WriteMessage(string message)
        {
            Info(message);
        }

        public virtual void WriteMessage(string format, params object[] args)
        {
            WriteMessage(string.Format(format, args));
        }

        /// <summary>
        /// Write a warning.
        /// </summary>
        /// <param name="message">The warning text</param>
        public virtual void WriteWarning(string message)
        {
            Warning(message);
        }

        public virtual void WriteWarning(string format, params object[] args)
        {
            WriteWarning(string.Format(format, args));
        }

        #region Info methods
        public void Info(string info)
        {
            Log4NetLogger.Info(info);
        }

        public void Info<T>(string info, IEnumerable<T> infoCollection)
        {
            Info(info, infoCollection, (t) => t.ToString());
        }

        public void Info<T>(string info, IEnumerable<T> infoCollection, Func<T, string> infoItemPrintDelegate)
        {
            Info(info, "{0},", infoCollection, infoItemPrintDelegate);
        }

        public void Info<T>(string info, string infoFormat, IEnumerable<T> infoCollection)
        {
            Info(info, infoFormat, infoCollection, (t) => t.ToString());
        }

        public void Info<T>(string info, string infoFormat, IEnumerable<T> infoCollection, Func<T, string> infoItemPrintDelegate)
        {
            Info(info);
            StringBuilder sb = new StringBuilder();
            foreach (T t in infoCollection)
            {
                sb.AppendLine(string.Format(infoFormat, infoItemPrintDelegate(t)));
            }

            Info(sb.ToString());
        }
        #endregion

        private void Error(string errorInfo)
        {
            Log4NetLogger.Error(errorInfo);
        }

        public void DebugInfo(string debugInfo)
        {
            Log4NetLogger.Debug(debugInfo);
        }

        private void Warning(string warningInfo)
        {
            Log4NetLogger.Warn(warningInfo);
        }

        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using ReMi.BusinessEntities.ProductRequests;
using ReMi.Common.Utils;

namespace ReMi.Queries.ProductRequests
{
    public class GetProductRequestsResponse
    {
        public IEnumerable<ProductRequestType> ProductRequestTypes { get; set; }

        public override string ToString()
        {
            return String.Format("[ProductRequestTypes={0}]", ProductRequestTypes.FormatElements());
        }
    }
}