text:
var vec2 = require('gl-matrix').vec2;

var Particle = function() {
    this.mass = 1;
    this.position = vec2.create();
    this.velocity = vec2.create();
    this.force = vec2.create();
    this.age = 0;
};

Particle.prototype.toString = function() {
    return 'position: ' + this.position +
           '\n velocity: ' + this.velocity +
           '\n force: ' + this.force +
           '\n age: ' + this.age;
};

Particle.prototype.reset = function() {
    this.mass = 1;
    vec2.set(this.position, 0, 0);
    vec2.set(this.velocity, 0, 0);
    vec2.set(this.force, 0, 0);
    this.age = 0;
};

module.exports = Particle;

redpajama_set_name: RedPajamaGithub


text:
package org.sakaiproject.evaluation.logic;

import junit.framework.Assert;

import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.scheduling.EvalJobLogicImpl;
import org.sakaiproject.evaluation.test.EvalTestDataLoad;

/**
 * FIXME test the rest of the methods -AZ
 *
 * @author Dick Ellis (rwellis@umich.edu)
 */
public class EvalJobLogicImplTest extends BaseTestEvalLogic {

	protected EvalJobLogicImpl jobLogic;
   private EvalEvaluationService evaluationService;

	// run this before each test starts
	protected void onSetUpBeforeTransaction() throws Exception {
      super.onSetUpBeforeTransaction();

      // load up any other needed spring beans
      EvalSettings settings = (EvalSettings) applicationContext.getBean("org.sakaiproject.evaluation.logic.EvalSettings");
      if (settings == null) {
         throw new NullPointerException("EvalSettings could not be retrieved from spring context");
      }

      evaluationService = (EvalEvaluationService) applicationContext.getBean("org.sakaiproject.evaluation.logic.EvalEvaluationService");
      if (evaluationService == null) {
         throw new NullPointerException("EvalEvaluationService could not be retrieved from spring context");
      }

      // setup the mock objects if needed
      EvalEmailsLogicImpl emailsLogicImpl = new EvalEmailsLogicImpl();
      emailsLogicImpl.setEvaluationService(evaluationService);
      emailsLogicImpl.setCommonLogic(commonLogic);
      emailsLogicImpl.setSettings(settings);

		//create and setup the object to be tested
		jobLogic = new EvalJobLogicImpl();
		jobLogic.setEmails(emailsLogicImpl);
		jobLogic.setEvaluationService(evaluationService);
		jobLogic.setCommonLogic(commonLogic);
		jobLogic.setSettings(settings);
		// FIXME set the remaining dependencies

	}

	// run this before each test starts and as part of the transaction
	protected void onSetUpInTransaction() {
		// preload additional data if desired

	}

	/**
	 * Test method for {@link EvalJobLogicImpl#isValidJobType(String)}
	 */
	public void testIsValidJobType() {
		//each valid type returns true
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_ACTIVE));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_CLOSED));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_CREATED));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_DUE));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_REMINDER));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_VIEWABLE));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_VIEWABLE_INSTRUCTORS));
		Assert.assertTrue( EvalJobLogicImpl.isValidJobType(EvalConstants.JOB_TYPE_VIEWABLE_STUDENTS));
		//invalid or "" type returns false
		Assert.assertFalse( EvalJobLogicImpl.isValidJobType(EvalTestDataLoad.INVALID_CONSTANT_STRING));
		Assert.assertFalse( EvalJobLogicImpl.isValidJobType(new String("")));
		//null type retuns false
		Assert.assertFalse( EvalJobLogicImpl.isValidJobType(null));
	}

	// FIXME add in the remaining test cases

}


text:
package platform

// Keys for all backends.
// In general, any backend that requires a new service config should be added here.
type Backend int

const (
	// Run in sidecar mode (GKE).
	GrpcBookstoreSidecar Backend = iota
	EchoSidecar
	GrpcEchoSidecar
	GrpcInteropSidecar

	// Run in API gateway mode for dynamic routing (Cloud Run).
	EchoRemote
	GrpcBookstoreRemote
	GrpcEchoRemote
)


text:
enum APPSTATE
{
    APP_MAIN_MENU,
    APP_CREATE_LOBBY,
    APP_JOIN_LOBBY,
    APP_JOIN_GAME,
    APP_SHOW_FRIEND_GAMES,
    APP_JOINING_LOBBY,
    APP_IN_GAME,
    APP_GET_TOURNAMENTS,
    APP_GET_TEAMS
};

// list of game modes
static WCHAR* g_gameModeStrings[] =
{
    L"Deathmatch",
    L"Team Battle",
    L"Capture the Flag",
    L"Heist",
    L"Conquest",
    L"Team Assault"
};

// list of maps
static WCHAR* g_mapStrings[] =
{
    L"Kunar Base",
    L"Leyte Gulf",
    L"Ardennes",
    L"Normandy",
    L"Helmand Valley"
};

// A basic sample implementation that creates a D3D11 device and
// provides a render loop.
class Sample : public DX::IDeviceNotify
{
public:

    Sample();

    // Initialization and management
    void Initialize(IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation);

    // Basic render loop
    void Tick();
    void Render();

    // Rendering helpers
    void Clear();

    // IDeviceNotify
    virtual void OnDeviceLost() override;
    virtual void OnDeviceRestored() override;

    // Messages
    void OnActivated();
    void OnDeactivated();
    void OnSuspending();
    void OnResuming();
    void OnProtocolActivated(Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ protocolArgs);
    void OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation);
    void ValidateDevice();

    // Properties
    void GetDefaultSize( int& width, int& height ) const;

private:

    // Xbox Live objects
    std::unique_ptr<ATG::LiveResources>     m_liveResources;

    // Multiplayer Manager logic
    uint64_t m_multiplayerContext;
    Concurrency::critical_section m_stateLock;
    std::vector<xbox::services::multiplayer::manager::multiplayer_event> m_multiplayerEventQueue;
    std::shared_ptr<xbox::services::multiplayer::manager::multiplayer_manager> m_multiplayerManager;
    Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ m_protocolActivatedEventArgs;

    // Multiplayer Manager Methods
    void InitializeMultiplayerManager(_In_ const string_t& templateName = LOBBY_TEMPLATE_NAME);
    void DoWork();
    void AddLocalUser();
    void RemoveLocalUser();
    void UpdateLocalMemberProperties();
    void UpdateLobbyProperties();
    void SetLobbyHost();
    void UpdateJoinability();
    void UpdateGameProperties();
    void SetGameHost();
    void JoinGameFromLobby();
    void JoinGame();
    void LeaveGameSession();
    void InviteFriends();
    void HandleProtocolActivation();

    void SetupUI();
    void Update(DX::StepTimer const& timer);
    void CreateDeviceDependentResources();
    void CreateWindowSizeDependentResources();

    // Tournament Methods
    void GetTournaments();
    void GetTournamentDetails(const string_t& organizerId, const string_t& tournamentId);
    void SubscribeForTournamentRTASubscription(const string_t& organizerId, const string_t& tournamentId);

    void GetTeams();
    void GetTeamDetailsAndSubscribeForRTA(xbox::services::xbox_live_result<xbox::services::tournaments::team_request_result> &result);
    void GetTeamDetails(const string_t& organizerId, const string_t& tournamentId, const string_t& teamId);
    void SubscribeForTeamRTASubscription(const string_t& organizerId, const string_t& tournamentId, const string_t& teamId);

    // Device resources.
    std::unique_ptr<DX::DeviceResources>    m_deviceResources;

    // Rendering loop timer.
    DX::StepTimer                           m_timer;

    // Input devices.
    std::unique_ptr<DirectX::GamePad>       m_gamePad;
    std::unique_ptr<DirectX::Keyboard>      m_keyboard;
    std::unique_ptr<DirectX::Mouse>         m_mouse;
    DirectX::GamePad::ButtonStateTracker    m_gamePadButtons;
    DirectX::Keyboard::KeyboardStateTracker m_keyboardButtons;

    // UI
    std::unique_ptr<ATG::UIManager>         m_ui;
    std::shared_ptr<DX::TextConsole>       m_eventQueueConsole;
    std::shared_ptr<DX::TextConsole>       m_errorMsgConsole;
    std::shared_ptr<DX::TextConsole>       m_perfConsole;
    ATG::IPanel*                           m_hudPanel;
    ATG::IPanel*                           m_mainMenuPanel;
    ATG::IPanel*                           m_sessionDetailsPanel;
    std::vector< std::wstring >            m_displayEventQueue;
    std::shared_ptr<SessionView>           m_lobbyView;
    std::shared_ptr<SessionView>           m_gameView;
    ATG::TextLabel*                        m_joinabilityLabel;
    ATG::ImageButton*                      m_joinGameBtn;
    std::unique_ptr<DX::Texture>           m_joinGameImage;
    std::unique_ptr<DX::Texture>           m_exitGameImage;

    // Sample utility helpers
    APPSTATE m_appState;
    UINT m_mapIndex;
    UINT m_gameModeIndex;
    bool m_isLeavingGame;
    bool m_isJoiningGame;
    float m_clearErrorMsgTimer;
    bool m_isProtocolActivated;
    string_t m_organizerId;
    string_t m_tournamentId;
    string_t m_teamId;
    std::shared_ptr<xbox::services::tournaments::team_change_subscription> m_teamSubscription;

    void ChangeAppStates();
    string_t CreateGuid();
    int32_t GetRandomizedGameModeIndex();
    int32_t GetRandomizedMapIndex();
    void RenderMultiplayerEventQueue();
    void RenderPerfCounters();
    void LogErrorFormat(const wchar_t* strMsg, ...);
    xbox::services::multiplayer::manager::joinability GetRandJoinabilityValue();
    int32_t GetActiveMemberCount(std::vector<std::shared_ptr<xbox::services::multiplayer::manager::multiplayer_member>> members);
    void RenderMultiplayerSessionDetails(
        string_t sessionName,
        std::shared_ptr<xbox::services::multiplayer::manager::multiplayer_member> hostMember,
        std::vector<std::shared_ptr<xbox::services::multiplayer::manager::multiplayer_member>> members,
        web::json::value properties,
        xbox::services::multiplayer::manager::multiplayer_session_type sessionType,
        std::shared_ptr<SessionView> sessionView
    );
};


text:
"""MySQL CLIENT constants.

These constants are used when creating the connection. Use bitwise-OR
(|) to combine options together, and pass them as the client_flags
parameter to MySQLdb.Connection. For more information on these flags,
see the MySQL C API documentation for mysql_real_connect().
"""


text:
node['snmp']['packages'].each do |snmppkg|
  package snmppkg
end

template '/etc/default/snmpd' do
  mode 0644
  owner 'root'
  group 'root'
  only_if { node['platform_family'] == 'debian' }
end

service node['snmp']['service'] do
  action [:start, :enable]
end

template '/etc/snmp/snmpd.conf' do
  mode 0644
  owner 'root'
  group 'root'
  notifies :restart, "service[#{node['snmp']['service']}]"
end


text:
package com.asakusafw.yaess.basic;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

import com.asakusafw.yaess.core.ExecutionContext;
import com.asakusafw.yaess.core.ExecutionMonitor;
import com.asakusafw.yaess.core.ExecutionPhase;
import com.asakusafw.yaess.core.Job;
import com.asakusafw.yaess.core.JobScheduler;
import com.asakusafw.yaess.core.PhaseMonitor;
import com.asakusafw.yaess.core.ProfileContext;
import com.asakusafw.yaess.core.ServiceProfile;

/**
 * Test for {@link BasicJobScheduler}.
 */
public class BasicJobSchedulerTest {

    private static final ExecutionContext CONTEXT = new ExecutionContext(
            "b", "f", "e", ExecutionPhase.MAIN, Collections.emptyMap());

    /**
     * Simple testing.
     * @throws Exception if failed
     */
    @Test
    public void simple() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock("a"));
        instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.STRICT);
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(0));
    }

    /**
     * Multiple execution.
     * @throws Exception if failed
     */
    @Test
    public void multiple() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock("a"));
        jobs.add(new Mock("b"));
        jobs.add(new Mock("c"));
        instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.STRICT);
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(0));
    }

    /**
     * with dependencies.
     * @throws Exception if failed
     */
    @Test
    public void dependencies() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        AtomicInteger group = new AtomicInteger();
        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock(group, "b", "a"));
        jobs.add(new Mock(group, "d", "b", "c"));
        jobs.add(new Mock(group, "a"));
        jobs.add(new Mock(group, "c", "a"));
        instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.STRICT);
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(0));

        assertThat(ordinary(jobs, "a"), lessThan(ordinary(jobs, "b")));
        assertThat(ordinary(jobs, "a"), lessThan(ordinary(jobs, "c")));
        assertThat(ordinary(jobs, "b"), lessThan(ordinary(jobs, "d")));
        assertThat(ordinary(jobs, "c"), lessThan(ordinary(jobs, "d")));
    }

    /**
     * with cyclic dependencies.
     * @throws Exception if failed
     */
    @Test
    public void cyclic() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        AtomicInteger group = new AtomicInteger();
        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock(group, "a"));
        jobs.add(new Mock(group, "b", "a", "d"));
        jobs.add(new Mock(group, "c", "b"));
        jobs.add(new Mock(group, "d", "c"));
        jobs.add(new Mock(group, "e", "d"));
        try {
            instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.STRICT);
            fail();
        } catch (IOException e) {
            // ok.
        }
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(4));
        assertThat(rest, hasItem("b"));
        assertThat(rest, hasItem("c"));
        assertThat(rest, hasItem("d"));
        assertThat(rest, hasItem("e"));
    }

    /**
     * Job failed.
     * @throws Exception if failed
     */
    @Test
    public void fail_job() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock("a") {
            @Override
            protected void hook() throws IOException {
                throw new IOException();
            }
        });
        try {
            instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.STRICT);
            fail();
        } catch (IOException e) {
            // ok.
        }
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(0));
    }

    /**
     * Job failed.
     * @throws Exception if failed
     */
    @Test
    public void fail_besteffort() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock("a") {
            @Override
            protected void hook() throws IOException {
                throw new IOException();
            }
        });
        jobs.add(new Mock("b"));
        jobs.add(new Mock("c"));
        try {
            instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.BEST_EFFORT);
            fail();
        } catch (IOException e) {
            // ok.
        }
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(0));
    }

    /**
     * Job failed and stucked.
     * @throws Exception if failed
     */
    @Test
    public void fail_stuck() throws Exception {
        Map<String, String> conf = new HashMap<>();
        ServiceProfile<JobScheduler> profile = new ServiceProfile<>(
                "testing", BasicJobScheduler.class, conf, ProfileContext.system(getClass().getClassLoader()));

        JobScheduler instance = profile.newInstance();

        List<Mock> jobs = new ArrayList<>();
        jobs.add(new Mock("a") {
            @Override
            protected void hook() throws IOException {
                throw new IOException();
            }
        });
        jobs.add(new Mock("b"));
        jobs.add(new Mock("c", "a", "b"));
        try {
            instance.execute(PhaseMonitor.NULL, CONTEXT, jobs, JobScheduler.BEST_EFFORT);
            fail();
        } catch (IOException e) {
            // ok.
        }
        Set<String> rest = collectRest(jobs);
        assertThat(rest.size(), is(1));
        assertThat(rest, hasItem("c"));
    }

    private int ordinary(List<Mock> jobs, String name) {
        for (Mock mock : jobs) {
            if (mock.getId().equals(name)) {
                return mock.count;
            }
        }
        throw new AssertionError(name);
    }

    private Set<String> collectRest(List<Mock> jobs) {
        Set<String> results = new HashSet<>();
        for (Mock mock : jobs) {
            if (mock.executed == false) {
                results.add(mock.id);
            }
        }
        return results;
    }

    private static class Mock extends Job {

        private final AtomicInteger counter;

        final String id;

        final Set<String> blockers;

        volatile boolean executed;

        volatile int count;

        Mock(String id, String... blockers) {
            this(new AtomicInteger(), id, blockers);
        }

        Mock(AtomicInteger c, String id, String... blockers) {
            assert id != null;
            assert blockers != null;
            this.counter = c;
            this.id = id;
            this.blockers = new HashSet<>(Arrays.asList(blockers));
        }

        @Override
        public void execute(ExecutionMonitor monitor, ExecutionContext context)
                throws InterruptedException, IOException {
            monitor.open(1);
            try {
                executed = true;
                count = counter.incrementAndGet();
                hook();
            } finally {
                monitor.close();
            }
        }

        /**
         * @throws InterruptedException if interrupted
         * @throws IOException if failed
         */
        protected void hook() throws InterruptedException, IOException {
            return;
        }

        @Override
        public String getJobLabel() {
            return id;
        }

        @Override
        public String getServiceLabel() {
            return id;
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public String getTrackingId(ExecutionContext context) {
            return computeTrackingId(context);
        }

        @Override
        public Set<String> getBlockerIds() {
            return blockers;
        }

        @Override
        public String getResourceId(ExecutionContext context) {
            return "testing";
        }
    }
}


text:
namespace Cik.MagazineWeb.Application
{
    using System.Web.Mvc;
    using Cik.Web.Utilities;
    using Cik.Web.Utilities.Configurations;

    public abstract class ApplicationBase
    {
        protected readonly IConfigurationManager ConfigurationManager;

        protected ApplicationBase()
            : this(DependencyResolver.Current.GetService<IConfigurationManager>())
        {
        }

        protected ApplicationBase(IConfigurationManager configurationManager)
        {
            Guard.ArgumentNotNull(configurationManager, "ConfigurationManager");

            ConfigurationManager = configurationManager;
        }
    }
}


text:
package speedy.model.database.mainmemory.paths;

import speedy.model.database.mainmemory.datasource.INode;
import speedy.model.database.mainmemory.paths.operators.GeneratePathExpression;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PathExpression implements Comparable<PathExpression>, Cloneable {

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

    protected List<String> pathSteps = new ArrayList<String>();

    public PathExpression(List<String> pathSteps) {
        this.pathSteps = pathSteps;
    }

    public PathExpression(PathExpression pathExpression) {
        this.pathSteps.addAll(pathExpression.getPathSteps());
    }

    public List<String> getPathSteps() {
        return this.pathSteps;
    }

    public String getFirstStep() {
        if (pathSteps.isEmpty()) {
            return null;
        }
        return pathSteps.get(0);
    }

    public String getLastStep() {
        if (pathSteps.isEmpty()) {
            return null;
        }
        return pathSteps.get(pathSteps.size() - 1);
    }

    public List<INode> getPathNodes(INode root) {
        return new GeneratePathExpression().generatePathStepNodes(pathSteps, root);
    }

    public List<PathExpression> getAttributePaths(INode root) {
        return new GeneratePathExpression().generateFirstLevelAttributeAbsolutePaths(this, root);
    }

    public int getLevel() {
        return this.pathSteps.size();
    }

    public INode getLastNode(INode root) {
        if (this.pathSteps.isEmpty()) {
            return null;
        }
        List<INode> pathNodes = new GeneratePathExpression().generatePathStepNodes(pathSteps, root);
        return pathNodes.get(pathNodes.size() - 1);
    }

    public int compareTo(PathExpression pathExpression) {
        return this.toString().compareTo(pathExpression.toString());
    }

    public PathExpression clone() {
        PathExpression clone = null;
        try {
            clone = (PathExpression) super.clone();
        } catch (CloneNotSupportedException ex) {
            return null;
        }
        clone.pathSteps = new ArrayList<String>(this.pathSteps);
        return clone;
    }

    public boolean equals(Object object) {
        if (logger.isTraceEnabled()) logger.trace("Comparing: " + this + " to " + object);
        if (!(object instanceof PathExpression)) {
            return false;
        }
        PathExpression otherPathExpression = (PathExpression) object;
        if (this.getPathSteps().size() != otherPathExpression.getPathSteps().size()) {
            return false;
        }
        for (int i = 0; i < this.getPathSteps().size(); i++) {
            if (!this.getPathSteps().get(i).equals(otherPathExpression.getPathSteps().get(i))) {
                if (logger.isTraceEnabled()) logger.trace("Found a different step: " + this.pathSteps.get(i) + " - Returning false");
                return false;
            }
        }
        if (logger.isTraceEnabled()) logger.trace("Paths are equal");
        return true;
    }

    public int hashCode() {
        return this.toString().hashCode();
    }

    public String toString() {
        String result = "";
        for (String nodeLabel : this.pathSteps) {
            if (!result.equals("")) {
                result += ".";
            }
            result += nodeLabel;
        }
        return result;
    }

}


text:
{% extends 'base.html' %}

{% block title %}
    Current Time
{% endblock %}

{% block content %}

Current time is {{ currenttime }}

{% endblock %}


text:
module ActsAsTaggableSimple #:nodoc:
  module Generators #:nodoc:

    # Generates a migration file for migrating two tables into the database for acts_as_taggable_simple to function:
    # * tags
    # * taggings
    #
    # Example usage:
    #
    #   rails generate acts_as_taggable_simple:migration
    #
    # To migrate the data:
    #
    #   rake db:migrate
    class MigrationGenerator < Rails::Generators::Base
      include Rails::Generators::Migration

      desc "Generates migration for Tag and Tagging models"

      # Gets the current orm that rails is using.
      #
      # ActiveRecord is the only orm currently supported.
      def self.orm
        Rails::Generators.options[:rails][:orm]
      end

      # The source root for template migration files
      def self.source_root
        File.join(File.dirname(__FILE__), 'templates', (orm.to_s unless orm.class.eql?(String)))
      end

      # Returns +true+ if the current orm has a migration file
      def self.orm_has_migration?
        [:active_record].include? orm
      end

      # Returns the timestamp for the migration
      def self.next_migration_number(path)
        Time.now.utc.strftime("%Y%m%d%H%M%S")
      end

      # Actually generates the migration file
      #
      # Only generates the migration if one exists for the current orm.
      # Looks for lib/generators/acts_as_taggable_simple/migration/templates/[orm]/migration.rb
      def create_migration_file
        if self.class.orm_has_migration?
          migration_template 'migration.rb', 'db/migrate/acts_as_taggable_simple_migration'
        end
      end
    end
  end
end


text:
<?php
use Illuminate\Foundation\Testing\AssertionsTrait;
use Jonlambert\ApplicationSettings\Setting;
use \Jonlambert\ApplicationSettings\SettingsManager;
use Jonlambert\ApplicationSettings\SettingsManager as SettingsManagerTwo;

/**
 * User: Jon
 * Date: 18/09/2014
 * Time: 17:48
 */

class SettingsManagerTest extends PHPUnit_Framework_TestCase {

	use AssertionsTrait;

	/**
	 *
	 */
	public function testInstantiation()
	{
		$settingsManager = new Setting();
	}
}


text:
devtools\bin\vpc.exe /episodic +game /mksln games.sln
pause


text:
/**
 * \file stencil.c
 * Stencil operations.
 *
 * Note: There's some conflict between GL_EXT_stencil_two_side and
 * OpenGL 2.0's two-sided stencil feature.
 *
 * With GL_EXT_stencil_two_side, calling glStencilOp/Func/Mask() only the
 * front OR back face state (as set by glActiveStencilFaceEXT) is set.
 *
 * But with OpenGL 2.0, calling glStencilOp/Func/Mask() sets BOTH the
 * front AND back state.
 *
 * Also, note that GL_ATI_separate_stencil is different as well:
 * glStencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, ...)  vs.
 * glStencilFuncSeparate(GLenum face, GLenum func, ...).
 *
 * This problem is solved by keeping three sets of stencil state:
 *  state[0] = GL_FRONT state.
 *  state[1] = OpenGL 2.0 / GL_ATI_separate_stencil GL_BACK state.
 *  state[2] = GL_EXT_stencil_two_side GL_BACK state.
 */

#include "glheader.h"
#include "imports.h"
#include "context.h"
#include "macros.h"
#include "stencil.h"
#include "mtypes.h"

static GLboolean
validate_stencil_op(struct gl_context *ctx, GLenum op)
{
   switch (op) {
   case GL_KEEP:
   case GL_ZERO:
   case GL_REPLACE:
   case GL_INCR:
   case GL_DECR:
   case GL_INVERT:
   case GL_INCR_WRAP:
   case GL_DECR_WRAP:
      return GL_TRUE;
   default:
      return GL_FALSE;
   }
}

static GLboolean
validate_stencil_func(struct gl_context *ctx, GLenum func)
{
   switch (func) {
   case GL_NEVER:
   case GL_LESS:
   case GL_LEQUAL:
   case GL_GREATER:
   case GL_GEQUAL:
   case GL_EQUAL:
   case GL_NOTEQUAL:
   case GL_ALWAYS:
      return GL_TRUE;
   default:
      return GL_FALSE;
   }
}

/**
 * Set the clear value for the stencil buffer.
 *
 * \param s clear value.
 *
 * \sa glClearStencil().
 *
 * Updates gl_stencil_attrib::Clear. On change
 * flushes the vertices and notifies the driver via
 * the dd_function_table::ClearStencil callback.
 */
void GLAPIENTRY
_mesa_ClearStencil( GLint s )
{
   GET_CURRENT_CONTEXT(ctx);

   ctx->Stencil.Clear = (GLuint) s;
}

/**
 * Set the function and reference value for stencil testing.
 *
 * \param frontfunc front test function.
 * \param backfunc back test function.
 * \param ref front and back reference value.
 * \param mask front and back bitmask.
 *
 * \sa glStencilFunc().
 *
 * Verifies the parameters and updates the respective values in
 * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
 * driver via the dd_function_table::StencilFunc callback.
 */
void GLAPIENTRY
_mesa_StencilFuncSeparateATI( GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask )
{
   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilFuncSeparateATI()\n");

   if (!validate_stencil_func(ctx, frontfunc)) {
      _mesa_error(ctx, GL_INVALID_ENUM,
                  "glStencilFuncSeparateATI(frontfunc)");
      return;
   }
   if (!validate_stencil_func(ctx, backfunc)) {
      _mesa_error(ctx, GL_INVALID_ENUM,
                  "glStencilFuncSeparateATI(backfunc)");
      return;
   }

   /* set both front and back state */
   if (ctx->Stencil.Function[0] == frontfunc &&
       ctx->Stencil.Function[1] == backfunc &&
       ctx->Stencil.ValueMask[0] == mask &&
       ctx->Stencil.ValueMask[1] == mask &&
       ctx->Stencil.Ref[0] == ref &&
       ctx->Stencil.Ref[1] == ref)
      return;
   FLUSH_VERTICES(ctx, _NEW_STENCIL);
   ctx->Stencil.Function[0]  = frontfunc;
   ctx->Stencil.Function[1]  = backfunc;
   ctx->Stencil.Ref[0]       = ctx->Stencil.Ref[1]       = ref;
   ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
   if (ctx->Driver.StencilFuncSeparate) {
      ctx->Driver.StencilFuncSeparate(ctx, GL_FRONT,
                                      frontfunc, ref, mask);
      ctx->Driver.StencilFuncSeparate(ctx, GL_BACK,
                                      backfunc, ref, mask);
   }
}

/**
 * Set the function and reference value for stencil testing.
 *
 * \param func test function.
 * \param ref reference value.
 * \param mask bitmask.
 *
 * \sa glStencilFunc().
 *
 * Verifies the parameters and updates the respective values in
 * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
 * driver via the dd_function_table::StencilFunc callback.
 */
void GLAPIENTRY
_mesa_StencilFunc( GLenum func, GLint ref, GLuint mask )
{
   GET_CURRENT_CONTEXT(ctx);
   const GLint face = ctx->Stencil.ActiveFace;

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilFunc()\n");

   if (!validate_stencil_func(ctx, func)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFunc(func)");
      return;
   }

   if (face != 0) {
      if (ctx->Stencil.Function[face] == func &&
          ctx->Stencil.ValueMask[face] == mask &&
          ctx->Stencil.Ref[face] == ref)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.Function[face] = func;
      ctx->Stencil.Ref[face] = ref;
      ctx->Stencil.ValueMask[face] = mask;

      /* Only propagate the change to the driver if EXT_stencil_two_side
       * is enabled.
       */
      if (ctx->Driver.StencilFuncSeparate && ctx->Stencil.TestTwoSide) {
         ctx->Driver.StencilFuncSeparate(ctx, GL_BACK, func, ref, mask);
      }
   }
   else {
      /* set both front and back state */
      if (ctx->Stencil.Function[0] == func &&
          ctx->Stencil.Function[1] == func &&
          ctx->Stencil.ValueMask[0] == mask &&
          ctx->Stencil.ValueMask[1] == mask &&
          ctx->Stencil.Ref[0] == ref &&
          ctx->Stencil.Ref[1] == ref)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.Function[0]  = ctx->Stencil.Function[1]  = func;
      ctx->Stencil.Ref[0]       = ctx->Stencil.Ref[1]       = ref;
      ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
      if (ctx->Driver.StencilFuncSeparate) {
         ctx->Driver.StencilFuncSeparate(ctx,
					 ((ctx->Stencil.TestTwoSide)
					  ? GL_FRONT : GL_FRONT_AND_BACK),
                                         func, ref, mask);
      }
   }
}

/**
 * Set the stencil writing mask.
 *
 * \param mask bit-mask to enable/disable writing of individual bits in the
 * stencil planes.
 *
 * \sa glStencilMask().
 *
 * Updates gl_stencil_attrib::WriteMask. On change flushes the vertices and
 * notifies the driver via the dd_function_table::StencilMask callback.
 */
void GLAPIENTRY
_mesa_StencilMask( GLuint mask )
{
   GET_CURRENT_CONTEXT(ctx);
   const GLint face = ctx->Stencil.ActiveFace;

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilMask()\n");

   if (face != 0) {
      /* Only modify the EXT_stencil_two_side back-face state.
       */
      if (ctx->Stencil.WriteMask[face] == mask)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.WriteMask[face] = mask;

      /* Only propagate the change to the driver if EXT_stencil_two_side
       * is enabled.
       */
      if (ctx->Driver.StencilMaskSeparate && ctx->Stencil.TestTwoSide) {
         ctx->Driver.StencilMaskSeparate(ctx, GL_BACK, mask);
      }
   }
   else {
      /* set both front and back state */
      if (ctx->Stencil.WriteMask[0] == mask &&
          ctx->Stencil.WriteMask[1] == mask)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.WriteMask[0] = ctx->Stencil.WriteMask[1] = mask;
      if (ctx->Driver.StencilMaskSeparate) {
         ctx->Driver.StencilMaskSeparate(ctx,
					 ((ctx->Stencil.TestTwoSide)
					  ? GL_FRONT : GL_FRONT_AND_BACK),
					  mask);
      }
   }
}

/**
 * Set the stencil test actions.
 *
 * \param fail action to take when stencil test fails.
 * \param zfail action to take when stencil test passes, but depth test fails.
 * \param zpass action to take when stencil test passes and the depth test
 * passes (or depth testing is not enabled).
 *
 * \sa glStencilOp().
 *
 * Verifies the parameters and updates the respective fields in
 * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
 * driver via the dd_function_table::StencilOp callback.
 */
void GLAPIENTRY
_mesa_StencilOp(GLenum fail, GLenum zfail, GLenum zpass)
{
   GET_CURRENT_CONTEXT(ctx);
   const GLint face = ctx->Stencil.ActiveFace;

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilOp()\n");

   if (!validate_stencil_op(ctx, fail)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(sfail)");
      return;
   }
   if (!validate_stencil_op(ctx, zfail)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zfail)");
      return;
   }
   if (!validate_stencil_op(ctx, zpass)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zpass)");
      return;
   }

   if (face != 0) {
      /* only set active face state */
      if (ctx->Stencil.ZFailFunc[face] == zfail &&
          ctx->Stencil.ZPassFunc[face] == zpass &&
          ctx->Stencil.FailFunc[face] == fail)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.ZFailFunc[face] = zfail;
      ctx->Stencil.ZPassFunc[face] = zpass;
      ctx->Stencil.FailFunc[face] = fail;

      /* Only propagate the change to the driver if EXT_stencil_two_side
       * is enabled.
       */
      if (ctx->Driver.StencilOpSeparate && ctx->Stencil.TestTwoSide) {
         ctx->Driver.StencilOpSeparate(ctx, GL_BACK, fail, zfail, zpass);
      }
   }
   else {
      /* set both front and back state */
      if (ctx->Stencil.ZFailFunc[0] == zfail &&
          ctx->Stencil.ZFailFunc[1] == zfail &&
          ctx->Stencil.ZPassFunc[0] == zpass &&
          ctx->Stencil.ZPassFunc[1] == zpass &&
          ctx->Stencil.FailFunc[0] == fail &&
          ctx->Stencil.FailFunc[1] == fail)
         return;
      FLUSH_VERTICES(ctx, _NEW_STENCIL);
      ctx->Stencil.ZFailFunc[0] = ctx->Stencil.ZFailFunc[1] = zfail;
      ctx->Stencil.ZPassFunc[0] = ctx->Stencil.ZPassFunc[1] = zpass;
      ctx->Stencil.FailFunc[0]  = ctx->Stencil.FailFunc[1]  = fail;
      if (ctx->Driver.StencilOpSeparate) {
         ctx->Driver.StencilOpSeparate(ctx,
				       ((ctx->Stencil.TestTwoSide)
					? GL_FRONT : GL_FRONT_AND_BACK),
                                       fail, zfail, zpass);
      }
   }
}

/* GL_EXT_stencil_two_side */
void GLAPIENTRY
_mesa_ActiveStencilFaceEXT(GLenum face)
{
   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glActiveStencilFaceEXT()\n");

   if (!ctx->Extensions.EXT_stencil_two_side) {
      _mesa_error(ctx, GL_INVALID_OPERATION, "glActiveStencilFaceEXT");
      return;
   }

   if (face == GL_FRONT || face == GL_BACK) {
      ctx->Stencil.ActiveFace = (face == GL_FRONT) ? 0 : 2;
   }
   else {
      _mesa_error(ctx, GL_INVALID_ENUM, "glActiveStencilFaceEXT(face)");
   }
}

/**
 * OpenGL 2.0 function.
 * \todo Make StencilOp() call this function.  And eventually remove the
 * ctx->Driver.StencilOp function and use ctx->Driver.StencilOpSeparate
 * instead.
 */
void GLAPIENTRY
_mesa_StencilOpSeparate(GLenum face, GLenum sfail, GLenum zfail, GLenum zpass)
{
   GLboolean set = GL_FALSE;
   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilOpSeparate()\n");

   if (!validate_stencil_op(ctx, sfail)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(sfail)");
      return;
   }
   if (!validate_stencil_op(ctx, zfail)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zfail)");
      return;
   }
   if (!validate_stencil_op(ctx, zpass)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zpass)");
      return;
   }
   if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(face)");
      return;
   }

   if (face != GL_BACK) {
      /* set front */
      if (ctx->Stencil.ZFailFunc[0] != zfail ||
          ctx->Stencil.ZPassFunc[0] != zpass ||
          ctx->Stencil.FailFunc[0] != sfail){
         FLUSH_VERTICES(ctx, _NEW_STENCIL);
         ctx->Stencil.ZFailFunc[0] = zfail;
         ctx->Stencil.ZPassFunc[0] = zpass;
         ctx->Stencil.FailFunc[0] = sfail;
         set = GL_TRUE;
      }
   }
   if (face != GL_FRONT) {
      /* set back */
      if (ctx->Stencil.ZFailFunc[1] != zfail ||
          ctx->Stencil.ZPassFunc[1] != zpass ||
          ctx->Stencil.FailFunc[1] != sfail) {
         FLUSH_VERTICES(ctx, _NEW_STENCIL);
         ctx->Stencil.ZFailFunc[1] = zfail;
         ctx->Stencil.ZPassFunc[1] = zpass;
         ctx->Stencil.FailFunc[1] = sfail;
         set = GL_TRUE;
      }
   }
   if (set && ctx->Driver.StencilOpSeparate) {
      ctx->Driver.StencilOpSeparate(ctx, face, sfail, zfail, zpass);
   }
}

/* OpenGL 2.0 */
void GLAPIENTRY
_mesa_StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
{
   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilFuncSeparate()\n");

   if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(face)");
      return;
   }
   if (!validate_stencil_func(ctx, func)) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(func)");
      return;
   }

   FLUSH_VERTICES(ctx, _NEW_STENCIL);

   if (face != GL_BACK) {
      /* set front */
      ctx->Stencil.Function[0] = func;
      ctx->Stencil.Ref[0] = ref;
      ctx->Stencil.ValueMask[0] = mask;
   }
   if (face != GL_FRONT) {
      /* set back */
      ctx->Stencil.Function[1] = func;
      ctx->Stencil.Ref[1] = ref;
      ctx->Stencil.ValueMask[1] = mask;
   }
   if (ctx->Driver.StencilFuncSeparate) {
      ctx->Driver.StencilFuncSeparate(ctx, face, func, ref, mask);
   }
}

/* OpenGL 2.0 */
void GLAPIENTRY
_mesa_StencilMaskSeparate(GLenum face, GLuint mask)
{
   GET_CURRENT_CONTEXT(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glStencilMaskSeparate()\n");

   if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
      _mesa_error(ctx, GL_INVALID_ENUM, "glStencilaMaskSeparate(face)");
      return;
   }

   FLUSH_VERTICES(ctx, _NEW_STENCIL);

   if (face != GL_BACK) {
      ctx->Stencil.WriteMask[0] = mask;
   }
   if (face != GL_FRONT) {
      ctx->Stencil.WriteMask[1] = mask;
   }
   if (ctx->Driver.StencilMaskSeparate) {
      ctx->Driver.StencilMaskSeparate(ctx, face, mask);
   }
}

/**
 * Update derived stencil state.
 */
void
_mesa_update_stencil(struct gl_context *ctx)
{
   const GLint face = ctx->Stencil._BackFace;

   ctx->Stencil._Enabled = (ctx->Stencil.Enabled &&
                            ctx->DrawBuffer->Visual.stencilBits > 0);

    ctx->Stencil._TestTwoSide =
       ctx->Stencil._Enabled &&
       (ctx->Stencil.Function[0] != ctx->Stencil.Function[face] ||
	ctx->Stencil.FailFunc[0] != ctx->Stencil.FailFunc[face] ||
	ctx->Stencil.ZPassFunc[0] != ctx->Stencil.ZPassFunc[face] ||
	ctx->Stencil.ZFailFunc[0] != ctx->Stencil.ZFailFunc[face] ||
	ctx->Stencil.Ref[0] != ctx->Stencil.Ref[face] ||
	ctx->Stencil.ValueMask[0] != ctx->Stencil.ValueMask[face] ||
	ctx->Stencil.WriteMask[0] != ctx->Stencil.WriteMask[face]);

   ctx->Stencil._WriteEnabled =
      ctx->Stencil._Enabled &&
      (ctx->Stencil.WriteMask[0] != 0 ||
       (ctx->Stencil._TestTwoSide && ctx->Stencil.WriteMask[face] != 0));
}

/**
 * Initialize the context stipple state.
 *
 * \param ctx GL context.
 *
 * Initializes __struct gl_contextRec::Stencil attribute group.
 */
void
_mesa_init_stencil(struct gl_context *ctx)
{
   ctx->Stencil.Enabled = GL_FALSE;
   ctx->Stencil.TestTwoSide = GL_FALSE;
   ctx->Stencil.ActiveFace = 0;  /* 0 = GL_FRONT, 2 = GL_BACK */
   ctx->Stencil.Function[0] = GL_ALWAYS;
   ctx->Stencil.Function[1] = GL_ALWAYS;
   ctx->Stencil.Function[2] = GL_ALWAYS;
   ctx->Stencil.FailFunc[0] = GL_KEEP;
   ctx->Stencil.FailFunc[1] = GL_KEEP;
   ctx->Stencil.FailFunc[2] = GL_KEEP;
   ctx->Stencil.ZPassFunc[0] = GL_KEEP;
   ctx->Stencil.ZPassFunc[1] = GL_KEEP;
   ctx->Stencil.ZPassFunc[2] = GL_KEEP;
   ctx->Stencil.ZFailFunc[0] = GL_KEEP;
   ctx->Stencil.ZFailFunc[1] = GL_KEEP;
   ctx->Stencil.ZFailFunc[2] = GL_KEEP;
   ctx->Stencil.Ref[0] = 0;
   ctx->Stencil.Ref[1] = 0;
   ctx->Stencil.Ref[2] = 0;
   ctx->Stencil.ValueMask[0] = ~0U;
   ctx->Stencil.ValueMask[1] = ~0U;
   ctx->Stencil.ValueMask[2] = ~0U;
   ctx->Stencil.WriteMask[0] = ~0U;
   ctx->Stencil.WriteMask[1] = ~0U;
   ctx->Stencil.WriteMask[2] = ~0U;
   ctx->Stencil.Clear = 0;
   ctx->Stencil._BackFace = 1;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.operator.scalar;

import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.prestosql.metadata.FunctionArgumentDefinition;
import io.prestosql.metadata.FunctionBinding;
import io.prestosql.metadata.FunctionMetadata;
import io.prestosql.metadata.Signature;
import io.prestosql.metadata.SqlScalarFunction;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.TypeSignature;

import java.lang.invoke.MethodHandle;

import static io.prestosql.metadata.FunctionKind.SCALAR;
import static io.prestosql.metadata.Signature.typeVariable;
import static io.prestosql.spi.function.InvocationConvention.InvocationArgumentConvention.NEVER_NULL;
import static io.prestosql.spi.function.InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL;
import static io.prestosql.spi.type.TypeSignature.arrayType;
import static io.prestosql.util.Reflection.methodHandle;

public class ElementToArrayConcatFunction
        extends SqlScalarFunction
{
    public static final ElementToArrayConcatFunction ELEMENT_TO_ARRAY_CONCAT_FUNCTION = new ElementToArrayConcatFunction();
    private static final String FUNCTION_NAME = "concat";

    private static final MethodHandle METHOD_HANDLE_BOOLEAN = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, boolean.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_LONG = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, long.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_DOUBLE = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, double.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_SLICE = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, Slice.class, Block.class);
    private static final MethodHandle METHOD_HANDLE_OBJECT = methodHandle(ArrayConcatUtils.class, "prependElement", Type.class, Object.class, Block.class);

    public ElementToArrayConcatFunction()
    {
        super(new FunctionMetadata(
                new Signature(
                        FUNCTION_NAME,
                        ImmutableList.of(typeVariable("E")),
                        ImmutableList.of(),
                        arrayType(new TypeSignature("E")),
                        ImmutableList.of(new TypeSignature("E"), arrayType(new TypeSignature("E"))),
                        false),
                false,
                ImmutableList.of(
                        new FunctionArgumentDefinition(false),
                        new FunctionArgumentDefinition(false)),
                false,
                true,
                "Concatenates an element to an array",
                SCALAR));
    }

    @Override
    protected ScalarFunctionImplementation specialize(FunctionBinding functionBinding)
    {
        Type type = functionBinding.getTypeVariable("E");
        MethodHandle methodHandle;
        if (type.getJavaType() == boolean.class) {
            methodHandle = METHOD_HANDLE_BOOLEAN;
        }
        else if (type.getJavaType() == long.class) {
            methodHandle = METHOD_HANDLE_LONG;
        }
        else if (type.getJavaType() == double.class) {
            methodHandle = METHOD_HANDLE_DOUBLE;
        }
        else if (type.getJavaType() == Slice.class) {
            methodHandle = METHOD_HANDLE_SLICE;
        }
        else {
            methodHandle = METHOD_HANDLE_OBJECT;
        }
        methodHandle = methodHandle.bindTo(type);

        return new ChoicesScalarFunctionImplementation(
                functionBinding,
                FAIL_ON_NULL,
                ImmutableList.of(NEVER_NULL, NEVER_NULL),
                methodHandle);
    }
}


text:
package texture.art;

import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import texture.art.processor.ImageSpec;
import texture.art.processor.PerlinNoise;
import texture.art.processor.Processor;

/**
 * Manage the main window
 */
public class MainWindowManager {

    private Stage stage;
    private Scene scene;
    private MenuBar menuBar;
    private ImageView imageViewer;

    MainWindowManager(Stage primaryStage) {
        stage = primaryStage;
        scene = new Scene(new VBox(), 400, 350);
        createMenu();
        createImageViewer();
        stage.setTitle("Texture Art");
        stage.setScene(scene);
        stage.show();

    }

    protected final void createMenu() {
        menuBar = new MenuBar();
        Menu menuFile = new Menu("File");
        Menu menuEdit = new Menu("Edit");
        Menu menuView = new Menu("View");
        menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
        ((VBox) scene.getRoot()).getChildren().addAll(menuBar);
    }

    protected final void createImageViewer() {
        imageViewer = new ImageView();
        ImageSpec imageSpec = new ImageSpec(500, 500);
        Processor processor = new PerlinNoise();
        processor.generateImage(imageSpec);
        Image image = processor.getImage();
        ((VBox) scene.getRoot()).getChildren().add(imageViewer);
        imageViewer.setImage(image);
        imageViewer.setPreserveRatio(true);
        imageViewer.setSmooth(true);
    }
}


text:
package in.clouthink.daas.sbb.sms.history.rest.dto;

import in.clouthink.daas.sbb.shared.domain.request.impl.DateRangedQueryParameter;
import in.clouthink.daas.sbb.sms.history.domain.model.SmsHistory;
import in.clouthink.daas.sbb.sms.history.domain.request.SmsHistoryQueryRequest;
import io.swagger.annotations.ApiModel;

@ApiModel
public class SmsHistoryQueryParameter extends DateRangedQueryParameter implements SmsHistoryQueryRequest {

	private String cellphone;

	private String category;

	private SmsHistory.SmsStatus status;

	public String getCellphone() {
		return cellphone;
	}

	public void setCellphone(String cellphone) {
		this.cellphone = cellphone;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public SmsHistory.SmsStatus getStatus() {
		return status;
	}

	public void setStatus(SmsHistory.SmsStatus status) {
		this.status = status;
	}
}


text:
package com.dwolla.cloudflare.domain.model

import com.dwolla.circe._
import io.circe._
import io.circe.generic.semiauto
import monix.newtypes.NewtypeWrapped
import org.http4s.{QueryParam, QueryParamEncoder, QueryParameterKey, QueryParameterValue}

package object wafrulepackages {
  type WafRulePackageName = WafRulePackageName.Type
  object WafRulePackageName extends NewtypeWrapped[String] {
    implicit val queryParam: QueryParam[WafRulePackageName] = new QueryParam[WafRulePackageName] {
      override def key: QueryParameterKey = QueryParameterKey("name")
    }
    implicit val queryParamEncoder: QueryParamEncoder[WafRulePackageName] = value => QueryParameterValue(value.value)
    implicit val jsonEncoder: Encoder[WafRulePackageName] = Encoder[String].contramap(_.value)
    implicit val jsonDecoder: Decoder[WafRulePackageName] = Decoder[String].map(WafRulePackageName(_))
  }
}

package wafrulepackages {
  trait WafRulePackageNameTag

  case class WafRulePackage(id: WafRulePackageId,
                            name: WafRulePackageName,
                            description: Option[String] = None,
                            zone_id: ZoneId,
                            detection_mode: DetectionMode,
                            sensitivity: Option[Sensitivity] = None,
                            action_mode: Option[ActionMode] = None)

  sealed trait DetectionMode
  object DetectionMode {
    case object Anomaly extends DetectionMode
    case object Traditional extends DetectionMode

    implicit val detectionModeEncoder: Encoder[DetectionMode] = Encoder[String].contramap {
      case DetectionMode.Anomaly => "anomaly"
      case DetectionMode.Traditional => "traditional"
    }

    implicit val detectionModeDecoder: Decoder[DetectionMode] = Decoder[String].map {
      case "anomaly" => DetectionMode.Anomaly
      case "traditional" => DetectionMode.Traditional
    }
  }

  sealed trait Status
  object Status {
    case object Active extends Status

    implicit val statusEncoder: Encoder[Status] = Encoder[String].contramap {
      case Status.Active => "active"
    }

    implicit val statusDecoder: Decoder[Status] = Decoder[String].emap {
      case "active" => Right(Status.Active)
      case other => Left(s""""$other" is not a valid status""")
    }
  }

  sealed trait Sensitivity
  object Sensitivity {
    case object High extends Sensitivity
    case object Medium extends Sensitivity
    case object Low extends Sensitivity
    case object Off extends Sensitivity

    implicit val sensitivityEncoder: Encoder[Sensitivity] = Encoder[String].contramap {
      case Sensitivity.High => "high"
      case Sensitivity.Medium => "medium"
      case Sensitivity.Low => "low"
      case Sensitivity.Off => "off"
    }

    implicit val sensitivityDecoder: Decoder[Sensitivity] = Decoder[String].map {
      case "high" => Sensitivity.High
      case "medium" => Sensitivity.Medium
      case "low" => Sensitivity.Low
      case "off" => Sensitivity.Off
    }
  }

  sealed trait ActionMode
  object ActionMode {
    case object Simulate extends ActionMode
    case object Block extends ActionMode
    case object Challenge extends ActionMode

    implicit val actionModeEncoder: Encoder[ActionMode] = Encoder[String].contramap {
      case ActionMode.Simulate => "simulate"
      case ActionMode.Block => "block"
      case ActionMode.Challenge => "challenge"
    }

    implicit val actionModeDecoder: Decoder[ActionMode] = Decoder[String].map {
      case "simulate" => ActionMode.Simulate
      case "block" => ActionMode.Block
      case "challenge" => ActionMode.Challenge
    }
  }

  object WafRulePackage {
    implicit val wafRulePackageCodec: Codec[WafRulePackage] = semiauto.deriveCodec
  }
}


text:
#ifndef PREDICTION_FSM_H
#define PREDICTION_FSM_H

#include "../prediction.h"
#include "../fsm.h"

typedef int (*prediction_fsm_metric_from_state_t)(fsm_state_t *state,
						  const char *metric_name,
						  sample_value_t *value);

prediction_t *prediction_fsm_create(fsm_t *fsm,
				    prediction_fsm_metric_from_state_t metric_state,
				    sample_time_t prediction_length,
				    sample_time_t transition_resolution_us);

/* metrics should be added before running the code */
int prediction_fsm_add_output_metric(prediction_t *pred_fsm, const char *metric_name);
void prediction_fsm_dump_probability_density(prediction_t *pred_fsm,
					    const char *filename_pattern);

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
            android:key="alerm_text"
            android:title="闹钟文本"
            android:summary="闹钟响起时显示的文本"
            android:defaultValue="时间到了。"
            />
</PreferenceScreen>


text:
struct integer {
	int* digits;
	int size;
};

struct integer* read_integer(char* stringInt);
void print(FILE *fo, struct integer *p);
struct integer* add(struct integer *p, struct integer *q);
struct integer* subtract(struct integer *p, struct integer *q);
int compare(struct integer *p, struct integer *q);

int main() {
    // Read in the number of cases
    FILE *fp = fopen("bigint.in", "r");
    FILE *fo = fopen("bigint.out", "w");
    int numCases, i;

    fscanf(fp, "%d", &numCases);

    int operation;
    char operand1[200], operand2[200];

    for (i = 0; i < numCases; i++) {
        fscanf(fp, "%d %s %s", &operation, operand1, operand2);

        // Create the big integer structures
        struct integer *bigInt1 = read_integer(operand1);
        struct integer *bigInt2 = read_integer(operand2);

        // Add or subtract the big integers
        struct integer *result;
        if (operation == 1) {
			// Print each big integer operand and the operation to the file
			print(fo, bigInt1);
			operation == 1 ? fprintf(fo, " + ") : fprintf(fo, " - ");
			print(fo, bigInt2);
			fprintf(fo, " = ");

            result = add(bigInt1, bigInt2);
        }
        else {
			// We want to subtract bigger - smaller
			int comparison = compare(bigInt1, bigInt2);
			struct integer *bigger  = comparison >= 0 ? bigInt1 : bigInt2;
			struct integer *smaller = comparison >= 0 ? bigInt2 : bigInt1;

			// Print each big integer operand and the operation to the file
			print(fo, bigger);
			operation == 1 ? fprintf(fo, " + ") : fprintf(fo, " - ");
			print(fo, smaller);
			fprintf(fo, " = ");

            result = subtract(bigger, smaller);
        }
        // Print the result
		print(fo, result);

        fprintf(fo, "\n");

		// Free the digits and then the structure
		free(bigInt1->digits);
		free(bigInt1);
		free(bigInt2->digits);
		free(bigInt2);
		free(result->digits);
		free(result);
    }

	fclose(fp);
	fclose(fo);
}

//Preconditions: the first parameter is string that stores
//               only contains digits, doesn't start with
//               0, and is 200 or fewer characters long.
//Postconditions: The function will read the digits of the
//	large integer character by character,
//	convert them into integers and return a
//             pointer to the appropriate struct integer.
struct integer* read_integer(char* stringInt) {
    // Allocate space for the struct, then for the digits array
	struct integer *myInt = (struct integer *)malloc(sizeof(struct integer));
    myInt->size = strlen(stringInt);
    myInt->digits = (int*)malloc(myInt->size*sizeof(int));

    int i, j;
	// convert each character to an int and then add to digits array
    for(i = 0, j = myInt->size-1; i < myInt->size, j>=0; i++, j--) {
        myInt->digits[j] = stringInt[i] - '0';
    }

    return myInt;
}

//Preconditions: p is a pointer to a big integer.
//Postconditions: The big integer pointed to by p is
//                printed out.
void print(FILE *fo, struct integer *p) {
    int j;
	// Print in reverse order
    for(j = p->size-1; j >= 0 ; j--) {
        fprintf(fo, "%d", p->digits[j]);
    }
}

//Preconditions: p and q are pointers to struct integers.
//Postconditions: A new struct integer is created that
//                stores the sum of the integers pointed to
//                by p and q and a pointer to it is
//                returned.
struct integer* add(struct integer *p, struct integer *q) {
    // Allocate memory for the result
	struct integer* result = (struct integer*)malloc(sizeof(struct integer));
	int maxSize = p->size > q->size ? p->size : q->size;
	result->digits = (int*)malloc((maxSize+1)*sizeof(int));
	result->size = 0;

	int i=0, carry=0, sum=0;

	while(i < p->size || i < q->size) {
		// Case 1:  both p and q still have digits to add
		if(i < p->size && i < q->size) {
			sum = p->digits[i] + q->digits[i] + carry;

			result->digits[i] = sum % 10;
			carry = sum > 9 ? 1 : 0;
		}
		// Case 2:  Just take digits from p
		else if (i < p->size) {
			sum = p->digits[i] + carry;

			result->digits[i] = sum % 10;
			carry = sum > 9 ? 1 : 0;
		}
		// Case 2:  Just take digits from q
		else {
			sum = q->digits[i] + carry;

			result->digits[i] = sum % 10;
			carry = sum > 9 ? 1 : 0;
		}

		result->size++;
		i++;
	}

	// Check for additional carry
	if (carry == 1)	{
		result->digits[i] = 1;
		result->size++;
	}

	return result;
}

//Preconditions: p and q are pointers to struct integers.
//					Assume bigger >= smaller
//Postconditions: A new struct integer is created that
//                stores the absolute value of the
//                difference between the two and a pointer
//                to this is returned.
struct integer* subtract(struct integer *bigger, struct integer *smaller) {
	// Allocate memory for result
	struct integer* result = (struct integer*)malloc(sizeof(struct integer));
	int maxSize = bigger->size;
	result->digits = (int*)malloc((maxSize)*sizeof(int));
	result->size = 0;

	int i = 0, sum = 0;
	while(i < maxSize) {
		if (i < bigger->size && i < smaller->size) {
			// Check if we have to borrow
			if (bigger->digits[i] < smaller->digits[i]) {
				bigger->digits[i+1]--;
				sum = bigger->digits[i] + 10 - smaller->digits[i];
			}
			else {
				sum = bigger->digits[i] - smaller->digits[i];
			}
		}
		else {
			sum = bigger->digits[i];
		}

		result->digits[i] = sum;
		result->size++;
		i++;
	}

	// Remove leading 0's
	i = result->size - 1;
	while (i > 0) {
		if (result->digits[i] == 0) {
			result->size--;
			i--;
		}
		else
			break;
	}

	return result;
}

//Preconditions: Both parameters of the function are
//	  pointers to struct integer.
//Postconditions: The function compares the digits of two
//	numbers and returns:
//    -1 if the first number is smaller than the second,
//     0 if the first number is equal to the second number,
//   1 if the first number is greater than the second.
int compare(struct integer *p, struct integer *q) {
	int i = 0, result = 0;

	if (p->size > q->size)
		return 1;
	else if (q->size > p->size)
		return -1;
	else {
		// The sizes are equal, now compare each digit until we're out, or we find unequal
		i = p->size - 1;
		while (i >= 0) {
			if (p->digits[i] > q->digits[i])
				return 1;
			else if (q->digits[i] > p->digits[i])
				return -1;
			//else continue checking
			i--;
		}
	}

	return 0;
}


text:
#ifndef __PROJECT_EULER_PROBLEM186_H__
#define __PROJECT_EULER_PROBLEM186_H__
/*
 * ProjectEuler/include/c/ProjectEuler/Problem186.h
 *
 * Connectedness of a network.
 * ===========================
 * Published on Saturday, 15th March 2008, 05:00 am
 *
 * Here are the records from a busy telephone system with one million users:
 * RecNrCallerCalled 1200007100053 2600183500439 3600863701497 .........   The
 * telephone number of the caller and the called number in record n are
 * Caller(n) = S2n-1 and Called(n) = S2n where S1,2,3,... come from the "Lagged
 * Fibonacci Generator": For 1  k  55, Sk = [100003 - 200003k + 300007k3]
 * (modulo 1000000)  For 56  k, Sk = [Sk-24 + Sk-55] (modulo 1000000) If
 * Caller(n) = Called(n) then the user is assumed to have misdialled and the
 * call fails; otherwise the call is successful. From the start of the records,
 * we say that any pair of users X and Y are friends if X calls Y or vice-versa.
 * Similarly, X is a friend of a friend of Z if X is a friend of Y and Y is a
 * friend of Z; and so on for longer chains. The Prime Minister's phone number
 * is 524287. After how many successful calls, not counting misdials, will 99%
 * of the users (including the PM) be a friend, or a friend of a friend etc., of
 * the Prime Minister?
 */

#  ifdef __cplusplus
extern "C" {
#  endif

#  ifdef __cplusplus
}
#  endif

#endif  /* __PROJECT_EULER_PROBLEM186_H__ */


text:
namespace Microsoft.Azure.Management.IotHub.Models
{

    /// <summary>
    /// Defines values for AuthenticationType.
    /// </summary>
    public static class AuthenticationType
    {
        public const string KeyBased = "keyBased";
        public const string IdentityBased = "identityBased";
    }
}


text:
from addict import Dict
from os.path import join

__all__ = ['model', 'solver']

_home_dir = 'expts/medium'
_log_fname = 'run.log'
# Configuration for setting up a test model
model = Dict()

model.mode = 'train'
model.batch_size = 32
model.num_samples = None  # filled while calling
model.time_steps = 26
model.vocab_size = None  # filled while calling
model.embedding_size = 512
model.lstm_cells = 512
model.dropout = 0.7
model.img_input_feed = 'image_feature'
model.cap_input_feed = 'input_feed'
model.cap_generated = 'cap_generated'
model.resume_from_model_path = None  # 'expts/medium'
model.model_path = None  # used in case of 'eval' or 'inference'
model.log_fname = join(_home_dir, _log_fname)

# Configuration for training the test model
solver = Dict()

solver.num_epochs = 100
solver.save_model_dir = join(_home_dir, 'model')
solver.max_to_keep = 100
solver.ckpt_epoch_freq = 5
solver.train_clip_gradients = 5.0

# fixed learning rate with Adam
solver.optimizer = 'Adam'
solver.learning_rate = 0.001

# decay learning rate with SGD
# solver.optimizer = 'SGD'
# solver.learning_rate = 2.0
# solver.lr_decay_method = 'piecewise'
# solver.lr_decay_boundaries = "2,5,7"
# solver.lr_decay_values = "2.0,1.0,0.5,0.1"

solver.log_fname = join(_home_dir, _log_fname)


text:
Installing hyperframe
=====================

hyperframe is trivial to install from the Python Package Index. Simply run:

.. code-block:: console

    $ pip install hyperframe

Alternatively, feel free to download one of the release tarballs from
`our GitHub page`_, extract it to your favourite directory, and then run

.. code-block:: console

    $ python setup.py install

hyperframe has no external dependencies.

.. _our GitHub page: https://github.com/python-hyper/hyperframe


text:
/*
	Theme Name: Services Theme
	Github Theme URI: https://github.com/sdescommunications/ucf-services-theme
	Description: Student services theme.
	Version: v0.3.3
	Author: SDES IT
	Author URI: http://github.com/ucf-sdes-it/ucf-services-theme/
*/

/*@import url('./css/style.css');*/
@import url('./css/style.0.css');
@import url('./css/style.1.css');


text:
#ifndef DS_LIST_H_INCLUDED
#define DS_LIST_H_INCLUDED

#include <stddef.h>
#include <stdbool.h>
#include <stddef.h>

#include "ds.h"

/*
 * ============================================================
 *  Macros
 * ============================================================
 */

/*
 * Static initializer -- can be used to initialize global structures.
 *
 * ds_list_t a = DS_LIST_INIT;
 */
#define DS_LIST_INIT(type, elem)        \
{                                       \
    .ol_cof     = offsetof(type, elem), \
    .ol_root    = { .oln_next = NULL }, \
    .ol_tail    = NULL,                 \
    .ol_ndel    = 0,                    \
}

/*
 * Dynamic initializer, used to initialize a list run-time.
 */
#define ds_list_init(list, type, elem)  __ds_list_init(list, offsetof(type, elem))

/*
 * The ever popular foreach statement
 */
#define ds_list_foreach(list, elem)     \
    for ((elem) = ds_list_head(list); (elem) != NULL; (elem) = ds_list_next(list, elem))

#define ds_list_foreach_iter(list, elem, iter)     \
    for ((elem) = ds_list_ifrst(&iter, list); (elem) != NULL; (elem) = ds_list_inext(&iter))

/*
 * ============================================================
 *  Typedefs
 * ============================================================
 */
typedef struct ds_list              ds_list_t;
typedef struct ds_list_node         ds_list_node_t;
typedef struct ds_list_iter         ds_list_iter_t;

/*
 * ============================================================
 *  Structs
 * ============================================================
 */
struct ds_list_node
{
    ds_list_node_t*                 oln_next;       /* Next node pointer                    */
};

struct ds_list
{
    size_t                          ol_cof;         /* Offset of the container structure    */
    ds_list_node_t                  ol_root;        /* Dummy root element                   */
    ds_list_node_t*                 ol_tail;        /* Tail of the list                     */
    uint32_t                        ol_ndel;        /* Number of deletions                  */
};

struct ds_list_iter
{
    ds_list_t*                      oli_list;       /* Root of the list                     */
    ds_list_node_t*                 oli_prev;       /* Prev element -- needed for deletion  */
    ds_list_node_t*                 oli_curr;       /* Current element -- null on remove    */
    ds_list_node_t*                 oli_next;       /* Next element                         */
    uint32_t                        oli_ndel;       /* Number of deletions                  */
};

static inline void __ds_list_init(ds_list_t *list, size_t cof);

/*
 * ===========================================================================
 *  Public API
 * ===========================================================================
 */

static inline bool   ds_list_is_empty(ds_list_t *list);
static inline void  *ds_list_next(ds_list_t *list, void *curr);
static inline void  *ds_list_head(ds_list_t *list);
static inline void  *ds_list_tail(ds_list_t *list);
static inline void   ds_list_insert_head(ds_list_t *list, void *data);
static inline void   ds_list_insert_tail(ds_list_t *list, void *data);
static inline void   ds_list_insert_after(ds_list_t *list, void *after, void *data);
static inline void  *ds_list_remove_after(ds_list_t *list, void *after);
static inline void  *ds_list_remove_head(ds_list_t* list);

/*
 * ===========================================================================
 *  Iterator API
 * ===========================================================================
 */
static inline void  *ds_list_ifirst(ds_list_iter_t* iter, ds_list_t* list);
static inline void  *ds_list_inext(ds_list_iter_t* iter);
static inline void  *ds_list_iinsert(ds_list_iter_t *iter, void *data);
static inline void  *ds_list_iremove(ds_list_iter_t* iter);

#include "ds_list.c.h"

#endif /* DS_LIST_H_INCLUDED */


text:
Framework for Informatica IPC utilites

            Environment.SetEnvironmentVariable("INFA_DOMAINS_FILE", @"C:\Informatica\9.6.1\clients\PowerCenterClient\domain.infa");
            PmrepConnection repo = new PmrepConnection
            {
                domain = "Domain_melchior",
                repository = "infa_rep_melchior",
                userName = "Administrator",
                password = "k2kb2bd"
            };
            Pmrep pmrep = new Pmrep("C:\\Informatica\\9.6.1\\clients\\PowerCenterClient\\client\\bin\\pmrep.exe", repo);

            pmrep.CreateFolder("TEST");
            var result=pmrep.ListObjects(new PmrepObject { objectType = "folder" });


text:
module Pushpop

  class Job

    class << self

      @@plugins = {}

      def plugins
        @@plugins
      end

      def register_plugin(name, klass)
        self.plugins ||= {}
        self.plugins[name.to_s] = klass
      end

    end

    attr_accessor :name
    attr_accessor :period
    attr_accessor :webhook_url
    attr_accessor :webhook_proc
    attr_accessor :every_options
    attr_accessor :steps

    def initialize(name=nil, &block)
      self.name = name || Pushpop.random_name
      self.steps = []
      self.every_options = {}
      self.instance_eval(&block)
    end

    def every(period, options={})
      self.period = period
      self.every_options = options
    end

    def webhook(url, &block)
      raise 'Webhook is already set' if @webhook_url
      raise 'Webhook must be set before steps' if self.steps.length > 0

      self.webhook_url = url
      self.webhook_proc = block

      Pushpop.web.add_route url, self
    end

    def step(name=nil, plugin=nil, &block)
      if plugin

        plugin_klass = self.class.plugins[plugin]
        raise "No plugin configured for #{plugin}" unless plugin_klass

        self.add_step(plugin_klass.new(name, plugin, &block))
      else
        self.add_step(Step.new(name, plugin, &block))
      end
    end

    def add_step(step)
      self.steps.push(step)
    end

    def schedule
      raise 'Set job period via "every"' unless self.period || @webhook_url

      if self.period
        Clockwork.manager.every(period, name, every_options) do
          run
        end
      end
    end

    def run(last_response = nil, step_responses = {})
      self.steps.each do |step|

        # track the last_response and all responses
        last_response = step.run(last_response, step_responses)
        step_responses[step.name] = last_response

        # abort unless this step returned truthily
        return unless last_response
      end

      # log responses in debug
      Pushpop.logger.debug("#{name}: #{step_responses}")

      # return the last response and all responses
      [last_response, step_responses]
    end

    def method_missing(method, *args, &block)
      plugin_class = self.class.plugins[method.to_s]

      unless plugin_class
        begin
          Pushpop.load_plugin method.to_s
          plugin_class = self.class.plugins[method.to_s]
          raise "Plugin not loaded: #{method.to_s}" if plugin_class.nil?
        rescue LoadError
          Pushpop.logger.warn("Could not find plugin #{method.to_s}")
        end
      end

      name = args[0]
      plugin = method.to_s

      if plugin_class
        step(name, plugin, &block)
      else
        super
      end
    end

  end

end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ringapp', '0003_commlogic_theorem'),
    ]

    operations = [
        migrations.RenameField(
            model_name='commequivalents',
            old_name='keywords',
            new_name='kwds',
        ),
        migrations.RenameField(
            model_name='equivalents',
            old_name='keywords',
            new_name='kwds',
        ),
        migrations.RenameField(
            model_name='ring',
            old_name='keywords',
            new_name='kwds',
        ),
    ]


text:
ACCEPTED

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

#### Published in
Lichenologist 27(4): 279 (1995)

#### Original name
Pseudopeltula Henssen

### Remarks
null


text:
Pollen Chart
============

Chart the [European Pollen Database](http://www.europeanpollendatabase.net/)

Synopsis
--------

[Pollen Chart](https://pollen.vinc.cc) is a website dedicated to help
exploring the [European Pollen Database](http://www.europeanpollendatabase.net/)
for a better understanding of our environment.

Installation
------------

To get the source do the following:

    $ git clone git://github.com/vinc/pollen.vinc.cc.git
    $ cd pollen.vinc.cc

Then visit the [download page](http://www.europeanpollendatabase.net/data/downloads/)
of the EPD and download a Postgres archive of the database:

    $ wget http://www.europeanpollendatabase.net/data/downloads/image/epd-postgres-distribution.zip
    $ unzip epd-postgres-distribution.zip
    $ gunzip dumpall_epd_db.sql.gz
    $ sed -i "s/epd\|wwwadm/$POSTGRES_USER/g" dumpall_epd_db.sql
    $ psql $POSTGRES_DATABASE < dumpall_epd_db.sql

Where `$POSTGRES_DATABASE` is your database and `$POSTGRES_USER` your database
user. You can avoid altering the dump by creating the two required users `epd`
and `wwwadm` instead.

License
-------

Copyright (c) 2017 Vincent Ollivier. Released under the MIT License.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.type;

import com.facebook.presto.spi.type.Type;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Optional;

import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.util.StructuralTestUtil.mapType;
import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals;

public class TestRowType
{
    @Test
    public void testRowDisplayName()
    {
        List<Type> types = asList(BOOLEAN, DOUBLE, new ArrayType(VARCHAR), mapType(BOOLEAN, DOUBLE));
        Optional<List<String>> names = Optional.of(asList("bool_col", "double_col", "array_col", "map_col"));
        RowType row = new RowType(types, names);
        assertEquals(
                row.getDisplayName(),
                "row(bool_col boolean, double_col double, array_col array(varchar), map_col map(boolean, double))");
    }

    @Test
    public void testRowDisplayNoColumnNames()
    {
        List<Type> types = asList(BOOLEAN, DOUBLE, new ArrayType(VARCHAR), mapType(BOOLEAN, DOUBLE));
        RowType row = new RowType(types, Optional.empty());
        assertEquals(
                row.getDisplayName(),
                "row(boolean, double, array(varchar), map(boolean, double))");
    }
}


text:
first = "Don't worry,"
second = 'be happy'
print(f'{first} {second}')


text:
<?php

namespace Application\EservicesBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ApplicationEservicesBundle extends Bundle
{
}


text:
"""
    stonemason.renderer.cartographer.image.factory
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Implementation of factory of image render nodes.
"""

__author__ = 'ray'
__date__ = '8/14/15'

from stonemason.renderer.engine.factory import RenderNodeFactory

from .terminal import *
from .transform import *
from .composite import *

class ImageNodeFactory(RenderNodeFactory):
    """Image Node Factory

    `ImageNodeFactory` create image render nodes from their prototype name and
    parameters described in the render expression.

    Example:

        1. A terminal single color render node could be created by the following
        expression:

        .. code-block:: javascript

            "white": {
                "prototype" : "image.input.color",
                "color": "fff"
            }

        2. A filter render node could be created by the following expression:

        .. code-block:: javascript

            "filter": {
                "prototype" : "image.transform.filter.min",
                "source": "source"
                "size": "3"
            }

        3. A alpha blending node could be created by the following expression:

        .. code-block:: javascript

            "composite": {
                "prototype" : "image.composite.alphacomposer",
                "sources": ["source1", "source2"],
                "alpha": 0.5
            }

    Currently available nodes:

        input nodes:

            'image.input.color'
            'image.input.mapnik'
            'image.input.mapnik.composer'
            'image.input.relief.simple'
            'image.input.relief.swiss'
            'image.input.relief.color'
            'image.input.storage.disk'
            'image.input.storage.s3'

        transform nodes:

            'image.transform.filter.min'

        composite nodes:

            'image.composite.alphacomposer'
            'image.composite.imagemagick'

    """
    def __init__(self):
        RenderNodeFactory.__init__(self)

        self.register_node('image.input.color', Color)
        self.register_node('image.input.mapnik', Mapnik_)
        self.register_node('image.input.mapnik.composer', MapnikComposer)
        self.register_node('image.input.relief.simple', SimpleRelief)
        self.register_node('image.input.relief.swiss', SwissRelief)
        self.register_node('image.input.relief.color', ColorRelief)
        self.register_node('image.input.storage.disk', DiskStorageNode)
        self.register_node('image.input.storage.s3', S3StorageNode)

        # load transform nodes
        self.register_node('image.transform.filter.min', MinFilter)

        # load composite nodes
        self.register_node('image.composite.alphacomposer', AlphaComposer)
        self.register_node('image.composite.imagemagick', IMComposer)

        # TODO: To be deprecated in the future release
        # load legacy names
        self.register_node('basic.color', Color)
        self.register_node('mapnik', Mapnik_)
        self.register_node('mapnik.composer', MapnikComposer)
        self.register_node('imagemagick', IMComposer)
        self.register_node('relief.simple', SimpleRelief)
        self.register_node('relief.swiss', SwissRelief)
        self.register_node('relief.color', ColorRelief)
        self.register_node('data.storage.disk', DiskStorageNode)
        self.register_node('data.storage.s3', S3StorageNode)


text:
rem ------------------------------------------------------------------------------
rem Tiny script to execute Assimp's fully unit test suite for all configurations
rem
rem Usage: call RunUnitTestSuite
rem ------------------------------------------------------------------------------

rem Setup the console environment
set errorlevel=0
color 4e
cls

@echo off

rem Setup target architecture
SET ARCHEXT=x64
IF %PROCESSOR_ARCHITECTURE% == x86 (
   SET ARCHEXT=win32
)

rem Setup standard paths from here
SET OUTDIR=results\
SET BINDIR=..\bin\
SET FIRSTUTFAILURE=nil
SET FIRSTUTNA=nil

echo #=====================================================================
echo # Open Asset Import Library - Unittests
echo #=====================================================================
echo #
echo # Executes the Assimp library unit test suite for the following
echo # build configurations (if available):
echo #
echo #  Release
echo #  Release -st
echo #  Release -noboost
echo #  Release -dll
echo #
echo #  Debug
echo #  Debug   -st
echo #  Debug   -noboost
echo #  Debug   -dll
echo ======================================================================
echo.
echo.

echo assimp-core release
echo **********************************************************************
call RunSingleUnitTestSuite unit_release_%ARCHEXT% release.txt

echo assimp-core release -st
echo **********************************************************************
call RunSingleUnitTestSuite unit_release-st_%ARCHEXT% release-st.txt

echo assimp-core release -noboost
echo **********************************************************************
call RunSingleUnitTestSuite unit_release-noboost-st_%ARCHEXT% release-st-noboost.txt

echo assimp-core release -dll
echo **********************************************************************
call RunSingleUnitTestSuite unit_release-dll_%ARCHEXT% release-dll.txt

echo assimp-core debug
echo **********************************************************************
call RunSingleUnitTestSuite unit_debug_%ARCHEXT% debug.txt

echo assimp-core debug -st
echo **********************************************************************
call RunSingleUnitTestSuite unit_debug-st_%ARCHEXT% debug-st.txt

echo assimp-core debug -noboost
echo **********************************************************************
call RunSingleUnitTestSuite unit_debug-noboost-st_%ARCHEXT% debug-st-noboost.txt

echo assimp-core debug -dll
echo **********************************************************************
call RunSingleUnitTestSuite unit_debug-dll_%ARCHEXT% debug-dll.txt

echo ======================================================================
IF %FIRSTUTNA% == nil (
   echo All test configs have been found.
) ELSE (
   echo One or more test configs are not available.
)

IF %FIRSTUTFAILURE% == nil (
   echo All tests have been successful.
) ELSE (
   echo One or more tests failed.
)
echo.

pause


text:
import {
  selectGlobal,
  makeSelectCurrentUser,
  makeSelectLoading,
  makeSelectError,
  makeSelectRepos,
} from '../selectors';

describe('selectGlobal', () => {
  it('should select the global state', () => {
    const globalState = {};
    const mockedState = {
      global: globalState,
    };
    expect(selectGlobal(mockedState)).toEqual(globalState);
  });
});

describe('makeSelectCurrentUser', () => {
  const currentUserSelector = makeSelectCurrentUser();
  it('should select the current user', () => {
    const username = 'mxstbr';
    const mockedState = {
      global: {
        currentUser: username,
      },
    };
    expect(currentUserSelector(mockedState)).toEqual(username);
  });
});

describe('makeSelectLoading', () => {
  const loadingSelector = makeSelectLoading();
  it('should select the loading', () => {
    const loading = false;
    const mockedState = {
      global: {
        loading,
      },
    };
    expect(loadingSelector(mockedState)).toEqual(loading);
  });
});

describe('makeSelectError', () => {
  const errorSelector = makeSelectError();
  it('should select the error', () => {
    const error = 404;
    const mockedState = {
      global: {
        error,
      },
    };
    expect(errorSelector(mockedState)).toEqual(error);
  });
});

describe('makeSelectRepos', () => {
  const reposSelector = makeSelectRepos();
  it('should select the repos', () => {
    const repositories = [];
    const mockedState = {
      global: {
        userData: {
          repositories,
        },
      },
    };
    expect(reposSelector(mockedState)).toEqual(repositories);
  });
});


text:
module Faker
  module Locale
    extend ModuleUtils
    extend self

    def code(given_language = nil)
      code_index = LANGUAGE.index(given_language)
      if given_language && code_index
        LANGUAGE_CODE[code_index]
      else
        LANGUAGE_CODE.sample
      end
    end

    def language(given_code = nil)
      language_index = LANGUAGE_CODE.index(given_code.upcase)
      if given_code && language_index
        LANGUAGE[language_index]
      else
        LANGUAGE.sample
      end
    end

  end
end


text:
module Martyr
  module Runtime
    class BaseLevelScope
      include Martyr::Level
      include Martyr::LevelComparator

      attr_accessor :level
      attr_reader :collection
      delegate :level_definition, :name, :dimension_name, :query?, :degenerate?, :to_i, to: :level
      delegate :fact_key, :fact_alias, to: :level_definition

      def initialize(collection, level)
        @collection = collection
        @level = level
        @cache = nil
      end

    end
  end
end


text:
#include <spine/PathConstraintData.h>
#include <spine/extension.h>

spPathConstraintData* spPathConstraintData_create (const char* name) {
	spPathConstraintData* self = NEW(spPathConstraintData);
	MALLOC_STR(self->name, name);
	return self;
}

void spPathConstraintData_dispose (spPathConstraintData* self) {
	FREE(self->name);
	FREE(self->bones);
	FREE(self);
}


text:
from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

while True:
    tcpCliSock = socket(AF_INET, SOCK_STREAM)
    tcpCliSock.connect(ADDR)
    data = input('> ')
    if not data:
        break
    tcpCliSock.send(('%s\r\n' % data).encode())
    data = tcpCliSock.recv(BUFSIZE).decode()
    if not data:
        break
    print(data.strip())
tcpCliSock.close()


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?
  #helper_method :current_user

  protected

	  def configure_permitted_parameters
	    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :phone_number, :password, :password_confirmation) }
	  end

  #private

  # def current_user
  #   @current_user ||= User.find(session[:user_id]) if session[:user_id]
  # end
# end
end


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

<title>ExecutionControl (Jason - AgentSpeak Java Interpreter)</title>
<meta name="date" content="2013-12-12">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

jason.control

Class ExecutionControl

<map id="G" name="G">
<area shape="rect" id="node1_0" href="./ExecutionControlGUI.html" title="jason.control.ExecutionControlGUI" alt="" coords="15,113,153,138"/>
<area shape="rect" id="node1" href="./ExecutionControlGUI.html" title="<TABLE>" alt="" coords="5,101,163,149"/>
<area shape="rect" id="node2_1" href="./ExecutionControl.html" title="jason.control.ExecutionControl" alt="" coords="27,17,141,42"/>
<area shape="rect" id="node2" href="./ExecutionControl.html" title="<TABLE>" alt="" coords="16,5,152,53"/>
</map>

java.lang.Object

jason.control.ExecutionControl

Direct Known Subclasses:

ExecutionControlGUI

public class ExecutionControl
extends java.lang.Object

Base class for the user implementation of execution control.

This default implementation synchronise the agents execution, i.e.,
 each agent will perform its next reasoning cycle only when all agents have
 finished its reasoning cycle.

Execution sequence:

setExecutionControlInfraTier,

init,

(receivedFinishedCycle)*,

stop.

Field Summary

Fields

Modifier and Type
Field and Description

protected ExecutionControlInfraTier
infraControl

protected static java.util.logging.Logger
logger

Constructor Summary

Constructors

Constructor and Description

ExecutionControl()

Method Summary

Methods

Modifier and Type
Method and Description

protected void
allAgsFinished()

Called when all agents have finished the current cycle

int
getCycleNumber()

protected int
getCycleTimeout()

returns the maximum number of milliseconds of a cycle

ExecutionControlInfraTier
getExecutionControlInfraTier()

int
getNbAgs()

Returns the number of agents in the MAS (used to test the end of a cycle)

void
init(java.lang.String[] args)

This method is called when setExecutionControlInfraTier was already called

boolean
isRunning()

void
receiveFinishedCycle(java.lang.String agName,
                    boolean breakpoint,
                    int cycle)

Called when the agent agName has finished its reasoning cycle.

void
setExecutionControlInfraTier(ExecutionControlInfraTier jasonControl)

void
setNbAgs(int n)

Set the number of agents

void
setRunningCycle(boolean rc)

protected void
startNewCycle()

void
stop()

This method is called when MAS execution is being finished

protected boolean
testEndCycle(java.util.Set<java.lang.String> finishedAgs)

Returns true when a new cycle can start, it normally
 holds when all agents are in the finishedAgs set.

java.lang.String
toString()

void
updateNumberOfAgents()

Updates the number of agents in the MAS, this default
  implementation, considers all agents in the MAS as actors .

Methods inherited from class java.lang.Object

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

Field Detail

infraControl

protected ExecutionControlInfraTier infraControl

logger

protected static java.util.logging.Logger logger

Constructor Detail

ExecutionControl

public ExecutionControl()

Method Detail

getCycleTimeout

protected int getCycleTimeout()

returns the maximum number of milliseconds of a cycle

startNewCycle

protected void startNewCycle()

updateNumberOfAgents

public void updateNumberOfAgents()

Updates the number of agents in the MAS, this default
  implementation, considers all agents in the MAS as actors .

getNbAgs

public int getNbAgs()

Returns the number of agents in the MAS (used to test the end of a cycle)

setNbAgs

public void setNbAgs(int n)

Set the number of agents

receiveFinishedCycle

public void receiveFinishedCycle(java.lang.String agName,
                        boolean breakpoint,
                        int cycle)

Called when the agent agName has finished its reasoning cycle.
 breakpoint is true in case the agent selected one plan with "breakpoint"
 annotation.

testEndCycle

protected boolean testEndCycle(java.util.Set<java.lang.String> finishedAgs)

Returns true when a new cycle can start, it normally
 holds when all agents are in the finishedAgs set.

Parameters:

finishedAgs - the set of agents' name that already finished the current cycle

setExecutionControlInfraTier

public void setExecutionControlInfraTier(ExecutionControlInfraTier jasonControl)

getExecutionControlInfraTier

public ExecutionControlInfraTier getExecutionControlInfraTier()

init

public void init(java.lang.String[] args)

This method is called when setExecutionControlInfraTier was already called

stop

public void stop()

This method is called when MAS execution is being finished

allAgsFinished

protected void allAgsFinished()

Called when all agents have finished the current cycle

isRunning

public boolean isRunning()

getCycleNumber

public int getCycleNumber()

setRunningCycle

public void setRunningCycle(boolean rc)

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using NSubstitute;
using NUnit.Framework;
using Stateless.WorkflowEngine.WebConsole.BLL.Data.Models;
using Stateless.WorkflowEngine.WebConsole.BLL.Data.Stores;
using Stateless.WorkflowEngine.WebConsole.BLL.Validators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test.Stateless.WorkflowEngine.WebConsole.BLL.Validators
{
    [TestFixture]
    public class UserValidatorTest
    {
        private IUserValidator _userValidator;

        private IUserStore _userStore;

        [SetUp]
        public void UserValidatorTest_SetUp()
        {
            _userStore = Substitute.For<IUserStore>();

            _userValidator = new UserValidator(_userStore);
        }

        [TestCase("")]
        [TestCase(null)]
        [TestCase("   ")]
        public void Validate_InvalidUserName_ReturnsFailure(string userName)
        {
            UserModel model = DataHelper.CreateUserModel();
            model.UserName = userName;

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].Contains("User name"));
        }

        [TestCase("")]
        [TestCase(null)]
        [TestCase("   ")]
        public void Validate_InvalidUserPassword_ReturnsFailure(string password)
        {
            UserModel model = DataHelper.CreateUserModel();
            model.Password = password;

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].Contains("Password"));
        }

        [TestCase("")]
        [TestCase(null)]
        [TestCase("   ")]
        public void Validate_InvalidRole_ReturnsFailure(string role)
        {
            UserModel model = DataHelper.CreateUserModel();
            model.Role = role;

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].Contains("Role"));
        }

        [Test]
        public void Validate_UserAlreadyExists_ReturnsFailure()
        {
            UserModel model = DataHelper.CreateUserModel();

            _userStore.GetUser(model.UserName).Returns(new UserModel());

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].Contains("already exists"));
        }

        [Test]
        public void Validate_AllFieldsValid_ReturnsSuccess()
        {
            UserModel model = DataHelper.CreateUserModel();

            ValidationResult result = _userValidator.Validate(model);

            Assert.IsTrue(result.Success);
            Assert.AreEqual(0, result.Messages.Count);
        }

    }
}


text:
<?php

namespace Drupal\ds\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides local task definitions for all entity bundles.
 */
class DsLocalTask extends DeriverBase implements ContainerDeriverInterface {

  use StringTranslationTrait;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Creates an DevelLocalTask object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The translation manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation) {
    $this->entityTypeManager = $entity_type_manager;
    $this->stringTranslation = $string_translation;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('string_translation')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('display')) {
        $this->derivatives["$entity_type_id.display_tab"] = array(
          'route_name' => "entity.$entity_type_id.display",
          'weight' => 10,
          'title' => $this->t('Manage display'),
          'base_route' => "entity.$entity_type_id.canonical",
        );
      }
    }

    foreach ($this->derivatives as &$entry) {
      $entry += $base_plugin_definition;
    }

    return $this->derivatives;
  }

}


text:
getImage = function(icon) {
	var i = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'icons/'+icon);
	if(!i.exists()) {
		// image hasn't been saved, so grab it and save it
		Ti.API.info('Fetching http://www.dimsatec.com/services/flisol/img/'+icon);
		// create an image view to hold our remote icon
		var tmpImage = Ti.UI.createImageView({
			image: 'http://www.dimsatec.com/services/flisol/img/'+icon
		});
		// it takes a few seconds to load the image from the URL, so wait 5 sec. to cache the image
		setTimeout(function() {
			var cachedImage = tmpImage.toImage();
			if(cachedImage.width == 50) {
				// actual images are 35 px wide, any other width indicates a failure to load the icon
				i.write(cachedImage);
				Ti.API.info('Caching '+icon);
			}
		}, 5000);
		// return the URL so that an image is shown the first time the app is run
		return 'http://www.dimsatec.com/services/flisol/img/'+icon;
	} else {
		// image has been cached previously, so return its path
		Ti.API.info('Returning cached image '+ i.name);
		return i.nativePath;
	}
};