text:
<?php

final class PhabricatorConfigClusterRepositoriesController
  extends PhabricatorConfigController {

  public function handleRequest(AphrontRequest $request) {
    $nav = $this->buildSideNavView();
    $nav->selectFilter('cluster/repositories/');

    $title = pht('Cluster Repository Status');

    $doc_href = PhabricatorEnv::getDoclink('Cluster: Repositories');
    $button = id(new PHUIButtonView())
      ->setIcon('fa-book')
      ->setHref($doc_href)
      ->setTag('a')
      ->setText(pht('Documentation'));

    $header = $this->buildHeaderView($title, $button);

    $repository_status = $this->buildClusterRepositoryStatus();
    $repo_status = $this->buildConfigBoxView(
      pht('Repository Status'), $repository_status);

    $repository_errors = $this->buildClusterRepositoryErrors();
    $repo_errors = $this->buildConfigBoxView(
      pht('Repository Errors'), $repository_errors);

    $crumbs = $this->buildApplicationCrumbs()
      ->addTextCrumb($title)
      ->setBorder(true);

    $content = id(new PHUITwoColumnView())
      ->setHeader($header)
      ->setNavigation($nav)
      ->setFixed(true)
      ->setMainColumn(array(
        $repo_status,
        $repo_errors,
      ));

    return $this->newPage()
      ->setTitle($title)
      ->setCrumbs($crumbs)
      ->appendChild($content);
  }

  private function buildClusterRepositoryStatus() {
    $viewer = $this->getViewer();

    Javelin::initBehavior('phabricator-tooltips');

    $all_services = id(new AlmanacServiceQuery())
      ->setViewer($viewer)
      ->withServiceTypes(
        array(
          AlmanacClusterRepositoryServiceType::SERVICETYPE,
        ))
      ->needBindings(true)
      ->needProperties(true)
      ->execute();
    $all_services = mpull($all_services, null, 'getPHID');

    $all_repositories = id(new PhabricatorRepositoryQuery())
      ->setViewer($viewer)
      ->withTypes(
        array(
          PhabricatorRepositoryType::REPOSITORY_TYPE_GIT,
        ))
      ->execute();
    $all_repositories = mpull($all_repositories, null, 'getPHID');

    $all_versions = id(new PhabricatorRepositoryWorkingCopyVersion())
      ->loadAll();

    $all_devices = $this->getDevices($all_services, false);
    $all_active_devices = $this->getDevices($all_services, true);

    $leader_versions = $this->getLeaderVersionsByRepository(
      $all_repositories,
      $all_versions,
      $all_active_devices);

    $push_times = $this->loadLeaderPushTimes($leader_versions);

    $repository_groups = mgroup($all_repositories, 'getAlmanacServicePHID');
    $repository_versions = mgroup($all_versions, 'getRepositoryPHID');

    $rows = array();
    foreach ($all_services as $service) {
      $service_phid = $service->getPHID();

      if ($service->getAlmanacPropertyValue('closed')) {
        $status_icon = 'fa-folder';
        $status_tip = pht('Closed');
      } else {
        $status_icon = 'fa-folder-open green';
        $status_tip = pht('Open');
      }

      $status_icon = id(new PHUIIconView())
        ->setIcon($status_icon)
        ->addSigil('has-tooltip')
        ->setMetadata(
          array(
            'tip' => $status_tip,
          ));

      $devices = idx($all_devices, $service_phid, array());
      $active_devices = idx($all_active_devices, $service_phid, array());

      $device_icon = 'fa-server green';

      $device_label = pht(
        '%s Active',
        phutil_count($active_devices));

      $device_status = array(
        id(new PHUIIconView())->setIcon($device_icon),
        ' ',
        $device_label,
      );

      $repositories = idx($repository_groups, $service_phid, array());

      $repository_status = pht(
        '%s',
        phutil_count($repositories));

      $no_leader = array();
      $full_sync = array();
      $partial_sync = array();
      $no_sync = array();
      $lag = array();

      // Threshold in seconds before we start complaining that repositories
      // are not synchronized when there is only one leader.
      $threshold = phutil_units('5 minutes in seconds');

      $messages = array();

      foreach ($repositories as $repository) {
        $repository_phid = $repository->getPHID();

        $leader_version = idx($leader_versions, $repository_phid);
        if ($leader_version === null) {
          $no_leader[] = $repository;
          $messages[] = pht(
            'Repository %s has an ambiguous leader.',
            $viewer->renderHandle($repository_phid)->render());
          continue;
        }

        $versions = idx($repository_versions, $repository_phid, array());

        // Filter out any versions for devices which are no longer active.
        foreach ($versions as $key => $version) {
          $version_device_phid = $version->getDevicePHID();
          if (empty($active_devices[$version_device_phid])) {
            unset($versions[$key]);
          }
        }

        $leaders = 0;
        foreach ($versions as $version) {
          if ($version->getRepositoryVersion() == $leader_version) {
            $leaders++;
          }
        }

        if ($leaders == count($active_devices)) {
          $full_sync[] = $repository;
        } else {
          $push_epoch = idx($push_times, $repository_phid);
          if ($push_epoch) {
            $duration = (PhabricatorTime::getNow() - $push_epoch);
            $lag[] = $duration;
          } else {
            $duration = null;
          }

          if ($leaders >= 2 || ($duration && ($duration < $threshold))) {
            $partial_sync[] = $repository;
          } else {
            $no_sync[] = $repository;
            if ($push_epoch) {
              $messages[] = pht(
                'Repository %s has unreplicated changes (for %s).',
                $viewer->renderHandle($repository_phid)->render(),
                phutil_format_relative_time($duration));
            } else {
              $messages[] = pht(
                'Repository %s has unreplicated changes.',
                $viewer->renderHandle($repository_phid)->render());
            }
          }

        }
      }

      $with_lag = false;

      if ($no_leader) {
        $replication_icon = 'fa-times red';
        $replication_label = pht('Ambiguous Leader');
      } else if ($no_sync) {
        $replication_icon = 'fa-refresh yellow';
        $replication_label = pht('Unsynchronized');
        $with_lag = true;
      } else if ($partial_sync) {
        $replication_icon = 'fa-refresh green';
        $replication_label = pht('Partial');
        $with_lag = true;
      } else if ($full_sync) {
        $replication_icon = 'fa-check green';
        $replication_label = pht('Synchronized');
      } else {
        $replication_icon = 'fa-times grey';
        $replication_label = pht('No Repositories');
      }

      if ($with_lag && $lag) {
        $lag_status = phutil_format_relative_time(max($lag));
        $lag_status = pht(' (%s)', $lag_status);
      } else {
        $lag_status = null;
      }

      $replication_status = array(
        id(new PHUIIconView())->setIcon($replication_icon),
        ' ',
        $replication_label,
        $lag_status,
      );

      $messages = phutil_implode_html(phutil_tag('br'), $messages);

      $rows[] = array(
        $status_icon,
        $viewer->renderHandle($service->getPHID()),
        $device_status,
        $repository_status,
        $replication_status,
        $messages,
      );
    }

    return id(new AphrontTableView($rows))
      ->setNoDataString(
        pht('No repository cluster services are configured.'))
      ->setHeaders(
        array(
          null,
          pht('Service'),
          pht('Devices'),
          pht('Repos'),
          pht('Sync'),
          pht('Messages'),
        ))
      ->setColumnClasses(
        array(
          null,
          'pri',
          null,
          null,
          null,
          'wide',
        ));
  }

  private function getDevices(
    array $all_services,
    $only_active) {

    $devices = array();
    foreach ($all_services as $service) {
      $map = array();
      foreach ($service->getBindings() as $binding) {
        if ($only_active && $binding->getIsDisabled()) {
          continue;
        }

        $device = $binding->getDevice();
        $device_phid = $device->getPHID();

        $map[$device_phid] = $device;
      }
      $devices[$service->getPHID()] = $map;
    }

    return $devices;
  }

  private function getLeaderVersionsByRepository(
    array $all_repositories,
    array $all_versions,
    array $active_devices) {

    $version_map = mgroup($all_versions, 'getRepositoryPHID');

    $result = array();
    foreach ($all_repositories as $repository_phid => $repository) {
      $service_phid = $repository->getAlmanacServicePHID();
      if (!$service_phid) {
        continue;
      }

      $devices = idx($active_devices, $service_phid);
      if (!$devices) {
        continue;
      }

      $versions = idx($version_map, $repository_phid, array());
      $versions = mpull($versions, null, 'getDevicePHID');
      $versions = array_select_keys($versions, array_keys($devices));
      if (!$versions) {
        continue;
      }

      $leader = (int)max(mpull($versions, 'getRepositoryVersion'));
      $result[$repository_phid] = $leader;
    }

    return $result;
  }

  private function loadLeaderPushTimes(array $leader_versions) {
    $viewer = $this->getViewer();

    if (!$leader_versions) {
      return array();
    }

    $events = id(new PhabricatorRepositoryPushEventQuery())
      ->setViewer($viewer)
      ->withIDs($leader_versions)
      ->execute();
    $events = mpull($events, null, 'getID');

    $result = array();
    foreach ($leader_versions as $key => $version) {
      $event = idx($events, $version);
      if (!$event) {
        continue;
      }

      $result[$key] = $event->getEpoch();
    }

    return $result;
  }

  private function buildClusterRepositoryErrors() {
    $viewer = $this->getViewer();

    $messages = id(new PhabricatorRepositoryStatusMessage())->loadAllWhere(
      'statusCode IN (%Ls)',
      array(
        PhabricatorRepositoryStatusMessage::CODE_ERROR,
      ));

    $repository_ids = mpull($messages, 'getRepositoryID');
    if ($repository_ids) {
      // NOTE: We're bypassing policies when loading repositories because we
      // want to show errors exist even if the viewer can't see the repository.
      // We use handles to describe the repository below, so the viewer won't
      // actually be able to see any particulars if they can't see the
      // repository.
      $repositories = id(new PhabricatorRepositoryQuery())
        ->setViewer(PhabricatorUser::getOmnipotentUser())
        ->withIDs($repository_ids)
        ->execute();
      $repositories = mpull($repositories, null, 'getID');
    }

    $rows = array();
    foreach ($messages as $message) {
      $repository = idx($repositories, $message->getRepositoryID());
      if (!$repository) {
        continue;
      }

      if (!$repository->isTracked()) {
        continue;
      }

      $icon = id(new PHUIIconView())
        ->setIcon('fa-exclamation-triangle red');

      $rows[] = array(
        $icon,
        $viewer->renderHandle($repository->getPHID()),
        phutil_tag(
          'a',
          array(
            'href' => $repository->getPathURI('manage/status/'),
          ),
          $message->getStatusTypeName()),
      );
    }

    return id(new AphrontTableView($rows))
      ->setNoDataString(
        pht('No active repositories have outstanding errors.'))
      ->setHeaders(
        array(
          null,
          pht('Repository'),
          pht('Error'),
        ))
      ->setColumnClasses(
        array(
          null,
          'pri',
          'wide',
        ));
  }

}


text:
#include "OgreD3D11GpuProgramManager.h"
#include "OgreD3D11Device.h"
#include "OgreException.h"

namespace Ogre {

    class D3D11UnsupportedGpuProgram : public GpuProgram
    {
    public:
        D3D11UnsupportedGpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle,
            const String& group, bool isManual, ManualResourceLoader* loader)
            : GpuProgram(creator, name, handle, group, isManual, loader) { }

        void throwException()
        {
            String message = "D3D11 dosn't support assembly shaders. Shader name:" + mName + "\n";
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message,
                "D3D11UnsupportedGpuProgram::loadFromSource");
        }

    protected:
        void loadImpl(void)         { throwException(); }
        void loadFromSource(void)   { throwException(); }
        void unloadImpl(void)       { }
    };

    //-----------------------------------------------------------------------------
    D3D11GpuProgramManager::D3D11GpuProgramManager()
        :GpuProgramManager()
    {
        // Superclass sets up members

        // Register with resource group manager
        ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this);

    }
    //-----------------------------------------------------------------------------
    D3D11GpuProgramManager::~D3D11GpuProgramManager()
    {
        // Unregister with resource group manager
        ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType);

    }
    //-----------------------------------------------------------------------------
    Resource* D3D11GpuProgramManager::createImpl(const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader,
        const NameValuePairList* params)
    {
        NameValuePairList::const_iterator paramIt;

        if (!params || (paramIt = params->find("type")) == params->end())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                "You must supply a 'type' parameter",
                "D3D11GpuProgramManager::createImpl");
        }

        return new D3D11UnsupportedGpuProgram(this, name, handle, group, isManual, loader);
    }
    //-----------------------------------------------------------------------------
    Resource* D3D11GpuProgramManager::createImpl(const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader,
        GpuProgramType gptype, const String& syntaxCode)
    {
        return new D3D11UnsupportedGpuProgram(this, name, handle, group, isManual, loader);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class VersionsControllerTest < ActionController::TestCase
  setup do
    @user = FactoryBot.create :user
    @role = FactoryBot.create :read_audits_role
    @user.roles << @role

    @user_session = { user_id: @user.id, current_role_name: @role.name }
    @least_recent = mock
    @most_recent = mock
    @least_recent.stubs(:start_date).returns(3.days.ago)
    @most_recent.stubs(:start_date).returns(DateTime.now)
    @most_recent.stubs(:end_date).returns(3.days.from_now)
    Convention.stubs(:least_recent).returns(@least_recent)
    Convention.stubs(:most_recent).returns(@most_recent)
  end

  test 'should get index' do
    get :index, session: @user_session
    assert_response :success
  end
end


text:
package org.jbpm.workbench.ht.client.editors.taskdetails;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.gwtbootstrap3.client.ui.html.Paragraph;
import org.gwtbootstrap3.extras.select.client.ui.Select;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import static org.mockito.Mockito.*;

@RunWith(GwtMockitoTestRunner.class)
public class TaskDetailsViewImplTest {

    @Mock
    public TextArea taskDescriptionTextArea;

    @Mock
    public Select taskPriorityListBox;

    @Mock
    public FlowPanel dateRangePickerInput;

    @Mock(name = "taskStatusText")
    public Paragraph taskStatusText;

    @Mock(name = "processInstanceIdText")
    public Paragraph processInstanceIdText;

    @Mock(name = "processIdText")
    public Paragraph processIdText;

    @Mock(name = "dueDateText")
    public Paragraph dueDateText;

    @Mock
    public Button updateTaskButton;

    @InjectMocks
    private TaskDetailsViewImpl view;

    @Test
    public void disableFieldsTest() {
        view.setDueDateEnabled(false);
        verify(dateRangePickerInput).setVisible(false);
        verify(dueDateText).setVisible(true);

        view.setTaskDescriptionEnabled(false);
        verify(taskDescriptionTextArea).setEnabled(false);

        view.setTaskPriorityEnabled(false);
        verify(taskPriorityListBox).setEnabled(false);

        view.setUpdateTaskVisible(false);
        verify(updateTaskButton).setVisible(false);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>vg.civcraft.mc</groupId>
	<artifactId>CivHelp</artifactId>
	<packaging>jar</packaging>
	<version>1.0.0</version>
	<name>CivHelp</name>
	<url>https://github.com/Civcraft/CivHelp</url>

	<properties>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<build>
		<sourceDirectory>${basedir}/src</sourceDirectory>

		<resources>
			<resource>
				<directory>${basedir}</directory>
				<includes>
					<include>*.yml</include>
					<include>license.txt</include>
				</includes>
				<filtering>true</filtering>
			</resource>
		</resources>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.spigotmc</groupId>
			<artifactId>spigot-api</artifactId>
			<version>1.8.7-R0.1-SNAPSHOT</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<repositories>
		<repository>
			<id>spigot-repo</id>
			<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
		</repository>
		<repository>
			<id>Jenkins-repo</id>
			<url>http://build.civcraft.com/plugin/repository/everything/</url>
		</repository>
	</repositories>
</project>


text:
///////////////////////////////////////////////////////////////////////////////
//
// File: NekMatrixFwd.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Matrix Forward Declarations
//
//
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_MATRIX_FWD_HPP
#define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_MATRIX_FWD_HPP

#include <LibUtilities/LinearAlgebra/MatrixType.h>
#include <LibUtilities/LinearAlgebra/MatrixStorageType.h>
#include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/type_traits.hpp>

#include <boost/typeof/typeof.hpp>
#include  BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

namespace Nektar
{
    template<typename DataType>
    class ConstMatrix;

    template<typename DataType>
    class Matrix;

    template<typename DataType, typename MatType = StandardMatrixTag>
    class NekMatrix;

    template<typename DataType, typename InnerMatrixType>
    class NekMatrix<NekMatrix<DataType, InnerMatrixType>, ScaledMatrixTag>;

    template<typename DataType, typename InnerMatrixType>
    class NekMatrix<NekMatrix<DataType, InnerMatrixType>, BlockMatrixTag>;

    template<typename DataType>
    class NekMatrix<DataType, StandardMatrixTag>;

    typedef boost::shared_ptr<NekMatrix<NekDouble, StandardMatrixTag> > SharedNekMatrixPtr;
    typedef NekMatrix<NekMatrix<NekDouble, StandardMatrixTag>, ScaledMatrixTag> DNekScalMat;
    typedef boost::shared_ptr<DNekScalMat> DNekScalMatSharedPtr;

    // Type registration must occur for the expression template machinery to
    // automatically detect the types of matrix operations.
    BOOST_TYPEOF_REGISTER_TEMPLATE(NekMatrix, 2);

#ifdef NEKTAR_USE_EXPRESSION_TEMPLATES
    template<typename T>
    struct IsMatrix : public boost::false_type {};

    template<typename DataType, typename MatrixType>
    struct IsMatrix<NekMatrix<DataType, MatrixType> > : public boost::true_type {};

    template<typename DataType>
    struct IsMatrix<ConstMatrix<DataType> > : public boost::true_type {};

    template<typename DataType>
    struct IsMatrix<Matrix<DataType> > : public boost::true_type {};
#endif

};

#endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_MATRIX_FWD_HPP

/**
    $Log: NekMatrixFwd.hpp,v $
    Revision 1.15  2008/03/09 22:39:29  bnelson
    Added IsMatrix.

    Revision 1.14  2007/08/16 02:08:12  bnelson
    Removed typeof registration

    Revision 1.13  2007/07/25 23:47:45  bnelson
    *** empty log message ***

    Revision 1.12  2007/07/22 23:03:28  bnelson
    Backed out Nektar::ptr.

    Revision 1.11  2007/07/20 00:24:13  bnelson
    Replaced boost::shared_ptr with Nektar::ptr

    Revision 1.10  2007/07/12 04:04:14  bnelson
    *** empty log message ***

    Revision 1.9  2007/06/24 17:59:33  bnelson
    *** empty log message ***

    Revision 1.8  2007/06/10 23:42:15  bnelson
    Matrix updates.

    Revision 1.7  2007/03/29 18:59:05  bnelson
    Refactoring in preparation for scaled matrices.  Fixed transpose problem.

    Revision 1.6  2007/02/15 06:56:55  bnelson
    *** empty log message ***

    Revision 1.5  2006/12/17 22:36:35  bnelson
    Removed Macintosh line endings.

**/


text:
package de.ailis.jollada.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Asset-management information.
 *
 * @author Klaus Reimer (k@ailis.de)
 */

public final class Asset implements Serializable
{
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;

    /** The contributors who worked on the parent element. */
    private final ArrayList<Contributor> contributors =
            new ArrayList<Contributor>();

    /** The creation time stamp. */
    private long created;

    /** The time stamp of the last modification. */
    private long modified;

    /** The geographic location. */
    private GeographicLocation geographicLocation;

    /** List of keywords. */
    private final ArrayList<String> keywords = new ArrayList<String>();

    /** Revision information. */
    private String revision;

    /** The description of the topical subject. */
    private String subject;

    /** The title. */
    private String title;

    /** The unit of distance. */
    private Unit unit = new Unit();

    /** The orientation of the coordinate system. */
    private UpAxis upAxis = UpAxis.Y_UP;

    /**
     * Creates new asset-management information with the created and modified
     * time stamp set to the current time.
     */

    public Asset()
    {
        this(System.currentTimeMillis());
    }

    /**
     * Creates new asset-management information with the created and modified
     * time stamp set to the specified time.
     *
     * @param created
     *            The date and time the parent element was created. Is also used
     *            for the modified time stamp.
     */

    public Asset(final long created)
    {
        this(created, created);
    }

    /**
     * Creates new asset-management information with the created and modified
     * time stamp set to the specified times.
     *
     * @param created
     *            The time stamp when the parent element was created.
     * @param modified
     *            The time stamp when the parent element was last modified.
     */

    public Asset(final long created, final long modified)
    {
        this.created = created;
        this.modified = modified;
    }

    /**
     * Full constructor.
     *
     * @param created
     *            The time stamp when the parent element was created.
     * @param modified
     *            The time stamp when the parent element was last modified.
     * @param unit
     *            The unit of distance. Must not be null.
     * @param upAxis
     *            The up Axis. Must not be null.
     * @param geographicLocation
     *            The geographic location. May be null.
     * @param revision
     *            The revision. May be null.
     * @param subject
     *            The description of the topical subject. May be null.
     * @param title
     *            The title. May be null.
     */

    public Asset(final long created, final long modified, final Unit unit,
        final UpAxis upAxis, final GeographicLocation geographicLocation,
        final String revision, final String subject, final String title)
    {
        this(created, modified);
        setUnit(unit);
        setUpAxis(upAxis);
        this.geographicLocation = geographicLocation;
        this.revision = revision;
        this.subject = subject;
        this.title = title;
    }

    /**
     * Returns the creation time stamp.
     *
     * @return The creation time stamp.
     */

    public long getCreated()
    {
        return this.created;
    }

    /**
     * Sets the creation time stamp.
     *
     * @param created
     *            The creation time stamp to set.
     */

    public void setCreated(final long created)
    {
        this.created = created;
    }

    /**
     * Returns last modification time stamp.
     *
     * @return The last modification time stamp.
     */

    public long getModified()
    {
        return this.modified;
    }

    /**
     * Sets the last modification time stamp.
     *
     * @param modified
     *            The last modification time stamp to set.
     */

    public void setModified(final long modified)
    {
        this.modified = modified;
    }

    /**
     * Returns the list of contributors.
     *
     * @return The list of contributors. Never null. May be empty.
     */

    public List<Contributor> getContributors()
    {
        return this.contributors;
    }

    /**
     * Returns the geographic location.
     *
     * @return The geographic location. May be null if not set.
     */

    public GeographicLocation getGeographicLocation()
    {
        return this.geographicLocation;
    }

    /**
     * Sets the geographic location.
     *
     * @param geographicLocation
     *            The geographic location to set. Null to unset.
     */

    public void setGeographicLocation(
        final GeographicLocation geographicLocation)
    {
        this.geographicLocation = geographicLocation;
    }

    /**
     * Returns the list of keywords.
     *
     * @return The list of keywords. Never null. May be empty.
     */

    public List<String> getKeywords()
    {
        return this.keywords;
    }

    /**
     * Returns the revision.
     *
     * @return The revision. May be null if not set.
     */

    public String getRevision()
    {
        return this.revision;
    }

    /**
     * Sets the revision.
     *
     * @param revision
     *            The revision to set. Null to unset.
     */

    public void setRevision(final String revision)
    {
        this.revision = revision;
    }

    /**
     * Returns the description of the topical subject.
     *
     * @return The subject. May be null if not set.
     */

    public String getSubject()
    {
        return this.subject;
    }

    /**
     * Sets the description of the topical subject.
     *
     * @param subject
     *            The subject to set. Null to unset.
     */

    public void setSubject(final String subject)
    {
        this.subject = subject;
    }

    /**
     * Returns the title.
     *
     * @return The title. May be null if not set.
     */

    public String getTitle()
    {
        return this.title;
    }

    /**
     * Sets the title.
     *
     * @param title
     *            The title to set. Null to unset.
     */

    public void setTitle(final String title)
    {
        this.title = title;
    }

    /**
     * Returns the unit of distance.
     *
     * @return The unit of distance. Never null.
     */

    public Unit getUnit()
    {
        return this.unit;
    }

    /**
     * Sets the unit of distance.
     *
     * @param unit
     *            The unit of distance to set. Most not be null.
     */

    public void setUnit(final Unit unit)
    {
        if (unit == null)
            throw new IllegalArgumentException("unit must not be null");
        this.unit = unit;
    }

    /**
     * Returns the orientation of the coordinate system.
     *
     * @return The orientation of the coordinate system. Never null.
     */

    public UpAxis getUpAxis()
    {
        return this.upAxis;
    }

    /**
     * Sets the orientation of the coordinate system.
     *
     * @param upAxis
     *            The coordinate system orientation to set. Most nut be null.
     */

    public void setUpAxis(final UpAxis upAxis)
    {
        if (upAxis == null)
            throw new IllegalArgumentException("upAxis must not be null");
        this.upAxis = upAxis;
    }

    /**
     * @see java.lang.Object#hashCode()
     */

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + this.contributors.hashCode();
        result = prime * result + (int) (this.created ^ (this.created >>> 32));
        result = prime
            * result
            + ((this.geographicLocation == null) ? 0 : this.geographicLocation
                    .hashCode());
        result = prime * result + this.keywords.hashCode();
        result = prime * result
            + (int) (this.modified ^ (this.modified >>> 32));
        result = prime * result
            + ((this.revision == null) ? 0 : this.revision.hashCode());
        result = prime * result
            + ((this.subject == null) ? 0 : this.subject.hashCode());
        result = prime * result
            + ((this.title == null) ? 0 : this.title.hashCode());
        result = prime * result + this.unit.hashCode();
        result = prime * result + this.upAxis.hashCode();
        return result;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */

    @Override
    public boolean equals(final Object obj)
    {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        final Asset other = (Asset) obj;
        if (!this.contributors.equals(other.contributors)) return false;
        if (this.created != other.created) return false;
        if (this.geographicLocation == null)
        {
            if (other.geographicLocation != null) return false;
        }
        else if (!this.geographicLocation.equals(other.geographicLocation))
            return false;
        if (!this.keywords.equals(other.keywords)) return false;
        if (this.modified != other.modified) return false;
        if (this.revision == null)
        {
            if (other.revision != null) return false;
        }
        else if (!this.revision.equals(other.revision)) return false;
        if (this.subject == null)
        {
            if (other.subject != null) return false;
        }
        else if (!this.subject.equals(other.subject)) return false;
        if (this.title == null)
        {
            if (other.title != null) return false;
        }
        else if (!this.title.equals(other.title))
            return false;
        else if (!this.unit.equals(other.unit)) return false;
        if (this.upAxis != other.upAxis) return false;
        return true;
    }

    /**
     * @see java.lang.Object#toString()
     */

    @Override
    public String toString()
    {
        return "Asset [contributors=" + this.contributors + ", created="
            + this.created + ", modified=" + this.modified
            + ", geographicLocation=" + this.geographicLocation + ", keywords="
            + this.keywords + ", revision=" + this.revision + ", subject="
            + this.subject + ", title=" + this.title + ", unit=" + this.unit
            + ", upAxis=" + this.upAxis + "]";
    }
}


text:
#ifndef _TREE_COMMON_H_
#define _TREE_COMMON_H_

#include "dict.h"

#define TREE_NODE_FIELDS(node_type) \
    void*		key; \
    void*		datum; \
    node_type*		parent; \
    node_type*		llink; \
    node_type*		rlink;

typedef struct tree_node_base {
    TREE_NODE_FIELDS(struct tree_node_base);
} tree_node_base;

#define TREE_FIELDS(node_type) \
    node_type*		root; \
    size_t		count; \
    dict_compare_func	cmp_func; \
    dict_delete_func	del_func; \
    size_t		rotation_count;

typedef struct tree_base {
    TREE_FIELDS(struct tree_node_base);
} tree_base;

#define TREE_ITERATOR_FIELDS(tree_type, node_type) \
    tree_type*		tree; \
    node_type*		node;

/* Rotate |node| left.
 * |node| and |node->rlink| must not be NULL. */
void	    tree_node_rot_left(void *tree, void *node);
/* Rotate |node| right.
 * |node| and |node->llink| must not be NULL. */
void	    tree_node_rot_right(void *tree, void *node);
/* Return the predecessor of |node|, or NULL if |node| has no predecessor.
 * |node| must not be NULL. */
void*	    tree_node_prev(void *node);
/* Return the successor of |node|, or NULL if |node| has no successor.
 * |node| must not be NULL. */
void*	    tree_node_next(void *node);
/* Return the left child of |node|, or |node| if it has no right child.
 * |node| must not be NULL. */
void*	    tree_node_min(void *node);
/* Return the rightmost child of |node|, or |node| if it has no right child.
 * |node| must not be NULL. */
void*	    tree_node_max(void *node);
/* Return the data associated with the key, or NULL if not found. */
void*	    tree_search(void *tree, const void *key);
/* Return the node has the key, or NULL if not found. */
void*	    tree_search_node(void *tree, const void *key);
/* Return the data/node associated with the first key less than or
 * equal to the specified key, or NULL if not found. */
void*	    tree_search_le(void *tree, const void *key);
void*	    tree_search_le_node(void *tree, const void *key);
/* Return the data/node associated with the first key less than the
 * specified key, or NULL if not found. */
void*	    tree_search_lt(void *tree, const void *key);
void*	    tree_search_lt_node(void *tree, const void *key);
/* Return the data/node associated with the first key greater than or
 * equal to the specified key, or NULL if not found. */
void*	    tree_search_ge(void *tree, const void *key);
void*	    tree_search_ge_node(void *tree, const void *key);
/* Return the data/node associated with the first key greater than the
 * specified key, or NULL if not found. */
void*	    tree_search_gt(void *tree, const void *key);
void*	    tree_search_gt_node(void *tree, const void *key);
/* Return the minimal key in the tree, or NULL if the tree is empty. */
const void* tree_min(const void *tree);
/* Return the maximal key in the tree, or NULL if the tree is empty. */
const void* tree_max(const void *tree);
/* Traverses the tree in order, calling |visit| with each key and value pair,
 * stopping if |visit| returns false. Returns the number of times |visit| was
 * called. */
size_t	    tree_traverse(void *tree, dict_visit_func visit);
/* Return a count of the elements in |tree|. */
size_t	    tree_count(const void *tree);
/* Remove all elements from |tree|. */
size_t	    tree_clear(void *tree);
/* Remove all elements from |tree| and free its memory. */
size_t	    tree_free(void *tree);
/* Return a clone of the tree |tree| where |tree_size| is the tree object size
 * in bytes, |node_size| is the node object size in bytes, and |clone_func| is
 * an optional key-datum cloning function. */
void*	    tree_clone(void *tree, size_t tree_size, size_t node_size,
		       dict_key_datum_clone_func clone_func);
/* Returns the depth of the leaf with minimal depth, or 0 for an empty tree. */
size_t	    tree_min_leaf_depth(const void *tree);
/* Returns the depth of the leaf with maximal depth, or 0 for an empty tree. */
size_t	    tree_max_leaf_depth(const void *tree);

bool	    tree_iterator_valid(const void *iterator);
void	    tree_iterator_invalidate(void *iterator);
void	    tree_iterator_free(void *iterator);
bool	    tree_iterator_next(void *iterator);
bool	    tree_iterator_prev(void *iterator);
bool	    tree_iterator_next_n(void *iterator, size_t count);
bool	    tree_iterator_prev_n(void *iterator, size_t count);
bool	    tree_iterator_first(void *iterator);
bool	    tree_iterator_last(void *iterator);
bool	    tree_iterator_search(void *iterator, const void *key);
bool	    tree_iterator_search_le(void *iterator, const void *key);
bool	    tree_iterator_search_lt(void *iterator, const void *key);
bool	    tree_iterator_search_ge(void *iterator, const void *key);
bool	    tree_iterator_search_gt(void *iterator, const void *key);
const void* tree_iterator_key(const void *iterator);
void**	    tree_iterator_data(void *iterator);

#endif /* !defined(_TREE_COMMON_H_) */


text:
sms
===

simple ruby wrapper to send sms via smsbao or nexmo


text:
using System;
using Windows.UI.Xaml.Data;
using AwfulRedux.UI.Models.Forums;

namespace AwfulRedux.Tools.Converters
{
    public class AddOrRemoveFavoriteTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var forum = (Forum) value;
            return forum.IsBookmarks ? "Remove Favorite" : "Add as Favorite";
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}


text:
set -eu

# assign R to 0
R=0

# find all haskells in src  # send them to entr
# and test                  # which will
                            # 1. run 'stack test' on start
                            # 2. run 'stack test' on file contents change
                            # 3. exit with code 2 if directory contents change
find src test -name '*.hs' | entr -d -r -c stack test || R=$?

# either entr exited with code not 2 or recursively execute self
[ $R -ne 2 ] || exec sh $0


text:
Pattern: Malformed `return` in function

Issue: -

## Description

Prefer `return;` in void functions and `return undefined;` in value-returning functions.

## Further Reading

* [TSLint - return-undefined](https://palantir.github.io/tslint/rules/return-undefined)


text:
package org.apache.hadoop.yarn.server;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.http.HttpConfig;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.api.ResourceTracker;
import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceTrackerService;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;

/**
 * Embedded Yarn minicluster for testcases that need to interact with a cluster.
 *

 * In a real cluster, resource request matching is done using the hostname, and
 * by default Yarn minicluster works in the exact same way as a real cluster.
 *

 * If a testcase needs to use multiple nodes and exercise resource request
 * matching to a specific node, then the property
 * {@YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME} should be set
 * true in the configuration used to initialize the minicluster.
 *

 * With this property set to true, the matching will be done using
 * the hostname:port of the namenodes. In such case, the AM must
 * do resource request using hostname:port as the location.
 */
public class MiniYARNCluster extends CompositeService {

  private static final Log LOG = LogFactory.getLog(MiniYARNCluster.class);

  // temp fix until metrics system can auto-detect itself running in unit test:
  static {
    DefaultMetricsSystem.setMiniClusterMode(true);
  }

  private NodeManager[] nodeManagers;
  private ResourceManager resourceManager;

  private ResourceManagerWrapper resourceManagerWrapper;

  private File testWorkDir;

  // Number of nm-local-dirs per nodemanager
  private int numLocalDirs;
  // Number of nm-log-dirs per nodemanager
  private int numLogDirs;

  /**
   * @param testName name of the test
   * @param noOfNodeManagers the number of node managers in the cluster
   * @param numLocalDirs the number of nm-local-dirs per nodemanager
   * @param numLogDirs the number of nm-log-dirs per nodemanager
   */
  public MiniYARNCluster(String testName, int noOfNodeManagers,
                         int numLocalDirs, int numLogDirs) {
    super(testName.replace("$", ""));
    this.numLocalDirs = numLocalDirs;
    this.numLogDirs = numLogDirs;
    String testSubDir = testName.replace("$", "");
    File targetWorkDir = new File("target", testSubDir);
    try {
      FileContext.getLocalFSFileContext().delete(
          new Path(targetWorkDir.getAbsolutePath()), true);
    } catch (Exception e) {
      LOG.warn("COULD NOT CLEANUP", e);
      throw new YarnRuntimeException("could not cleanup test dir: "+ e, e);
    }

    if (Shell.WINDOWS) {
      // The test working directory can exceed the maximum path length supported
      // by some Windows APIs and cmd.exe (260 characters).  To work around this,
      // create a symlink in temporary storage with a much shorter path,
      // targeting the full path to the test working directory.  Then, use the
      // symlink as the test working directory.
      String targetPath = targetWorkDir.getAbsolutePath();
      File link = new File(System.getProperty("java.io.tmpdir"),
        String.valueOf(System.currentTimeMillis()));
      String linkPath = link.getAbsolutePath();

      try {
        FileContext.getLocalFSFileContext().delete(new Path(linkPath), true);
      } catch (IOException e) {
        throw new YarnRuntimeException("could not cleanup symlink: " + linkPath, e);
      }

      // Guarantee target exists before creating symlink.
      targetWorkDir.mkdirs();

      ShellCommandExecutor shexec = new ShellCommandExecutor(
        Shell.getSymlinkCommand(targetPath, linkPath));
      try {
        shexec.execute();
      } catch (IOException e) {
        throw new YarnRuntimeException(String.format(
          "failed to create symlink from %s to %s, shell output: %s", linkPath,
          targetPath, shexec.getOutput()), e);
      }

      this.testWorkDir = link;
    } else {
      this.testWorkDir = targetWorkDir;
    }

    resourceManagerWrapper = new ResourceManagerWrapper();
    addService(resourceManagerWrapper);
    nodeManagers = new CustomNodeManager[noOfNodeManagers];
    for(int index = 0; index < noOfNodeManagers; index++) {
      addService(new NodeManagerWrapper(index));
      nodeManagers[index] = new CustomNodeManager();
    }
  }

  @Override
  public void serviceInit(Configuration conf) throws Exception {
    super.serviceInit(conf instanceof YarnConfiguration ? conf
                                                        : new YarnConfiguration(
                                                          conf));
  }

  public File getTestWorkDir() {
    return testWorkDir;
  }

  public ResourceManager getResourceManager() {
    return this.resourceManager;
  }

  public NodeManager getNodeManager(int i) {
    return this.nodeManagers[i];
  }

  public static String getHostname() {
    try {
      return InetAddress.getLocalHost().getHostName();
    }
    catch (UnknownHostException ex) {
      throw new RuntimeException(ex);
    }
  }

  private class ResourceManagerWrapper extends AbstractService {
    public ResourceManagerWrapper() {
      super(ResourceManagerWrapper.class.getName());
    }

    @Override
    public synchronized void serviceStart() throws Exception {
      try {
        getConfig().setBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER, true);
        if (!getConfig().getBoolean(
            YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS,
            YarnConfiguration.DEFAULT_YARN_MINICLUSTER_FIXED_PORTS)) {
          // pick free random ports.
          String hostname = MiniYARNCluster.getHostname();
          getConfig().set(YarnConfiguration.RM_ADDRESS,
              hostname + ":0");
          getConfig().set(YarnConfiguration.RM_ADMIN_ADDRESS,
              hostname + ":0");
          getConfig().set(YarnConfiguration.RM_SCHEDULER_ADDRESS,
              hostname + ":0");
          getConfig().set(YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS,
              hostname + ":0");
          WebAppUtils.setRMWebAppHostnameAndPort(getConfig(), hostname, 0);
        }
        resourceManager = new ResourceManager() {
          @Override
          protected void doSecureLogin() throws IOException {
            // Don't try to login using keytab in the testcase.
          };
        };
        resourceManager.init(getConfig());
        new Thread() {
          public void run() {
            resourceManager.start();
          };
        }.start();
        int waitCount = 0;
        while (resourceManager.getServiceState() == STATE.INITED
            && waitCount++ < 60) {
          LOG.info("Waiting for RM to start...");
          Thread.sleep(1500);
        }
        if (resourceManager.getServiceState() != STATE.STARTED) {
          // RM could have failed.
          throw new IOException(
              "ResourceManager failed to start. Final state is "
                  + resourceManager.getServiceState());
        }
        super.serviceStart();
      } catch (Throwable t) {
        throw new YarnRuntimeException(t);
      }
      LOG.info("MiniYARN ResourceManager address: " +
               getConfig().get(YarnConfiguration.RM_ADDRESS));
      LOG.info("MiniYARN ResourceManager web address: " +
               WebAppUtils.getRMWebAppURLWithoutScheme(getConfig()));
    }

    @Override
    public synchronized void serviceStop() throws Exception {
      if (resourceManager != null) {
        resourceManager.stop();
      }
      super.serviceStop();

      if (Shell.WINDOWS) {
        // On Windows, clean up the short temporary symlink that was created to
        // work around path length limitation.
        String testWorkDirPath = testWorkDir.getAbsolutePath();
        try {
          FileContext.getLocalFSFileContext().delete(new Path(testWorkDirPath),
            true);
        } catch (IOException e) {
          LOG.warn("could not cleanup symlink: " +
            testWorkDir.getAbsolutePath());
        }
      }
    }
  }

  private class NodeManagerWrapper extends AbstractService {
    int index = 0;

    public NodeManagerWrapper(int i) {
      super(NodeManagerWrapper.class.getName() + "_" + i);
      index = i;
    }

    public synchronized void serviceInit(Configuration conf) throws Exception {
      Configuration config = new YarnConfiguration(conf);
      super.serviceInit(config);
    }

    /**
     * Create local/log directories
     * @param dirType type of directories i.e. local dirs or log dirs
     * @param numDirs number of directories
     * @return the created directories as a comma delimited String
     */
    private String prepareDirs(String dirType, int numDirs) {
      File []dirs = new File[numDirs];
      String dirsString = "";
      for (int i = 0; i < numDirs; i++) {
        dirs[i]= new File(testWorkDir, MiniYARNCluster.this.getName()
            + "-" + dirType + "Dir-nm-" + index + "_" + i);
        dirs[i].mkdirs();
        LOG.info("Created " + dirType + "Dir in " + dirs[i].getAbsolutePath());
        String delimiter = (i > 0) ? "," : "";
        dirsString = dirsString.concat(delimiter + dirs[i].getAbsolutePath());
      }
      return dirsString;
    }

    public synchronized void serviceStart() throws Exception {
      try {
        // create nm-local-dirs and configure them for the nodemanager
        String localDirsString = prepareDirs("local", numLocalDirs);
        getConfig().set(YarnConfiguration.NM_LOCAL_DIRS, localDirsString);
        // create nm-log-dirs and configure them for the nodemanager
        String logDirsString = prepareDirs("log", numLogDirs);
        getConfig().set(YarnConfiguration.NM_LOG_DIRS, logDirsString);

        File remoteLogDir =
            new File(testWorkDir, MiniYARNCluster.this.getName()
                + "-remoteLogDir-nm-" + index);
        remoteLogDir.mkdir();
        getConfig().set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
            	remoteLogDir.getAbsolutePath());
        // By default AM + 2 containers
        getConfig().setInt(YarnConfiguration.NM_PMEM_MB, 4*1024);
        getConfig().set(YarnConfiguration.NM_ADDRESS,
                        MiniYARNCluster.getHostname() + ":0");
        getConfig().set(YarnConfiguration.NM_LOCALIZER_ADDRESS,
                        MiniYARNCluster.getHostname() + ":0");
        WebAppUtils
            .setNMWebAppHostNameAndPort(getConfig(),
                MiniYARNCluster.getHostname(), 0);

        // Disable resource checks by default
        if (!getConfig().getBoolean(
            YarnConfiguration.YARN_MINICLUSTER_CONTROL_RESOURCE_MONITORING,
            YarnConfiguration.
                DEFAULT_YARN_MINICLUSTER_CONTROL_RESOURCE_MONITORING)) {
          getConfig().setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
          getConfig().setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
        }

        LOG.info("Starting NM: " + index);
        nodeManagers[index].init(getConfig());
        new Thread() {
          public void run() {
            nodeManagers[index].start();
          };
        }.start();
        int waitCount = 0;
        while (nodeManagers[index].getServiceState() == STATE.INITED
            && waitCount++ < 60) {
          LOG.info("Waiting for NM " + index + " to start...");
          Thread.sleep(1000);
        }
        if (nodeManagers[index].getServiceState() != STATE.STARTED) {
          // RM could have failed.
          throw new IOException("NodeManager " + index + " failed to start");
        }
        super.serviceStart();
      } catch (Throwable t) {
        throw new YarnRuntimeException(t);
      }
    }

    @Override
    public synchronized void serviceStop() throws Exception {
      if (nodeManagers[index] != null) {
        nodeManagers[index].stop();
      }
      super.serviceStop();
    }
  }

  private class CustomNodeManager extends NodeManager {
    @Override
    protected void doSecureLogin() throws IOException {
      // Don't try to login using keytab in the testcase.
    };

    @Override
    protected NodeStatusUpdater createNodeStatusUpdater(Context context,
        Dispatcher dispatcher, NodeHealthCheckerService healthChecker) {
      return new NodeStatusUpdaterImpl(context, dispatcher,
          healthChecker, metrics) {
        @Override
        protected ResourceTracker getRMClient() {
          final ResourceTrackerService rt = resourceManager
              .getResourceTrackerService();
          final RecordFactory recordFactory =
            RecordFactoryProvider.getRecordFactory(null);

          // For in-process communication without RPC
          return new ResourceTracker() {

            @Override
            public NodeHeartbeatResponse nodeHeartbeat(
                NodeHeartbeatRequest request) throws YarnException,
                IOException {
              NodeHeartbeatResponse response = recordFactory.newRecordInstance(
                  NodeHeartbeatResponse.class);
              try {
                response = rt.nodeHeartbeat(request);
              } catch (YarnException e) {
                LOG.info("Exception in heartbeat from node " +
                    request.getNodeStatus().getNodeId(), e);
                throw e;
              }
              return response;
            }

            @Override
            public RegisterNodeManagerResponse registerNodeManager(
                RegisterNodeManagerRequest request)
                throws YarnException, IOException {
              RegisterNodeManagerResponse response = recordFactory.
                  newRecordInstance(RegisterNodeManagerResponse.class);
              try {
                response = rt.registerNodeManager(request);
              } catch (YarnException e) {
                LOG.info("Exception in node registration from "
                    + request.getNodeId().toString(), e);
                throw e;
              }
              return response;
            }
          };
        };

        @Override
        protected void stopRMProxy() {
          return;
        }
      };
    };
  }
}


text:
package nl.appsrus.vhack2012;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.viewpagerindicator.TitlePageIndicator;

public class ProfileActivity extends SherlockFragmentActivity {

	private static final String TAG = ProfileActivity.class.getSimpleName();

	public static final String EXTRA_SELECTED_PAGE = "page";
	public static final int PAGE_MY_PROFILE = 0;
	public static final int PAGE_RECEIVED = 1;
	public static final int PAGE_SENT = 2;

	private ViewPager mViewPager;
	private ProfileFragmentAdapter mAdapter;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_profile);

        mAdapter = new ProfileFragmentAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAdapter);

        TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
        titleIndicator.setViewPager(mViewPager);

        if (getIntent().hasExtra(EXTRA_SELECTED_PAGE)) {
        	mViewPager.setCurrentItem(getIntent().getIntExtra(EXTRA_SELECTED_PAGE, 0));
        }
    }

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.menu_delete:
			Toast.makeText(this, R.string.not_implemented_yet, Toast.LENGTH_LONG).show();
			break;
		}

		return super.onMenuItemSelected(featureId, item);
	}

    @Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    	getSupportMenuInflater().inflate(R.menu.activity_profile, menu);
        return true;
    }

    private class ProfileFragmentAdapter extends FragmentPagerAdapter {

    	public ProfileFragmentAdapter(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

    	@Override
    	public int getCount() {
    		return 3;
    	}

    	@Override
    	public Fragment getItem(int position) {
    		switch (position) {
    		case 0: return new MyProfileFragment();
    		case 1: return new ReceivedWishesProfileFragment();
    		case 2: return new SentWishesProfileFragment();
    		}
    		return null;
    	}

    	@Override
    	public CharSequence getPageTitle(int position) {
    		switch (position) {
    		case 0: return getText(R.string.title_profile_my);
    		case 1: return getText(R.string.title_profile_received);
    		case 2: return getText(R.string.title_profile_sent);
    		}
    		return null;
    	}
    }

}


text:
'use strict';

// MODULES //

var isNumber = require( 'validate.io-number-primitive' ),
	cast = require( 'dstructs-cast-arrays' ),
	ctors = require( 'dstructs-array-constructors' );

// FUNCTIONS //

var CTOR = ctors( 'float64' );

// ARRAY //

/**
* FUNCTION: array( x[, dtype] )
*	Returns an array instance.
*
* @param {Number|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} x - input array or output array length
* @param {String} [dtype="float64"] - output array data type
* @returns {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array
*/
function array( x, dtype ) {
	/* jshint newcap:false */
	var ctor;
	if ( isNumber( x ) ) {
		if ( arguments.length === 1 ) {
			return new CTOR( x );
		}
		ctor = ctors( dtype );
		return new ctor( x );
	}
	return cast( x, dtype || 'float64' );
} // end FUNCTION array()

// EXPORTS //

module.exports = array;


text:
from tempest.api.compute import base
from tempest import exceptions
from tempest import test

class AbsoluteLimitsNegativeTestJSON(base.BaseV2ComputeTest):

    @classmethod
    def setUpClass(cls):
        super(AbsoluteLimitsNegativeTestJSON, cls).setUpClass()
        cls.client = cls.limits_client
        cls.server_client = cls.servers_client

    @test.attr(type=['negative', 'gate'])
    def test_max_image_meta_exceed_limit(self):
        # We should not create vm with image meta over maxImageMeta limit
        # Get max limit value
        max_meta = self.client.get_specific_absolute_limit('maxImageMeta')

        # Create server should fail, since we are passing > metadata Limit!
        max_meta_data = int(max_meta) + 1

        meta_data = {}
        for xx in range(max_meta_data):
            meta_data[str(xx)] = str(xx)

        self.assertRaises(exceptions.OverLimit,
                          self.server_client.create_server,
                          name='test', meta=meta_data,
                          flavor_ref=self.flavor_ref,
                          image_ref=self.image_ref)

class AbsoluteLimitsNegativeTestXML(AbsoluteLimitsNegativeTestJSON):
    _interface = 'xml'


text:
@class DBFILESListFolderLongpollError;

#pragma mark - API Object

///
/// The `ListFolderLongpollError` union.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBFILESListFolderLongpollError : NSObject <DBSerializable>

#pragma mark - Instance fields

/// The `DBFILESListFolderLongpollErrorTag` enum type represents the possible
/// tag states with which the `DBFILESListFolderLongpollError` union can exist.
typedef NS_ENUM(NSInteger, DBFILESListFolderLongpollErrorTag) {
  /// Indicates that the cursor has been invalidated. Call `listFolder` to
  /// obtain a new cursor.
  DBFILESListFolderLongpollErrorReset,

  /// (no description).
  DBFILESListFolderLongpollErrorOther,

};

/// Represents the union's current tag state.
@property (nonatomic, readonly) DBFILESListFolderLongpollErrorTag tag;

#pragma mark - Constructors

///
/// Initializes union class with tag state of "reset".
///
/// Description of the "reset" tag state: Indicates that the cursor has been
/// invalidated. Call `listFolder` to obtain a new cursor.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithReset;

///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithOther;

#pragma mark - Tag state methods

///
/// Retrieves whether the union's current tag state has value "reset".
///
/// @return Whether the union's current tag state has value "reset".
///
- (BOOL)isReset;

///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;

///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString * _Nonnull)tagName;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `DBFILESListFolderLongpollError` union.
///
@interface DBFILESListFolderLongpollErrorSerializer : NSObject

///
/// Serializes `DBFILESListFolderLongpollError` instances.
///
/// @param instance An instance of the `DBFILESListFolderLongpollError` API
/// object.
///
/// @return A json-compatible dictionary representation of the
/// `DBFILESListFolderLongpollError` API object.
///
+ (NSDictionary * _Nonnull)serialize:(DBFILESListFolderLongpollError * _Nonnull)instance;

///
/// Deserializes `DBFILESListFolderLongpollError` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBFILESListFolderLongpollError` API object.
///
/// @return An instantiation of the `DBFILESListFolderLongpollError` object.
///
+ (DBFILESListFolderLongpollError * _Nonnull)deserialize:(NSDictionary * _Nonnull)dict;

@end


text:
const svgNS = 'http://www.w3.org/2000/svg';

// The values below are the global defaults for labels, colors, etc. They
// have to be defined here, in order to be referenced as fallback values for
// the parameters of createChartGroup() and as initial values for the internal
// fields in the Polymer element.
let labels = ['-Inf', '-', '0', '+', '+Inf', 'NaN'];
let colors = ['#22b0dc', '#1c1c1c', '#808080 ', '#ddd', '#ffdb00', '#c00'];
let heightWidthRatio = 0.2;
let heightToFontRatio = 1 / 6;

export function attachChartGroup(
    data: Array<number>, width: number, parentElement: Element,
    _labels = labels, _colors = colors, _heightWidthRatio = heightWidthRatio,
    _heightToFontRatio = heightToFontRatio) {
  // Calculate the total of all entries in the data array.
  let dataSum = data.reduce(function(prevResult, currValue) {
    return prevResult + currValue;
  });
  let height = width * _heightWidthRatio;

  // Render data.
  let outerGroup = document.createElementNS(svgNS, 'g');
  Polymer.dom(parentElement).appendChild(outerGroup);

  let currentOffset = 0 as number;
  let currentDataLength = data.length as number;

  for (let slice = 0; slice < currentDataLength; slice++) {
    let sliceGroup = document.createElementNS(svgNS, 'g');
    Polymer.dom(outerGroup).appendChild(sliceGroup);
    let percentage = data[slice] / dataSum;
    let sliceWidth = percentage * width;

    // Create rectangle.
    let rect = createRect(currentOffset, sliceWidth, height, _colors[slice]);

    // Add to new rectangle to SVG.
    Polymer.dom(sliceGroup).appendChild(rect);

    // Add text to rectangle.
    let text = createText(
        currentOffset, sliceWidth, height, _labels[slice], _colors[slice],
        sliceGroup, _heightToFontRatio);

    // Add tooltip to rectangle and text.
    let rectTitle = createTitle(_labels[slice], data[slice]);
    let textTitle = createTitle(_labels[slice], data[slice]);
    Polymer.dom(rect).appendChild(rectTitle);
    Polymer.dom(text).appendChild(textTitle);

    currentOffset += sliceWidth;
  }
  return outerGroup;
}

function createText(
    currentOffset: number, sliceWidth: number, height: number, label: string,
    color: string, group: Element, heightToFontRatio: number) {
  // Add text to rectangle.
  let text = document.createElementNS(svgNS, 'text');
  Polymer.dom(group).appendChild(text);

  text.innerHTML = label;

  // Set location.
  text.setAttribute('x', (currentOffset + sliceWidth / 2).toString());
  text.setAttribute('y', (height / 2).toString());
  // Set text properties.
  let textColor = getTextColor(color);
  text.setAttribute('fill', textColor);
  // Center text.
  text.setAttribute('text-anchor', 'middle');
  text.setAttribute('dominant-baseline', 'middle');
  // Font size.
  let fontSize = height * heightToFontRatio;
  text.setAttribute('font-size', fontSize.toString());
  let textWidth = text.getBoundingClientRect().width;
  let textHeight = text.getBoundingClientRect().height;
  // Hide text if text is wider than the slice.
  if (textWidth > sliceWidth || textHeight > height || fontSize < 7) {
    text.innerHTML = '';
  }

  return text;
}

function createTitle(label: string, numberOfEntries: number) {
  let title = document.createElementNS(svgNS, 'title');
  title.innerHTML = label + ': ' + numberOfEntries.toString();

  return title;
}

function createRect(
    currentOffset: number, sliceWidth: number, height: number, color: string) {
  let rect = document.createElementNS(svgNS, 'rect') as HTMLElement;

  // Set location.
  rect.setAttribute('x', currentOffset.toString());
  rect.setAttribute('y', '0');
  // Set dimensions.
  rect.setAttribute('width', sliceWidth.toString());
  rect.setAttribute('height', height.toString());
  // Set colour.
  rect.setAttribute('fill', color);

  return rect;
}

function getTextColor(hexTripletColor: string) {
  let color = hexTripletColor;
  if (color.substring(0, 1) !== '#') {  // Lookup hex from name.
    let convertedHex = colorToHex(color);
    if (convertedHex) {
      color = convertedHex;
    } else {
      // RGB string is currently not handled.
      /* tslint:disable:no-console */
      console.warn(
          'WARNING: Could not convert color to hex,' +
          'please specify color as name or hex string.');
      return 'black';
    }
  }

  color = color.substring(1);  // Remove #.
  if (color.length === 3) {    // If short hex format is used.
    color = color.split('').reduce(
        // Double every character.
        function(initial: string, current: string) {
          return initial + current + current;
        },
        ''  // Initial value.
        );
  }

  let colorInt = parseInt(color, 16);   // Convert to integer.
  let r = (colorInt & 0xFF0000) >> 16;  // Extract each color component.
  let g = (colorInt & 0x00FF00) >> 8;
  let b = colorInt & 0x0000FF;
  // Calculate human perceptible luminance.
  let alpha = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;

  if (alpha < 0.5) {
    return 'black';
  } else {
    return 'white';
  }
}

/**
 * Renders a pixel using the provided color string to an unattached canvas,
 * then reads and returns the rgb image data of the pixel.
 *
 * @param color The color string to be converted.
 *
 * @example
 * // Returns [0, 0, 255, 255]
 * colorToRGBA('blue')
 *
 * @returns Returns the rgba colors as an array, i.e.
 * [r, g, b, a]
 */
function colorToRgba(color: string) {
  let canvas = document.createElement('canvas');
  canvas.height = 1;
  canvas.width = 1;

  let ctx = canvas.getContext('2d');
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, 1, 1);
  let retArray = [] as number[];
  let imageData = ctx.getImageData(0, 0, 1, 1).data;
  imageData.forEach(function(d: number) {  // Copy data into standard Array.
    retArray.push(d);
  });
  return retArray;
}

/**
 * Turns a number (0-255) into a 2-character hex number (00-ff).
 * @param num
 *
 * @returns The converted string.
 */
function numToHex(num: number) {
  return ('0' + num.toString(16)).slice(-2);
}

/**
 * Converts any color string to its hex representation.
 * @param color The color string to be converted.
 *
 * @example
 * // Returns '#0000ff'
 * colorToHex('blue')
 *
 * @returns The hex color string.
 */
function colorToHex(color: string) {
  let rgba = colorToRgba(color) as Array<number|string>;
  return '#' +
      rgba.slice(0, 3)  // Remove alpha channel.
          .map(function(value: number) { return numToHex(value); })
          .join('');
}
Polymer({
  is: 'vz-data-summary',
  properties: {
    colors: {
      type: Array,
      // Has to match number of elements in the data array.
      observer: '_onColorsChange'
    },
    data: {type: Array, value: [], observer: '_onDataChange'},
    heightWidthRatio:
        {type: Number, value: heightWidthRatio, observer: '_onRatioChange'},
    heightToFontRatio: {
      type: Number,
      value: heightToFontRatio,
      observer: '_onFontRatioChange'
    },
    labels: {type: Array, observer: '_onLabelChange'},
    _colors: {
      type: Array,
      value: colors,
    },
    _data: Array,
    _labels: {type: Array, value: labels},
    _dataSum: {type: Number},
    _drawRequested: {type: Boolean, value: false},
    _height: {type: String},
    _isReady: {type: Boolean, value: false},
    _width: {type: Number}
  },
  behaviors: [Polymer.IronResizableBehavior],
  listeners: {'iron-resize': '_onWidthChange'},
  ready: function() {
    this._isReady = true;
    this._updateDimensions();
    // Trigger rendering if draw was requested before element was ready.
    if (this._drawRequested) {
      this._renderData();
    }
  },
  attached: function() {
    if (this._isReady) {
      this._updateInternalVariables();
      this._renderData();
    }
  },
  /**
   * Observer for this.colors.
   * @private
   */
  _onColorsChange: function() {
    // Verify passed array is valid.
    if (this._isColorsValid()) {
      // Copy over the array to the internal field if it has the correct
      // length.
      this._updateInternalVariables();
      this._renderData();
    }
  },
  /**
   * Data change handler, if new data is valid, sets flag to indicate data
   * now valid, updates the data extent and renders the new data.
   */
  _onDataChange: function() {
    // Validate new data.
    if (!this._isDataValid(this.data)) {
      return;
    }

    this._updateInternalVariables();  // Update the internal variables.

    // Calculate the sum.
    this._dataSum =
        this.data.reduce(function(prevResult: number, currValue: number) {
          return prevResult + currValue;
        });

    this._renderData();
  },
  /**
   * Observer for this.labels. Validates that this.labels is an array of
   * 6 elements before copying its contents to an internal array.
   */
  _onLabelChange: function() {
    if (this._isLabelsValid()) {
      this._updateInternalVariables();
      this._renderData();
    }
  },
  _onFontRatioChange: function() {
    if ((typeof this.heightToFontRatio) === 'number') {
      this._renderData();
    }
  },
  /**
   * Observer for this.heightWidthRatio.
   */
  _onRatioChange: function() {
    if (this.heightWidthRatio) {
      this._renderData();
    }
  },
  /**
   * Observer for width change. Depends on iron-resizable-behavior.
   */
  _onWidthChange: function() {
    this._width = this.$.summary.parentNode.width;
    this._renderData();
  },
  _internalFieldsValid: function() {
    return !!(this._data && this._labels && this._colors);
  },
  /**
   * Renders data, if element is ready, the dimensions are set, and valid
   * data exists.
   * @private
   */
  _renderData: function() {
    if (!this._isReady || !this._internalFieldsValid()) {
      this._drawRequested = true;
      return;
    }

    // Ensure dimensions are up-to-date and valid before starting rendering.
    this._updateDimensions();
    if (!this._width || !this._height) {
      return;
    }

    // Find element to append heat map to and determine dimensions.
    let svgSelection = this.$.summary as SVGElement;

    // Clear the SVG.
    this.resetSVG();

    // Render data.
    attachChartGroup(
        this._data, this._width, svgSelection, this._labels, this._colors,
        this.heightWidthRatio, this.heightToFontRatio);
  },
  /**
   * Verifies whether input data is valid.
   * @param [internal] {bool} Whether to check the internal or external
   * field.
   * @private
   */
  _isDataValid: function(internal: boolean = false) {
    return this._validateArrayByName('data', internal, isNumeric);
  },
  _isColorsValid: function(internal: boolean = false) {
    return this._validateArrayByName('colors', internal, isString);
  },
  _isLabelsValid: function(internal: boolean = false) {
    return this._validateArrayByName('labels', internal, isString);
  },
  _validateArrayByName: function(
      name: string, internal: boolean, typeChecker: CheckingFunctionType) {
    if (internal) {
      name = '_' + name;
    }
    return _isValidArray(this[name], typeChecker);
  },
  _updateInternalVariables: function() {
    // If all new data is valid.
    let isDataValid = this._isDataValid();
    let isColorsValid = this._isColorsValid();
    let isLabelsValid = this._isLabelsValid();

    if (isDataValid && isColorsValid && isLabelsValid) {
      // Ensure they all have the same length.
      let length = this.data.length;
      if (length === this.labels.length && length === this.colors.length) {
        this._data = this.data.slice();
        this._colors = this.colors.slice();
        this._labels = this.labels.slice();
      }
    } else {  // Check whether any new fields have the correct length.
      let internalDataValid = this._isDataValid(true);
      let internalColorsValid = this._isColorsValid(true);
      let internalLabelsValid = this._isLabelsValid(true);
      length = (internalDataValid && this._data.length) ||
          (internalColorsValid && this._colors.length) ||
          (internalLabelsValid && this._labels.length);

      this._updateIfSameLength(length, 'data');
      this._updateIfSameLength(length, 'colors');
      this._updateIfSameLength(length, 'labels');
    }
  },
  /**
   * Updates dimensions based on the width of the parent element.
   * @private
   */
  _updateDimensions: function() {
    let svgSelection = this.$.summary as SVGElement;

    // Recalculate height and width, and ensure data can be rendered.
    this._width = svgSelection.parentElement.clientWidth;
    this._height = this._width * this.heightWidthRatio;
    // Update the attribute height and width.
    svgSelection.setAttribute('height', this._height);
    svgSelection.setAttribute('width', this._width);
  },
  /**
   * Called when either colors, data, or labels are called. Copies calues
   * into internal fields iff the length of all three arrays is equal.
   */
  _updateIfSameLength: function(length: number, name: string) {
    if (this[name] && this[name].length === length) {
      this['_' + name] = this[name].slice();
    }
  },
  /**
   * Resets the SVG. Used by _renderData() but is exposed to provide the
   * user more control of the SVG's contents.
   */
  resetSVG: function() {
    // Reset the SVG.
    (this.$.summary as SVGElement).innerHTML = '';
  }
});

/**
 * Helper method for _isDataValid, _isColorsValid, _isLabelsValid. Check
 * whether the passed data is a) an array, b) the provided function
 * returns true for every element of the array.
 */
interface CheckingFunctionType {
  (value: any, index: number, array: any[]): boolean;
}

function _isValidArray(
    newData: Object[], typeCheckingFunction: CheckingFunctionType) {
  return Array.isArray(newData) &&
      // Returns true is every element in the array is numeric.
      newData.every(typeCheckingFunction);
}

function isNumeric(n: any) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function isString(s: any) {
  return (typeof s) === 'string';
}


text:
package cmd

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
)

// getSHA256Hash returns SHA-256 hash in hex encoding of given data.
func getSHA256Hash(data []byte) string {
	return hex.EncodeToString(getSHA256Sum(data))
}

// getSHA256Hash returns SHA-256 sum of given data.
func getSHA256Sum(data []byte) []byte {
	hash := sha256.New()
	hash.Write(data)
	return hash.Sum(nil)
}

// getMD5Sum returns MD5 sum of given data.
func getMD5Sum(data []byte) []byte {
	hash := md5.New()
	hash.Write(data)
	return hash.Sum(nil)
}

// getMD5Hash returns MD5 hash in hex encoding of given data.
func getMD5Hash(data []byte) string {
	return hex.EncodeToString(getMD5Sum(data))
}


text:
import { ProviderMixin } from "../utils/ProviderMixin";

export class WordPress extends ProviderMixin {
  constructor(
    url = document.location.href,
    title = document.title,
    description = document.querySelector('meta[name="description"]'),
    image = document.querySelector('link[rel="apple-touch-icon"]')
  ) {
    super();
    this.url = encodeURIComponent(url);
    this.title = encodeURIComponent(title);
    this.description = description
      ? encodeURIComponent(description.content)
      : "";
    this.image = image ? encodeURIComponent(image.href) : "";
    this.createEvents = this.createEvents.bind(this);
  }

  getPreparedData(item) {
    const url = item.dataset.url
      ? encodeURIComponent(item.dataset.url)
      : this.url;
    const title = item.dataset.title
      ? encodeURIComponent(item.dataset.title)
      : this.title;
    const description = item.dataset.description
      ? encodeURIComponent(item.dataset.description)
      : this.description;
    const image = item.dataset.image
      ? encodeURIComponent(item.dataset.image)
      : this.image;
    const share_url = `https://wordpress.com/wp-admin/press-this.php?u=${url}&t=${title}&s=${description}&i=${image}&v=2`;

    return {
      callback: this.callback,
      share_url: share_url,
      windowTitle: "Share this",
      windowWidth: 640,
      windowHeight: 480
    };
  }

  // Share event
  shareWindow() {
    const share_elements = document.querySelectorAll(
      '[data-social="wordpress"]'
    );

    return this.createEvents(share_elements);
  }
}


text:
namespace Pluton.Events
{
    public class LandmineTriggerEvent
    {
        private Landmine _landmine;
        private Player _player;
        private bool _explode = true;

        public LandmineTriggerEvent(Landmine landmine, BasePlayer player)
        {
            _landmine = landmine;
            _player = Server.GetPlayer(player);
        }

        public Landmine Landmine {
            get { return _landmine; }
        }

        public Player Player {
            get { return _player; }
        }

        public bool Explode {
            get { return _explode; }
        }

        public void CancelExplosion()
        {
            _explode = false;
        }
    }
}


text:
package org.jetbrains.plugins.gradle.codeInspection;

import com.intellij.DynamicBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;

import java.util.function.Supplier;

public final class GradleInspectionBundle extends DynamicBundle {
  @NonNls private static final String BUNDLE = "messages.GradleInspectionBundle";
  private static final GradleInspectionBundle INSTANCE = new GradleInspectionBundle();

  private GradleInspectionBundle() { super(BUNDLE); }

  @NotNull
  public static @Nls String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getMessage(key, params);
  }

  @NotNull
  public static Supplier<@Nls String> messagePointer(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) {
    return INSTANCE.getLazyMessage(key, params);
  }
}


text:
package com.lhjz.portal.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Properties;

import lombok.extern.slf4j.Slf4j;

/**
 * classpath:writable.properties配置读写操作.
 *
 * @creation 2014年3月26日 下午12:11:10
 * @modification 2014年3月26日 下午12:11:10
 * @company Canzs
 * @author xiweicheng
 * @version 1.0
 *
 */
@Slf4j
public final class PropUtil {

	public static final Properties PROPERTIES;

	private PropUtil() {
	}

	static {
		PROPERTIES = new Properties();
		InputStream inputStream = null;

		try {
			inputStream = PropUtil.class.getClassLoader().getResourceAsStream("writable.properties");
			PROPERTIES.load(inputStream);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	/**
	 * 获取运行时可以修改的配置属性值.
	 *
	 * @author xiweicheng
	 * @creation 2014年3月26日 下午5:30:11
	 * @modification 2014年3月26日 下午5:30:11
	 * @param key
	 * @param defaultVal
	 * @return
	 */
	public static String getValueByRealtime(String key, String defaultVal) {

		Properties properties = new Properties();
		InputStream inputStream = null;

		try {
			inputStream = PropUtil.class.getClassLoader().getResourceAsStream("writable.properties");
			properties.load(inputStream);

			return properties.getProperty(key, defaultVal);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return null;
	}

	/**
	 * 获取运行时可以修改的配置属性值.
	 *
	 * @author xiweicheng
	 * @creation 2014年3月26日 下午5:30:58
	 * @modification 2014年3月26日 下午5:30:58
	 * @param key
	 * @return
	 */
	public static String getValueByRealtime(String key) {

		return getValueByRealtime(key, null);
	}

	/**
	 * 获取配置属性值.
	 *
	 * @author xiweicheng
	 * @creation 2014年3月26日 上午11:26:51
	 * @modification 2014年3月26日 上午11:26:51
	 * @param key
	 * @param defaultVal
	 * @return
	 */
	public static String getValue(String key, String defaultVal) {
		if (PROPERTIES.containsKey(key)) {
			return PROPERTIES.getProperty(key);
		} else {
			return defaultVal;
		}
	}

	/**
	 * 获取配置属性值.
	 *
	 * @author xiweicheng
	 * @creation 2014年3月26日 上午11:28:15
	 * @modification 2014年3月26日 上午11:28:15
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		return getValue(key, null);
	}

	/**
	 * 保存配置键值对
	 *
	 * @author xiweicheng
	 * @creation 2014年3月26日 下午12:05:53
	 * @modification 2014年3月26日 下午12:05:53
	 * @param key
	 * @param val
	 * @return
	 */
	public static boolean save(String key, String val) {

		log.debug("保存配置键值对");

		PROPERTIES.setProperty(key, val);

		try (FileOutputStream fos = new FileOutputStream(
				new File(PropUtil.class.getResource("/writable.properties").toURI()))) {
			PROPERTIES.store(fos, "系统可读写配置");
			return true;
		} catch (URISyntaxException | IOException e) {
			log.error(e.getMessage(), e);
		}

		return false;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">
    <TextView
        android:text="Hello World this is a test"
        android:layout_height="wrap_content"
        android:background="@drawable/shadow_background"
        android:id="@+id/textView"
        android:textAlignment="center"
        android:maxWidth="240dp"
        android:textSize="20dp"
        android:layout_width="200dp" />
</LinearLayout>


text:
exports.GeneticAlgorithm = require('./GeneticAlgorithm');
exports.ICreature = exports.ICreature;
exports.ICreaturePair = exports.ICreaturePair;
exports.IRandomizer = exports.IRandomizer;
exports.ICreatureBuilder = exports.ICreatureBuilder;
exports.IFitnessFunction = exports.IFitnessFunction;
exports.IMutationOperator = exports.IMutationOperator;
exports.ICrossoverOperator = exports.ICrossoverOperator;
exports.IEvolver = exports.IEvolver;
exports.IPreselection = exports.IPreselection;
exports.IPopulation = exports.IPopulation;
exports.ISettings = exports.ISettings;
//# sourceMappingURL=index.js.map


text:
package com.moilioncircle.redis.replicator.cmd.impl;

import com.moilioncircle.redis.replicator.cmd.CommandSpec;

/**
 * @author Leon Chen
 * @since 2.1.0
 */
@CommandSpec(command = "DEL")
public class DelCommand extends AbstractCommand {

    private static final long serialVersionUID = 1L;

    private byte[][] keys;

    public DelCommand() {
    }

    public DelCommand(byte[][] keys) {
        this.keys = keys;
    }

    public byte[][] getKeys() {
        return keys;
    }

    public void setKeys(byte[][] keys) {
        this.keys = keys;
    }
}


text:
Firebase UI for authentication provides a simple and easy way to implement authentication in your Flutter app.
The library provides fully featured UI screens to drop into new or existing applications, along with
lower level abstractions for developers looking for tighter control.

## Installation

Activate FlutterFire CLI

```sh
dart pub global activate flutterfire_cli
```

Install dependencies

```sh
flutter pub add firebase_core
flutter pub add firebase_auth
# required for email link sign in and email verification
flutter pub add firebase_dynamic_links
flutter pub add firebase_ui_auth
```

## Configuration

Configure firebase using cli:

```sh
flutterfire configure
```

Initialize firebase app:

```dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
}
```

## macOS entitlements

If you're building for macOS, make sure to add necessary entitlements. Learn more [from the official Flutter documentation](https://docs.flutter.dev/development/platform-integration/macos/building).

## Next steps

To understand what Firebase UI for authentication offers, the following documentation pages walk you through the various topics on
how to use the package within your Flutter app.

- Available auth providers:

  - [EmaiAuthProvider](./providers/email.md) - allows registering and signing in using email and password.
  - [EmailLinkAuthProvider](./providers/email-link.md) - allows registering and signing in using a link sent to email.
  - [PhoneAuthProvider](./providers/phone.md) - allows registering and signing in using a phone number
  - [UniversalEmailSignInProvider](./providers/universal-email-sign-in.md) - gets all connected auth providers for a given email.
  - [OAuth](./providers/oauth.md)

- [Localization](../../firebase_ui_localizations/README.md)
- [Theming](./theming.md)
- [Navigation](./navigation.md)


text:
define([
  "jquery",
  "lib/mixins/events",
  "lib/page/pushstate",
  "lib/mixins/page_state",
  "jquery-bbq-deparam/jquery-deparam"
], function($, asEventEmitter, PushState, withPageState) {

  "use strict";

  var defaults = {
    el: "#js-card-holder"
  };

  function Controller(args) {
    this.config = $.extend({}, defaults, args);
    this.$el = $(this.config.el);

    this.init();
    this.listen();
  }

  Controller.prototype.states = null;
  Controller.prototype.layerResetState = -1;

  asEventEmitter.call(Controller.prototype);
  withPageState.call(Controller.prototype);

  Controller.prototype.init  = function() {
    this.pushState = new PushState;
    this._generateState(this.getSlug());
  };

  // Subscribe
  Controller.prototype.listen = function() {
    this.$el.on(":cards/request", function(event, data, analytics) {
      this._updateState(data);
      this.pushState.navigate(this._serializeState(), this._currentRoot());
      this._callServer({
        analytics: analytics,
        callback: this.replace,
        eventType: event.type,
        url: this._createRequestUrl()
      });
    }.bind(this))

    .on(":cards/append", function(event, data, analytics) {
      this._updateState(data);
      this._callServer({
        analytics: analytics,
        callback: this.append,
        eventType: event.type,
        url: this._createRequestUrl()
      });
    }.bind(this))

    .on(":page/request", function(event, data, analytics) {
      var urlParts = data.url.split("?");
      this._generateState(urlParts[0], urlParts[1]);
      this.pushState.navigate(this._serializeState(), this._currentRoot());
      this._callServer({
        analytics: analytics,
        callback: this.newPage,
        eventType: event.type,
        url: this._createJSONUrl(data.url)
      });
    }.bind(this))

    .on(":layer/request", function(event, data) {
      var replaceState = true,
          urlParts;
      if (this.layerResetState === -1){
        this.layerResetState = this.currentState;
        replaceState = false;
      }

      urlParts = data.url.split("?");
      this._generateState(urlParts[0], urlParts[1]);
      this.pushState.navigate(this._serializeState(), this._currentRoot(), replaceState);
      this._callServer({
        callback: this.newLayer,
        eventType: event.type,
        url: this._createJSONUrl(data.url)
      });
    }.bind(this))

    .on(":controller/back", function() {
      this._removeState();
      this._generateState();
      this.pushState.navigate(this._serializeState(), this._currentRoot());
    }.bind(this))

    .on(":controller/reset", function() {
      if (this.layerResetState != -1) {
        this.states = [ this.states[this.layerResetState] ];
        this.layerResetState = -1;
      } else {
        this.states = [ this.states[0] ];
      }
      this.currentState = 0;

      this.pushState.navigate(this._serializeState(), this._currentRoot(), true);
    }.bind(this))

    .on(":controller/updatePath", function(event, data) {
      var urlParts = data.url.split("?");
      this._generateState(urlParts[0], urlParts[1]);
      this.pushState.navigate(this._serializeState(), this._currentRoot());
      this._updateGoogleAnalytics(data);
      this.trigger(":ads/refresh", { ads: data.ads });
    }.bind(this));
  };

  // Publish

  // Page offset currently lives within search so we must check and update each time
  Controller.prototype.replace = function(data, analytics) {
    this._updateGoogleAnalytics(data);
    this._updateAdConfig(data);
    data.pagination && data.pagination.page_offsets && this._updateOffset(data.pagination); // jshint ignore:line
    this.trigger(":cards/received", [ data, this._currentState(), analytics ]);
  };

  Controller.prototype.append = function(data, analytics) {
    this._updateGoogleAnalytics(data);
    this._updateAdConfig(data);
    data.pagination && data.pagination.page_offsets && this._updateOffset(data.pagination); // jshint ignore:line
    this._removePageParam();
    this.trigger(":cards/append/received", [ data, this._currentState(), analytics ]);
  };

  Controller.prototype.newPage = function(data, analytics) {
    this._updateGoogleAnalytics(data);
    this._updateAdConfig(data);
    data.pagination && data.pagination.page_offsets && this._updateOffset(data.pagination); // jshint ignore:line
    this.trigger(":page/received", [ data, this._currentState(), analytics ]);
  };

  Controller.prototype.newLayer = function(data) {
    this._updateGoogleAnalytics(data);
    this._updateAdConfig(data);
    this.trigger(":layer/received", [ data, this._currentState() ]);
  };

  Controller.prototype._callServer = function(opts) {
    var callback = opts.callback.bind(this);

    return $.ajax({
      url: opts.url,
      dataType: opts.dataType || "json",
      error: function(jqXHR, status, err) {
        this.trigger(opts.eventType.split("/")[0] + "/error", [ jqXHR.status, err ] );
      }.bind(this),
      success: function(data) {
        callback(data, opts.analytics);
      }
    });
  };

  Controller.prototype._generateState = function(newDocumentRoot, newParams) {
    this.states || (this.states = []);
    this.currentState == null ? this.currentState = 0 : this.currentState += 1;
    this.states.push({
      state: $.deparam(newParams || this.getParams()),
      documentRoot: newDocumentRoot || this.getDocumentRoot()
    });
    return this._removePageParam();
  };

  Controller.prototype._removeState = function() {
    this.states.splice(this.states.length - 1, 1);
    this.currentState = this.currentState - 1;
  };

  Controller.prototype._updateState = function(params) {
    var state = this._currentState(),
        key;
    for (key in params) {
      if (params.hasOwnProperty(key)) {
        state[key] = params[key];
      }
    }
  };

  Controller.prototype._updateOffset = function(pagination) {
    var state = this._currentState();
    state.search && (state.search.page_offsets = pagination.page_offsets); // jshint ignore:line
  };

  Controller.prototype._removePageParam = function() {
    delete this.states[this.currentState].state.page;
    delete this.states[this.currentState].state.nearby_offset; // jshint ignore:line
  };

  Controller.prototype._serializeState = function() {
    return $.param(this.states[this.currentState].state);
  };

  Controller.prototype._createRequestUrl = function(rootUrl) {
    var documentRoot = rootUrl || this.getDocumentRoot();
    documentRoot = documentRoot.replace(/\/$/, "").replace(/\.json$/, "");

    return this._createJSONUrl(documentRoot + "?" + this._serializeState());
  };

  Controller.prototype._createJSONUrl = function(url) {
    var urlParts = url.split("?"),
        params = "";

    if (url.indexOf(".json") > -1) return url;

    if (urlParts.length > 1) {
      params = "?" + urlParts[1];
    }

    return urlParts[0] + ".json" + params;
  };

  Controller.prototype._updateGoogleAnalytics = function(data) {
    if (data.datalayer && window.lp.analytics.api) {
      window.lp.analytics.dataLayer = data.datalayer;
      window.lp.analytics.api.trackPageView(window.lp.analytics.dataLayer);
    }
  };

  Controller.prototype._updateAdConfig = function(data) {
    if (data.ads) {
      window.lp.ads = data.ads;
    }
  };

  Controller.prototype._currentRoot = function() {
    return this.states[this.currentState].documentRoot;
  };

  Controller.prototype._currentState = function() {
    return this.states[this.currentState].state;
  };

  return Controller;
});