text:
#pragma once

#include <assert.h>
#include <boost/noncopyable.hpp>
#include <errno.h>
#include <glog/logging.h>
#include <atomic>
#include <functional>
#include <mutex>
#include <thread>
#include <unordered_set>
#include <vector>

#include <folly/ScopeGuard.h>
#include <folly/concurrency/CacheLocality.h>
#include <folly/detail/Futex.h>
#include <folly/portability/Semaphore.h>
#include <folly/synchronization/detail/AtomicUtils.h>

namespace folly {
namespace test {

// This is ugly, but better perf for DeterministicAtomic translates
// directly to more states explored and tested
#define FOLLY_TEST_DSCHED_VLOG(...)                             \
  do {                                                          \
    if (false) {                                                \
      VLOG(2) << std::hex << std::this_thread::get_id() << ": " \
              << __VA_ARGS__;                                   \
    }                                                           \
  } while (false)

/* signatures of user-defined auxiliary functions */
using AuxAct = std::function<void(bool)>;
using AuxChk = std::function<void(uint64_t)>;

/**
 * DeterministicSchedule coordinates the inter-thread communication of a
 * set of threads under test, so that despite concurrency the execution is
 * the same every time.  It works by stashing a reference to the schedule
 * in a thread-local variable, then blocking all but one thread at a time.
 *
 * In order for DeterministicSchedule to work, it needs to intercept
 * all inter-thread communication.  To do this you should use
 * DeterministicAtomic<T> instead of std::atomic<T>, create threads
 * using DeterministicSchedule::thread() instead of the std::thread
 * constructor, DeterministicSchedule::join(thr) instead of thr.join(),
 * and access semaphores via the helper functions in DeterministicSchedule.
 * Locks are not yet supported, although they would be easy to add with
 * the same strategy as the mapping of sem_wait.
 *
 * The actual schedule is defined by a function from n -> [0,n). At
 * each step, the function will be given the number of active threads
 * (n), and it returns the index of the thread that should be run next.
 * Invocations of the scheduler function will be serialized, but will
 * occur from multiple threads.  A good starting schedule is uniform(0).
 */
class DeterministicSchedule : boost::noncopyable {
 public:
  /**
   * Arranges for the current thread (and all threads created by
   * DeterministicSchedule::thread on a thread participating in this
   * schedule) to participate in a deterministic schedule.
   */
  explicit DeterministicSchedule(
      const std::function<size_t(size_t)>& scheduler);

  /** Completes the schedule. */
  ~DeterministicSchedule();

  /**
   * Returns a scheduling function that randomly chooses one of the
   * runnable threads at each step, with no history.  This implements
   * a schedule that is equivalent to one in which the steps between
   * inter-thread communication are random variables following a poisson
   * distribution.
   */
  static std::function<size_t(size_t)> uniform(uint64_t seed);

  /**
   * Returns a scheduling function that chooses a subset of the active
   * threads and randomly chooses a member of the subset as the next
   * runnable thread.  The subset is chosen with size n, and the choice
   * is made every m steps.
   */
  static std::function<size_t(size_t)>
  uniformSubset(uint64_t seed, size_t n = 2, size_t m = 64);

  /** Obtains permission for the current thread to perform inter-thread
   *  communication. */
  static void beforeSharedAccess();

  /** Releases permission for the current thread to perform inter-thread
   *  communication. */
  static void afterSharedAccess();

  /** Calls a user-defined auxiliary function if any, and releases
   *  permission for the current thread to perform inter-thread
   *  communication. The bool parameter indicates the success of the
   *  shared access (if conditional, true otherwise). */
  static void afterSharedAccess(bool success);

  /** Launches a thread that will participate in the same deterministic
   *  schedule as the current thread. */
  template <typename Func, typename... Args>
  static inline std::thread thread(Func&& func, Args&&... args) {
    // TODO: maybe future versions of gcc will allow forwarding to thread
    auto sched = tls_sched;
    auto sem = sched ? sched->beforeThreadCreate() : nullptr;
    auto child = std::thread([=](Args... a) {
      if (sched) {
        sched->afterThreadCreate(sem);
        beforeSharedAccess();
        FOLLY_TEST_DSCHED_VLOG("running");
        afterSharedAccess();
      }
      SCOPE_EXIT {
        if (sched) {
          sched->beforeThreadExit();
        }
      };
      func(a...);
    }, args...);
    if (sched) {
      beforeSharedAccess();
      sched->active_.insert(child.get_id());
      FOLLY_TEST_DSCHED_VLOG("forked " << std::hex << child.get_id());
      afterSharedAccess();
    }
    return child;
  }

  /** Calls child.join() as part of a deterministic schedule. */
  static void join(std::thread& child);

  /** Calls sem_post(sem) as part of a deterministic schedule. */
  static void post(sem_t* sem);

  /** Calls sem_trywait(sem) as part of a deterministic schedule, returning
   *  true on success and false on transient failure. */
  static bool tryWait(sem_t* sem);

  /** Calls sem_wait(sem) as part of a deterministic schedule. */
  static void wait(sem_t* sem);

  /** Used scheduler_ to get a random number b/w [0, n). If tls_sched is
   *  not set-up it falls back to std::rand() */
  static size_t getRandNumber(size_t n);

  /** Deterministic implemencation of getcpu */
  static int getcpu(unsigned* cpu, unsigned* node, void* unused);

  /** Sets up a thread-specific function for call immediately after
   *  the next shared access by the thread for managing auxiliary
   *  data. The function takes a bool parameter that indicates the
   *  success of the shared access (if it is conditional, true
   *  otherwise). The function is cleared after one use. */
  static void setAuxAct(AuxAct& aux);

  /** Sets up a function to be called after every subsequent shared
   *  access (until clearAuxChk() is called) for checking global
   *  invariants and logging. The function takes a uint64_t parameter
   *  that indicates the number of shared accesses so far. */
  static void setAuxChk(AuxChk& aux);

  /** Clears the function set by setAuxChk */
  static void clearAuxChk();

 private:
  static FOLLY_TLS sem_t* tls_sem;
  static FOLLY_TLS DeterministicSchedule* tls_sched;
  static FOLLY_TLS unsigned tls_threadId;
  static thread_local AuxAct tls_aux_act;
  static AuxChk aux_chk;

  std::function<size_t(size_t)> scheduler_;
  std::vector<sem_t*> sems_;
  std::unordered_set<std::thread::id> active_;
  unsigned nextThreadId_;
  /* step_ keeps count of shared accesses that correspond to user
   * synchronization steps (atomic accesses for now).
   * The reason for keeping track of this here and not just with
   * auxiliary data is to provide users with warning signs (e.g.,
   * skipped steps) if they inadvertently forget to set up aux
   * functions for some shared accesses. */
  uint64_t step_;

  sem_t* beforeThreadCreate();
  void afterThreadCreate(sem_t*);
  void beforeThreadExit();
  /** Calls user-defined auxiliary function (if any) */
  void callAux(bool);
};

/**
 * DeterministicAtomic<T> is a drop-in replacement std::atomic<T> that
 * cooperates with DeterministicSchedule.
 */
template <typename T>
struct DeterministicAtomic {
  std::atomic<T> data;

  DeterministicAtomic() = default;
  ~DeterministicAtomic() = default;
  DeterministicAtomic(DeterministicAtomic<T> const&) = delete;
  DeterministicAtomic<T>& operator=(DeterministicAtomic<T> const&) = delete;

  constexpr /* implicit */ DeterministicAtomic(T v) noexcept : data(v) {}

  bool is_lock_free() const noexcept { return data.is_lock_free(); }

  bool compare_exchange_strong(
      T& v0,
      T v1,
      std::memory_order mo = std::memory_order_seq_cst) noexcept {
    return compare_exchange_strong(
        v0, v1, mo, detail::default_failure_memory_order(mo));
  }
  bool compare_exchange_strong(
      T& v0,
      T v1,
      std::memory_order success,
      std::memory_order failure) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    auto orig = v0;
    bool rv = data.compare_exchange_strong(v0, v1, success, failure);
    FOLLY_TEST_DSCHED_VLOG(this << ".compare_exchange_strong(" << std::hex
                                << orig << ", " << std::hex << v1 << ") -> "
                                << rv << "," << std::hex << v0);
    DeterministicSchedule::afterSharedAccess(rv);
    return rv;
  }

  bool compare_exchange_weak(
      T& v0,
      T v1,
      std::memory_order mo = std::memory_order_seq_cst) noexcept {
    return compare_exchange_weak(
        v0, v1, mo, detail::default_failure_memory_order(mo));
  }
  bool compare_exchange_weak(
      T& v0,
      T v1,
      std::memory_order success,
      std::memory_order failure) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    auto orig = v0;
    bool rv = data.compare_exchange_weak(v0, v1, success, failure);
    FOLLY_TEST_DSCHED_VLOG(this << ".compare_exchange_weak(" << std::hex << orig
                                << ", " << std::hex << v1 << ") -> " << rv
                                << "," << std::hex << v0);
    DeterministicSchedule::afterSharedAccess(rv);
    return rv;
  }

  T exchange(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data.exchange(v, mo);
    FOLLY_TEST_DSCHED_VLOG(this << ".exchange(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  /* implicit */ operator T() const noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    FOLLY_TEST_DSCHED_VLOG(this << "() -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T load(std::memory_order mo = std::memory_order_seq_cst) const noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data.load(mo);
    FOLLY_TEST_DSCHED_VLOG(this << ".load() -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data = v);
    FOLLY_TEST_DSCHED_VLOG(this << " = " << std::hex << v);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  void store(T v, std::memory_order mo = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    data.store(v, mo);
    FOLLY_TEST_DSCHED_VLOG(this << ".store(" << std::hex << v << ")");
    DeterministicSchedule::afterSharedAccess(true);
  }

  T operator++() noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = ++data;
    FOLLY_TEST_DSCHED_VLOG(this << " pre++ -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator++(int /* postDummy */) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data++;
    FOLLY_TEST_DSCHED_VLOG(this << " post++ -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator--() noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = --data;
    FOLLY_TEST_DSCHED_VLOG(this << " pre-- -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator--(int /* postDummy */) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data--;
    FOLLY_TEST_DSCHED_VLOG(this << " post-- -> " << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator+=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data += v);
    FOLLY_TEST_DSCHED_VLOG(this << " += " << std::hex << v << " -> " << std::hex
                                << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T fetch_add(T v,
              std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data += v;
    FOLLY_TEST_DSCHED_VLOG(this << ".fetch_add(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator-=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data -= v);
    FOLLY_TEST_DSCHED_VLOG(this << " -= " << std::hex << v << " -> " << std::hex
                                << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T fetch_sub(T v,
              std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data -= v;
    FOLLY_TEST_DSCHED_VLOG(this << ".fetch_sub(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator&=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data &= v);
    FOLLY_TEST_DSCHED_VLOG(this << " &= " << std::hex << v << " -> " << std::hex
                                << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T fetch_and(T v,
              std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data &= v;
    FOLLY_TEST_DSCHED_VLOG(this << ".fetch_and(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator|=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data |= v);
    FOLLY_TEST_DSCHED_VLOG(this << " |= " << std::hex << v << " -> " << std::hex
                                << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T fetch_or(T v,
             std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data |= v;
    FOLLY_TEST_DSCHED_VLOG(this << ".fetch_or(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T operator^=(T v) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = (data ^= v);
    FOLLY_TEST_DSCHED_VLOG(this << " ^= " << std::hex << v << " -> " << std::hex
                                << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  T fetch_xor(T v,
              std::memory_order /* mo */ = std::memory_order_seq_cst) noexcept {
    DeterministicSchedule::beforeSharedAccess();
    T rv = data;
    data ^= v;
    FOLLY_TEST_DSCHED_VLOG(this << ".fetch_xor(" << std::hex << v << ") -> "
                                << std::hex << rv);
    DeterministicSchedule::afterSharedAccess(true);
    return rv;
  }

  /** Read the value of the atomic variable without context switching */
  T load_direct() const noexcept {
    return data.load(std::memory_order_relaxed);
  }
};

/**
 * DeterministicMutex is a drop-in replacement of std::mutex that
 * cooperates with DeterministicSchedule.
 */
struct DeterministicMutex {
  std::mutex m;

  DeterministicMutex() = default;
  ~DeterministicMutex() = default;
  DeterministicMutex(DeterministicMutex const&) = delete;
  DeterministicMutex& operator=(DeterministicMutex const&) = delete;

  void lock() {
    FOLLY_TEST_DSCHED_VLOG(this << ".lock()");
    while (!try_lock()) {
      // Not calling m.lock() in order to avoid deadlock when the
      // mutex m is held by another thread. The deadlock would be
      // between the call to m.lock() and the lock holder's wait on
      // its own tls_sem scheduling semaphore.
    }
  }

  bool try_lock() {
    DeterministicSchedule::beforeSharedAccess();
    bool rv = m.try_lock();
    FOLLY_TEST_DSCHED_VLOG(this << ".try_lock() -> " << rv);
    DeterministicSchedule::afterSharedAccess();
    return rv;
  }

  void unlock() {
    FOLLY_TEST_DSCHED_VLOG(this << ".unlock()");
    m.unlock();
  }
};
} // namespace test
} // namespace folly

/* Specialization declarations */

namespace folly {
namespace detail {

template <>
int Futex<test::DeterministicAtomic>::futexWake(int count, uint32_t wakeMask);

template <>
FutexResult Futex<test::DeterministicAtomic>::futexWaitImpl(
    uint32_t expected,
    std::chrono::time_point<std::chrono::system_clock>* absSystemTime,
    std::chrono::time_point<std::chrono::steady_clock>* absSteadyTime,
    uint32_t waitMask);
} // namespace detail

template <>
Getcpu::Func AccessSpreader<test::DeterministicAtomic>::pickGetcpuFunc();

} // namespace folly


text:
//----------------------------------------------------------------------------
//
// License:  See top level LICENSE.txt file
//
// Author:  David Burken
//
// Description: OSSIM Portable Network Graphics (PNG) plugin initialization
// code.
//
//----------------------------------------------------------------------------
// $Id: ossimPngPluginInit.cpp 22998 2014-11-23 21:38:13Z gpotts $

#include <ossim/plugin/ossimSharedObjectBridge.h>
#include <ossim/plugin/ossimPluginConstants.h>
#include "ossimPngReaderFactory.h"
#include "ossimPngWriterFactory.h"
#include "ossimPngCodecFactory.h"
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimCodecFactoryRegistry.h>

extern "C"
{
   static ossimSharedObjectInfo  myPngInfo;
   static ossimString thePngDescription;
   static std::vector<ossimString> thePngObjList;

   static const char* getPngDescription()
   {
      if (thePngDescription.empty())
      {
         thePngDescription = "PNG reader / writer plugin.\n";
      }
      return thePngDescription.c_str();
   }

   static int getPngNumberOfClassNames()
   {
      return (int)thePngObjList.size();
   }

   static const char* getPngClassName(int idx)
   {
      if(idx < (int)thePngObjList.size())
      {
         return thePngObjList[idx].c_str();
      }
      return (const char*)0;
   }

   /* Note symbols need to be exported on windoze... */
   OSSIM_PLUGINS_DLL void ossimSharedLibraryInitialize(ossimSharedObjectInfo** info,
                                                       const char* /*options*/)
   {
      thePngObjList.push_back("ossimPngReader");
      thePngObjList.push_back("ossimPngWriter");
      thePngObjList.push_back("ossimPngCodec");

      myPngInfo.getDescription = getPngDescription;
      myPngInfo.getNumberOfClassNames = getPngNumberOfClassNames;
      myPngInfo.getClassName = getPngClassName;

      *info = &myPngInfo;

      /* Register the readers... */
      ossimImageHandlerRegistry::instance()->
        registerFactory(ossimPngReaderFactory::instance());

      /* Register the writers... */
      ossimImageWriterFactoryRegistry::instance()->
         registerFactory(ossimPngWriterFactory::instance());

      ossimCodecFactoryRegistry::instance()->registerFactory(ossimPngCodecFactory::instance());

      ossimPngReaderFactory::instance()->getTypeNameList(thePngObjList);
      ossimPngWriterFactory::instance()->getTypeNameList(thePngObjList);
      ossimPngCodecFactory::instance()->getTypeNameList(thePngObjList);

  }

   /* Note symbols need to be exported on windoze... */
  OSSIM_PLUGINS_DLL void ossimSharedLibraryFinalize()
  {
     ossimImageHandlerRegistry::instance()->
        unregisterFactory(ossimPngReaderFactory::instance());

     ossimImageWriterFactoryRegistry::instance()->
        unregisterFactory(ossimPngWriterFactory::instance());

     ossimCodecFactoryRegistry::instance()->unregisterFactory(ossimPngCodecFactory::instance());
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.socialmoms.config;

import org.junit.experimental.categories.Category;
import org.socialmoms.init.AppInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by: Bilal Clarance, bclarance@apple.com
 * On: 4/28/14 10:00 AM
 * social-moms
 */
@Configuration
@ContextConfiguration(classes = AppInitializer.class)
@ComponentScan(basePackages = { "org.socialmoms" })
@EnableWebMvc
@Category(IntegrationTest.class)
public class TestContext extends WebMvcConfigurerAdapter {
}


text:
var mirror = debug.MakeMirror(void 0);
var json = mirror.toJSONProtocol(true);

// Check the mirror hierachy.
assertTrue(mirror instanceof debug.Mirror);
assertTrue(mirror instanceof debug.UndefinedMirror);

// Check the mirror properties.
assertTrue(mirror.isUndefined());
assertEquals('undefined', mirror.type());
assertTrue(mirror.isPrimitive());

// Test text representation
assertEquals('undefined', mirror.toText());

// Parse JSON representation and check.
var fromJSON = eval('(' + json + ')');
assertEquals('undefined', fromJSON.type);


text:
package com.commercetools.sunrise.framework.template.engine.handlebars;

import com.commercetools.sunrise.framework.SunriseModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;

import java.io.IOException;

final class HandlebarsJsonHelper<T> extends SunriseModel implements Helper<T> {

    @Override
    public CharSequence apply(final T context, final Options options) throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(context);
    }
}


text:
<?php

class AdminIcepayController extends ModuleAdminController
{
    public function __construct()
    {
        // Set variables
        $this->table = 'icepay_pminfo';
        $this->className = 'IcepayPaymentMethod';
        $this->position_identifier = 'position';
        $this->show_toolbar = false;
        $this->_orderBy = 'position';
        $this->bulk_actions = array();
        $this->shopLinkType = 'shop';
        $this->list_simple_header = true;

        // Call of the parent constructor method
        parent::__construct();

        $this->fields_list = array(
            'position' => array('title' => $this->l('Position'), 'position' => 'position', 'align' => 'center', 'class' => 'fixed-width-md'),
            'readablename' => array('title' => $this->l('Payment Method'), 'width' => 140, 'type' => 'text'),
            'displayname' => array('title' => $this->l('Display Name'), 'width' => 140, 'type' => 'text'),
            'active' => array('title' => $this->l('Enabled'), 'width' => 140, 'type' => 'bool', 'active' => 'active', 'ajax' => true,),
        );

        // Set fields form for form view
        $this->context = Context::getContext();
        $this->context->controller = $this;
        $this->fields_form = array(
            'legend' => array('title' => $this->l('Add / Edit Payment Method'), 'image' => '../img/admin/edit.gif'),
            'input' => array(
                array('type' => 'text', 'label' => $this->l('Display Name'), 'name' => 'displayname', 'size' => 30, 'required' => true),
                array('type' => 'switch', 'label' => $this->l('Active'), 'name' => 'active', 'values' => array(
                    array(
                        'id' => 'enable_test_mode_1',
                        'value' => 1,
                        'label' => $this->l('Enabled')
                    ),
                    array(
                        'id' => 'enable_test_mode_0',
                        'value' => 0,
                        'label' => $this->l('Disabled')
                    ),
                ),

                ),
            ),
            'submit' => array('title' => $this->l('Save')),

        );

        // Enable bootstrap
        $this->bootstrap = true;

        // Add actions
        $this->addRowAction('view');
        $this->addRowAction('edit');

        // Define meta and toolbar title
        $this->meta_title = $this->l('Payment Methods');
        $this->toolbar_title[] = $this->meta_title;
    }

    public function initToolbar()
    {
        $this->toolbar_btn = array();
    }

    public function ajaxProcessactiveicepayPminfo()
    {
        $target = pSQL(Tools::getValue('id_icepay_pminfo'));

        if (!empty($target)) {
            //toggle status
            $query = 'UPDATE `' . $this->module->dbPmInfo . '` SET `active` = 1 - active WHERE `id_icepay_pminfo` = ' . (int)$target;
            if (Db::getInstance()->execute($query)) {
                echo Tools::jsonEncode(array(
                    'text' => 'Values updated',
                    'success' => 1,
                ));
                die();
            }
        }

        echo Tools::jsonEncode(array(
            'text' => 'Error',
            'success' => 0,
        ));
        die();
    }

    public function processSyncIcepay()
    {
        $merchantId = Configuration::get('ICEPAY_MERCHANTID');
        $secretCode = Configuration::get('ICEPAY_SECRETCODE');
        $activeShopID = (int)Context::getContext()->shop->id;

        if (!empty($merchantId) && !empty($secretCode)) {
            IcepayPaymentMethod::syncIcepayPaymentMethods($merchantId, $secretCode, $activeShopID);
        }

        Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules', true) . '&configure=' . $this->module->name . '&tab_module=' . $this->module->tab . '&module_name=' . $this->module->name);
    }

    public function renderList()
    {
        $output = '';

        if ($this->context->shop->getContext() == Shop::CONTEXT_GROUP) {
            $message = $this->module->l('Payment method editing for shop groups is not supported');
            $tpl = $this->context->smarty->createTemplate(dirname(__FILE__) . '/../../views/templates/admin/warning.tpl');
            $tpl->assign('warningmessage', $message);
            return $tpl->fetch();
        }

        //Show massage to help users with module configuration
        if (!IcepayPaymentMethod::checkPaymentMethodsDefined((int)Context::getContext()->shop->id)) {
            $link = $this->context->link->getAdminLink('AdminModules', true) . '&configure=' . $this->module->name . '&tab_module=' . $this->module->tab . '&module_name=' . $this->module->name;
            $message = $this->module->l('Payment methods are not configured yet. Please synchronize available payment methods in module configuration ') . '' . $this->module->l('page') . '.';
            $tpl = $this->context->smarty->createTemplate(dirname(__FILE__) . '/../../views/templates/admin/warning.tpl');
            $tpl->assign('warningmessage', $message);
            $output = $tpl->fetch();
        }

        return $output . parent::renderList();
    }

    public function renderView()
    {
        $tpl = $this->context->smarty->createTemplate(dirname(__FILE__) . '/../../views/templates/admin/view.tpl');
        $tpl->assign('icepaypaymentmethod', $this->object);
        return $tpl->fetch();
    }

    public function initContent()
    {

        //Dispatcher
        $actions_list = array('sync' => 'processSyncIcepay');
        $module_action = Tools::getValue('module_action');

        if (isset($actions_list[$module_action])) {
            $this->{$actions_list[$module_action]}();
        }

        parent::initContent();
    }

    public function ajaxProcessUpdatePositions()
    {
        $way = (int)(Tools::getValue('way'));
        $id_paymentmethod = (int)(Tools::getValue('id'));
        $positions = Tools::getValue($this->table);

        foreach ($positions as $position => $value) {
            $pos = explode('_', $value);

            if (isset($pos[2]) && (int)$pos[2] === $id_paymentmethod) {
                if ($paymentmethod = new IcepayPaymentMethod((int)$pos[2])) {
                    if (isset($position) && $paymentmethod->updatePosition($way, $position)) {
                        echo 'ok position ' . (int)$position . ' for payment method ' . (int)$pos[1] . '\r\n';
                    } else {
                        echo '{"hasError" : true, "errors" : "Can not update payment method ' . (int)$id_paymentmethod . ' to position ' . (int)$position . ' "}';
                    }
                } else {
                    echo '{"hasError" : true, "errors" : "This payment method (' . (int)$id_paymentmethod . ') can t be loaded"}';
                }

                break;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="GID_MYUNIVAQ2_war_2.0esamePU" transaction-type="JTA">
    <jta-data-source>myunivaqdb</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>


text:
package com.flowci.core.test.auth;

import com.flowci.core.common.helper.ThreadHelper;
import com.flowci.core.user.domain.User;
import com.flowci.core.auth.helper.JwtHelper;
import com.flowci.domain.ObjectWrapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class JwtHelperTest {

    private final User user  = new User("test@flow.ci", "12345", User.Role.Admin, null);

    private ObjectWrapper<String> token = new ObjectWrapper<>();

    @Before
    public void createToken() {
        user.setRole(User.Role.Admin);

        token.setValue(JwtHelper.create(user, 60));
        Assert.assertNotNull(token.getValue());
    }

    @Test
    public void should_decode_token_and_get_user_id() {
        String email = JwtHelper.decode(token.getValue());
        Assert.assertEquals(user.getEmail(), email);
    }

    @Test
    public void should_verify_token() {
        boolean verify = JwtHelper.verify(token.getValue(), user, false);
        Assert.assertTrue(verify);
    }

    @Test
    public void should_fail_if_pw_changed() {
        user.setPasswordOnMd5("22345");
        boolean verify = JwtHelper.verify(token.getValue(), user, false);
        Assert.assertFalse(verify);
    }

    @Test
    public void should_fail_if_token_expired() {
        // init: set expired seconds to 1
        token.setValue(JwtHelper.create(user, 1));

        // when:
        ThreadHelper.sleep(3000);
        boolean verify = JwtHelper.verify(token.getValue(), user, true);

        // then: should be fail
        Assert.assertFalse(verify);
    }
}


text:
#ifndef _DEFAULT_SOURCE
     #define _DEFAULT_SOURCE
#endif

#include <stdlib.h>
#include <unistd.h>
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

#include "sdlib/plugin.h"
#include "modules.h"
#include "xutils.h"
#include "list.h"

static sdplist *new_sdplist (void);
static sdplugindata *new_sdplugindata (void);
static sdplugin *new_sdplugin (void);
static void unload_all_modules (void);
static int module_equals (void *c1, void *c2);
static void free_sdplugindata (sdplugindata *ptr);
static void free_sdplugin (sdplugin *ptr);

static sdplist *modules_list = NULL;
static int nb_modules = 255;

int nb_found = 0;
mod mods[255];

extern char *plugindir;

/* initialization function, locate all available modules for further use */
/* plugins must be stored in a hierarchical way in order to class them   */
/* here is the hierarchy that must be followed:                          */
/*                                                                       */
/* topdir                                                                */
/* ├── parsing                                                           */
/* │   ├── env                                                           */
/* │   │   ├── env.c                                                     */
/* │   │   ├── env.so                                                    */
/* │   │   └── Makefile                                                  */
/* │   ├── jobs                                                          */
/* │   │   ├── jobs.c                                                    */
/* │   │   ├── jobs.so                                                   */
/* │   │   └── Makefile                                                  */
/* │   └── wildcards                                                     */
/* │       ├── Makefile                                                  */
/* │       ├── wildcards.c                                               */
/* │       └── wildcards.so                                              */
/* ├── prompt                                                            */
/* │   ├── default                                                       */
/* │   │   ├── default.c                                                 */
/* │   │   ├── default.so                                                */
/* │   │   └── Makefile                                                  */
/* │   ├── dummy                                                         */
/* │   │   ├── dummy.c                                                   */
/* │   │   ├── dummy.so                                                  */
/* │   │   └── Makefile                                                  */
/* │   └── sale                                                          */
/* │       ├── Makefile                                                  */
/* │       ├── sale.c                                                    */
/* │       └── sale.so                                                   */
/* └── README                                                            */
/*                                                                       */
/* This way we'll have 2 categories: prompt and parsing each containing  */
/* three modules: env, jobs and wildcard for the parsing category and    */
/* default, dummy and sale for the prompt category                       */
/*                                                                       */
/* /!\      The .so file *MUST* be named as the directory name       /!\ */
/*                                                                       */
/* There are currently 3 categories implemented: prompt, parsing and     */
/* builtin                                                               */
void
init_modules (void)
{
    struct dirent **files = NULL;
    /* opening the top directory */
    int nbfiles = scandir (plugindir, &files, NULL, NULL);
    int i, j;
    xdebug (NULL);
    modules_list = new_sdplist ();
    for (i = 0; i < nbfiles; i++)
    {
        /* locate the directories within the top directory */
        if (S_ISDIR(DTTOIF(files[i]->d_type)) &&
            xstrcmp (files[i]->d_name, ".") != 0 &&
            xstrcmp (files[i]->d_name, "..") != 0)
        {
            struct dirent **subfiles = NULL;
            int nbsubfiles;
            char *path;
            size_t len = xstrlen (plugindir) + xstrlen (files[i]->d_name) + 2;
            path = xmalloc (len * sizeof (char));
            snprintf (path, len, "%s/%s", plugindir, files[i]->d_name);
            /* open this subdirectory */
            nbsubfiles = scandir (path, &subfiles, NULL, NULL);
            xfree (path);
            for (j = 0; j < nbsubfiles; j++)
            {
                /* record each subdirectory */
                if (nb_found < nb_modules &&
                    S_ISDIR(DTTOIF(subfiles[j]->d_type)) &&
                    xstrcmp (subfiles[j]->d_name, ".") != 0 &&
                    xstrcmp (subfiles[j]->d_name, "..") != 0)
                {
                    mods[nb_found].type = xstrdup (files[i]->d_name);
                    mods[nb_found].name = xstrdup (subfiles[j]->d_name);
                    nb_found++;
                }
                xfree (subfiles[j]);
            }
            xfree (subfiles);
        }
        xfree (files[i]);
    }
    xfree (files);
}

/* clearing function */
void
clear_modules (void)
{
    int i;
    xdebug (NULL);
    /* unload each loaded plugins */
    unload_all_modules ();
    /* frees memory */
    free_sdplist (modules_list);

    for (i = 0; i < nb_found; i++)
    {
        xfree (mods[i].type);
        xfree (mods[i].name);
        mods[i].name = NULL;
        mods[i].type = NULL;
    }
    nb_found = 0;
}

/* unload all loaded plugins */
static void
unload_all_modules (void)
{
    sdplugin *tmp = modules_list->head;
    while (tmp != NULL)
    {
        sdplugin *tmp2 = tmp->next;
        if (tmp->content->loaded)
        {
            unload_module (tmp->content);
        }
        tmp = tmp2;
    }
}

/* allocate memory for a new plugin list */
static sdplist *
new_sdplist (void)
{
    sdplist *ret = xcalloc (1, sizeof(*ret));
    ret->head = NULL;
    ret->tail = NULL;
    ret->size = 0;

    return ret;
}

/* allocate memory for a new plugin (data) */
static sdplugindata *
new_sdplugindata (void)
{
    sdplugindata *ret = xcalloc (1, sizeof (*ret));

    ret->name = NULL;
    ret->prio = 0;
    ret->loaded = FALSE;
    ret->type = UNKNOWN;
    ret->init = NULL;
    ret->clean = NULL;
    ret->main = NULL;
    ret->config = NULL;
    ret->lib = NULL;

    return ret;
}

/* allocate memory for a new plugin (element in the list) */
static sdplugin *
new_sdplugin (void)
{
    sdplugin *ret = xcalloc (1, sizeof (*ret));
    ret->content = new_sdplugindata ();

    ret->next = NULL;
    ret->prev = NULL;

    return ret;
}

/* allocate memory for a new empty element for the plugin list */
static sdplugin *
new_sdplugin_empty (void)
{
    sdplugin *ret = xcalloc (1, sizeof (*ret));
    ret->content = NULL;

    ret->next = NULL;
    ret->prev = NULL;

    return ret;
}

/* frees the plugin (data) */
static void
free_sdplugindata (sdplugindata *ptr)
{
    if (ptr != NULL)
    {
        xfree (ptr);
    }
}

/* frees the plugin container */
static void
free_sdplugin (sdplugin *ptr)
{
    xdebug (NULL);
    if (ptr != NULL)
    {
        /* recursively frees content */
        free_sdplugindata (ptr->content);
        xfree (ptr);
    }
}

/* frees the plugin list */
void
free_sdplist (sdplist *ptr)
{
    if (ptr != NULL)
    {
        sdplugin *tmp = ptr->head;
        while (tmp != NULL)
        {
            sdplugin *tmp2 = tmp->next;

            free_sdplugindata (tmp->content);
            /* we remove the head of the list each time so we don't need to
             * increase our index */
            list_remove_id ((sdlist **)&ptr, 0, NULL);

            tmp = tmp2;
        }
        xfree (ptr);
    }
}

/* duplicates a plugin (data) */
static sdplugindata *
copy_sdplugindata (sdplugindata *src)
{
    sdplugindata *ret = NULL;
    if (src != NULL)
    {
        ret = new_sdplugindata ();
        if (src->lib != NULL)
            memcpy (&(ret->lib), &(src->lib), sizeof (ret->lib));
        if (src->init != NULL)
            memcpy (&(ret->init), &(src->init), sizeof (ret->init));
        if (src->clean != NULL)
            memcpy (&(ret->clean), &(src->clean), sizeof (ret->clean));
        if (src->main != NULL)
            memcpy (&(ret->main), &(src->main), sizeof (ret->main));
        if (src->config != NULL)
            memcpy (&(ret->config), &(src->config), sizeof (ret->config));
        ret->name = src->name;
        ret->prio = src->prio;
        ret->type = src->type;
        ret->loaded = src->loaded;
    }
    return ret;
}

/* duplicates a plugin */
static sdplugin *
copy_sdplugin (sdplugin *src)
{
    sdplugin *ret = NULL;
    if (src != NULL)
    {
        ret = new_sdplugin_empty ();
        ret->content = copy_sdplugindata (src->content);
    }
    return ret;
}

/* comparison function based on the plugin name */
static int
module_equals (void *c1, void *c2)
{
    sdplugindata *tmp = (sdplugindata *)c1;
    sdplugindata *tmp2 = (sdplugindata *)c2;
    return xstrcmp (tmp->name, tmp2->name);
}

/* determines if a module has already been loaded */
unsigned int
is_module_present (const char *name)
{
    sdplugindata *tmp = new_sdplugindata ();
    int ret;
    tmp->name = name;
    ret = list_get_id ((sdlist *)modules_list, (void *)tmp, module_equals, FALSE);
    free_sdplugindata (tmp);
    return (ret != -1);
}

/* calls the main functions of the plugins present in the given list */
int
foreach_module (sdplist *list, void **data, function f)
{
    int r = 1;
    if (list != NULL)
    {
        sdplugin *tmp = list->head;
        while (tmp != NULL && r == 1)
        {
            if ((f & CLEAN) && tmp->content->clean != NULL)
                tmp->content->clean ();
            if (f & INIT)
                tmp->content->init (tmp->content);
            if (f & MAIN)
                r = tmp->content->main (data);
            if ((f & CONFIG) && tmp->content->config != NULL)
                tmp->content->config (data);
            tmp = tmp->next;
        }
    }
    return r;
}

/* comparison function based on the plugin priority */
static int
module_order (const void *m1, const void *m2)
{
    const sdplugin *p1 = * (sdplugin * const *) m1;
    const sdplugin *p2 = * (sdplugin * const *) m2;

    return (p1->content->prio - p2->content->prio);
}

/* returns a list of plugins of a given type */
sdplist *
get_modules_list_by_type (sdplugin_type type)
{
    sdplist *ret = NULL;
    sdplugin *curr = modules_list->head;
    int cpt = 0;
    /* first of all, are there any plugins of the given type? */
    while (curr != NULL)
    {
        if (curr->content->type & type)
            cpt++;
        curr = curr->next;
    }

    if (cpt < 1)
        return NULL;

    ret = new_sdplist ();
    sdplugin **tmp = xcalloc (cpt, sizeof (*tmp));
    int i = 0;

    curr = modules_list->head;
    while (curr != NULL && i < cpt)
    {
        /* we store a copy of all the plugins we found in a temporary array */
        if (curr->content->type & type)
        {
            tmp[i] = copy_sdplugin (curr);
            i++;
        }
        curr = curr->next;
    }

    /* we can then sort the array by plugin priority */
    qsort (tmp, cpt, sizeof (*tmp), module_order);

    /* we finally populate our list */
    for (i = 0; i < cpt; i++)
        list_append ((sdlist **)&ret, (sddata *)tmp[i]);

    xfree (tmp);

    return ret;
}

/* unload a module by its name */
void
unload_module_by_name (const char *name)
{
    sdplugin *tmp = modules_list->head;
    int cpt = 0;
    while (tmp != NULL)
    {
        if (xstrcmp (tmp->content->name, name) == 0)
        {
            unload_module (tmp->content);
            free_sdplugindata (tmp->content);
            list_remove_id ((sdlist **)&modules_list, cpt, NULL);
            break;
        }
        tmp = tmp->next;
        cpt++;
    }
}

/* unload a module */
void
unload_module (sdplugindata *ptr)
{
    if (ptr != NULL && ptr->loaded)
    {
        sd_info ("Unloading '%s' module\n", ptr->name);
        if (ptr->clean != NULL)
            ptr->clean ();
        if (ptr->lib != NULL)
            dlclose (ptr->lib);
        ptr->loaded = FALSE;
    }
}

/* load a module by its name */
unsigned int
load_module_by_name (const char *name)
{
    char *path;
    int i;
    size_t len;
    unsigned int found = FALSE;
    /* is the module present? */
    for (i = 0; i < nb_found; i++)
    {
        if (xstrcmp (name, mods[i].name) == 0)
        {
            found = TRUE;
            /*
             * the full path is something like:
             * plugindir/type/name/name.so
             * so the length is 3 '/' + ".so" + '\0' = 7 char + length of the
             * rest
             */
            len = (xstrlen (name) * 2) + xstrlen (plugindir) + 7 +
                  xstrlen (mods[i].type);
            break;
        }
    }
    if (!found)
        return FALSE;

    /* build the full path of the plugin */
    path = xmalloc (len * sizeof (char));
    snprintf (path, len, "%s/%s/%s/%s.so", plugindir, mods[i].type,
                                           name, name);
    load_module (path);
    xfree (path);

    return TRUE;
}

/* load a module by its full path */
/*
The plugins MUST implements at least the 'sd_plugin_init' and 'sd_plugin_main'
functions. In option they can also implement the 'sd_plugin_clean' function.
They must include the sdlib/plugin.h header.

Here is an empty one:

#include <stdio.h>
#include <sdlib/plugin.h>

void
sd_plugin_init (sdplugindata *ptr)
{
    ptr->name = "example";
    ptr->prio = 1;
    ptr->type = PROMPT;
}

int
sd_plugin_main (void **data)
{
    (void) data;
    fprintf (stdout, "$ ");

    return 1;
}

void
sd_plugin_config (void **data)
{
    (void) data;

    return;
}

void
sd_plugin_clean (void)
{
    return;
}
*/
void
load_module (const char *path)
{
    sdplugin *pl = new_sdplugin ();
    sdplugindata *ptr = pl->content;
    void *func;
    char *error = NULL;

    /* first of all we load the .so */
    ptr->lib = dlopen (path, RTLD_LAZY);
    error = dlerror ();
    if (error != NULL)
    {
        fprintf (stderr, "Unable to load the module '%s': %s\n",
                         path,
                         error);
        free_sdplugin (pl);
        return;
    }

    /* we search for an init function */
    func = dlsym (ptr->lib, "sd_plugin_init");
    error = dlerror ();
    if (error != NULL)
    {
        fprintf (stderr,
                 "Failed to locate the 'sd_plugin_init' function: %s\n",
                 error);
        dlclose (ptr->lib);
        free_sdplugin (pl);
        return;
    }
    memcpy (&(ptr->init), &func, sizeof (ptr->init));

    /* we search for a main function */
    func = dlsym (ptr->lib, "sd_plugin_main");
    error = dlerror ();
    if (error != NULL)
    {
        fprintf (stderr,
                 "Failed to locate the 'sd_plugin_main' function: %s\n",
                 error);
        dlclose (ptr->lib);
        free_sdplugin (pl);
        return;
    }
    memcpy (&(ptr->main), &func, sizeof (ptr->main));

    /* optionaly we search for a cleaning function */
    func = dlsym (ptr->lib, "sd_plugin_clean");
    error = dlerror ();
    if (error != NULL)
    {
        sd_debug ("%s\n", error);
        ptr->clean = NULL;
    }
    else
    {
        memcpy (&(ptr->clean), &func, sizeof (ptr->clean));
    }

    /* optionaly we search for a config function */
    func = dlsym (ptr->lib, "sd_plugin_config");
    error = dlerror ();
    if (error != NULL)
    {
        sd_debug ("%s\n", error);
        ptr->config = NULL;
    }
    else
    {
        memcpy (&(ptr->config), &func, sizeof (ptr->config));
    }

    ptr->loaded = TRUE;

    /* here we have a plugin with all the requirements */

    /* we call the initlialization function */
    ptr->init (ptr);
    /* the initialization function must have populate our ptr */
    /* we can check the plugin is not loaded a second time */
    if (is_module_present (ptr->name))
    {
        fprintf (stderr, "Module '%s' already loaded\n", ptr->name);
/*        unload_module (ptr);*/
        dlclose (ptr->lib);
        free_sdplugin (pl);
        return;
    }

    /* we store our plugin into the list */
    list_append ((sdlist **)&modules_list, (sddata *)pl);
    sd_info ("Module '%s' successfuly loaded\n", ptr->name);
}


text:
@interface ShiftAddressTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *infoLbl;
@property (weak, nonatomic) IBOutlet UILabel *addressLbl;

@end


text:
package org.thymeleaf.engine;

import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

import org.thymeleaf.processor.element.IElementProcessor;
import org.thymeleaf.util.ProcessorComparators;

/**
 *
 * @author Daniel Fernández
 * @since 3.0.0
 *
 */
public abstract class ElementDefinition {

    final ElementName elementName;
    private final Set<IElementProcessor> associatedProcessorsSet;
    final IElementProcessor[] associatedProcessors; // The internal representation is an array for better performance
    final boolean hasAssociatedProcessors;

    ElementDefinition(final ElementName elementName, final Set<IElementProcessor> associatedProcessors) {

        super();

        if (elementName == null) {
            throw new IllegalArgumentException("Element name cannot be null");
        }
        if (associatedProcessors == null) {
            throw new IllegalArgumentException("Associated processors cannot be null");
        }

        this.elementName = elementName;
        this.associatedProcessorsSet = Collections.unmodifiableSet(associatedProcessors);
        this.associatedProcessors = new IElementProcessor[this.associatedProcessorsSet.size()];
        int i = 0;
        for (final IElementProcessor processor : this.associatedProcessorsSet) {
            this.associatedProcessors[i++] = processor;
        }
        Arrays.sort(this.associatedProcessors, ProcessorComparators.PROCESSOR_COMPARATOR);
        this.hasAssociatedProcessors = this.associatedProcessors.length > 0;

    }

    public final ElementName getElementName() {
        return this.elementName;
    }

    public boolean hasAssociatedProcessors() {
        return this.hasAssociatedProcessors;
    }

    public Set<IElementProcessor> getAssociatedProcessors() {
        return this.associatedProcessorsSet;
    }

    public final String toString() {
        return getElementName().toString();
    }

    @Override
    public boolean equals(final Object o) {

        if (this == o) {
            return true;
        }

        if (!o.getClass().equals(this.getClass())) {
            return false;
        }

        final ElementDefinition that = (ElementDefinition) o;

        if (!this.elementName.equals(that.elementName)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return this.elementName.hashCode();
    }

}


text:
<?php if (!defined('VB_ENTRY')) die('Access denied.');

/**
 * @package vBForum
 * @subpackage Search
 * @author Kevin Sours, vBulletin Development Team
 * @version $Revision: 30635 $
 * @since $Date: 2009-05-04 17:00:33 -0700 (Mon, 04 May 2009) $
 * @copyright vBulletin Solutions Inc.
 */

require_once (DIR . '/vb/search/type.php');
require_once (DIR . '/vb/legacy/post.php');
require_once (DIR . '/packages/vbforum/search/result/post.php');
require_once (DIR . '/packages/vbforum/search/result/thread.php');

/**
* There is a type file for each search type. This is the one for posts
*
* @package vBulletin
* @subpackage Search
*/
class vBForum_Search_Type_Post extends vB_Search_Type
{
// ###################### Start fetch_validated_list ######################
/**
* vBForum_Search_Type_Post::fetch_validated_list()
* When displaying results we get passed a list of id's. This
* function determines which are viewable by the user.
*
* @param object $user
* @param array $ids : the postid's returned from a search
* @param array $gids : the group id's for the posts
* @return array (array of viewable posts, array of rejected posts)
*/
	public function fetch_validated_list($user, $ids, $gids)
	{
		require_once(DIR . '/includes/functions_forumlist.php');
		cache_moderators_once();

		global $vbulletin;
		$map = array();
		foreach ($ids AS $i => $id)
		{
			$map[$gids[$i]][] = $id;
		}

		$threads = vB_Legacy_Thread::create_array(array_unique($gids));
		$rejected_groups = array();
		foreach ($threads as $thread)
		{
			if (!$thread->can_search($user))
			{
				$rejected_groups[] = $thread->get_field('threadid');
				unset($map[$thread->get_field('threadid')]);
			}
		}

		$searchids = array();
		foreach ($map as $gid => $value)
		{
			$searchids = array_merge($searchids, $value);
		}

		$list = array_fill_keys($ids, false);
		if (count($searchids))
		{
			$posts = vB_Legacy_Post::create_array($searchids, $threads);
			foreach ($posts AS $id => $post)
			{
				$item = vBForum_Search_Result_Post::create_from_object($post);
				if ($item->can_search($user))
				{
					$list[$id] = $item;
				}
			}
		}
		return array('list' => $list, 'groups_rejected' => $rejected_groups);
	}

// ###################### Start prepare_render ######################
/**
* vBForum_Search_Type_Post::prepare_render()
* This function does setup preparatory to  rendering the search resuls.
* In this case that means checking moderation options for this user.
*
* @param object $user
* @param object $results
* @return nothing
*/
	public function prepare_render($user, $results)
	{
		foreach ($results AS $result)
		{
			$forumid = $result->get_post()->get_thread()->get_field('forumid');

			$this->mod_rights['managethread'] = ($this->mod_rights['managethread'] OR
				$user->canModerateForum($item['forumid'], 'canmanagethreads'));

			$this->mod_rights['managepost'] = ($this->mod_rights['managepost'] OR
				($user->canModerateForum($item['forumid'], 'candeleteposts') OR
					$user->canModerateForum($item['forumid'], 'canremoveposts')));

			$this->mod_rights['approvepost'] = ($this->mod_rights['approvepost'] OR
				$user->canModerateForum($item['forumid'], 'canmoderateposts'));

			$this->mod_rights['approveattachment'] = ($this->mod_rights['approveattachment'] OR
				$user->canModerateForum($item['forumid'], 'canmoderateattachments'));
		}
	}

// ###################### Start get_display_name ######################
/**
* vBForum_Search_Type_Post::get_display_name()
* Each search type has some responsibilities, one of which is to give
* its display name.
*
* @return string
*/
	public function get_display_name()
	{
		return new vB_Phrase('search', 'searchtype_posts');
	}

// ###################### Start create_item ######################
/**
* vBForum_Search_Type_Post::create_item()
* This is how the type objects are created
*
* @param integer $id
* @return vBForum_Search_Type_Post object
*/
	public function create_item($id)
	{
		return vBForum_Search_Result_Post::create($id);
	}

// ###################### Start additional_pref_defaults ######################
/**
* Each search type has some responsibilities, one of which is to tell
* what the default search preferences are.
* vBForum_Search_Type_Post::additional_pref_defaults()
*
* @return array
*/
	public function additional_pref_defaults()
	{
		return array(
			'childforums' => 1,
			'replyless'   => 0,
			'replylimit'  => 0,
			'query'       => '',
			'forumchoice' => 0,
			'prefixchoice'=> 0,
			'titleonly'   => 0,
			'nocache'     => '',
			'searchuser'  => '',
			'starteronly' => 0,
			'showposts'   => 0,
			'exactname'   => '',
			'searchdate'  => 0,
			'beforeafter' => 0,
			'sortby'      => 'dateline',
			'order' 	     => 'descending',
			'tag'         => '',
			'showposts'	  => 0);
	}

// ###################### Start can_group ######################
/**
* vBForum_Search_Type_Post::can_group()
* Each search type has some responsibilities, one of which is to tell
* whether it is groupable- Forums, for example are not, but posts are.
* They are naturally grouped by thread.
*
* @return
*/
	public function can_group()
	{
		return true;
	}

// ###################### Start group_by_default ######################
/**
* vBForum_Search_Type_Post::group_by_default()
* Each search type has some responsibilities, one of which is to tell
* whether it is grouped by default
*
* @return
*/
	public function group_by_default()
	{
		return true;
	}

// ###################### Start listUi ######################
/**
 * vBForum_Search_Type_Post::listUi()
 *This function generates the search elements for the user to search for posts
 * @param mixed $prefs : the array of user preferences / propogated form values.
 * @param mixed $contenttypeid : the content type for which we are going to
 *    search
 * @param array registers : any additional elements to be registered. These are
 * 	just passed to the template
 * @param string $template_name : name of the template to use for display. We have
 *		a default template.
 * @return $html: complete html for the search elements
 */
	public function listUi($prefs = null, $contenttypeid = null, $registers = null,
		$template_name = null)
	{
		global $vbulletin, $vbphrase;

		if (!isset($template_name))
		{
			$template_name = 'search_input_post';
		}

		if (!isset($contenttypeid))
		{
			$contenttypeid = $this->get_contenttypeid();
		}

		$template = vB_Template::create($template_name);

		if ($prefs['searchthreadid'])
		{
			if ($thread = vB_Legacy_Thread::create_from_id($prefs['searchthreadid']))
			{
				$template->register('thread_title', $thread->get_field('title'));
			}
		}

		$template->register('securitytoken', $vbulletin->userinfo['securitytoken']);
		$template->register('contenttypeid', $contenttypeid);
		$template->register('search_forum_options', $this->showForumOptions($prefs['forumchoice']));
		$template->register('tag_cloud', fetch_tagcloud('selectlist', $prefs['tags']));

		$prefix_selected = array (
			'anythread' => (empty($prefs['prefixchoice']) OR in_array('', $prefs['prefixchoice']) ) ?
				'selected="selected"' : '',
			'anyprefix' => ($prefs['prefixchoice'] AND in_array('-2', $prefs['prefixchoice'])) ?
				'selected="selected"' : '',
			'none' => ($prefs['prefixchoice'] AND in_array('-1', $prefs['prefixchoice'])) ?
				'selected="selected"' : ''
		);

		$template->register('prefix_selected', $prefix_selected);
		$template->register('search_prefix_options', vB_Search_Searchtools::getPrefixOptions($prefs['prefixchoice'], false));

		$this->setPrefs($template, $prefs,
			array(
				'select'=> array('sortby', 'order', 'forumchoice',
					'prefixchoice', 'titleonly', 'starteronly', 'searchdate',
					'beforeafter'),
				'cb' => array('childforums', 'exactname', 'nocache'),
				'value' => array('query', 'searchuser', 'tag', 'searchthreadid'),
				'rb' => array('showposts')
		 	)
		);

		vB_Search_Searchtools::searchIntroRegisterHumanVerify($template);

		if (isset($registers) and is_array($registers) )
		{
			foreach($registers as $key => $value)
			{
				$template->register($key, htmlspecialchars_uni($value));
			}
		}
		return $template->render();
	}
// ###################### Start showForumSelect ######################
/**
 * vBForum_Search_Type_Post::showForumSelect()
 * This function generates the select scrolling list for forums, use in search for posts
 */
	private function showForumOptions($forumchoice=array())
	{
		global $vbulletin, $vbphrase, $show;

		//this will fill out $searchforumids as well as set the depth param in $vbulletin->forumcache
		global $searchforumids;
		fetch_search_forumids_array();

		$options = array();
		$non_searchable_forums = array();
		foreach ($searchforumids AS $forumid)
		{
			$forum = & $vbulletin->forumcache["$forumid"];
			if (trim($forum['link']))
			{
				continue;
			}

			//note that this code relies on the fact that searchforumids is ordered so that
			//parents appear before their childern (actually the what the display works depends
			//heavily on that fact so its not much of an assumption here).

			//if the forum isn't searchable, then don't show it.
			if(!($forum['options'] & $vbulletin->bf_misc_forumoptions['indexposts']))
			{
				$non_searchable_forums[$forumid] = $forumid;
			}

			//unless it has children that are searchable.
			else
			{
				unset($non_searchable_forums[$forum['parentid']]);
			}

			$optionvalue = $forumid;
			$optiontitle = "$forum[depthmark] $forum[title_clean]";

			if (
				!($vbulletin->userinfo['forumpermissions'][$forumid] & $vbulletin->bf_ugp_forumpermissions['canviewthreads'])
			)
			{
				$optiontitle .= '*';
				$show['cantsearchposts'] = true;
			}

			$optionselected = '';

			if ($forumchoice AND in_array($forumid, $forumchoice))
			{
				$optionselected = 'selected="selected"';
				$haveforum = true;
			}

			$options[$forumid] = render_option_template($optiontitle, $forumid, $optionselected,
				'd' . min(4, $forum['depth']));
		}

		foreach ($non_searchable_forums AS $forumid)
		{
			unset($options[$forumid]);
		}

		$options = implode("", $options);
		$options =
			render_option_template($vbphrase['search_all_open_forums'], '',
				$haveforum ? '' : 'selected="selected"') .
			render_option_template($vbphrase['search_subscribed_forums'], 'subscribed') .
			$options;
		return $options;
	}

// ###################### Start get_inlinemod_options ######################
/**
* vBForum_Search_Type_Post::get_inlinemod_options()
* This tells inline moderation what options are applicable to posts
*
* @return array of options
*/
	public function get_inlinemod_options()
	{
		global $vbphrase, $show;
		$options = array();

		$mod_options = array();

		if ($this->mod_rights['managepost'])
		{
			$mod_options[$vbphrase['delete_posts']] = 'deleteposts';
			$mod_options[$vbphrase['undelete_posts']] = 'undeleteposts';
		}

		if ($this->mod_rights['deletethread'] OR $this->mod_rights['movethread'])
		{
			$mod_options[$vbphrase['delete_threads_as_spam']] = 'spamthread';
		}

		if ($this->mod_rights['approvepost'])
		{
			$mod_options[$vbphrase['approve_posts']] = 'approveposts';
			$mod_options[$vbphrase['unapprove_posts']] = 'unapproveposts';
		}

		if ($this->mod_rights['approveattachment'])
		{
			$mod_options[$vbphrase['approve_attachments']] = 'approveattachments';
			$mod_options[$vbphrase['unapprove_attachments']] = 'unapproveattachments';
		}

		if ($this->mod_rights['managethread'])
		{
			$mod_options[$vbphrase['move_posts']] = 'moveposts';
			$mod_options[$vbphrase['merge_posts']] = 'mergeposts';
			$mod_options[$vbphrase['copy_posts']] = 'copyposts';
		}

		//if we have any mod options then we add the rest
		if ($mod_options)
		{
			$options[$vbphrase['option']] = $mod_options;
			$basic_options = array();
			$basic_options[$vbphrase['view_selected_posts']] = 'viewpost';
			$basic_options[$vbphrase['clear_post_list']] = 'clearpost';
			$options ["____________________"] = $basic_options;
		}
		return $options;
	}

// ###################### Start get_inlinemod_type ######################
/**
* vBForum_Search_Type_Post::get_inlinemod_type()
* Tell what type of object this is for inline moderation
*
* @return string
*/
	public function get_inlinemod_type()
	{
		return 'post';
	}

	public function get_inlinemod_action()
	{
		return 'inlinemod.php';
	}

	public function add_advanced_search_filters($criteria, $registry)
	{
		if ($registry->GPC['searchthreadid'])
		{
			$criteria->add_group_filter($registry->GPC['searchthreadid']);

			//some special handling for searching in threads
			$vbulletin->GPC['forumchoice'] = array();
			$vbulletin->GPC['replyless'] = false;
			$vbulletin->GPC['replylimit'] = false;
		}

		if ($registry->GPC_exists['forumchoice'])
		{
			$this->add_forumid_filter($criteria, $registry->GPC['forumchoice'],
				$registry->GPC['childforums']);
		}

		if ($registry->GPC_exists['prefixchoice'])
		{
			$this->add_prefix_filter($criteria, $registry->GPC['prefixchoice']);
		}
		else if ($prefixchoice = $criteria->get_equals_filter('prefix'))
		{
			$this->add_prefix_filter($criteria, $prefixchoice);
		}

		if ($registry->GPC_exists['pollidmin'])
		{
			$this->add_pollid_filter($criteria, $registry->GPC['pollidmin'], vB_Search_Core::OP_GT);
		}

		if ($registry->GPC['pollidmax'])
		{
			$this->add_pollid_filter($criteria, $registry->GPC['pollidmin'], vB_Search_Core::OP_LT);
		}

		if ($registry->GPC['pollid'])
		{
			$this->add_pollid_filter($criteria, $registry->GPC['pollid'], vB_Search_Core::OP_EQ);
		}

		if ($registry->GPC['replylimit'] OR $registry->GPC['replylimit'] === '0')
		{
			$op = $registry->GPC['replyless'] ? vB_Search_Core::OP_LT : vB_Search_Core::OP_GT;
			$criteria->add_filter('replycount', $op, $registry->GPC['replylimit'], true);

			$criteria->add_display_strings('replycount',
				vB_Search_Searchtools::getCompareString($registry->GPC['replyless'])
				. $registry->GPC['replylimit'] . ' ' . $vbphrase['replies']);
		}
	}

	public function get_db_query_info($fieldname)
	{
		$result['corejoin']['thread'] = sprintf(self::$thread_join, TABLE_PREFIX,
				vB_Types::instance()->getContentTypeId("vBForum_Post"));

		$result['groupjoin']['thread'] = sprintf(self::$thread_group_join, TABLE_PREFIX,
				vB_Types::instance()->getContentTypeId("vBForum_Thread"));

		$result['table'] = 'thread';

		$fields = array('forumid', 'prefixid', 'replycount', 'views');
		if (in_array($fieldname, $fields))
		{
			$result['field'] = $fieldname;
		}
		else if ($fieldname == 'threadstart')
		{
			$result['field'] = 'dateline';
		}
		else if ($fieldname == 'pollid')
		{
			$result['field'] = 'pollid';
		}
		else if ($fieldname == 'views')
		{
			$result['field'] = 'views';
		}
		else if ($fieldname == 'replycount')
		{
			$result['field'] = 'replycount';
		}
		else if ($fieldname == 'lastpost')
		{
			$result['field'] = 'lastpost';
		}
		else if ($fieldname == 'forum')
		{
			$result['join']['forum'] = sprintf(self::$forum_thread_join, TABLE_PREFIX);
			$result['table'] = 'forum';
			$result['field'] = 'title';
		}
		else
		{
			return false;
		}

		return $result;
	}

	/**
	*	Add a filter for forums to search.
	*
	*	@param array $forumids
	* @param boolean $include_children -- If the children should be included.
	*/
	protected function add_forumid_filter($criteria, $forumids, $include_children)
	{
		if (in_array(' ', $forumids) OR in_array('', $forumids))
		{
			return;
		}

		global $vbulletin, $vbphrase;

		$all_forumids = fetch_search_forumids($forumids, $include_children);
		if ($all_forumids)
		{
			$criteria->add_filter('forumid', vB_Search_Core::OP_EQ, $all_forumids);

			$forum_strings =  vB_Search_Searchtools::getDisplayString('forum', $vbphrase['forum'], 'title',
				'forumid', $all_forumids,	vB_Search_Core::OP_EQ, false);
			$criteria->add_display_strings('forumid', $forum_strings .
 				( $include_children ? ' ' . $vbphrase['and_child_forums'] : ''));
		}
		else
		{
			$criteria->add_error('invalidid', $vbphrase['forum'], $vbulletin->options['contactuslink']);
		}
	}

	protected function add_prefix_filter($criteria, $prefixids)
	{
		global $vbphrase;
		if (!is_array($prefixids))
		{
			$prefixids = array($prefixids);
		}

		//if "everything" is selected, we don't need to filter.
		if (in_array(' ', $prefixids) OR in_array('', $prefixids))
		{
			return;
		}

		$restrictive = true;
		$noprefix_pos = array_search('-1',  $prefixids);
		$anyprefix = in_array('-2', $prefixids);

		//if we select thread with a prefix and threads without a prefix,
		//that's everything -- no filter
		if ($noprefix_pos !== false AND $anyprefix)
		{
			return;
		}

		//if we want any prefix don't worry about any "non special" values
		//we'll take well, anything.  The special values should already
		//be accounted for.
		if ($anyprefix)
		{
			$criteria->add_filter('prefixid', vB_Search_Core::OP_NEQ, '', false);
			return;
		}

		if ($noprefix_pos !== false)
		{
			//convert to the actual database value for no prefix
			$prefixids[$noprefix_pos] = '';

			//if "no prefix" is selected, then this isn't a restrictive filter
			//otherwise it is.
			$restrictive = false;
		}

		$criteria->add_filter('prefixid', vB_Search_Core::OP_EQ, $prefixids, $restrictive);

		$prefixes = array();
		foreach ($prefixids as $prefixid)
		{
			$prefixes[] = $vbphrase["prefix_{$prefixid}_title_rich"];
		}

		$criteria->add_display_strings($field, $vbphrase['prefix'] . ":" .
			implode( ', ' , $prefixes));
	}

	/***
	* This is needed by the poll widget, which passes "pollid > 0"
	*
	***/
	protected function add_pollid_filter($criteria, $pollids, $op)
	{
		global $vbphrase;
		if (!is_array($pollids) and $pollids and $op = vB_Search_Core::OP_EQ)
		{
			$criteria->add_filter('pollid', $op, $pollids, $restrictive);

			$criteria->add_display_strings($field, $vbphrase['poll'] . ' ' . $vbphrase['at_least']
				. ' ' . $pollid);
			return;
		}

		if (!is_array($pollids))
		{
			$pollids = array($pollids);
		}

		//if "everything" is selected, bail -- we don't need to filter.
		if (in_array(' ', $pollids) OR in_array('', $pollids))
		{
			return;
		}

		$restrictive = true;
		$pos = array_search('-1',  $pollids);

		if ($pos !== false)
		{
			//convert to the actual database value for no prefix
			$pollids[$pos] = '';

			//if "no prefix" is selected, then this isn't a restrictive filter
			//otherwise it is.
			$restrictive = false;
		}

		$criteria->add_filter('pollid', $op, $pollids, $restrictive);

		$criteria->add_display_strings($field, $vbphrase['poll'] . vB_Search_Searchtools::getCompareString($op) .
			implode( ', ' , $pollids));
	}

	protected $package = "vBForum";
	protected $class = "Post";
	protected $group_package = "vBForum";
	protected $group_class = "Thread";

	protected $type_globals = array (
		'searchthreadid'      => TYPE_INT,
		'showposts'      => TYPE_INT,
		'forumchoice'	  => TYPE_ARRAY,
		'starteronly'    => TYPE_INT,
		'prefixchoice'	  => TYPE_ARRAY,
		'childforums'	  => TYPE_BOOL,
		'replyless'  => TYPE_BOOL,
		'replylimit' => TYPE_NOHTML
	);

	private static $thread_join =
	  " INNER JOIN %sthread AS thread ON (
				searchcore.contenttypeid = %u  AND searchcore.groupid = thread.threadid)";

	private static $thread_group_join =
	  " INNER JOIN %sthread AS thread ON (
				searchgroup.contenttypeid = %u  AND searchgroup.groupid = thread.threadid)";

	private static $forum_thread_join =
		" INNER JOIN %sforum AS forum ON (thread.forumid = forum.forumid)";
}

/*======================================================================*\
|| ####################################################################
|| #
|| # SVN: $Revision: 30635 $
|| ####################################################################
\*======================================================================*/


text:
#include <bgcc.h>
#include "event_handler.h"
#include "ims_log.h"
#include "fs_struct.h"
#include "fs_opr.h"
#include "fs_mgr.h"
#include "ims_core_session_mgr.h"

using namespace bgcc;
namespace ims {

void event_handler_t::handle_ivrtransfer_event(const fs_event_t& evt) {
    debug_func("ivrtransfer", evt);

    std::string oricaller, oricalled;
    session_mgr->get_callercalled(evt.sessionid, oricaller, oricalled);

    if (strcasecmp(evt.name, "CHANNEL_PROGRESS") == 0
            || strcasecmp(evt.name, "CHANNEL_PROGRESS_MEDIA") == 0) { //agent alerting

        if (!session_mgr->rt_query_dn(edata.channel_name, DnTypeT::AgentDn)) {
            //client ring
            DEBUG_LOG("ims got client's CHANNEL_PROGRESS event, do nothing.");
            return;
        }

        //if TT_RING, signal get event CHANNEL_PROGRESS
        char transType[26] = {0};//magic number:26 ÊÇ×µÄÀàÐ͵Ä×Ö·û´®³¤¶È¡£

        if (session_mgr->get_rundata(evt.sessionid, "TransferTypeT", transType, 25)) {
            if (strncmp("TransferTypeT::TT_RING", transType, 22) == 0) {
                TRACE_LOG("transferType is TT_RING, signal get event CHANNEL_PROGRESS");
                ims_route_info_t info;

                if (!session_mgr->rt_query_session_route(evt.sessionid, info)) {
                    WARNING_LOG("query session route info failed(sid=%ld)", evt.sessionid);
                }

                info.state_signal = STATE_RING;

                if (info.psema) {
                    TRACE_LOG("after agent ring, signal get event %s", evt.name);
                    bgcc::Semaphore* psema = info.psema;
                    info.psema = NULL;

                    if (!session_mgr->rt_update_route(info.requestId, info)) {
                        WARNING_LOG("update session route info failed(requestId=%ld)", info.requestId);
                    }

                    ims_route_info_t temp;
                    session_mgr->rt_query_route(info.requestId, temp);
                    DEBUG_LOG("temp: requestId=%ld, psema=%p, state_signal = %u", temp.requestId, temp.psema,
                              temp.state_signal);
                    psema->signal();
                }
            }//if transType == TT_RING
            else {
                TRACE_LOG("transferType is not TT_RING, do nothing.");
            }
        }//if(session_mgr->get_rundata()
        else {
            WARNING_LOG("get transferType from rundata error.");
        }

        CallEventT callevent;
        session_mgr->get_channel_callstate(edata.uuid, callevent.state);

        if (callevent.state == CallStateT::SG_AlertingState) {
            return;
        }

        //agent ringring
        session_mgr->update_call_dnis(evt.sessionid, evt.callid, edata.deviceno);
        ims_tool_t::prepare_call_event(callevent, evt.timestamp,
                                       evt.sessionid, ims_tool_t::num2str(evt.callid),
                                       edata.deviceno, CallStateT::SG_AlertingState);

        callevent.eventType = CallEventTypeT::SG_InboundCall_NormalCall;
        callevent.partyNum = 2;
        callevent.otherAttr = PartyAttributeT::P_Normal;
        callevent.otherDevice = oricaller;

        session_mgr->update_channel_callstate(edata.uuid, callevent.state);
        session_mgr->add_imsevent_call(evt.sessionid, callevent);
        //session_mgr->set_callercalled(evt.sessionid, oricaller, edata.deviceno);
    } else if (strcasecmp(evt.name, "CHANNEL_ANSWER") == 0) {
        if (!session_mgr->rt_query_dn(edata.channel_name, DnTypeT::AgentDn)) {
            //client answer
            DEBUG_LOG("ims got client's CHANNEL_ANSWER event, do nothing.");
            return;
        }

        //agent answer, only if transferType is TT_ANSWER, call uuid_bridge()
        char transType[26] = {0};//magic number:26 ÊÇ×µÄÀàÐ͵Ä×Ö·û´®³¤¶È¡£

        if (session_mgr->get_rundata(evt.sessionid, "TransferTypeT", transType, 25)) {
            if (strncmp("TransferTypeT::TT_ANSWER", transType, 24) == 0) {
                TRACE_LOG("transferType is TT_ANSWER, signal get event CHANNEL_ANSWER`");
                ims_route_info_t info;

                if (!session_mgr->rt_query_session_route(evt.sessionid, info)) {
                    WARNING_LOG("query session route info failed(sid=%ld, sessionid not exist)",
                                evt.sessionid);
                }

                info.state_signal = STATE_ANSWER;

                if (info.psema) { //only when TT_RING, info.ring_sema != NULL
                    TRACE_LOG("after agent answer, signal get event %s", evt.name);
                    bgcc::Semaphore* psema = info.psema;
                    info.psema = NULL;

                    if (!session_mgr->rt_update_route(info.requestId, info)) {
                        WARNING_LOG("update session route info failed(requestId=%ld)", info.requestId);
                    }

                    psema->signal();
                }

                TRACE_LOG("transferType is TT_ANSWER, uuid_bridge agent and custom.");
                std::list<const char*> other_ids;

                if (!session_mgr->locate_otherchannel(evt.sessionid, evt.callid, edata.uuid, other_ids)
                        || other_ids.size() == 0) {
                    WARNING_LOG("sid=%ld locate_otherchannel failed,chid:[%s]", evt.sessionid, edata.uuid);
                    return;
                }

                fs_tool_t opr(ims_tool_t::get_fsno(evt.sessionid));

                if (!opr.valid()) {
                    WARNING_LOG("get opr by session=%ld failed.", evt.sessionid);
                    return;
                }

                //opr.opr().hangup(edata.uuid);//for test when uuid_bridge failed
                if (opr.opr().uuid_bridge(edata.uuid, other_ids.front()) != IMS_SUCCESS) {
                    WARNING_LOG("uuid_bridge failed, hangup both. session=%ld", evt.sessionid);
                    opr.opr().hangup(edata.uuid);
                    opr.opr().hangup(other_ids.front());
                    return;
                }
            }//if transType == TT_ANSWER
            else {
                TRACE_LOG("transferType is not TT_ANSWER, do nothing.");
            }
        }//if(session_mgr->get_rundata()
        else {
            WARNING_LOG("get transferType from rundata error.");
        }

    } else if (strcasecmp(evt.name, "CHANNEL_BRIDGE") == 0) {
        //if(edata.deviceno == oricaller){//client bridge
        TRACE_LOG("oricaller=%s, oricalled=%s", oricaller.c_str(), oricalled.c_str());
        session_mgr->update_session_operation(evt.sessionid, SOPR_MAKECALL,
                                              (edata.deviceno == oricaller) ? edata.other_channel_name : edata.channel_name);
        session_mgr->update_create_reason(evt.sessionid, SCRT_INBOUND_IVR);

        CallEventT callevent;
        ims_tool_t::prepare_call_event(callevent,
                                       evt.timestamp,
                                       evt.sessionid,
                                       ims_tool_t::num2str(evt.callid),
                                       (edata.deviceno == oricaller) ? edata.other_deviceno : edata.deviceno,
                                       CallStateT::SG_ConnectedState);

        callevent.eventType = CallEventTypeT::SG_ThisPartyAnswered_NormalCall;
        callevent.partyNum = 2;
        callevent.otherAttr = PartyAttributeT::P_Normal;
        callevent.otherDevice = (edata.deviceno == oricaller) ? edata.deviceno : edata.other_deviceno;

        session_mgr->update_channel_callstate(edata.uuid, callevent.state);
        session_mgr->add_imsevent_call(evt.sessionid, callevent);
        //}
    } else if (strcasecmp(evt.name, "CHANNEL_HANGUP") == 0) {
        std::list<const char*> other_ids;
        session_mgr->locate_otherchannel(evt.sessionid, evt.callid, edata.uuid, other_ids);

        fs_tool_t opr(ims_tool_t::get_fsno(evt.sessionid));

        if (!opr.valid()) {
            WARNING_LOG("[%ld]ivrtransfer_handler fetch_opr error.", evt.sessionid);
            return;
        }

        ims_route_info_t info;

        if (!session_mgr->rt_query_session_route(evt.sessionid, info)) {
            WARNING_LOG("query session route info failed(sid=%ld, sessionid not exist)",
                        evt.sessionid);
        }

        if (info.psema) {
            TRACE_LOG("if info.psema != NULL, signal get event %s", evt.name);
            info.psema->signal();
            info.psema = NULL;

            if (!session_mgr->rt_update_route(info.requestId, info)) {
                WARNING_LOG("update session route info failed(requestId=%ld)", info.requestId);
            }
        }

        if (session_mgr->rt_query_dn(edata.channel_name, DnTypeT::AgentDn)) { //agent hangup
            TRACE_LOG("agent hangup. edata.channelname=%s, edata.other_channel_name=%s",
                      edata.channel_name, edata.other_channel_name);
            CallEventT callevent;
            ims_tool_t::prepare_call_event(callevent, evt.timestamp, evt.sessionid,
                                           ims_tool_t::num2str(evt.callid), edata.deviceno, CallStateT::SG_IdleState);
            callevent.eventType = CallEventTypeT::SG_ThisPartyDisconnected_NormalCall;
            callevent.partyNum = 1;
            callevent.otherAttr = PartyAttributeT::P_Unknown;
            //callevent.otherDevice=oricaller;

            ims::CallStateT state;
            session_mgr->get_channel_callstate(edata.uuid, state);

            session_mgr->update_channel_callstate(edata.uuid, callevent.state);
            session_mgr->add_imsevent_call(evt.sessionid, callevent);

            //Èç¹ûתÒÆÀàÐͲ»ÊÇTT_ANSWER, ¹Ò¶Ï¿Í»§
            char transType[26] = {0};//magic number:26 ÊÇ×µÄÀàÐ͵Ä×Ö·û´®³¤¶È¡£

            if (session_mgr->get_rundata(evt.sessionid, "TransferTypeT", transType, 25)) {
                if (state != CallStateT::SG_AlertingState && //´¦ÀíûÓÐchannel_progress¾ÍÖ±½Ó¹Ò¶ÏµÄÇé¿ö¡£
                        strncmp("TransferTypeT::TT_INSTANT", transType, 25) != 0) { //¼ÙÈçÊÇINSTANT£¬¿Ï¶¨Òª¹Ò¶Ï¿Í»§
                    TRACE_LOG("channel state is not alerting and transferType is not TT_INSTANT");
                    return;
                }

                TRACE_LOG("Transfer type is %s, other_ids.size()=%ld", transType, other_ids.size());

                if (strncmp("TransferTypeT::TT_ANSWER", transType, 24) != 0  && other_ids.size() != 0) {
                    TRACE_LOG("hangup client uuid=%s", other_ids.front());
                    opr.opr().hangup(other_ids.front());
                }

                session_mgr->del_rundata(evt.sessionid, "TransferTypeT");
            } else {
                WARNING_LOG("get transferType from rundata error.");
            }
        } else { //client hangup
            TRACE_LOG("client hangup. edata.channelname=%s, edata.other_channel_name=%s"
                      "other_uuid=%s.", edata.channel_name, edata.other_channel_name, edata.other_uuid);

            if (other_ids.size() != 0) { // Èç¹ûÒѾµ÷ÓÃÁËtransferAgent
                std::string name;
                session_mgr->get_channelnamebyid(evt.sessionid, other_ids.front(), name);
                CallEventT callevent;
                ims_tool_t::prepare_call_event(callevent, evt.timestamp, evt.sessionid,
                                               ims_tool_t::num2str(evt.callid),
                                               ims_tool_t::chlname2no(name),//agent deviceno
                                               CallStateT::SG_IdleState);
                callevent.eventType  = CallEventTypeT::SG_OtherPartyDisconnected_NormalCall;
                callevent.partyNum = 1;
                callevent.otherAttr = PartyAttributeT::P_Unknown;
                //callevent.otherDevice=edata.deviceno;//client device no

                session_mgr->update_channel_callstate(edata.uuid, callevent.state);
                session_mgr->add_imsevent_call(evt.sessionid, callevent);
                //¹Ò¶Ï×øϯ
                opr.opr().hangup(other_ids.front());
            }

            //È¡Ïû·ÓÉÇëÇó
            ims_route_info_t info;

            if (!session_mgr->rt_query_session_route(evt.sessionid, info)) {
                WARNING_LOG("query session route info failed(sid=%ld, sessionid not exist)",
                            evt.sessionid);
                return;
            }

            session_mgr->rt_del_session_route(evt.sessionid);

            RouteEventT ims_event;
            ims_tool_t::prepare_route_event(ims_event, evt.sessionid, info);
            ims_event.eventType = RouteEventTypeT::RT_RouteRequestCancel;
            ims_event.reason = RouteEventReasonT::RouteReasonClientHangup;

            if (session_mgr->rt_add_imsevent_route(info.dest_reqid, ims_event)) {
                session_mgr->rt_del_route(info.requestId);
            } else {
                WARNING_LOG("add ims route event failed");
            }
        }//client hangup

        //ɾ³ý·ÓÉÐÅÏ¢
        session_mgr->rt_del_session_route(evt.sessionid);
    } else if (strcasecmp(evt.name, "OPERATION_FAILED") == 0) {
        ims_route_info_t info;

        if (!session_mgr->rt_query_session_route(evt.sessionid, info)) {
            WARNING_LOG("query session route info failed(sid=%ld, sessionid not exist)",
                        evt.sessionid);
            return;
        }

        if (info.psema) {
            TRACE_LOG("if info.psema != NULL, signal get event %s", evt.name);
            info.psema->signal();
            info.psema = NULL;

            if (!session_mgr->rt_update_route(info.requestId, info)) {
                WARNING_LOG("update session route info failed(requestId=%ld)", info.requestId);
            }
        }

        std::list<callid_t> calls;
        session_mgr->locate_call(evt.sessionid, calls);

        OtherEventT otherevent;
        otherevent.sessionid = evt.sessionid;
        otherevent.device = info.targetUri;
        otherevent.callid = ims_tool_t::num2str(calls.front());
        otherevent.eventType = OtherEventTypeT::OG_OperationFailed;
        otherevent.timestamp = ims_tool_t::get_timestamp_ms();
        session_mgr->add_imsevent_other(evt.sessionid, otherevent);

        //hangup client
        std::list<const char*> chls;
        session_mgr->get_channelsbysession(evt.sessionid, chls);
        fs_tool_t opr(ims_tool_t::get_fsno(evt.sessionid));

        if (!opr.valid()) {
            WARNING_LOG("[%ld]ivrtransfer_handler fetch_opr error.", evt.sessionid);
            return;
        }

        opr.opr().hangup(chls.front());//front is client's channel id.

        //ɾ³ý·ÓÉÐÅÏ¢
        session_mgr->rt_del_session_route(evt.sessionid);
    }//if(strcasecmp(evt.name,"OPERATION_FAILED")
}
}//namespace ims

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */


text:
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@TestFile

//@Require('TypeUtil')
//@Require('bugdouble.BugDouble')
//@Require('bugmeta.BugMeta')
//@Require('bugmeta.TagProcessor')
//@Require('bugunit.TestTag')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var TypeUtil        = bugpack.require('TypeUtil');
    var BugDouble       = bugpack.require('bugdouble.BugDouble');
    var BugMeta         = bugpack.require('bugmeta.BugMeta');
    var TagProcessor    = bugpack.require('bugmeta.TagProcessor');
    var TestTag         = bugpack.require('bugunit.TestTag');

    //-------------------------------------------------------------------------------
    // Simplify References
    //-------------------------------------------------------------------------------

    var bugmeta         = BugMeta.context();
    var spyOnFunction   = BugDouble.spyOnFunction;
    var test            = TestTag.test;

    //-------------------------------------------------------------------------------
    // Declare Tests
    //-------------------------------------------------------------------------------

    var tagProcessorInstantiationTest = {

        //-------------------------------------------------------------------------------
        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function(test) {
            this.testProcessorFunction      = function(tag) {};
            this.testTagProcessor    = new TagProcessor(this.testProcessorFunction);
        },

        //-------------------------------------------------------------------------------
        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            test.assertEqual(this.testTagProcessor.getTagProcessorFunction(), this.testProcessorFunction,
                "Assert #getTagProcessorFunction returns testProcessorFunction");
        }
    };

    var tagProcessorInstantiationMissingProcessorFunctionTest = {

        //-------------------------------------------------------------------------------
        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function(test) {

        },

        //-------------------------------------------------------------------------------
        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            var _this = this;
            test.assertThrows(function() {
                var tagProcessor = new TagProcessor();
            }, "Assert instantiating an TagProcessor without processorFunction parameter throws an Error");
        }
    };

    var tagProcessorProcessTagTest = {

        //-------------------------------------------------------------------------------
        // Setup Test
        //-------------------------------------------------------------------------------

        setup: function(test) {
            var _this                       = this;
            this.testTag             = {};
            this.testProcessorFunction      = function(tag) {
                test.assertEqual(tag, _this.testTag,
                    "Assert tag received in processorFunction is testTag");
            };
            this.testProcessorFunctionSpy   = spyOnFunction(this.testProcessorFunction);
            this.testTagProcessor    = new TagProcessor(this.testProcessorFunctionSpy);
        },

        //-------------------------------------------------------------------------------
        // Run Test
        //-------------------------------------------------------------------------------

        test: function(test) {
            this.testTagProcessor.process(this.testTag);
            test.assertTrue(this.testProcessorFunctionSpy.wasCalled(),
                "Assert processorFunction was called");
        }
    };

    //-------------------------------------------------------------------------------
    // BugMeta
    //-------------------------------------------------------------------------------

    bugmeta.tag(tagProcessorInstantiationTest).with(
        test().name("TagProcessor - instantiation Test")
    );
    bugmeta.tag(tagProcessorInstantiationMissingProcessorFunctionTest).with(
        test().name("TagProcessor - instantiation missing processorFunction Test")
    );
    bugmeta.tag(tagProcessorProcessTagTest).with(
        test().name("TagProcessor - #processTag Test")
    );
});


text:
package org.gradoop.flink.model.impl.operators.matching.single.cypher.operators.join;

import com.google.common.collect.Lists;
import org.apache.flink.api.common.operators.base.CrossOperatorBase;
import org.apache.flink.api.java.DataSet;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.operators.PhysicalOperator;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.operators.PhysicalOperatorTest;
import org.junit.Test;

import static org.gradoop.flink.model.impl.operators.matching.single.cypher.common.pojos.EmbeddingTestUtils.*;
import static org.junit.Assert.assertEquals;

public class CartesianProductTest extends PhysicalOperatorTest {
  private static GradoopId v0 = GradoopId.get();
  private static GradoopId v1 = GradoopId.get();
  private static GradoopId v2 = GradoopId.get();
  private static GradoopId e0 = GradoopId.get();
  private static GradoopId e1 = GradoopId.get();
  private static GradoopId e2 = GradoopId.get();
  private static GradoopId e3 = GradoopId.get();

  @Test
  public void testCross() throws Exception {
    Embedding l1 = new Embedding();
    l1.add(v0, PropertyValue.create("Foobar"));
    l1.add(e0, PropertyValue.create(42));
    l1.add(v1);
    Embedding l2 = new Embedding();
    l2.add(e1, PropertyValue.create("Foobar"));
    l2.add(e2, PropertyValue.create(42));
    l2.add(e3);
    DataSet<Embedding> left = getExecutionEnvironment().fromElements(l1, l2);

    Embedding r1 = new Embedding();
    r1.add(v2, PropertyValue.create("Baz"));
    r1.add(e1);
    Embedding r2 = new Embedding();
    r2.add(v0, PropertyValue.create("Baz"));
    r2.add(e2);
    DataSet<Embedding> right = getExecutionEnvironment().fromElements(r1, r2);

    PhysicalOperator join = new CartesianProduct(
      left, right, 2,
      Lists.newArrayList(), Lists.newArrayList(),
      Lists.newArrayList(), Lists.newArrayList(),
      CrossOperatorBase.CrossHint.OPTIMIZER_CHOOSES
    );

    DataSet<Embedding> result = join.evaluate();

    assertEquals(4, result.count());

    assertEveryEmbedding(result, embedding ->
      embedding.getProperties().equals(Lists.newArrayList(
        PropertyValue.create("Foobar"),
        PropertyValue.create(42),
        PropertyValue.create("Baz")
      )
    ));

    assertEmbeddingExists(result, v0, e0, v1, v2, e1);
    assertEmbeddingExists(result, v0, e0, v1, v0, e2);
    assertEmbeddingExists(result, e1, e2, e3, v2, e1);
    assertEmbeddingExists(result, e1, e2, e3, v0, e2);
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('firestation', '0018_assign_station_number'),
    ]

    sql = """
BEGIN TRANSACTION;

-- If postgres supported negative lookbehind regexes, this'd be a little simpler
SELECT src.id, array_to_string(regexp_matches(src.newname, '(\d+)'), ',') as num, src.name
INTO TEMP tmp_fs
FROM (
	SELECT sd.id, regexp_replace(sd.name, 'Battalion\s+\d+', '') as newname, sd.name
	FROM firestation_firestation fs
	INNER JOIN firestation_usgsstructuredata sd on sd.id = fs.usgsstructuredata_ptr_id
	WHERE sd.name ~ '.*\d+.*'
		AND fs.station_number is null
) AS src;

UPDATE firestation_firestation
SET station_number = cast(tmp_fs.num as int)
FROM tmp_fs
WHERE tmp_fs.id = usgsstructuredata_ptr_id;

DROP TABLE tmp_fs;

COMMIT;
"""

    operations = [
        migrations.RunSQL(sql),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Button
            android:id="@+id/showViewBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="View with a grid" />

        <Button
            android:id="@+id/showDialogBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog with simple list" />

        <Button
            android:id="@+id/showDialogLongBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog with long list" />

        <Button
            android:id="@+id/showDialogHeadersBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog with submenus" />

        <Button
            android:id="@+id/showDialogGridBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog with a grid" />

    </LinearLayout>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_share_white_24dp" />

</android.support.design.widget.CoordinatorLayout>