text:
namespace base {

class ConditionVariable;

namespace internal {

// Determines which tasks are allowed to run.
enum class CanRunPolicy {
  // All tasks are allowed to run.
  kAll,
  // Only USER_VISIBLE and USER_BLOCKING tasks are allowed to run.
  kForegroundOnly,
  // No tasks can run.
  kNone,
};

// TaskTracker enforces policies that determines whether:
// - A task can be pushed to a task source (WillPostTask).
// - A task source can be queued (WillQueueTaskSource).
// - Tasks for a given priority can run (CanRunPriority).
// - The next task in a queued task source can run (RunAndPopNextTask).
// TaskTracker also sets up the environment to run a task (RunAndPopNextTask)
// and records metrics and trace events. This class is thread-safe.
class BASE_EXPORT TaskTracker {
 public:
  TaskTracker();
  TaskTracker(const TaskTracker&) = delete;
  TaskTracker& operator=(const TaskTracker&) = delete;
  virtual ~TaskTracker();

  // Initiates shutdown. Once this is called, only BLOCK_SHUTDOWN tasks will
  // start running (doesn't affect tasks that are already running). This can
  // only be called once.
  void StartShutdown();

  // Synchronously completes shutdown. StartShutdown() must be called first.
  // Returns when:
  // - All SKIP_ON_SHUTDOWN tasks that were already running have completed their
  //   execution.
  // - All posted BLOCK_SHUTDOWN tasks have completed their execution.
  // CONTINUE_ON_SHUTDOWN tasks still may be running after Shutdown returns.
  // This can only be called once.
  void CompleteShutdown();

  // Waits until there are no incomplete task sources. May be called in tests
  // to validate that a condition is met after all task sources have run.
  //
  // Does not wait for delayed tasks. Waits for task sources posted from
  // other threads during the call. Returns immediately when shutdown completes.
  void FlushForTesting();

  // Returns and calls |flush_callback| when there are no incomplete undelayed
  // tasks. |flush_callback| may be called back on any thread and should not
  // perform a lot of work. May be used when additional work on the current
  // thread needs to be performed during a flush. Only one
  // FlushAsyncForTesting() may be pending at any given time.
  void FlushAsyncForTesting(OnceClosure flush_callback);

  // Sets the new CanRunPolicy policy, possibly affecting result of
  // CanRunPriority(). The caller must wake up worker as appropriate so that
  // tasks that are allowed to run by the new policy can be scheduled.
  void SetCanRunPolicy(CanRunPolicy can_run_policy);

  // Informs this TaskTracker that |task| with |shutdown_behavior| is about to
  // be pushed to a task source (if non-delayed) or be added to the
  // DelayedTaskManager (if delayed). Returns true if this operation is allowed
  // (the operation should be performed if-and-only-if it is). This method may
  // also modify metadata on |task| if desired.
  bool WillPostTask(Task* task, TaskShutdownBehavior shutdown_behavior);

  // Informs this TaskTracker that |task| that is about to be pushed to a task
  // source with |priority|. Returns true if this operation is allowed (the
  // operation should be performed if-and-only-if it is).
  [[nodiscard]] bool WillPostTaskNow(const Task& task, TaskPriority priority);

  // Informs this TaskTracker that |task_source| is about to be queued. Returns
  // a RegisteredTaskSource that should be queued if-and-only-if it evaluates to
  // true.
  RegisteredTaskSource RegisterTaskSource(
      scoped_refptr<TaskSource> task_source);

  // Returns true if a task with |priority| can run under to the current policy.
  bool CanRunPriority(TaskPriority priority) const;

  // Runs the next task in |task_source| unless the current shutdown state
  // prevents that. Then, pops the task from |task_source| (even if it didn't
  // run). Returns |task_source| if non-empty after popping a task from it
  // (which indicates that it should be reenqueued). WillPostTask() must have
  // allowed the task in front of |task_source| to be posted before this is
  // called.
  RegisteredTaskSource RunAndPopNextTask(RegisteredTaskSource task_source);

  // Returns true once shutdown has started (StartShutdown() was called).
  // Note: sequential consistency with the thread calling StartShutdown() isn't
  // guaranteed by this call.
  bool HasShutdownStarted() const;

  // Returns true if shutdown has completed (StartShutdown() was called and
  // no tasks are blocking shutdown).
  bool IsShutdownComplete() const;

  TrackedRef<TaskTracker> GetTrackedRef() {
    return tracked_ref_factory_.GetTrackedRef();
  }

  // Returns true if there are task sources that haven't completed their
  // execution (still queued or in progress). If it returns false: the side-
  // effects of all completed tasks are guaranteed to be visible to the caller.
  bool HasIncompleteTaskSourcesForTesting() const;

 protected:
  // Runs and deletes |task|. |task| is deleted in the environment where it
  // runs. |task_source| is the task source from which |task| was extracted.
  // |traits| are the traits of |task_source|. An override is expected to call
  // its parent's implementation but is free to perform extra work before and
  // after doing so.
  virtual void RunTask(Task task,
                       TaskSource* task_source,
                       const TaskTraits& traits);

  // Allow a subclass to wait more interactively for any running shutdown tasks
  // before blocking the thread.
  virtual void BeginCompleteShutdown(base::WaitableEvent& shutdown_event);

  // Asserts that FlushForTesting() is allowed to be called. Overridden in tests
  // in situations where it is not.
  virtual void AssertFlushForTestingAllowed() {}

 private:
  friend class RegisteredTaskSource;
  class State;

  void PerformShutdown();

  // Called before WillPostTask() informs the tracing system that a task has
  // been posted. Updates |num_items_blocking_shutdown_| if necessary and
  // returns true if the current shutdown state allows the task to be posted.
  bool BeforeQueueTaskSource(TaskShutdownBehavior shutdown_behavior);

  // Called before a task with |effective_shutdown_behavior| is run by
  // RunTask(). Updates |num_items_blocking_shutdown_| if necessary and returns
  // true if the current shutdown state allows the task to be run.
  bool BeforeRunTask(TaskShutdownBehavior shutdown_behavior);

  // Called after a task with |effective_shutdown_behavior| has been run by
  // RunTask(). Updates |num_items_blocking_shutdown_| if necessary.
  void AfterRunTask(TaskShutdownBehavior shutdown_behavior);

  // Informs this TaskTracker that |task_source| won't be reenqueued and returns
  // the underlying TaskSource. This is called before destroying a valid
  // RegisteredTaskSource. Updates |num_items_blocking_shutdown_| if necessary.
  scoped_refptr<TaskSource> UnregisterTaskSource(
      scoped_refptr<TaskSource> task_source);

  // Called when an item blocking shutdown finishes after shutdown has started.
  void DecrementNumItemsBlockingShutdown();

  // Decrements the number of incomplete task sources and signals |flush_cv_|
  // if it reaches zero.
  void DecrementNumIncompleteTaskSources();

  // Invokes all |flush_callbacks_for_testing_| if any in a lock-safe manner.
  void InvokeFlushCallbacksForTesting();

  // Dummy frames to allow identification of shutdown behavior in a stack trace.
  void RunContinueOnShutdown(Task& task,
                             const TaskTraits& traits,
                             TaskSource* task_source,
                             const SequenceToken& token);
  void RunSkipOnShutdown(Task& task,
                         const TaskTraits& traits,
                         TaskSource* task_source,
                         const SequenceToken& token);
  void RunBlockShutdown(Task& task,
                        const TaskTraits& traits,
                        TaskSource* task_source,
                        const SequenceToken& token);
  void RunTaskWithShutdownBehavior(Task& task,
                                   const TaskTraits& traits,
                                   TaskSource* task_source,
                                   const SequenceToken& token);

  void NOT_TAIL_CALLED RunTaskImpl(Task& task,
                                   const TaskTraits& traits,
                                   TaskSource* task_source,
                                   const SequenceToken& token);

  TaskAnnotator task_annotator_;

  // Indicates whether logging information about TaskPriority::BEST_EFFORT tasks
  // was enabled with a command line switch.
  const bool has_log_best_effort_tasks_switch_;

  // Number of tasks blocking shutdown and boolean indicating whether shutdown
  // has started. |shutdown_lock_| should be held to access |shutdown_event_|
  // when this indicates that shutdown has started because State doesn't provide
  // memory barriers. It intentionally trades having to use a Lock on shutdown
  // with not needing memory barriers at runtime.
  const std::unique_ptr<State> state_;

  // Number of task sources that haven't completed their execution. Is
  // decremented with a memory barrier after the last task of a task source
  // runs. Is accessed with an acquire memory barrier in FlushForTesting(). The
  // memory barriers ensure that the memory written by flushed task sources is
  // visible when FlushForTesting() returns.
  std::atomic_int num_incomplete_task_sources_{0};

  // Global policy the determines result of CanRunPriority().
  std::atomic<CanRunPolicy> can_run_policy_;

  // Lock associated with |flush_cv_|. Partially synchronizes access to
  // |num_incomplete_task_sources_|. Full synchronization isn't needed
  // because it's atomic, but synchronization is needed to coordinate waking and
  // sleeping at the right time. Fully synchronizes access to
  // |flush_callbacks_for_testing_|.
  mutable CheckedLock flush_lock_;

  // Signaled when |num_incomplete_task_sources_| is or reaches zero or when
  // shutdown completes.
  const std::unique_ptr<ConditionVariable> flush_cv_;

  // All invoked, if any, when |num_incomplete_task_sources_| is zero or when
  // shutdown completes.
  base::circular_deque<OnceClosure> flush_callbacks_for_testing_
      GUARDED_BY(flush_lock_);

  // Synchronizes access to shutdown related members below.
  mutable CheckedLock shutdown_lock_;

  // Event instantiated when shutdown starts and signaled when shutdown
  // completes.
  std::unique_ptr<WaitableEvent> shutdown_event_ GUARDED_BY(shutdown_lock_);

  // Ensures all state (e.g. dangling cleaned up workers) is coalesced before
  // destroying the TaskTracker (e.g. in test environments).
  // Ref. https://crbug.com/827615.
  TrackedRefFactory<TaskTracker> tracked_ref_factory_;
};

}  // namespace internal
}  // namespace base

#endif  // BASE_TASK_THREAD_POOL_TASK_TRACKER_H_


text:
package com.snacks.common.util;

import com.snacks.common.model.PaginationData;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

public class PaginationQuery<T> {
	/** 别名数 */
	private static volatile long aliasCount = 0;
	private static final long maxAliasCount = 10000;
	EntityManager entityManager;

	public PaginationQuery(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	private void copyFetches(Fetch<?, ?> from, Fetch<?, ?> to) {
		for (final Fetch<?, ?> fetch : from.getFetches()) {
			final Fetch<?, ?> toFetch = to.fetch(fetch.getAttribute().getName());
			copyFetches(fetch, toFetch);
		}
	}

	private void copyJoins(From<?, ?> from, From<?, ?> to) {
		for (final Join<?, ?> join : from.getJoins()) {
			final Join<?, ?> toJoin = to.join(join.getAttribute().getName(), join.getJoinType());
			toJoin.alias(getAlias(join));
			copyJoins(join, toJoin);
		}
		for (final Fetch<?, ?> fetch : from.getFetches()) {
			final Fetch<?, ?> toFetch = to.fetch(fetch.getAttribute().getName());
			copyFetches(fetch, toFetch);
		}
	}

	private synchronized String getAlias(Selection<?> selection) {
		if (selection != null) {
			String alias = selection.getAlias();
			if (alias == null) {
				if (aliasCount >= maxAliasCount) {
					aliasCount = 0;
				}
				alias = "shopxxGeneratedAlias" + aliasCount++;
				selection.alias(alias);
			}
			return alias;
		}
		return null;
	}

	private Root<T> getRoot(CriteriaQuery<?> criteriaQuery, Class<T> clazz) {
		if (criteriaQuery != null && criteriaQuery.getRoots() != null && clazz != null) {
			for (final Root<?> root : criteriaQuery.getRoots()) {
				if (clazz.equals(root.getJavaType())) {
					return (Root<T>) root.as(clazz);
				}
			}
		}
		return null;
	}

	private Root<T> getRoot(CriteriaQuery<T> criteriaQuery) {
		if (criteriaQuery != null) {
			return getRoot(criteriaQuery, criteriaQuery.getResultType());
		}
		return null;
	}

	public PaginationData<T> queryListByPage(CriteriaQuery<T> criteriaQuery, int pageNum, int rows) {
		final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		final CriteriaQuery<Long> countCriteriaQuery = cb.createQuery(Long.class);
		final Root<T> root = getRoot(criteriaQuery);
		for (final Root<?> r : criteriaQuery.getRoots()) {
			final Root<?> dest = countCriteriaQuery.from(r.getJavaType());
			dest.alias(getAlias(r));
			copyJoins(r, dest);
		}
		countCriteriaQuery.select(cb.count(root));
		if (criteriaQuery.getRestriction() != null) {
			countCriteriaQuery.where(criteriaQuery.getRestriction());
		}

		final Long total = entityManager.createQuery(countCriteriaQuery).getSingleResult();
		final int page = PageUtil.calcPage(pageNum) * rows;
		final List<T> list = entityManager.createQuery(criteriaQuery).setFirstResult(page).setMaxResults(rows)
				.getResultList();
		final PaginationData<T> result = new PaginationData<>();
		result.setResultList(list);
		result.setTotal(total);
		result.setPageNum(pageNum);
		return result;
	}

	/**
	 * 原生sql分页查询
	 *
	 * @param sql sql
	 * @param param 参数
	 * @param start 开始
	 * @param rows 查询行
	 * @param t 对象
	 * @return 查询结果
	 */
	public PaginationData<T> queryListByPage(String sql, Object[] param, int start, int rows, T t) {
		final PaginationData<T> result = new PaginationData<T>();
		final String countSql = "select count(1) from (" + sql + ") a";
		final Query queryTotal = entityManager.createNativeQuery(countSql);
		for (int i = 0; i < param.length; i++) {
			queryTotal.setParameter(i + 1, param[i]);
		}
		final Long total = Long.valueOf(queryTotal.getFirstResult());
		result.setTotal(total);
		sql += " limit " + start + "," + rows;

		final Query queryResult = entityManager.createNativeQuery(sql, t.getClass());
		for (int i = 0; i < param.length; i++) {
			queryResult.setParameter(i + 1, param[i]);
		}
		@SuppressWarnings("unchecked")
		final List<T> list = queryResult.getResultList();
		result.setResultList(list);
		final int page = total % rows == 0 ? Double.valueOf(total / rows).intValue()
				: Double.valueOf(total / rows).intValue() + 1;
		result.setPageNum(page);
		return result;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.june.util;

/**
 *
 * 日志 <br>
 *
 * @author 王俊伟 wjw.happy.love@163.com
 * @date 2016年8月18日 上午9:21:28
 */
public class Logger {

	private org.apache.log4j.Logger logger;

	/**
	 * 构造方法,初始化Log4j的日志对象
	 */
	private Logger(org.apache.log4j.Logger log4jLogger) {
		logger = log4jLogger;
	}

	/**
	 * 获取构造器,根据类初始化Logger对象
	 *
	 * @param Class
	 *            Class对象
	 * @return Logger对象
	 */
	public static Logger getLogger(Class<?> classObject) {
		return new Logger(org.apache.log4j.Logger.getLogger(classObject));
	}

	/**
	 * 获取构造器,根据类名初始化Logger对象
	 *
	 * @param String
	 *            类名字符串
	 * @return Logger对象
	 */
	public static Logger getLogger(String loggerName) {
		return new Logger(org.apache.log4j.Logger.getLogger(loggerName));
	}

	public void debug(Object object) {
		logger.debug(object);
	}

	public void debug(Object object, Throwable e) {
		logger.debug(object, e);
	}

	public void info(Object object) {
		logger.info(object);
	}

	public void info(Object object, Throwable e) {
		logger.info(object, e);
	}

	public void warn(Object object) {
		logger.warn(object);
	}

	public void warn(Object object, Throwable e) {
		logger.warn(object, e);
	}

	public void error(Object object) {
		logger.error(object);
	}

	public void error(Object object, Throwable e) {
		logger.error(object, e);
	}

	public void fatal(Object object) {
		logger.fatal(object);
	}

	public String getName() {
		return logger.getName();
	}

	public org.apache.log4j.Logger getLog4jLogger() {
		return logger;
	}

	public boolean equals(Logger newLogger) {
		return logger.equals(newLogger.getLog4jLogger());
	}
}


text:
from pact_test.either import Right
from pact_test.models.request import PactRequest
from pact_test.matchers.request_matcher import match
from tests.acceptance.acceptance_test_loader import load_acceptance_test

def test():
    data = load_acceptance_test(__file__)

    actual = PactRequest(
        headers=[{'ACCEPT': 'alligators'}]
    )
    expected = PactRequest(
        headers=[{'Accept': 'alligators'}]
    )

    test_result = match(actual, expected)
    assert type(test_result) is Right


text:
#### Rocco Rake Tasks
#
# To use the Rocco Rake tasks, require `rocco/tasks` in your `Rakefile`
# and define a Rake task with `rocco_task`. In its simplest form, `rocco_task`
# takes the path to a destination directory where HTML docs should be built:
#
#     require 'rocco/tasks'
#
#     desc "Build Rocco Docs"
#     Rocco::make 'docs/'
#
# This creates a `:rocco` rake task, which can then be run with:
#
#     rake rocco
#
# It's a good idea to guard against Rocco not being available, since your
# Rakefile will fail to load otherwise. Consider doing something like this,
# so that your Rakefile will still work
#
#     begin
#       require 'rocco/tasks'
#       Rocco::make 'docs/'
#     rescue LoadError
#       warn "#$! -- rocco tasks not loaded."
#       task :rocco
#     end
#
# It's also possible to pass a glob pattern:
#
#     Rocco::make 'html/', 'lib/thing/**/*.rb'
#
# Or a list of glob patterns:
#
#     Rocco::make 'html/', ['lib/thing.rb', 'lib/thing/*.rb']
#
# Finally, it is also possible to specify which language you would
# like to use to highlight the code, as well as the comment characters for the
# language in the `options` hash:
#
#    Rocco::make 'html/', 'lib/thing/**/*.rb', {
#      :language => 'io',
#      :comment_chars => '#'
#    }
#

# Might be nice to defer this until we actually need to build docs but this
# will have to do for now.
require 'rocco'

# Reopen the Rocco class and add a `make` class method. This is a simple bit
# of sugar over `Rocco::Task.new`. If you want your Rake task to be named
# something other than `:rocco`, you can use `Rocco::Task` directly.
class Rocco
  def self.make(dest='docs/', source_files='lib/**/*.rb', options={})
    Task.new(:rocco, dest, source_files, options)
  end

  # `Rocco::Task.new` takes a task name, the destination directory docs
  # should be built under, and a source file pattern or file list.
  class Task
    include Rake::DSL if defined?(Rake::DSL)

    def initialize(task_name, dest='docs/', sources='lib/**/*.rb', options={})
      @name = task_name
      @dest = dest[-1] == ?/ ? dest : "#{dest}/"
      @sources = FileList[sources]
      @options = options

      # Make sure there's a `directory` task defined for our destination.
      define_directory_task @dest

      # Run over the source file list, constructing destination filenames
      # and defining file tasks.
      @sources.each do |source_file|
        dest_file = source_file.sub(Regexp.new("#{File.extname(source_file)}$"), ".html")
        define_file_task source_file, "#{@dest}#{dest_file}"

        # If `rake/clean` was required, add the generated files to the list.
        # That way all Rocco generated are removed when running `rake clean`.
        CLEAN.include "#{@dest}#{dest_file}" if defined? CLEAN
      end
    end

    # Define the destination directory task and make the `:rocco` task depend
    # on it. This causes the destination directory to be created if it doesn't
    # already exist.
    def define_directory_task(path)
      directory path
      task @name => path
    end

    # Setup a `file` task for a single Rocco output file (`dest_file`). It
    # depends on the source file, the destination directory, and all of Rocco's
    # internal source code, so that the destination file is rebuilt when any of
    # those changes.
    #
    # You can run these tasks directly with Rake:
    #
    #     rake docs/foo.html docs/bar.html
    #
    # ... would generate the `foo.html` and `bar.html` files but only if they
    # don't already exist or one of their dependencies was changed.
    def define_file_task(source_file, dest_file)
      prerequisites = [@dest, source_file] + rocco_source_files
      file dest_file => prerequisites do |f|
        verbose { puts "rocco: #{source_file} -> #{dest_file}" }
        rocco = Rocco.new(source_file, @sources.to_a, @options)
        FileUtils.mkdir_p(File.dirname(dest_file))
        File.open(dest_file, 'wb') { |fd| fd.write(rocco.to_html) }
      end
      task @name => dest_file
    end

    # Return a `FileList` that includes all of Roccos source files. This causes
    # output files to be regenerated properly when someone upgrades the Rocco
    # library.
    def rocco_source_files
      libdir = File.expand_path('../..', __FILE__)
      FileList["#{libdir}/rocco.rb", "#{libdir}/rocco/**"]
    end

  end
end


text:
package org.kuali.kra.iacuc.auth;

import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.infrastructure.PermissionConstants;

public class IacucModifyPermissionsAuthorizer extends IacucProtocolAuthorizer {

    @Override
    public boolean isAuthorized(String userId, IacucProtocolTask task) {
        IacucProtocol protocol = task.getProtocol();
        boolean hasPermission = !protocol.getIacucProtocolDocument().isViewOnly() &&
                !isPessimisticLocked(protocol.getIacucProtocolDocument()) &&
                (!kraWorkflowService.isInWorkflow(protocol.getIacucProtocolDocument())) &&
                hasPermission(userId, protocol, PermissionConstants.MODIFY_IACUC_PROTOCOL);
        return hasPermission;
    }

}


text:
using MediaBrowser.Naming.Common;
using MediaBrowser.Naming.Video;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Patterns.Logging;

namespace MediaBrowser.Naming.Audio
{
    public class AlbumParser
    {
        private readonly ILogger _logger;
        private readonly NamingOptions _options;

        public AlbumParser(NamingOptions options, ILogger logger)
        {
            _options = options;
            _logger = logger;
        }

        public MultiPartResult ParseMultiPart(string path)
        {
            var result = new MultiPartResult();

            var filename = Path.GetFileName(path);

            if (string.IsNullOrWhiteSpace(filename))
            {
                return result;
            }

            // TODO: Move this logic into options object
            // Even better, remove the prefixes and come up with regexes
            // But Kodi documentation seems to be weak for audio

            // Normalize
            // Remove whitespace
            filename = filename.Replace("-", " ");
            filename = filename.Replace(".", " ");
            filename = filename.Replace("(", " ");
            filename = filename.Replace(")", " ");
            filename = Regex.Replace(filename, @"\s+", " ");

            filename = filename.TrimStart();

            foreach (var prefix in _options.AlbumStackingPrefixes)
            {
                if (filename.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var tmp = filename.Substring(prefix.Length);

                    tmp = tmp.Trim().Split(' ').FirstOrDefault() ?? string.Empty;

                    int val;
                    if (int.TryParse(tmp, NumberStyles.Any, CultureInfo.InvariantCulture, out val))
                    {
                        result.IsMultiPart = true;
                        break;
                    }
                }
            }

            return result;
        }
    }
}


text:
<?php

/* TodoClientBundle:List:show.html.twig */
class __TwigTemplate_6e732fd5f89866acc57c4f27553fbbe0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("TodoClientBundle::layout.html.twig");

        $this->blocks = array(
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "TodoClientBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_content($context, array $blocks = array())
    {
        // line 4
        echo "

            <button class=\"btn btn-large disabled ";
        // line 6
        if ($this->getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
            echo " btn-primary";
        } else {
            echo " btn-inverse";
        }
        echo "\">
                ";
        // line 7
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "name"), "html", null, true);
        echo "
            </button>
            ";
        // line 9
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "title"), "html", null, true);
        echo "

                ";
        // line 13
        if ($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "eventTime")) {
            // line 14
            echo "                    getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
                echo "  btn-primary";
            } else {
                echo " btn-inverse";
            }
            echo "\">
                        ";
            // line 15
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "eventTime"), "d-m-Y @ H:i"), "html", null, true);
            echo "

                ";
        }
        // line 18
        echo "

getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active"))) {
            echo " progress-warning";
        }
        echo "\" title=\"";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "progress"), "html", null, true);
        echo "%\">

env, ($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "progress") . "%"), "html", null, true);
        echo ";\">

getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
            echo " class=\"text-info\"";
        }
        echo ">
                env, $this->env->getExtension('routing')->getPath("todo_task_show", array("id" => $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "id"))), "html", null, true);
        echo "\">

                        ";
        // line 26
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "title"), "html", null, true);
        echo "

            ";
        // line 30
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "customField"));
        foreach ($context['_seq'] as $context["_key"] => $context["custom"]) {
            // line 31
            echo "

                ";
            // line 32
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["custom"]) ? $context["custom"] : $this->getContext($context, "custom")), "key"), "html", null, true);
            echo ":

                    ";
            // line 34
            if (($this->getAttribute($this->getAttribute((isset($context["custom"]) ? $context["custom"] : $this->getContext($context, "custom")), "fieldType"), "dataType") == "DATETIME")) {
                // line 35
                echo "                        getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
                    echo " badge-info";
                }
                echo "\">
                            ";
                // line 36
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["custom"]) ? $context["custom"] : $this->getContext($context, "custom")), "value"), "html", null, true);
                echo "

                    ";
            } else {
                // line 39
                echo "                        ";
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["custom"]) ? $context["custom"] : $this->getContext($context, "custom")), "value"), "html", null, true);
                echo "
                    ";
            }
            // line 41
            echo "

            ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['custom'], $context['_parent'], $context['loop']);
        $context = array_merge($_parent, array_intersect_key($context, $_parent));
        // line 44
        echo "

";
        // line 45
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "description"), "html", null, true);
        echo "

            <form action=\"";
        // line 47
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("todo_task_show", array("id" => $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "id"))), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo ">
                ";
        // line 48
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "
                <input type=\"submit\" class=\"btn btn-primary\" value=\"Comment\">
                env, $this->env->getExtension('routing')->getPath("todo_task_edit", array("id" => $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "id"))), "html", null, true);
        echo "\" class=\"btn btn-small\">Update
                Remove
            </form>

            ";
        // line 54
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable(twig_reverse_filter($this->env, $this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "comments")));
        foreach ($context['_seq'] as $context["_key"] => $context["comment"]) {
            // line 55
            echo "

                    ";
            // line 56
            if ((null === $this->getAttribute((isset($context["comment"]) ? $context["comment"] : $this->getContext($context, "comment")), "changed"))) {
                // line 57
                echo "

                            getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
                    echo " badge-info";
                }
                echo "\">
                                ";
                // line 59
                echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["comment"]) ? $context["comment"] : $this->getContext($context, "comment")), "createdAt"), "d-m-Y @ H:i"), "html", null, true);
                echo "

                            Commented:
                            ";
                // line 62
                echo twig_escape_filter($this->env, $this->getAttribute((isset($context["comment"]) ? $context["comment"] : $this->getContext($context, "comment")), "comment"), "html", null, true);
                echo "

                    ";
            } else {
                // line 65
                echo "

                            getAttribute($this->getAttribute((isset($context["task"]) ? $context["task"] : $this->getContext($context, "task")), "status"), "active")) {
                    echo " badge-info";
                }
                echo "\">
                                ";
                // line 67
                echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["comment"]) ? $context["comment"] : $this->getContext($context, "comment")), "createdAt"), "d-m-Y @ H:i"), "html", null, true);
                echo "

                            Updated. Before update:

                            ";
                // line 71
                echo $this->getAttribute((isset($context["comment"]) ? $context["comment"] : $this->getContext($context, "comment")), "changed");
                echo "

                    ";
            }
            // line 74
            echo "

            ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['comment'], $context['_parent'], $context['loop']);
        $context = array_merge($_parent, array_intersect_key($context, $_parent));
        // line 76
        echo "

";
    }

    public function getTemplateName()
    {
        return "TodoClientBundle:List:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  233 => 76,  226 => 74,  220 => 71,  213 => 67,  207 => 66,  204 => 65,  198 => 62,  192 => 59,  186 => 58,  183 => 57,  181 => 56,  178 => 55,  174 => 54,  167 => 50,  162 => 48,  156 => 47,  151 => 45,  148 => 44,  140 => 41,  134 => 39,  128 => 36,  121 => 35,  119 => 34,  114 => 32,  111 => 31,  107 => 30,  100 => 26,  95 => 24,  89 => 23,  83 => 20,  75 => 19,  72 => 18,  66 => 15,  57 => 14,  55 => 13,  48 => 9,  43 => 7,  35 => 6,  31 => 4,  28 => 3,);
    }
}


text:
The Symantec Endpoint Protection program downloads the Virus Defs but doesn't always clean it up effectively.

## My solution

* View the VirusDef directories
* Delete directories with mask yyyyMMdd.###

## Explore VirusDefs.cmd

[Script](Explore%20VirusDefs.cmd) to open directory where the VirusDefs are stored.

```batch
explorer.exe "%PROGRAMDATA%\Symantec\Definitions\VirusDefs\"
```


text:
package com.quantiply.samza.system.druid;

import org.apache.samza.system.OutgoingMessageEnvelope;

/**
 * Interface that plugins need to implement to extract event time (ms since epoch) from messages
 */
public interface EventTimeExtractor {

  long getEventTsMs(OutgoingMessageEnvelope envelope);

}


text:
package structural.businessobjects;

public interface VLCplayer {
	public void playVLCFile(String filename);
}


text:
package com.google.job.data;

/** Class for the job listings query using builder pattern. */
public final class JobQuery {
    private int minLimit = 0;
    private int maxLimit = Integer.MAX_VALUE;
    private SingaporeRegion region = SingaporeRegion.ENTIRE;
    private Filter sortBy = Filter.SALARY;
    private Order order = Order.DESCENDING;
    private int pageSize = 100;
    private int pageIndex = 0;

    public JobQuery() {}

    public JobQuery setMinLimit(int minLimit) {
        if (minLimit < 0) {
            throw new IllegalArgumentException("minLimit should not be negative");
        }

        this.minLimit = minLimit;
        return this;
    }

    public JobQuery setMaxLimit(int maxLimit) {
        if (maxLimit <= 0 || maxLimit < this.minLimit) {
            throw new IllegalArgumentException("maxLimit should not be negative or zero or less than minLimit");
        }

        this.maxLimit = maxLimit;
        return this;
    }

    public JobQuery setRegion(SingaporeRegion region) {
        this.region = region;
        return this;
    }

    public JobQuery setSortBy(Filter sortBy) {
        this.sortBy = sortBy;
        return this;
    }

    public JobQuery setOrder(Order order) {
        this.order = order;
        return this;
    }

    public JobQuery setPageSize(int pageSize) {
        if (pageSize < 1) {
            throw new IllegalArgumentException("pageSize should not be less than 1");
        }

        this.pageSize = pageSize;
        return this;
    }

    public JobQuery setPageIndex(int pageIndex) {
        if (pageIndex < 0) {
            throw new IllegalArgumentException("pageIndex should not be less than 0");
        }

        this.pageIndex = pageIndex;
        return this;
    }

    /** Returns the lower limit for the filter. */
    public int getMinLimit() {
        return minLimit;
    }

    /** Returns the upper limit for the filter. */
    public int getMaxLimit() {
        return maxLimit;
    }

    /** Returns the region in Singapore. */
    public SingaporeRegion getRegion() {
        return region;
    }

    /** Returns the sorting. */
    public Filter getSortBy() {
        return sortBy;
    }

    /** Returns the ordering of the sorting. */
    public Order getOrder() {
        return order;
    }

    /** Returns the page size. */
    public int getPageSize() {
        return pageSize;
    }

    /** Returns a page number (or index). */
    public int getPageIndex() {
        return pageIndex;
    }
}


text:
<?php

namespace Evolution7\SocialApi\Entity;

use Evolution7\SocialApi\Config\Config;

/**
 * Base class for all entities
 * @SuppressWarnings(PHPMD.ShortVariable)
 */
abstract class Base
{
    protected $platform;
    protected $id;
    protected $paginationId;
    protected $url;

    /**
     * {@inheritdoc}
     */
    public function setPlatform($platform)
    {
        if (config::validatePlatform($platform)) {
            $this->platform = $platform;
        } else {
            throw new \InvalidArgumentException(
                sprintf("Platform '%s' not supported", $platform)
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getPlatform()
    {
        return $this->platform;
    }

    /**
     * {@inheritdoc}
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function setPaginationId($paginationId)
    {
        $this->paginationId = $paginationId;
    }

    /**
     * {@inheritdoc}
     */
    public function getPaginationId()
    {
        return $this->paginationId;
    }

    /**
     * {@inheritdoc}
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * {@inheritdoc}
     */
    public function getUrl()
    {
        return $this->url;
    }
}


text:
package com.snowplowanalytics.weather
package providers.openweather

import scala.concurrent.duration._

import cats.effect.IO
import cats.effect.unsafe.implicits.global

import cats.syntax.either._
import io.circe.Decoder
import org.mockito.ArgumentMatchers.{eq => eqTo}
import org.specs2.Specification
import org.specs2.mock.Mockito

import errors.{InvalidConfigurationError, TimeoutError}
import requests.OwmRequest
import responses.History

// Mock transport which returns predefined responses
class OWMCacheSpec extends Specification with Mockito {
  def is =
    s2"""

  Test cache specification

    do not bother server on identical requests $e1
    do not bother server on similar requests (example from README) $e4
    retry request on timeout error $e2
    check geoPrecision $e5
    make requests again after full cache $e3
    be left for invalid precision $e6
    be left for invalid cache size $e7
  """

  val ioEmptyHistoryResponse: IO[Either[TimeoutError, History]] =
    IO.pure(History(BigInt(100), "0", List()).asRight)
  val ioTimeoutErrorResponse: IO[Either[TimeoutError, History]] =
    IO.pure(TimeoutError("java.util.concurrent.TimeoutException: Futures timed out after [1 second]").asLeft)

  def e1 = {
    implicit val ioTransport = mock[Transport[IO]].defaultReturn(ioEmptyHistoryResponse)
    val ioAction = for {
      client <- CreateOWM[IO].create("host", "key", 1.seconds, true, 2, 1).map(_.toOption.get)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
    } yield ()
    ioAction.unsafeRunSync()
    there.was(
      1.times(ioTransport)
        .receive[History](any[OwmRequest], eqTo("host"), eqTo("key"), eqTo(1.seconds), eqTo(true))(eqTo(implicitly))
    )

  }

  def e2 = {
    implicit val ioTransport = mock[Transport[IO]]
    ioTransport
      .receive[History](any[OwmRequest], any[String], any[String], any[FiniteDuration], any[Boolean])(
        any[Decoder[History]]
      )
      .returns(ioTimeoutErrorResponse)
      .thenReturn(ioEmptyHistoryResponse)
    val ioAction = for {
      client <- CreateOWM[IO].create("host", "key", 1.seconds, true, 2, 1).map(_.toOption.get)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
    } yield ()
    ioAction.unsafeRunSync()
    there.was(
      2.times(ioTransport)
        .receive[History](any[OwmRequest], eqTo("host"), eqTo("key"), eqTo(1.seconds), eqTo(true))(eqTo(implicitly))
    )
  }

  def e3 = {
    implicit val ioTransport = mock[Transport[IO]].defaultReturn(ioEmptyHistoryResponse)
    val ioAction = for {
      client <- CreateOWM[IO].create("host", "key", 1.seconds, true, 2, 1).map(_.toOption.get)
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
      _      <- client.cachingHistoryByCoords(6.44f, 3.33f, 100)
      _      <- client.cachingHistoryByCoords(8.44f, 3.33f, 100)
      _      <- IO.sleep(1 second) // give some time for cache cleanup
      _      <- client.cachingHistoryByCoords(4.44f, 3.33f, 100)
    } yield ()
    ioAction.unsafeRunSync()
    there.was(
      4.times(ioTransport)
        .receive[History](any[OwmRequest], eqTo("host"), eqTo("key"), eqTo(1.seconds), eqTo(true))(eqTo(implicitly))
    )
  }

  def e4 = {
    implicit val ioTransport = mock[Transport[IO]].defaultReturn(ioEmptyHistoryResponse)
    val ioAction = for {
      client <- CreateOWM[IO].create("host", "key", 1.seconds, true, 10, 1).map(_.toOption.get)
      _      <- client.cachingHistoryByCoords(10.4f, 32.1f, 1447070440) // Nov 9 12:00:40 2015 GMT
      _      <- client.cachingHistoryByCoords(10.1f, 32.312f, 1447063607) // Nov 9 10:06:47 2015 GMT
      _      <- client.cachingHistoryByCoords(10.2f, 32.4f, 1447096857) // Nov 9 19:20:57 2015 GMT
    } yield ()
    ioAction.unsafeRunSync()
    there.was(
      1.times(ioTransport)
        .receive[History](any[OwmRequest], eqTo("host"), eqTo("key"), eqTo(1.seconds), eqTo(true))(eqTo(implicitly))
    )
  }

  def e5 = {
    implicit val ioTransport = mock[Transport[IO]].defaultReturn(ioEmptyHistoryResponse)
    val ioAction = for {
      client <- CreateOWM[IO].create("host", "key", 1.seconds, true, 10, 2).map(_.toOption.get)
      _      <- client.cachingHistoryByCoords(10.8f, 32.1f, 1447070440) // Nov 9 12:00:40 2015 GMT
      _      <- client.cachingHistoryByCoords(10.1f, 32.312f, 1447063607) // Nov 9 10:06:47 2015 GMT
      _      <- client.cachingHistoryByCoords(10.2f, 32.4f, 1447096857) // Nov 9 19:20:57 2015 GMT
    } yield ()
    ioAction.unsafeRunSync()
    there.was(
      2.times(ioTransport)
        .receive[History](any[OwmRequest], eqTo("host"), eqTo("key"), eqTo(1.seconds), eqTo(true))(eqTo(implicitly))
    )
  }

  def e6 =
    CreateOWM[IO].create("host", "KEY", 1.seconds, true, 10, geoPrecision = 0).unsafeRunSync() must beLeft.like {
      case InvalidConfigurationError(msg) => msg must be_==("geoPrecision must be greater than 0")
    }

  def e7 =
    CreateOWM[IO].create("host", "KEY", 1.seconds, true, cacheSize = 0, 10).unsafeRunSync() must beLeft.like {
      case InvalidConfigurationError(msg) => msg must be_==("cacheSize must be greater than 0")
    }

}


text:
<?php
class Services_TwitterNotify implements Services_NotifyInterface {
    /**
     * @var Model_LocalConfig
     */
    protected $_localConfig;

    public function __construct(Model_LocalConfig $config)
    {
        $this->_localConfig = $config;
    }

    /**
     * @param Model_User $to
     * @param Model_User $from
     * @param string $message
     * @return bool|string
     */
    public function send($to, $from = "", $message = "") {

        if ($message == "") {
            // Construct Tweet
            $message = "@".$to->getTwitterUsername()." you were upvoted by @".$from->getTwitterUsername(). " on magehero.com/" . $to->getGithubUsername();
        }

        $settings = array(
            'oauth_access_token' => $this->_localConfig->get('twitter_oauth_access_token'),
            'oauth_access_token_secret' => $this->_localConfig->get('twitter_oauth_access_token_secret'),
            'consumer_key' => $this->_localConfig->get('twitter_consumer_api_key'),
            'consumer_secret' => $this->_localConfig->get('twitter_consumer_api_secret')
        );
        $url = 'https://api.twitter.com/1.1/statuses/update.json';
        $requestMethod = 'POST';
        $postfields = array("status" => $message);
        try{
        $twitter = new TwitterAPIExchange($settings);
        $response = $twitter
            ->buildOauth($url, $requestMethod)
            ->setPostfields($postfields)
            ->performRequest();
        // Error handling for tweet failurs , is not required. I am pretty sure that the voters are not interested
        // in knowing if the tweet was posted or now.
        return $response;
        }catch(Exception $e) {
            return false;
        }
        //var_dump(json_decode($response));die;
    }
}


text:
package com.github.pukkaone.gelf.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.github.pukkaone.gelf.protocol.GelfAMQPSender;
import com.github.pukkaone.gelf.protocol.GelfMessage;
import com.github.pukkaone.gelf.protocol.GelfSSLSender;
import com.github.pukkaone.gelf.protocol.GelfSender;
import com.github.pukkaone.gelf.protocol.GelfTCPSender;
import com.github.pukkaone.gelf.protocol.GelfUDPSender;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * Appender which sends events to GELF server.
 */
public class GelfAppender extends AppenderBase<ILoggingEvent> {

    private String graylogHost;
    private int graylogPort = GelfSender.DEFAULT_PORT;
    private String originHost;
    private boolean levelIncluded = true;
    private boolean locationIncluded;
    private boolean loggerIncluded = true;
    private boolean markerIncluded;
    private boolean mdcIncluded;
    private boolean threadIncluded;
    private Map<String, String> additionalFields = new HashMap<>();
    private String amqpURI;
    private String amqpExchange;
    private String amqpRoutingKey;
    private int amqpMaxRetries;
    private boolean sslTrustAllCertificates;
    private GelfMessageFactory marshaller = new GelfMessageFactory();
    private GelfSender gelfSender;

    public String getGraylogHost() {
        return graylogHost;
    }

    public void setGraylogHost(String graylogHost) {
        this.graylogHost = graylogHost;
    }

    public int getGraylogPort() {
        return graylogPort;
    }

    public void setGraylogPort(int graylogPort) {
        this.graylogPort = graylogPort;
    }

    private String getLocalHostName() {
        String hostName = null;
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            addError("Unknown local hostname", e);
        }

        return hostName;
    }

    public String getOriginHost() {
        if (originHost == null) {
            originHost = getLocalHostName();
        }
        return originHost;
    }

    public void setOriginHost(String originHost) {
        this.originHost = originHost;
    }

    public boolean isLevelIncluded() {
        return levelIncluded;
    }

    public void setLevelIncluded(boolean levelIncluded) {
        this.levelIncluded = levelIncluded;
    }

    public boolean isLocationIncluded() {
        return this.locationIncluded;
    }

    public void setLocationIncluded(boolean locationIncluded) {
        this.locationIncluded = locationIncluded;
    }

    public boolean isLoggerIncluded() {
        return loggerIncluded;
    }

    public void setLoggerIncluded(boolean loggerIncluded) {
        this.loggerIncluded = loggerIncluded;
    }

    public boolean isMarkerIncluded() {
        return markerIncluded;
    }

    public void setMarkerIncluded(boolean markerIncluded) {
        this.markerIncluded = markerIncluded;
    }

    public boolean isMdcIncluded() {
        return mdcIncluded;
    }

    public void setMdcIncluded(boolean mdcIncluded) {
        this.mdcIncluded = mdcIncluded;
    }

    public boolean isThreadIncluded() {
        return threadIncluded;
    }

    public void setThreadIncluded(boolean threadIncluded) {
        this.threadIncluded = threadIncluded;
    }

    public Map<String, String> getAdditionalFields() {
        return additionalFields;
    }

    public void addAdditionalField(String keyValue) {
        String[] parts = keyValue.split("=", 2);
        if (parts.length != 2) {
            addError(String.format(
                "additionalField must be in the format key=value, but found [%s]",
                keyValue));
            return;
        }
         additionalFields.put(parts[0], parts[1]);
    }

    public String getAmqpURI() {
        return amqpURI;
    }

    public void setAmqpURI(String amqpURI) {
        this.amqpURI = amqpURI;
    }

    public String getAmqpExchange() {
        return amqpExchange;
    }

    public void setAmqpExchange(String amqpExchange) {
        this.amqpExchange = amqpExchange;
    }

    public String getAmqpRoutingKey() {
        return amqpRoutingKey;
    }

    public void setAmqpRoutingKey(String amqpRoutingKey) {
        this.amqpRoutingKey = amqpRoutingKey;
    }

    public int getAmqpMaxRetries() {
        return amqpMaxRetries;
    }

    public void setAmqpMaxRetries(int amqpMaxRetries) {
        this.amqpMaxRetries = amqpMaxRetries;
    }

    public boolean isSslTrustAllCertificates() {
        return sslTrustAllCertificates;
    }

    public void setSslTrustAllCertificates(boolean sslTrustAllCertificates) {
        this.sslTrustAllCertificates = sslTrustAllCertificates;
    }

    private GelfUDPSender getGelfUDPSender(String graylogHost, int graylogPort)
        throws IOException
    {
        return new GelfUDPSender(graylogHost, graylogPort);
    }

    private GelfTCPSender getGelfTCPSender(String graylogHost, int graylogPort)
        throws IOException
    {
        return new GelfTCPSender(graylogHost, graylogPort);
    }

    private GelfSSLSender getGelfSSLSender(
            String graylogHost, int graylogPort, boolean sslTrustAllCertificates)
        throws IOException
    {
        return new GelfSSLSender(graylogHost, graylogPort, sslTrustAllCertificates);
    }

    private GelfAMQPSender getGelfAMQPSender(
            String amqpURI,
            String amqpExchange,
            String amqpRoutingKey,
            int amqpMaxRetries)
        throws IOException, URISyntaxException, NoSuchAlgorithmException, KeyManagementException
    {
        return new GelfAMQPSender(amqpURI, amqpExchange, amqpRoutingKey, amqpMaxRetries);
    }

    @Override
    public void start() {
        if (graylogHost == null && amqpURI == null) {
            addError("Graylog2 hostname and AMQP URI are empty!");
            return;
        }
        if (graylogHost != null && amqpURI != null) {
            addError("Graylog2 hostname and AMQP URI are both set!");
            return;
        }

        try {
            if (graylogHost != null && graylogHost.startsWith("ssl:")) {
                String sslGraylogHost = graylogHost.substring(4);
                gelfSender = getGelfSSLSender(sslGraylogHost, graylogPort, sslTrustAllCertificates);
            } else if (graylogHost != null && graylogHost.startsWith("tcp:")) {
                String tcpGraylogHost = graylogHost.substring(4);
                gelfSender = getGelfTCPSender(tcpGraylogHost, graylogPort);
            } else if (graylogHost != null && graylogHost.startsWith("udp:")) {
                String udpGraylogHost = graylogHost.substring(4);
                gelfSender = getGelfUDPSender(udpGraylogHost, graylogPort);
            } else if (amqpURI != null) {
                gelfSender = getGelfAMQPSender(amqpURI, amqpExchange, amqpRoutingKey, amqpMaxRetries);
            } else {
                gelfSender = getGelfUDPSender(graylogHost, graylogPort);
            }
        } catch (UnknownHostException e) {
            addError(String.format("Unknown Graylog2 hostname [%s]", getGraylogHost()), e);
            return;
        } catch (SocketException e) {
            addError("Socket exception", e);
            return;
        } catch (IOException e) {
            addError("IO exception", e);
            return;
        } catch (URISyntaxException e) {
            addError(String.format("Invalid AMQP URI [%s]", getAmqpURI()), e);
            return;
        } catch (NoSuchAlgorithmException e) {
            addError("AMQP algorithm exception", e);
            return;
        } catch (KeyManagementException e) {
            addError("AMQP key exception", e);
            return;
        }

        super.start();
    }

    protected GelfSender getGelfSender() {
        return gelfSender;
    }

    @Override
    protected void append(ILoggingEvent event) {
        GelfMessage message = marshaller.createMessage(this, event);

        if (getGelfSender() == null || !getGelfSender().sendMessage(message)) {
            addError("Could not send GELF message");
        }
    }

    @Override
    public void stop() {
        gelfSender.close();
        super.stop();
    }
}


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

<TITLE>
Uses of Class org.rlcommunity.rlglue.codec.util.AgentLoader (RL-Glue Java Codec 2.06)
</TITLE>

<META NAME="date" CONTENT="2009-02-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.rlcommunity.rlglue.codec.util.AgentLoader

Packages that use AgentLoader

org.rlcommunity.rlglue.codec.util

Uses of AgentLoader in org.rlcommunity.rlglue.codec.util

Methods in org.rlcommunity.rlglue.codec.util that return AgentLoader

static AgentLoader
AgentLoader.loadAgent(java.lang.String agentClassName)

          Loads the class agentClassName as an rl-glue agent.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<?php

namespace RC\TokenMatcher\Assertion\Expr;

use RC\TokenMatcher\Assertion\ExprAssertion;

class ShellExecAssertion extends ExprAssertion
{
}


text:
package tdl.record.sourcecode.snapshot;

import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import tdl.record.sourcecode.content.CopyFromDirectorySourceCodeProvider;
import tdl.record.sourcecode.snapshot.helpers.GitHelper;
import tdl.record.sourcecode.test.FileTestHelper;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class SnapshotRecorderTest {
    private int maximumFileSizeLimitInMB = 2;

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void takeSnapshot() throws Exception {
        Path directory = Paths.get("./src/test/resources/diff/test1/dir1/");
        Path tmpDir = folder.getRoot().toPath();
        FileUtils.copyDirectory(directory.toFile(), tmpDir.toFile());
        SnapshotRecorder recorder = new SnapshotRecorder(new CopyFromDirectorySourceCodeProvider(tmpDir, maximumFileSizeLimitInMB), 5);
        recorder.init();

        Snapshot snapshot1 = recorder.takeSnapshot();
        assertTrue(snapshot1 instanceof KeySnapshot);
        printSnapshot(snapshot1);

        FileTestHelper.appendStringToFile(tmpDir, "file1.txt", "\ndata1");
        Snapshot snapshot2 = recorder.takeSnapshot();
        assertTrue(snapshot2 instanceof PatchSnapshot);
        printSnapshot(snapshot2);

        FileTestHelper.appendStringToFile(tmpDir, "file2.txt", "\nLOREM");
        Snapshot snapshot3 = recorder.takeSnapshot();
        assertTrue(snapshot3 instanceof PatchSnapshot);
        printSnapshot(snapshot3);

        FileTestHelper.appendStringToFile(tmpDir, "subdir1/file1.txt", "\nIPSUM");
        Snapshot snapshot4 = recorder.takeSnapshot();
        assertTrue(snapshot4 instanceof PatchSnapshot);
        printSnapshot(snapshot4);

        FileTestHelper.appendStringToFile(tmpDir, "subdir1/file1.txt", "SIT");
        Snapshot snapshot5 = recorder.takeSnapshot();
        assertTrue(snapshot5 instanceof PatchSnapshot);
        printSnapshot(snapshot5);

        FileTestHelper.appendStringToFile(tmpDir, "subdir1/file1.txt", "AMENT");
        Snapshot snapshot6 = recorder.takeSnapshot();
        assertTrue(snapshot6 instanceof KeySnapshot);
        printSnapshot(snapshot6);
    }

    private static void printSnapshot(Snapshot snapshot) {
        //System.out.println(new String(snapshot.getData()));
        //do nothing
    }

    private SnapshotRecorder createDefaultRecorder(Path tmpDir) throws Exception {
        SnapshotRecorder recorder = new SnapshotRecorder(new CopyFromDirectorySourceCodeProvider(tmpDir, maximumFileSizeLimitInMB), 5);
        recorder.init();
        return recorder;
    }

    @Test
    public void constructShouldCreateGitDirectory() throws Exception {
        Path tmpDir = folder.getRoot().toPath();
        try (SnapshotRecorder recorder = createDefaultRecorder(tmpDir)) {
            Path gitDir = recorder.getGitDirectory();
            assertTrue(gitDir.toFile().exists());
            assertTrue(gitDir.resolve(".git").toFile().exists());
        }
    }

    @Test
    public void syncToGitDirectoryShouldCopyDirectory() throws Exception {
        Path tmpDir = folder.getRoot().toPath();
        try (SnapshotRecorder recorder = createDefaultRecorder(tmpDir)) {
            Path gitDir = recorder.getGitDirectory();

            assertFalse(gitDir.resolve("file1.txt").toFile().exists());
            assertFalse(gitDir.resolve("file2.txt").toFile().exists());
            FileTestHelper.appendStringToFile(tmpDir, "file1.txt", "Hello World!");
            FileTestHelper.appendStringToFile(tmpDir, "file2.txt", "Lorem Ipsum!");

            recorder.syncToGitDirectory();
            assertTrue(gitDir.resolve("file1.txt").toFile().exists());
            assertTrue(gitDir.resolve("file2.txt").toFile().exists());

            assertFalse(gitDir.resolve("subdir/file1.txt").toFile().exists());
            FileTestHelper.appendStringToFile(tmpDir, "subdir/file1.txt", "Hello World!");

            recorder.syncToGitDirectory();
            assertTrue(gitDir.resolve("subdir").toFile().isDirectory());
            assertTrue(gitDir.resolve("subdir/file1.txt").toFile().exists());

            Files.delete(tmpDir.resolve("file1.txt"));
            recorder.syncToGitDirectory();
            assertFalse(gitDir.resolve("file1.txt").toFile().exists());

            Files.delete(tmpDir.resolve("subdir/file1.txt"));
            recorder.syncToGitDirectory();
            assertFalse(gitDir.resolve("subdir/file1.txt").toFile().exists());
        }
    }

    @Test
    public void syncToGitDirectoryShouldCopyDirectoryWithDotGitignore() throws Exception {
        Path tmpDir = folder.getRoot().toPath();
        try (SnapshotRecorder recorder = createDefaultRecorder(tmpDir)) {
            Path gitDir = recorder.getGitDirectory();

            assertFalse(gitDir.resolve(".gitignore").toFile().exists());
            FileTestHelper.appendStringToFile(tmpDir, ".gitignore", "*.orig");

            recorder.syncToGitDirectory();
            assertTrue(gitDir.resolve(".gitignore").toFile().exists());
        }
    }

    @Test
    public void syncToGitDirectoryShouldCopyDirectoryWithoutDotGitDirectory() throws Exception {
        Path tmpDir = folder.getRoot().toPath();
        try (SnapshotRecorder recorder = createDefaultRecorder(tmpDir)) {
            Path gitDir = recorder.getGitDirectory();

            assertFalse(tmpDir.resolve(".git").toFile().exists());
            Git.init().setDirectory(tmpDir.toFile()).call();
            FileTestHelper.appendStringToFile(tmpDir, ".git/randomfile", "TEST");
            assertTrue(tmpDir.resolve(".git").toFile().exists());

            recorder.syncToGitDirectory();
            assertTrue(gitDir.resolve(".git").toFile().exists());
            assertFalse(gitDir.resolve(".git/randomfile").toFile().exists());
        }
    }

    @Test
    public void commitAllChanges() throws Exception {
        Path tmpDir = folder.getRoot().toPath();
        try (SnapshotRecorder recorder = createDefaultRecorder(tmpDir)) {
            Git git = recorder.getGit();

            assertEquals(1, GitHelper.getCommitCount(git));
            FileTestHelper.appendStringToFile(tmpDir, "file1.txt", "Hello World!");
            FileTestHelper.appendStringToFile(tmpDir, "file2.txt", "Lorem Ipsum!");

            recorder.syncToGitDirectory();
            recorder.commitAllChanges();
            assertEquals(2, GitHelper.getCommitCount(git));

            recorder.commitAllChanges();
            assertEquals(3, GitHelper.getCommitCount(git));
        }
    }
}


text:
{-
  This is a module for reading and parsing *.csv files.
-}

module DataBuilder
  ( getData
  , filterDataContainer
  , getMatrixFromDataContainer
  , getMatrixFromNumContainer
  , NumContainer(..)
  , Header
  , DataContainer
  )where

    import Data.Char
    import Data.List.Split
    import System.IO
    import Control.Exception
    import Exceptions

    import Matrix hiding (decreaseAll)

    -- * Types
    -- | Simply String containing path to a file§
    type Filepath = String
    type Header = String
    -- | String that seperates data, in csv it is: ","
    type Separator = String

    -- | DataContainer is a container for headers of data and data itself
    newtype DataContainer = DataContainer ([Header], Matrix String)
    -- | NumContainer stores the same as DataContainer except non-numerical values
    newtype NumContainer = NumContainer ([Header], Matrix Double)

    -- * Instances
    instance Show DataContainer where
      show (DataContainer (xs, m)) = show xs ++ "\n" ++ show m

    instance Show NumContainer where
      show (NumContainer (xs, m)) = show xs ++ "\n" ++ show m

    -- * FUNCTION INDEX
    -- | Takes list of indexes of columns that are to be deleted, DataContainer with data and return NumContainer with only numeric values.
    -- | If it cannot get a number out of a field it removes this one training set.
    filterDataContainer :: [Int] -> DataContainer -> NumContainer
    -- | Takes a path to the file, seperator that seperates data and returns DataContainer
    getData :: Filepath -> Separator -> IO (DataContainer)

    -- BODIES
    filterDataContainer columnsToDelete (DataContainer (s, m)) = NumContainer ( deleteElements columnsToDelete s,
                                                  fmap (\(Just e) -> e) .
                                                  filterLinesHor (\s -> if s == Nothing then False else True) .
                                                  fmap getNumber .
                                                  deleteColumns columnsToDelete $ m)

    getData path sep = (do
      handle <- openFile path ReadMode
      contents <- hGetContents handle
      if isFileOK contents
        then return  (getDataContainer sep . lines $ contents)
        else throwE "\n The file is not a valid csv file.")
      `catch` handler

    handler :: IOError -> IO (DataContainer)
    handler e = do
      throwE (show e ++ "Error while getting data.")

    getMatrixFromDataContainer :: DataContainer -> Matrix String
    getMatrixFromDataContainer (DataContainer (_, m)) = m

    getMatrixFromNumContainer :: NumContainer -> Matrix Double
    getMatrixFromNumContainer (NumContainer (_, m)) = m

    --PRIVATE FUNCTIONS

    isFileOK :: String -> Bool    -- here we can evaluate on errors that can appear
    isFileOK s
      | length s == 0 = False     -- when empty file
      | otherwise = True

    getDataContainer :: Separator -> [String] -> DataContainer
    getDataContainer sep contentInLines = DataContainer (map filterHeader . splitOn sep . head $ contentInLines, transposeM $ (packM inside))
                                where
                                  inside = map (\s -> splitOn sep $ s) . tail $ contentInLines

    filterHeader :: Header -> Header
    filterHeader s = filter (\ch -> (ch /= '\"') && (ch /= '\'')) s

    deleteElements :: [Int] -> [a] -> [a]
    deleteElements [] l = l
    deleteElements _ [] = []
    deleteElements (a:as) xs = deleteElements (decreaseAll (as)) (deleteElement a xs)

    deleteElement :: Int -> [a] -> [a]
    deleteElement a xs  = loop a xs
          where
            loop _ [] = []
            loop 1 (y:ys) = loop 0 ys
            loop n (y:ys) = y:(loop (n-1) ys)

    decreaseAll :: [Int] -> [Int]
    decreaseAll [] = []
    decreaseAll (x:xs) = (x-1):(decreaseAll xs)

    getNumber :: String -> Maybe Double
    getNumber s = case head s == '\"' || head s == '\'' || (length s == 0) ||(isLetter . head $ s) of
      True -> Nothing
      False -> Just $ (read s :: Double)


text:
using UnityEngine;
using System.Collections;

public class DamageCounter : MonoBehaviour {
	private float timer;
	private const float COOLDOWN = 0.55f;
	public bool isDamage = true;
	// Use this for initialization
	void Start () {
		timer = Time.time;
	}

	// Update is called once per frame
	void Update () {
		transform.Translate(new Vector3(0f,0.001f,0f));
		//math taken from http://answers.unity3d.com/questions/174819/damage-gui-pop-up-on-enemy-hit.html
		if(isDamage) {
			guiText.material.color = new Color(guiText.material.color.r, guiText.material.color.g, guiText.material.color.b, Mathf.Cos((Time.time - timer)*((Mathf.PI/2)/COOLDOWN)));
		} else {
			guiText.material.color = new Color(0f, 205f, 0f, Mathf.Cos((Time.time - timer)*((Mathf.PI/2)/COOLDOWN)));
		}
		Destroy(gameObject, COOLDOWN);
	}
}


text: Selection is HERE only


text:
require 'json'

module Shell
  module Commands
    class ListLocks < Command
      def help
        <<-EOF
List all locks in hbase. Examples:

  hbase> list_locks
EOF
      end

      def command
        list = JSON.parse(admin.list_locks)

        list.each do |lock|
          formatter.output_strln("#{lock['resourceType']}(#{lock['resourceName']})")

          case lock['lockType']
          when 'EXCLUSIVE' then
            formatter.output_strln("Lock type: #{lock['lockType']}, " \
              "procedure: #{lock['exclusiveLockOwnerProcedure']}")
          when 'SHARED' then
            formatter.output_strln("Lock type: #{lock['lockType']}, " \
              "count: #{lock['sharedLockCount']}")
          end

          if lock['waitingProcedures']
            formatter.header(['Waiting procedures'])

            lock['waitingProcedures'].each do |waiting_procedure|
              formatter.row([waiting_procedure])
            end

            formatter.footer(lock['waitingProcedures'].size)
          end

          formatter.output_strln('')
        end
      end
    end
  end
end