text:
using System;
using System.IO;
using JiebaNet.Analyser;
using NUnit.Framework;

namespace JiebaNet.Segmenter.Tests
{
    [TestFixture]
    public class TestTfidfExtractor
    {
        private string GetFileContents(string fileName)
        {
            return File.ReadAllText(fileName);
        }

        [TestCase]
        public void TestExtractTags()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article.txt"));
            var result = tfidf.ExtractTags(text, 30);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        public void TestExtractTagsWithWeights()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article.txt"));
            var result = tfidf.ExtractTagsWithWeight(text);
            foreach (var tag in result)
            {
                Console.WriteLine("({0}, {1})", tag.Word, tag.Weight);
            }
        }

        [TestCase]
        public void TestSetStopWords()
        {
            var tfidf = new TfidfExtractor();
            // Use less stopwords than default stopword list.
            tfidf.SetStopWords(TestHelper.GetResourceFilePath("stop_words_test.txt"));
            var text = GetFileContents(TestHelper.GetResourceFilePath("article.txt"));
            var result = tfidf.ExtractTags(text, 30);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        public void TestExtractTagsOfSportsNews()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article_sports.txt"));
            var result = tfidf.ExtractTags(text);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        public void TestExtractTagsOfSocialNews()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article_social.txt"));
            var result = tfidf.ExtractTags(text, 30);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        public void TestExtractTagsWithPos()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article_social.txt"));
            var result = tfidf.ExtractTags(text, 30, Constants.NounAndVerbPos);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        public void TestExtractIdioms()
        {
            var tfidf = new TfidfExtractor();
            var text = GetFileContents(TestHelper.GetResourceFilePath("article_social.txt"));
            var result = tfidf.ExtractTags(text, 50, Constants.IdiomPos);
            foreach (var tag in result)
            {
                Console.WriteLine(tag);
            }
        }

        [TestCase]
        [Category("Issue")]
        public void TestIssues()
        {
            // case 1
            var text = @"整併";
            var extractor = new TfidfExtractor();
            var keywords = extractor.ExtractTags(text, 10, Constants.NounPos);
            foreach (var keyword in keywords)
            {
                Console.WriteLine(keyword);
            }

            keywords = extractor.ExtractTags(text, 10, Constants.VerbPos);
            foreach (var keyword in keywords)
            {
                Console.WriteLine(keyword);
            }

            // case 2:
            text = "開発支援工具FLEXITE";
            keywords = extractor.ExtractTags(text, 10, Constants.NounPos);
            foreach (var keyword in keywords)
            {
                Console.WriteLine(keyword);
            }
        }
    }
}


text:
(function (window, undefined) {//
// Contains helper functions that will be hidden in the library's closure.
//

var isArray = function(arg)
{
  if (typeof Array.isArray !== 'undefined')
  {
    return Array.isArray(arg);
  }
  else
  {
    return Object.prototype.toString.call(arg) === '[object Array]';
  }
};

var encodePair = function(key, value, prefix)
{
  return prefix + "[" + key + "]=" + encodeURIComponent(value);
};

var encodeHash = function(hash, name)
{
  var components = [];

  for (var key in hash)
  {
    if (hash.hasOwnProperty(key))
    {
      components[components.length] = encodePair(key, hash[key], name);
    }
  }
  return components;
};

var encodeArray = function(array, name)
{
  var components = [];

  for (var i=0; i < array.length; i++)
  {
    components[components.length] = encodeHash(array[i], name + "[" + i + "]").join("&");
  }
  return components;
};

var isOnline = function()
{
  return navigator.userAgent.match(/PhantomJS/) || navigator.onLine;
};

var XHRPost = (function()
{
  var failuref = function(evt, xhr, url, handler) {
    if (handler)
    {
      var request = {
        status: xhr.status,
        headers: xhr.getResponseHeader,
        url: url
      };
      var payload = {};

      try {
          payload = JSON.parse(xhr.responseText);
      } catch (e) {}

      handler(payload, request);
    }
  };

  var successf = function(evt, xhr, url, handler) {
    if (handler)
    {
      var request = {
        status: xhr.status,
        headers: xhr.getResponseHeader,
        url: url
      };
      var payload = {};

      try {
          payload = JSON.parse(xhr.responseText);
      } catch (e) {}

      handler(payload, request);
    }
  };

  var that = {

    send: function(url, data, onSuccess, onFailure)
    {
      var string = JSON.stringify(data);
      var self = this;

      var xhr = new XMLHttpRequest();

      xhr.addEventListener("load", function(evt) {
        if (xhr.status !== 200 && xhr.status !== 201) {
          failuref(evt, xhr, url, onFailure);
        }
        else {
          successf(evt, xhr, url, onSuccess);
        }
      }, true);

      xhr.addEventListener("error", function(evt) {
        failuref(evt, xhr, url, onFailure);
      });

      xhr.open("POST", url);
      xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');

      xhr.send(string);
    }
  };

  return that;

})();

var Pixel = (function() {

  var counter   = 9900;
  var wrapperId = 'sample-js-iframes';

  var insertElement = function(url, callback)
  {
    var hook   = document.getElementById(wrapperId);

    if (!hook)
    {
      var body = document.getElementsByTagName("body")[0];
      hook = document.createElement('div');
      hook.id = wrapperId;
      hook.style.display = 'none';
      hook.style.width   = "0";
      hook.style.height  = "0";
      hook.style.margin  = "0";
      body.insertBefore(hook, body.childNodes[0]);
    }

    var element = document.createElement('iframe');
    var key     = "sample-key-" + counter++;

    function handler()
    {
      if (callback)
      {
        callback();
      }
      hook.removeChild(element);
    }

    element.onload  = handler;
    element.onerror = handler;

    element.src = url;
    element.id = key;
    element.style.position = "fixed";
    element.style.width    = "1px";
    element.style.height   = "1px";
    element.style.border   = "0";
    element.style.margin   = "0";
    element.style.padding  = "0";
    element.style.left     = "0";
    element.style.top      = "0";

    hook.appendChild(element);
  };

  var that = {

    send: function(url, data, onSuccess, onFailure)
    {
      var str = "";

      if (isArray(data.p))
      {
        str = encodeArray(data.p, 'p').join("&");
      }
      else if (typeof data.p === "object")
      {
        str = encodeHash(data.p, 'p').join("&");
      }

      if (url.indexOf("?") === -1)
      {
        url += "?" + str;
      }
      else
      {
        url += "&" + str;
      }

      insertElement(url, onSuccess);
    }
  };

  return that;
})();

var createGroup = function() {
  return {
    callback: function() {},
    events: []
  };
};

var connector = (function() {
  var queue = [], group = createGroup(),
      sending = false, running = false, timer = null, grouping = false,
      timeout=500, maxTimeout=60000, failureCount=0;

  var that = {

    useXHR: true,

    start: function() {
      if (running) {
        return ;
      }
      running = true;
      timer = setInterval(function() {
        that.sendNext();
      }, 5000);
    },

    stop: function() {
      if (!running) {
        return ;
      }
      running = false;
      clearInterval(timer);
    },

    isRunning: function() {
      return running === true;
    },

    setRequestMethod: function(method)
    {
      this.useXHR = method === "xhr";
    },

    length: function () {
      return queue.length;
    },

    isEmpty: function() {
      return queue.length === 0;
    },

    isSending: function() {
      return sending === true;
    },

    startGroup: function() {
      grouping = true;
    },

    endGroup: function() {
      var tmp = group;
      grouping = false;

      if (group.events.length === 0) {
        return ;
      }

      group = createGroup();
      this.add(tmp.url, tmp.events, tmp.callback);
    },

    isGroup: function() {
      return grouping;
    },

    add: function(url, event, callback) {
      if (grouping) {
        if (callback) {
          var gc = group.callback;
          group.callback = function() {
            callback.apply(this, arguments);
            gc.apply(this, arguments);
          };
        }
        group.events[group.events.length] = event;
        group.url = url; // last url will win
      }
      else {
        queue[queue.length] = {
          event: event,
          callback: callback,
          url: url
        };
        this.sendNext();
      }
    },

    clear: function() {
      queue = [];
    },

    sendNext: function() {
      if (!running || !isOnline() || sending || this.isEmpty()) {
        return ;
      }

      sending = true;
      var data = queue[0];
      var self = this;

      var url = data.url;
      var payload = { p: data.event };

      var success = function(payload, request)
      {
        queue.shift();
        failureCount = 0;

        sending = false;
        self.sendNext();
        if (typeof data.callback === "function")
        {
          data.callback.call(data.callback, payload, request);
        }
      };

      var error = function(payload, request)
      {
        sending = false;
        failureCount += 1;

        if (request.status === 400 || request.status === 500)
        {
          queue.shift();
          self.sendNext();

          if (typeof data.callback === "function")
          {
            data.callback.call(data.callback, payload, request);
          }
        }
        else
        {
          setTimeout(function() {
            self.sendNext();
          }, Math.min(timeout * failureCount, maxTimeout));
        }
      };

      if (this.useXHR) {
        XHRPost.send(url, payload, success, error);
      }
      else {
        Pixel.send(url, payload, success, error);
      }
    }
  };

  document.addEventListener("online", function() {
    that.sendNext();
  });
  document.addEventListener("offline", function() {
    // presently nothing to do on going offline.
  });

  that.start();

  return that;

})();
var chooseProtocol = function()
{
  var protocol = (location.protocol || "https:");
  if (protocol !== "http:" && protocol !=="https:")
  {
    protocol = "https:";
  }
  return protocol;
};

var endpoint       = chooseProtocol() + "//events.psiori.com/sample/v01/event",
    sdk            = "Sample.JS",
    sdk_version    = "0.0.5",
    installToken   = null,
    appToken       = null,
    sessionToken   = null,
    module         = null,
    userId         = null,
    email          = null,
    platform       = null,
    client         = null,
    client_version = null,
    longitude      = null,
    latitude       = null,
    ad_referer     = null,
    ad_campaign    = null,
    ad_placement   = null,
    locale         = null,
    autoping       = null,
    host           = null,
    facebook_id    = null,
    country_code   = null,
    present_page_id= null,
    timestamp      = null,
    browserMode    = true,
    debugMode      = false,
    forceDate      = false,
    acc_value      = null;

var getItemInStorage = function(key, storage)
{
  storage = storage || "sessionStorage";

  try // safari on private settings (do not allow websites to store local data)
  {   // throws a security exception already when trying to get the typeof.
    if (typeof window[storage] !== "undefined")
    {
      return window[storage].getItem(key);
    }
  }
  catch (e)
  {}

  return null;
};

var setItemInStorage = function(key, value, storage)
{
  storage = storage || "sessionStorage"; // default is sessionStorage

  try // safari on private settings (do not allow websites to store local data)
  {   // throws a security exception already when trying to get the typeof.
    if (typeof window[storage] !== "undefined")
    {
      window[storage].setItem(key, value);
      return window[storage].getItem(key);
    }
  }
  catch (e)
  {}

  return null;
};

var removeItemInStorage = function(key, storage)
{
  storage = storage || "sessionStorage"; // default is sessionStorage

  try // safari on private settings (do not allow websites to store local data)
  {   // throws a security exception already when trying to get the typeof.
    if (typeof window[storage] !== "undefined")
    {
      window[storage].removeItem(key);
    }
  }
  catch (e)
  {}

  return null;
};

var setPageId = function(page_id)
{
  present_page_id = page_id;
  return setItemInStorage('page_id', page_id);
};

var getPageId = function()
{
  return getItemInStorage('page_id') || present_page_id || null;
};

var clearPageId = function()
{
  present_page_id = null;
  removeItemInStorage('page_id');
};

var mergeParams = function(userParams, eventName, eventCategory)
{
  var params = {};

  var add = function(key, value)
  {
    // we'll add "0" but ignore value that equals null
    if (key && typeof value !== "undefined" && (typeof value === "number" || value))
    {
      params[key] = value;
    }
  };

  add("sdk",            sdk);
  add("sdk_version",    sdk_version);

  add("platform",       userParams.platform       || platform);
  add("client",         userParams.client         || client);
  add("client_version", userParams.client_version || client_version);

  add("event_name",     eventName);
  add("app_token",      appToken);
  add("install_token",  installToken);
  add("session_token",  sessionToken);
  add("debug",          debugMode);
  add("force_date",     forceDate);
  add("timestamp",      userParams.timestamp || timestamp || Math.round(new Date().getTime() /1000));
  add("user_id",        userId);

  add("event_category", eventCategory || "custom");
  add("module",         userParams.module || module);
  add("content_id",     userParams.content_id);
  add("content_ids",    userParams.content_ids);
  add("content_type",   userParams.content_type);
  add("page_id",        userParams.page_id || getPageId());
  add("translation",    userParams.translation);

  add("parameter1",     userParams.parameter1);
  add("parameter2",     userParams.parameter2);
  add("parameter3",     userParams.parameter3);
  add("parameter4",     userParams.parameter4);
  add("parameter5",     userParams.parameter5);
  add("parameter6",     userParams.parameter6);

  add("callback",       userParams.callback);
  add("automatic",      userParams.automatic);

  if (eventName === "purchase" ||
      eventName === "chargeback")
  {
    add("pur_provider",           userParams.pur_provider);
    add("pur_gross",              userParams.pur_gross);
    add("pur_currency",           userParams.pur_currency);
    add("pur_country_code",       userParams.pur_country_code);
    add("pur_earnings",           userParams.pur_earnings);
    add("pur_product_sku",        userParams.pur_product_sku);
    add("pur_product_category",   userParams.pur_product_category);
    add("pur_receipt_identifier", userParams.pur_receipt_identifier);
  }

  if (eventName === "session_start"  ||
      eventName === "session_update" ||
      eventName === "session_resume" ||
      (eventCategory && eventCategory === "account"))
  {
    add("email",         userParams.email     || email);
    add("locale",        userParams.locale    || locale);

    add("ad_referer",    userParams.ad_referer   || ad_referer);
    add("ad_campaign",   userParams.ad_campaign  || ad_campaign);
    add("ad_placement",  userParams.ad_placement || ad_placement);

    add("longitute",     userParams.longitude || longitude);
    add("latitude",      userParams.latitude  || latitude);

    add("country_code",  userParams.country_code  || country_code);
    add("facebook_id",   userParams.facebook_id   || facebook_id);

    add("target_group",  userParams.target_group);

    if (browserMode)
    {
      add("http_referrer", document.referrer);
      add("http_request", window.location.href);
    }

    // send host only, if explicitly set or presently in browser mode
    add("host", host || (browserMode ? window.location.host : null));
  }
  if (eventCategory === "custom")
  {
    add("acc_value", userParams.acc_value || acc_value);
  }
  return params;
};

var randomToken = function(length)
{
  var str = "";

  for (var i=0; i < length; ++i)
  {
    if (i > 0 && i % 4 === 0)
    {
      str += "-";
    }
    str += Math.floor(16*Math.random()).toString(16).toUpperCase();
  }

  return str;
};

var Sample =
{
  PLATFORM_BROWSER:  'browser',
  PLATFORM_IOS:      'ios',
  PLATFORM_ANDROID:  'android',
  PLATFORM_WINDOWS:  'windows',
  PLATFORM_FACEBOOK: 'facebook',

  init: function(params)
  {
    if (!(installToken = getItemInStorage('SampleToken', 'localStorage')))
    {
      setItemInStorage('SampleToken', (installToken = randomToken(24)), 'localStorage');
    }

    if (!(sessionToken = getItemInStorage('SampleToken', 'sessionStorage')))
    {
      setItemInStorage('SampleToken', (sessionToken = randomToken(32)), 'sessionStorage');
    }

    platform = this.PLATFORM_BROWSER;
    connector.setRequestMethod("xhr");
  },

  /** Stops the tracking of user events */
  stop: function()
  {
    connector.stop();
  },

  /** Resumes the tracking of user events */
  resume: function()
  {
    connector.start();
  },

  /** Sets the endpoint.
    * The endpoint specifies the location where the events will be send to
    */
  setEndpoint: function(newEndpoint)
  {
    endpoint = newEndpoint;
  },

  /** Returns the endpoint */
  getEndpoint: function()
  {
    return endpoint;
  },

  /** Sets the method being used to communicate with the event server.
    * request methods to choose from: xhr (recommended), img (legacy,
    * works across different origins), iframe (legacy with same origin)
    */
  setRequestMethod: function(method)
  {
    connector.setRequestMethod(method);
  },

  /** Sets the app token.
    * Remember that it should be unique across all your apps
    */
  setAppToken: function(newAppToken)
  {
    appToken = newAppToken;
  },

  /** Sets the module.
    * Probably you want to separate your app into parts for better event
    * evaluation
    */
  setModule: function(newModule)
  {
    module = newModule;
  },

  /** Sets the plattform
    * E.g. iOS, android
    */
  setPlatform: function(newPlatform)
  {
    platform = newPlatform;
  },

  /** Returns the current platform
    */
  getPlatform: function()
  {
    return platform;
  },

  /** Sets the client id */
  setClient: function(clientId)
  {
    client = clientId;
  },

  /** Sets the clients version */
  setClientVersion: function(newClientVersion)
  {
    client_version = newClientVersion;
  },

  /** Sets the user id of the current user */
  setUserId: function(newUserId)
  {
    userId = newUserId;
  },

  /** Sets the facebook id of the current facebook user */
  setFacebookId: function(newFacebookId)
  {
    facebook_id = newFacebookId;
  },

  /** Sets the email of the current user
    */
  setEmail: function(newEmail)
  {
    email = newEmail;
  },

  /** Sets the users location in form of latitude and longitude
    */
  setLocation: function(newLongitude, newLatitude)
  {
    longitude = newLogitude;
    latitude = newLatitude;
  },

  /** Sets the local
    * E.g. DE, EN
    */
  setLocale: function(newLocale)
  {
    locale = newLocale;
  },

  /** Sets the ad referrer, campaign and placement for all events
    */
  setReferer: function(referer, campaign, placement)
  {
    ad_referer = referer || null;
    ad_campaign = campaign || null;
    ad_placement = placement || null;
  },

  /** Enable debug mode if the event should not be considered in evaluations
    */
  setDebug: function(flag)
  {
    debugMode = flag;
  },

  /** Forces Psiori to use the client date although it's unreliable
    */
  setForceDate: function(flag)
  {
    forceDate = flag;
  },

  /** Usually, the tracking SDK uses now as the timestamp, but
    * with this method Sample.JS can be forced to send any
    * arbitrary event creation date to the server. Usually
    * you'd use it in combination with setForceDate(true) to
    * force the PSIORI server to use your date instead of
    * the date the event came in. Please note, that the
    * given date will be used for all subsequent events
    * until you either set a different timestamp OR set
    * it back to null with Sample.setTimestamp(null) what
    * will cause the SDK to use NOW again.
    *
    * Alternatively, you can pass-in a timestamp with the
    * user parameters of a tracking event.
    */
  setTimestamp: function(date)
  {
    timestamp = date ? Math.round(date.getTime() /1000) : null;
  },

  /** sets the browser mode
    * Indicates whether or not the application runs in a browser. If browser mode is enabled
    * additional such as the http_referer, the http_request and the host will be send with each
    * event.
    */
  setBrowserMode: function(flag)
  {
    inBrowser = !!flag;
  },

  /** sets the hostname
    * The host name will be send with each event, if it is set explicitly or when browser mode is
    * enabled
    */
  setHost : function(hostname)
  {
    host = hostname;
  },

  /** sets the installToken
    * Only use this method when you really need to overwrite the installToken.
    * E.g when you create a hybrid mobile version or switch hosts during one session.
    * The preferred way is to let PSIORI create an installToken for each Device.
    */
  setInstallToken: function(newInstallToken)
  {
    setItemInStorage('SampleToken', (installToken = newInstallToken), 'localStorage');
  },

  /** returns the present install token */
  installToken: function()
  {
    return installToken;
  },

  /** sets the sessionToken
    * Only use this method when you really need to overwrite the sessionToken.
    * E.g when you create a hybrid mobile version or switch hosts during one session.
    * The preferred way is to let PSIORI create an sessionToken for each session.
    */
  setSessionToken: function(newSessionToken)
  {
    setItemInStorage('SampleToken', (sessionToken = newSessionToken), 'sessionStorage');
  },

  /** returns the present session token */
  sessionToken: function()
  {
    return sessionToken;
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   EVENT GROUPING
  //
  // /////////////////////////////////////////////////////////////////////////

  /** start an event group. All tracking events created between startGroup()
    * and endGroup() will be grouped together and send in one single HTTP
    * packet right after the closing call to endGroup(). */
  startGroup: function()
  {
    connector.startGroup();
  },

  /** closes an event group and sends all grouped events in one HTTP packet
    * to the server. */
  endGroup: function()
  {
    connector.endGroup();
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   GENERIC TRACKING EVENT
  //
  // /////////////////////////////////////////////////////////////////////////

  /** generic tracking event that could be used to send pre-defined tracking
    * events as well as user-defined, custom events. Just pass the eventName,
    * the eventCategory (used for grouping in reports of the backend) and
    * an optional hash of parameters.
    *
    * Please note that only known parameters will be passed to the server.
    * If you want to come up with your own parameters in you custom events,
    * use the six pre-defined fields "parameter1" to "parameter6" for this
    * purpose.
    *
    * Examples:
    * Sample.track('session_start', 'session'); // send the session start event
    * Sample.track('found_item', 'custom', {    // send custom item event
    *   parameter1: 'Black Stab',               // custom item name
    *   parameter2: '21',                       // level of item
    * });
    */
  track: function(eventName, eventCategory, params)
  {
    params = mergeParams(params || {}, eventName, eventCategory);
    connector.add(endpoint, params, params.callback);
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   SESSION EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  /** should be send on the start of a new session.
    * At the start of each session send one sessionStart event with an appToken. Make sure that
    * the userId is set before starting this function.
    * The params are optional.
    */
  sessionStart: function(newAppToken, newUserId, params)
  {
    appToken = newAppToken || appToken;
    userId = newUserId || userId;

    this.pageEnd({
      automatic: true
    }); // close a page that has been opened earlier.

    this.track('session_start', 'session', params);
  },

  /** should be send when the session receives an update
    * The parameters field is optional.
    */
  sessionUpdate: function(params)
  {
    this.track('session_update', 'session', params);
  },

  /** should be send when the session gets paused */
  sessionPause: function()
  {
    this.track('session_pause', 'session');
  },

  /** should be send when the session resumes */
  sessionResume: function()
  {
    this.track('session_resume', 'session');
  },

  /** sends one ping event to the server.
    * if you want to send ping events automaticaly use the autoping method
    */
  ping: function()
  {
    this.track('ping', 'session');
  },

  /** starts or stops autopinging every seconds seconds.
    * pass seconds = 0 to stop pinging. */
  autoPing: function(seconds)
  {
    var that = this;
    if (typeof seconds === "undefined")
    {
      seconds = 60;
    }
    clearTimeout(autoping);
    autoping = null;
    if (seconds && seconds > 0)
    {
      autoping = setInterval(function() {
        that.ping();
      }, seconds * 1000);
    }
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   ACCOUNT EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  /** Should be send when a new user did register
    * Each registration takes, besides the user id, an optional list of key-value pairs.
    */
  registration: function(newUserId, params)
  {
    userId = newUserId || userId;
    this.track('registration', 'account', params);
  },

  /** Should be send when an existing user signs in
    * Each sign intakes, besides the user id, an optional list of key-value pairs.
    */
  signIn: function(newUserId, params)
  {
    userId = newUserId || userId;
    this.track('sign_in', 'account', params);
  },

  /** Should be send when the account of the current user needs an update.
    * For example when an field relating to the account changes. Like the target group
    * or country
    */
  profileUpdate: function(params)
  {
    this.track('update', 'account', params);
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   CONTENT EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  /** should be send when a user views one or more contents. This event is
    * used for counting views per-content. An event should send at least one
    * content id. Multiple content ids can be passed as array. The content type
    * is optional, wheres if no type is provided the default
    * one, 'content' is taken (to distinguish this event from page-related
    * views).
    */
  contentView: function(content_ids, content_type, params)
  {
    params = params || {};
    params.content_type = content_type || params.content_type || 'content';

    if (isArray(content_ids))
    {
      params.content_ids = content_ids;
    }
    else
    {
      params.content_id = content_ids;
    }
    this.track('view', 'content', params);
  },

  /** should be send when a user interacts with one or more contents in-app
    * A content usage event should take at least one product id. Multiple
    * product ids can be passed as array. The content type is optional,
    * wheres if no type is provided the default
    * one, 'content' is taken.
    */
  contentUsage: function(content_ids, content_type, params)
  {
    params = params || {};
    params.content_type = content_type || params.content_type || 'content';

    if (isArray(content_ids))
    {
      params.content_ids = content_ids;
    }
    else
    {
      params.content_id = content_ids;
    }
    this.track('usage', 'content', params);
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //  PAGE EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  /** manually tracks a single page view / page impression. Each time you
   * send this event, the number of page impressions of the given page_id
   * will be increased by one.
   *
   * This method is the most simplest way to track page impressions. You
   * have the full control in the client what is counted and what is not
   * counted.
   *
   * Please note that this event is stateless in the sense, that it does
   * not support tracking of the time a user stayed on a particular page.
   * If you want more detailed information about page usage, use the
   * alternative methods pageStart and pageEnd instead of using this
   * method.
   *
   * Please note, if you use pageStart AND pageView, two events will be
   * send and a page view will be counted twice.
   */
  pageView: function(page_id, params)
  {
    params              = params || {};
    params.content_type = 'page';
    params.page_id      = page_id;
    this.track('view', 'content', params);
  },

  /** tracks a single view / page impression and sets the given page_id as
   * the present page viewed by the user. From hereon, ping-events will send
   * this page_id until the page impression is manually ended (by calling
   * pageEnd), another page is set with pageStart, or a call to sessionStart
   * happens.
   *
   * To indicate that the user has left this page or time shouldn't be tracked
   * any further, call pageEnd. pageEnd will be send automatically, if the
   * user browses to another page where a new sessionStart or / pageStart is
   * called, or in case you do another call to pageStart within the same session,
   * for example, because you've loaded a second page using AJAX, thus, replacing
   * the old page, but not ending the page session.
   *
   * A usual implementation would have the following lines at the start of a page
   * inside a script tag:
   *   Sample.sessionStart();
   *   Sample.pageStart(your_page_id);
   *
   * An explicit call to pageEnd is not necessary, as each page uses these calls
   * and thus would trigger an automatic page end.
   *
   * If a pageStart is NOT ended, because for example the user closed the browser
   * tab, PSIORI will first accumulate the time of the time-stamps of ping events
   * including this page id, and, if there's not even a ping, would assume a
   * default view time of 1s.
   *
   * PSIORI will also give you the precentage of page-start events that were not
   * "closed" by an end-event.
   *
   * Please note that the more simple pageView call is a completely separated
   * mechanism that does NOT interfere with pageStart / pageEnd and that you should
   * NOT mix in your implementation, as it could lead to page views being counted
   * twice. Use either pageStart/pageEnd OR pageView.
   */
  pageStart: function(page_id, params)
  {
    this.pageEnd({
      automatic: true
    }); // close a page that has been opened earlier.

    setPageId(page_id);
    this.pageView(page_id, params);
  },

  /** sends a view-end envent to indicate the user has left the present page.
   * Will only send an event, if there's a page that has been "opened" with
   * a pageStart event and that hasn't been closed so far by a corresponding
   * pageEnd call.
   */
  pageEnd: function(params)
  {
    var page_id = getPageId();

    if (page_id)
    {
      params = params || {};
      params.page_id      = page_id;
      params.content_type = 'page';

      this.track('view-end', 'content', params);
      clearPageId();
    }
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   PROGRESSION EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  // /////////////////////////////////////////////////////////////////////////
  //
  //   PURCHASE EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  /** should be send when a user triggers a purchase
    * A purchase event should take at minimum the product_id, provider(payment provider), gross,
    * currency, country and the product_category. The product id is identical with the product
    * sku.
    */
  purchase: function(product_id, params)
  {
    var userParams = params || {};
    userParams.pur_product_sku = product_id;
    this.track('purchase', 'revenue', userParams);
  },

  /** should be send when a users charges his money back
    * A chargeback event should take at minimum the product_id, provider(payment provider), gross,
    * currency, country and the product_category. The product id is identical with the product
    * sku.
    */
  chargeback: function(product_id, params)
  {
    var userParams = params || {};
    userParams.product_sku = product_id;
    this.track('chargeback', 'revenue', userParams);
  },

  // /////////////////////////////////////////////////////////////////////////
  //
  //   VIRTUAL CURRENCY EVENTS
  //
  // /////////////////////////////////////////////////////////////////////////

  isWebkit: (function()
  {
    var memo = null;

    return function()
    {
      if (memo === null)
      {
        var ua = navigator.userAgent.toLowerCase();
        memo = ua.indexOf('safari') !== -1 || ua.indexOf('chrome') !== -1;
      }
      return memo;
    };
  })(),

  isIE: (function()
  {
    var memo = null;

    return function()
    {
      if (memo === null)
      {
        var ua = navigator.userAgent;
        memo = (ua.indexOf('MSIE') !== -1 || ua.indexOf('Trident/') > 0);
      }
      return memo;
    };
  })(),

  // /////////////////////////////////////////////////////////////////////////
  //
  //   Custom events
  //
  // /////////////////////////////////////////////////////////////////////////

  /** This function can be used to send custom Events
  * an eventName has to be included. If the event is tied to some sort of
  * numeric value it can be passed with the key acc_value. If no accumulator value
  * is supplied the event will be ignored in min,max and accumulator computations.
  * However it will still be counted through the C_COUNT metric.
  */
  customEvent: function(eventName,params)
  {
    var userParams = params || {};
    this.track(eventName, 'custom', userParams);
  }

};

Sample.init();

window.Sample = Sample;
})(window);

redpajama_set_name: RedPajamaGithub


text:
Run command synchronously with administrator privilege.

## Installing

```sh
npm install runas
```

## Building
  * Clone the repository
  * Run `npm install`
  * Run `grunt` to compile the native and CoffeeScript code
  * Run `grunt test` to run the specs

## Docs

```coffeescript
runas = require 'runas'
```

### runas(command, args[, options])

* `options` Object
  * `hide` Boolean - Hide the console window, `true` by default.
  * `admin` Boolean - Run command as administrator, `false` by default.
  * `catchOutput` Boolean - Catch the stdout and stderr of the command, `false`
    by default.
  * `stdin` String - String which would be passed as stdin input.

Launches a new process with the given `command`, with command line arguments in
`args`.

This function is synchronous and returns the exit code when the `command`
finished.

When the `catchOutput` option is specified to `true`, an object that contains
`exitCode`, `stdout` and `stderr` will be returned.

## Limitations

* The `admin` option has only been implemented on Windows and OS X.
* The `stdin` option has only been implemented on POSIX systems.
* The `hide` option is only meaningful on Windows.
* When `catchOutput` is `true`,
  * on Linux `exitCode`, `stdout` and `stderr` will be returned,
  * on OS X
    * if `admin` is `false`, `exitCode`, `stdout` and `stderr` will be returned,
    * if `admin` is `true`, `exitCode` and `stdout` will be returned,
  * on Windows only `exitCode` will be returned.


text:
package de.thaso.mpt.be.domain.service;

import java.io.Serializable;
import java.util.Date;

/**
 * NickNameData
 *
 * @author thaler
 * @since 21.09.16
 */
public class NickNameData implements Serializable {

    private static final long serialVersionUID = -7049489388682590929L;

    private Long id;
    private Date since;
    private String name;
    private String nick;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public Date getSince() {
        return since;
    }

    public void setSince(final Date since) {
        this.since = since;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(final String nick) {
        this.nick = nick;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        this.password = password;
    }
}


text:
package com.asksunny.validator;

import com.asksunny.validator.annotation.ValueValidation;

public class NotWinthinValuesValidator extends WinthinValuesValidator {

	public NotWinthinValuesValidator(Class<?> targetType, Class<?> fieldType, String fieldName, ValueValidation fv) {
		super(targetType, fieldType, fieldName, fv);
		setNegate(true);
	}

	public NotWinthinValuesValidator(Class<?> fieldType, String fieldName, ValueValidation fv) {
		super(fieldType, fieldName, fv);
		setNegate(true);
	}

	public NotWinthinValuesValidator(String fieldName, ValueValidationRule rule) {
		super(fieldName, rule);
		setNegate(true);
	}

}


text:
package fi.cosky.sdk.tests;

/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import fi.cosky.sdk.*;
import fi.cosky.sdk.CoordinateData.CoordinateSystem;

public class TestHelper {
	public static API apis  = null;

	static String apiUrl = "";
	static String clientKey    = "";
	static String clientSecret = "";

	static API authenticate() {
 		if (apis == null) {
			API api = new API(apiUrl);
			api.setTimed(true);
			if (api.authenticate(clientKey, clientSecret)) {
				apis = api;
			} else {
				System.out.println("Could not authenticate, please check service and credentials");
				return null;
			}

		}
		return apis;
	}

	static UserData getOrCreateUser( API api ) {
		return getOrCreateUser(api, false);
	}

	static UserData getOrCreateUser( API api, boolean initialize ) {
		try {
			ApiData apiData = api.navigate(ApiData.class, api.getRoot());
			UserData user = new UserData();

			if (initialize) {
				UserDataSet users = api.navigate(UserDataSet.class, apiData.getLink("list-users"));
				initialize(api, users);
			}

			ResponseData createdUser = api.navigate(ResponseData.class, apiData.getLink("create-user"), user);
			user = api.navigate(UserData.class, createdUser.getLocation());

			return user;
		} catch (NFleetRequestException e) {
			System.out.println("Something went wrong");
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	static RoutingProblemData createProblem(API api, UserData user) {
		try {
			RoutingProblemData problem = new RoutingProblemData("exampleProblem");
			ResponseData created = api.navigate(ResponseData.class, user.getLink("create-problem"), problem);
			problem = api.navigate(RoutingProblemData.class, created.getLocation());
			return problem;
		} catch (NFleetRequestException e) {
			System.out.println("Something went wrong");
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	static RoutingProblemData createProblemWithDemoData(API api, UserData user) {
		RoutingProblemData problem = createProblem(api, user);
		TestData.CreateDemoData(problem, api);
		return problem;
	}

	static VehicleData getVehicle(API api, UserData user, RoutingProblemData problem) {
		try {
			TestData.CreateDemoData(problem, api);
			VehicleDataSet vehicles = api.navigate(VehicleDataSet.class, problem.getLink("list-vehicles"));
			VehicleData vehicle = null;
			vehicle = api.navigate(VehicleData.class, vehicles.getItems().get(0).getLink("self"));
			return vehicle;
		} catch (NFleetRequestException e) {
			System.out.println("Something went wrong: " + e.toString());
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	static TaskData getTask(API api, RoutingProblemData problem) {
		LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
		LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);

		CapacityData capacity = new CapacityData("Weight", 20);
		List<CapacityData> capacities = new ArrayList<CapacityData>();
		capacities.add(capacity);

		TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
		TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);

		TimeWindowData twstart = createTimeWindow(7, 20);
		ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
		timewindows.add(twstart);
		task1.setTimeWindows(timewindows);
		task2.setTimeWindows(timewindows);
		List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
		both.add(task1);
		both.add(task2);
		TaskUpdateRequest task = new TaskUpdateRequest(both);
		task.setName("testTask");
		task.setRelocationType("None");
		task.setActivityState("Active");
		try {
			ResponseData createdTask = api.navigate(ResponseData.class, problem.getLink("create-task"), task);
			TaskData td = api.navigate(TaskData.class, createdTask.getLocation());
			return td;
		} catch (NFleetRequestException e) {
			System.out.println("Something went wrong " + e.toString());
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	static TaskUpdateRequest createTaskUpdateRequest(String name) {
		LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
		LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);
		CapacityData capacity = new CapacityData("Weight", 20);
		List<CapacityData> capacities = new ArrayList<CapacityData>();
		capacities.add(capacity);
		TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);

		List<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();
		TimeWindowData tw = createTimeWindow(7, 20);
		timeWindows.add(tw);

		task1.setTimeWindows(timeWindows);
		TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);
		task2.setTimeWindows(timeWindows);
		List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
		both.add(task1);
		both.add(task2);
		TaskUpdateRequest task = new TaskUpdateRequest(both);
		task.setName(name);
		task.setRelocationType("None");
		return task;
	}

	static List<TaskUpdateRequest> createListOfTasks(int howMany) {
		List<TaskUpdateRequest> tasks = new ArrayList<TaskUpdateRequest>();
		for (int i = 0; i < howMany; i++) {
			LocationData pi = createLocationWithCoordinates(Location.TASK_PICKUP);
			LocationData de = createLocationWithCoordinates(Location.TASK_DELIVERY);

			CapacityData capacity = new CapacityData("Weight", 20);
			List<CapacityData> capacities = new ArrayList<CapacityData>();
			capacities.add(capacity);
			TaskEventUpdateRequest task1 = new TaskEventUpdateRequest(Type.Pickup, pi, capacities);
			TaskEventUpdateRequest task2 = new TaskEventUpdateRequest(Type.Delivery, de, capacities);

			TimeWindowData twstart = createTimeWindow(7, 20);
			ArrayList<TimeWindowData> timewindows = new ArrayList<TimeWindowData>();
			timewindows.add(twstart);
			task1.setTimeWindows(timewindows);
			task2.setTimeWindows(timewindows);
			List<TaskEventUpdateRequest> both = new ArrayList<TaskEventUpdateRequest>();
			both.add(task1);
			both.add(task2);
			TaskUpdateRequest task = new TaskUpdateRequest(both);
			task.setName("testTask" + i);
			task.setRelocationType("None");
			task.setActivityState("Active");
			tasks.add(task);
		}
		return tasks;
	}

	static VehicleUpdateRequest createVehicleUpdateRequest(String name) {
		ArrayList<CapacityData> capacities = new ArrayList<CapacityData>();
        capacities.add(new CapacityData("Weight", 100000));
        ArrayList<TimeWindowData> timeWindows = new ArrayList<TimeWindowData>();

        timeWindows.add(createTimeWindow(7, 20));

        LocationData startLocation = createLocationWithCoordinates(Location.VEHICLE_START);
		VehicleUpdateRequest vehicleRequest = new VehicleUpdateRequest(name, capacities, startLocation, startLocation);
		vehicleRequest.setVehicleSpeedProfile( SpeedProfile.Max80Kmh.toString() );
		vehicleRequest.setVehicleSpeedFactor(0.7);
        vehicleRequest.setTimeWindows(timeWindows);
        return vehicleRequest;

	}

	static DepotUpdateRequest createDepotUpdateRquest(String name) {
		 LocationData location = new LocationData();
         location.setCoordinatesData(new CoordinateData( 0.0, 0.0, CoordinateSystem.Euclidian ));

         ArrayList<CapacityData> capacities = new ArrayList<CapacityData>();
         capacities.add(new CapacityData("Weight", 1000));
         DepotUpdateRequest request = new DepotUpdateRequest();
         request.setLocation(location);
         request.setCapacities(capacities);
         request.setName(name);
         request.setInfo1("Info");
         return request;
	}

	static LocationData createLocationWithCoordinates(Location name) {
		CoordinateData coordinates = new CoordinateData();
		switch (name){
			case TASK_PICKUP: {
				coordinates.setLatitude(62.244958);
				coordinates.setLongitude(25.747143);
				break;
			}
			case TASK_DELIVERY: {
				coordinates.setLatitude(62.244589);
				coordinates.setLongitude(25.74892);
				break;
			}
			case VEHICLE_END: {
				coordinates.setLatitude(62.300666);
				coordinates.setLongitude(25.727949);
				break;
			}
			case VEHICLE_START:
			default: {
	            coordinates.setLatitude(62.247906);
	            coordinates.setLongitude(25.867395);
	            break;
			}

		}
		coordinates.setSystem(CoordinateSystem.Euclidian);
		LocationData data = new LocationData();
		data.setCoordinatesData(coordinates);
		return data;
	}

	static LocationData createLocationWithAddress() {
		AddressData address = new AddressData();
		address.setCity("Jyväskylä");
		address.setCountry("Finland");
		address.setPostalCode("40320");
		address.setStreet("Tuohitie");
		address.setApartmentNumber(22);

		LocationData data = new LocationData();
		data.setAddress(address);
		return data;
	}

	static VehicleData createAndGetVehicle(API api, RoutingProblemData problem, VehicleUpdateRequest request) {
		try {
			ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-vehicle"), request);
			VehicleData vehicle = api.navigate(VehicleData.class, result.getLocation());
			return vehicle;
		}
		catch (Exception e) {
			System.out.println("Something went wrong. Unable to create a vehicle.");
		}
		return null;
	}

	static TaskData createAndGetTask(API api, RoutingProblemData problem, TaskUpdateRequest request) {
		try {
			ResponseData result = api.navigate(ResponseData.class, problem.getLink("create-task"), request);
			TaskData task = api.navigate(TaskData.class, result.getLocation());
			return task;
		}
		catch (Exception e) {
			System.out.println("Something went wrong. Unable to create a task.");
		}
		return null;
	}

	enum Location{ VEHICLE_START, TASK_PICKUP, TASK_DELIVERY, VEHICLE_END };

	static TimeWindowData createTimeWindow(int start, int end) {
		Calendar calendar = Calendar.getInstance();

		calendar.set(Calendar.HOUR_OF_DAY, start);
		Date startD = calendar.getTime();

		calendar.set(Calendar.HOUR_OF_DAY, end);
		Date endD = calendar.getTime();

		TimeWindowData twd = new TimeWindowData(startD, endD);
		return twd;
	}

	static void initialize(API api, UserDataSet users) {
		try {
			if (users.getItems().size() > 0) {
				UserData us = null;
				for (UserData u : users.getItems() ) {
					us = api.navigate(UserData.class, u.getLink("self"));
					Link l = null;
					if ((l = us.getLink("delete-user")) == null) break;
					ResponseData response = api.navigate(ResponseData.class, us.getLink("delete-user"));
				}
			}
		} catch (Exception e) { System.out.println("Something went wrong deleting users " + e.getMessage()); }
	}

	static String getInfo1WithRouteEvent(RouteEventData routeEvent, TaskDataSet tasks) {
		  if (routeEvent == null) return "";
		  if (tasks == null) return "";

		  for (TaskData t : tasks.getItems()) {
		    if (t.getId() == routeEvent.getTaskId()) return t.getInfo();
		  }
		  return "";
	}
}


text:
/**
 *
 * Delete cookies visible to the current page. By providing a cookie name it just removes the single cookie.
 *
 * <example>
    :deleteSingleCookie.js
    client
        .setCookie({name: 'test', value: '123'})
        .getCookie().then(function(cookies) {
            console.log(cookies); // outputs: [{ name: 'test', value: '123' }]
        })
        .deleteCookie('test')
        .getCookie().then(function(cookies) {
            console.log(cookies); // outputs: []
        });

    :deleteMultipleCookies.js
    client
        .setCookie({name: 'test', value: '123'})
        .setCookie({name: 'test2', value: '456'})
        .getCookie().then(function(cookies) {
            console.log(cookies);
            // outputs:
            // [
            //     { name: 'test', value: '123' },
            //     { name: 'test2', value: '456' }
            // ]
        })
        .deleteCookie()
        .getCookie().then(function(cookies) {
            console.log(cookies); // outputs: []
        });
 * </example>
 *
 * @param {String=} name name of cookie to be deleted
 *
 * @uses protocol/cookie
 * @type cookie
 *
 */

module.exports = function deleteCookie (name) {

    /*!
     * parameter check
     */
    if(typeof name !== 'string') {
        name = null;
    }

    return this.cookie('DELETE', name);

};


text:
#settings-sections {
	position: absolute;
	top: 0;
	left: 0;
	width: 200px;
	bottom: 0;
}

#pluginbody,
#settings-right {
	position: absolute;
	top: 0;
	left: 212px;
	right: 0;
	bottom: 0;
}

#sectionslist {
	position: absolute;
	top: 0;
	left: 0;
	width: 260px;
	bottom: 0;
}

#preferences-box {
	position: absolute;
	top: 0;
	left: 272px;
	right: 0;
	bottom: 0;
}

#preferences-frame {
	border: 0;
	border-radius: 4px 4px 0 0;
}

#sections-table tbody td.section,
#settings-sections span.listitem a,
#settings-sections span.tablink a {
	padding-left: 36px;
	background-image: url(images/listicons.png?v=bd98.25486);
	background-position: -100px 0;
	background-repeat: no-repeat;
}

/* note: support span.tablink because this is used by plugins */
#settings-sections span.listitem a,
#settings-sections span.tablink a {
	background-position: 6px -862px;
}

#settings-sections span.selected a,
#settings-sections span.tablink.selected a {
	background-position: 6px -887px;
}

#settings-sections span.preferences a {
	background-position: 6px -431px;
}

#settings-sections span.preferences.selected a {
	background-position: 6px -455px;
}

#settings-sections span.folders a,
#sections-table #rcmrowfolders td.section {
	background-position: 6px 2px;
}

#settings-sections span.folders.selected a,
#sections-table #rcmrowfolders.selected td.section {
	background-position: 6px -22px;
}

#settings-sections span.identities a {
	background-position: 6px -478px;
}

#settings-sections span.identities.selected a {
	background-position: 6px -502px;
}

#settings-sections span.filter a {
	background-position: 6px -1746px;
}

#settings-sections span.filter.selected a {
	background-position: 6px -1770px;
}

#settings-sections span.password a {
	background-position: 6px -1795px;
}

#settings-sections span.password.selected a {
	background-position: 6px -1819px;
}

#sections-table #rcmrowgeneral td.section {
	background-position: 6px -573px;
}

#sections-table #rcmrowgeneral.selected td.section {
	background-position: 6px -598px;
}

#sections-table #rcmrowmailbox td.section {
	background-position: 6px -621px;
}

#sections-table #rcmrowmailbox.selected td.section {
	background-position: 6px -646px;
}

#sections-table #rcmrowcompose td.section {
	background-position: 6px -670px;
}

#sections-table #rcmrowcompose.selected td.section {
	background-position: 6px -695px;
}

#sections-table #rcmrowmailview td.section {
	background-position: 6px -718px;
}

#sections-table #rcmrowmailview.selected td.section {
	background-position: 6px -742px;
}

#sections-table #rcmrowaddressbook td.section {
	background-position: 6px -766px;
}

#sections-table #rcmrowaddressbook.selected td.section {
	background-position: 6px -791px;
}

#sections-table #rcmrowserver td.section {
	background-position: 6px -814px;
}

#sections-table #rcmrowserver.selected td.section {
	background-position: 6px -838px;
}

#sections-table #rcmrowcalendar td.section {
	background-position: 6px -526px;
}

#sections-table #rcmrowcalendar.selected td.section {
	background-position: 6px -550px;
}

#folderslist,
#identitieslist {
	position: absolute;
	top: 0;
	left: 0;
	width: 260px;
	bottom: 0;
}

#identities-table {
	width: 100%;
	table-layout: fixed;
}

#identities-table tbody td.mail {
	width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
}

#folder-details,
#identity-details {
	position: absolute;
	top: 0;
	left: 272px;
	right: 0;
	bottom: 0;
}

#subscription-table {
	table-layout: fixed;
}

#subscription-table tr.root td {
	font-size: 5%;
	height: 5px;
	padding: 2px;
}

#subscription-table td.name {
	width: 85%;
	overflow: hidden;
	text-overflow: ellipsis;
}

#subscription-table td.subscribed {
	min-width: 30px;
	padding: 3px 12px 3px 3px;
	text-align: right;
}

.skinselection {
	display: block;
}

.skinselection span {
	display: inline-block;
	vertical-align: middle;
	padding-right: 1em;
}

.skinselection .skinname {
	font-weight: bold;
}

.skinselection .skinlicense,
.skinselection .skinlicense a {
	font-style: italic;
	color: #666;
	text-decoration: none;
}

.skinselection .skinlicense a:hover {
	text-decoration: underline;
}

img.skinthumbnail {
	width: 64px;
	height: 64px;
	border: 1px solid #ccc;
	background: #fff;
	border-radius: 4px;
}

#pluginlist td.version {
	width: 5em;
}

.webkit #pluginlist td.version {
	width: 6em;
}

#pluginlist td.license,
#pluginlist td.source {
	width: 8em;
}

.webkit #pluginlist td.license,
.webkit #pluginlist td.source {
	width: 9em;
}


text:
package com.vanco.abplayer.adapter;

import com.vanco.abplayer.fragment.DonghuaFragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * FragmentPager适配器
 *
 * @author wwj_748
 * @2014/8/9
 */
public class DonghuaTabAdapter extends FragmentPagerAdapter {
	// 内容标题
	public static final String[] DONG_HUA_TITLE = new String[] { "全区动态", "MAD·AMV",
			"MMD·3D", "动画短片", "综合" };

	public DonghuaTabAdapter(FragmentManager fm) {
		super(fm);
		// TODO Auto-generated constructor stub
	}

	// 获取项
	@Override
	public Fragment getItem(int position) {
		System.out.println("Fragment position:" + position);

		switch (position) {
		case 0:
			return new DonghuaFragment(1);
		case 1:
			return new DonghuaFragment(24);
		case 2:
			return new DonghuaFragment(25);
		case 3:
			return new DonghuaFragment(47);
		case 4:
			return new DonghuaFragment(27);
		default:
			return new DonghuaFragment(1);
		}

		// MainFragment fragment = new MainFragment(position);
		// return fragment;
	}

	@Override
	public CharSequence getPageTitle(int position) {
		// 返回页面标题
		return DONG_HUA_TITLE[position % DONG_HUA_TITLE.length].toUpperCase();
	}

	@Override
	public int getCount() {
		// 页面个数
		return DONG_HUA_TITLE.length;
	}

}


text:
var parserMgr = require("./parserMgr.js");
var utils = require("./utils.js");
if (process.send) {
  var inst = init();
  process.on("message", function(m) {
    var action = getAction(m.action);
    inst[action](m, function(err, res) {
      if (err) {
        //error handling
      }
      if (!res){
        res={};
      }
      res.action = m.action;
      process.send(res);
    });
  });
}

function getAction(action) {
  return action.split("_")[0];
}

function init() {
  var headRow, parseRules;

  function genConstHeadRow(msg,cb){
      var Parser=require("./parser");
      var number=msg.number;
      parseRules=[];
      headRow=[];
      while (number>0){
        var p=new Parser("field"+number,/.*/,function(params){
          var name=this.getName();
          params.resultRow[name]=params.item;
        },true);
        parseRules.unshift(p);
        headRow.unshift(p.getName());
        number--;
      }
      cb();
  }
  function processHeadRow(msg, cb) {
    headRow = msg.row;
    var param = msg.param;
    parseRules = parserMgr.initParsers(headRow, param.checkType);
    cb(null, {});
  }

  function processRow(msg, cb) {
    var i, item, parser, head,
      data = msg.data,
      param = msg.param,
      index = msg.index;
    var row = utils.rowSplit(data, param.delimiter, param.quote, param.trim);
    var resultRow = {};
    for (i = 0; i < parseRules.length; i++) {
      item = row[i];
      if (param.ignoreEmpty && item === '') {
        continue;
      }
      parser = parseRules[i];
      head = headRow[i];
      parser.parse({
        head: head,
        item: item,
        itemIndex: i,
        rawRow: row,
        resultRow: resultRow,
        rowIndex: index,
        config: param || {}
      });
    }
    cb(null, {
      resultRow: resultRow,
      row: row,
      index: index
    });

  }
  return {
    processHeadRow: processHeadRow,
    processRow: processRow,
    genConstHeadRow:genConstHeadRow
  }
}
module.exports=init;


text:
@interface AdView : UIView

-(void)setMainQues:(NSString *)detial andComment:(NSString *)comment;
@end


text:
layout: post
title: Instalando WordPress en Linux (Parte I - LAMPP)
---

En esta nueva entrada voy a compartirles mi experiencia de como instalar WordPress de forma local usando LAMPP.

# ¿Que es WordPress?

WordPress, según su sitio [oficial](https://wordpress.org), es un Software Web que puedes usar para construir hermosas sitios web, blog o aplicaciones.

# ¿Que es LAMPP?

XAMPP es software libre que nos brinda un stack completo para el desarrollo de aplicaciones Web. La X significa que es multiplataforma y dependiendo del sistema operativo adopta un nombre, LAMPP en el caso de Linux, MAMPP en el caso de Mac OS X y WAMPP en el caso de Windows. La A hace referencia al servidor Web Apache, la M es por el sistema de gestión de base de datos MariaDB (Fork de MySQL, desde las versiones 5.5.30 y 5.6.14) y los lenguajes de programación PHP y Perl.

### Consideraciones antes de continuar

Desde mi punto de vista veo mas factible instalar y configurar los servicios por separado, (Apache, MariaDB y PHP), pero esta instalación la hice en una PC con Elementary OS Freya de un compañero que le esta dando una oportunidad a las distribuciones GNU/Linux y hasta el momento esta enamorado de su distribución. Por ende, la instalación va a ser basada a usuarios finales con poca o ninguna experiencia con la terminal. Debido a que yo solo iba a ser un mediador y mi compañero haría la instalación el mismo (Aprender haciendo) fue mas viable elegir el stack LAMPP usando XAMPP. A continuación te describo los pasos que seguimos:

### Instalar LAMPP

- Descargar el archivo de instalación de XAMPP desde la web de Apache Friends, haciendo [click Aquí](https://www.apachefriends.org/es/index.html), seleccionamos el archivo para nuestra plataforma (Linux en este caso) y la guardamos por ejemplo en la carpeta Descarga.

- Una vez finalizada la descarga tendremos un archivo .run, deberemos darle los permisos necesario para ejecutarlo y hacer la instalacion, para eso abriremos la termina y correremos los siguientes comandos.

``` sh
$ cd Descargas
```

Con esto entraremos en la carpeta descarga, para asignarle los permisos necesarios usaremos el siguiente comando, e ingresar tu clave de usuario:

``` sh
$ sudo chmod 755 xampp-linux-5.6.19-0-installer.run
```

**consejo:**  puedes apoyarte con la tecla tabulador para autocompletar el nombre de archivo, por ejemplo escribes xampp y presionas la tecla tabulador y autocompletara todo.

Para instalar solo necesitamos correr el .run como usuario administrador para ello usamos el comando:

``` sh
$ sudo ./xampp-linux-5.6.19-0-installer.run
```

Esto nos abrirá un asistente de instalación, dejaremos las configuraciones por defecto y haremos click en siguiente  la veces que  necesarias y dejaremos que se completa la instalación:

![xampp](/images/xampp.png)

si dejamos la casilla marcada y hacemos click en finish, nos mostrar el panel de control de xampp, donde veremos los servicios que estan corriendo, verifiquemos que  estan corriendo los servicios de Apache y MySQL

![xamp_panel](/images/xampp_panel.png)

**Nota:**  Cada vez que quieras acceder a este panel basta con escribir en la terminal

``` sh
$ sudo ./opt/lampp/share/xampp-control-panel/xampp-control-panel
```

Verificaremos que nuestra instalación vaya bien, para eso nos dirigimos al navegador y en la varra de dirección escribimos:

``` sh
localhost
```

![xampp_worked](/images/xampp_worked.jpg)

En la siguiente publicación crearemos la base de datos e instalaremos WordPress, para no hacer mas largo este articulo.

``` python
print exit()
```


text:
#ifndef HTTPD_H_
#define HTTPD_H_
/*
 * The default number of simultaneous server connections is 4. Multiple connections can be triggered
 * by requests for embedded images, style sheets, icons, etc. and a TCP RESET is issued when no more
 * connections are available.
 * The Firefox default connections per server is 15. It can be reduced to 1 in about:config and generally
 * will improve throughput in the half-duplex 6LoWPAN link as embedded files will be requested sequentially.
 * Tictactoe is a good test for multiple connections; it can use as many as 9, but should also work when
 * Firefox network.http.max-connections-per-server is set to a lower number.
 * The RAM needed for each entry depends on script enabling and buffer sizes; see struct httpd_state below.
 * Typical range is 100 - 200 bytes per connection
 * cgi's that use PSOCK_GENERATOR_SEND will have truncated output if UIP_CONF_RECEIVE_WINDOW and UIP_CONF_TCP_MSS
 * are not large enough. The header-menu cgi needs ~340 bytes if all options are enabled, while the file-stats * cgi
 * can exceed any MSS if there are enough files to display (e.g. tic-tac-toe).
 * The advertised MSS is easily seen in wireshark.
 * Some example set a small MSS by default. rpl-border-router for example uses a receive window of 60.
 */

 /* Titles of web pages served with the !header cgi can be configured to show characteristics of the node.
  * For example "CD1A:3456" to show the node id and clock time of last access.
  * Change this line and rebuild to make indentifiable instances.
  * Undefine to reduce program size, giving "Contiki-Nano" title on all pages.
  * WAD indexes into the uip destaddr field, which contains the address that we responded to.
  */
#define WEBSERVER_CONF_PAGETITLE sprintf(buf,"[%02x%02x]",WAD[14],WAD[15]);
//#define WEBSERVER_CONF_PAGETITLE sprintf(buf,"Nano[%02x%02x%02x]",WAD[13],WAD[14],WAD[15]);
//#define WEBSERVER_CONF_PAGETITLE sprintf(buf,"Nano[%02x%02x...%02x%02x]",WAD[0],WAD[1],WAD[14],WAD[15]);
//#define WEBSERVER_CONF_PAGETITLE sprintf(buf,"%2x%02x...%2x%02x [%lu]",WAD[0],WAD[1],WAD[14],WAD[15],clock_seconds());

#ifndef WEBSERVER_CONF_NANO
#if CONTIKI_TARGET_SKY || CONTIKI_TARGET_STK500
#define WEBSERVER_CONF_NANO 1
#elif CONTIKI_TARGET_REDBEE_ECONOTAG || CONTIKI_TARGET_AVR_RAVEN || CONTIKI_TARGET_AVR_ATMEGA128RFA1
#define WEBSERVER_CONF_NANO 2
#else
#define WEBSERVER_CONF_NANO 3
#endif
#endif

#if WEBSERVER_CONF_NANO==1
/* nano-size for constrained MCUs */
#define WEBSERVER_CONF_CONNS     2
#define WEBSERVER_CONF_NAMESIZE 16
#define WEBSERVER_CONF_BUFSIZE  40
/* Short tcp timeouts allow new connections sooner */
#define WEBSERVER_CONF_TIMEOUT  20
/* Allow include in .shtml pages, e.g. %!: /header.html */
#define WEBSERVER_CONF_INCLUDE   1
/* Allow cgi in .shtml pages, e.g. %! file-stats . */
#define WEBSERVER_CONF_CGI       1
/* MAX_SCRIPT_NAME_LENGTH should be at least the maximum file name length+2 for %!: includes */
#define MAX_SCRIPT_NAME_LENGTH   WEBSERVER_CONF_NAMESIZE+2
/* Enable specific cgi's */
#define WEBSERVER_CONF_HEADER    1
//#define WEBSERVER_CONF_HEADER_W3C  1 //Proper header
#define WEBSERVER_CONF_HEADER_MENU 1 //with links to other pages
//#define WEBSERVER_CONF_HEADER_ICON 1 //with favicon
#define WEBSERVER_CONF_LOADTIME  0  //show load time in filestats
#define WEBSERVER_CONF_FILESTATS 1
#define WEBSERVER_CONF_TCPSTATS  0
#define WEBSERVER_CONF_PROCESSES 0
#define WEBSERVER_CONF_ADDRESSES 1
#define WEBSERVER_CONF_NEIGHBORS 1
#define WEBSERVER_CONF_NEIGHBOR_STATUS 0
#define WEBSERVER_CONF_ROUTES    0
#define WEBSERVER_CONF_ROUTE_LINKS  0
#define WEBSERVER_CONF_SENSORS   0
#define WEBSERVER_CONF_STATISTICS   0
#define WEBSERVER_CONF_TICTACTOE 0   //Needs passquery of at least 10 chars
#define WEBSERVER_CONF_AJAX      0
//#define WEBSERVER_CONF_PASSQUERY 10
#if WEBSERVER_CONF_PASSQUERY
extern char httpd_query[WEBSERVER_CONF_PASSQUERY];
#endif
/* Enable specific file types */
#define WEBSERVER_CONF_JPG       0
#define WEBSERVER_CONF_PNG       0
#define WEBSERVER_CONF_GIF       0
#define WEBSERVER_CONF_TXT       1
#define WEBSERVER_CONF_CSS       0
#define WEBSERVER_CONF_BIN       0

/* Log page accesses */
#define WEBSERVER_CONF_LOG       0
/* Include referrer in log */
#define WEBSERVER_CONF_REFERER   0
/*-----------------------------------------------------------------------------*/
#elif WEBSERVER_CONF_NANO==2
/* webserver-mini having more content */
#define WEBSERVER_CONF_CONNS     2
#define WEBSERVER_CONF_NAMESIZE 20
#define WEBSERVER_CONF_BUFSIZE  40
#define WEBSERVER_CONF_TIMEOUT  20
/* Allow include in .shtml pages, e.g. %!: /header.html */
#define WEBSERVER_CONF_INCLUDE   1
/* Allow cgi in .shtml pages, e.g. %! file-stats . */
#define WEBSERVER_CONF_CGI       1
/* MAX_SCRIPT_NAME_LENGTH should be at least the maximum file name length+2 for %!: includes */
#define MAX_SCRIPT_NAME_LENGTH   WEBSERVER_CONF_NAMESIZE+2
/* Enable specific cgi's */
#define WEBSERVER_CONF_HEADER    1
//#define WEBSERVER_CONF_HEADER_W3C  1 //Proper header
#define WEBSERVER_CONF_HEADER_MENU 1 //with links to other pages
//#define WEBSERVER_CONF_HEADER_ICON 1 //with favicon
#define WEBSERVER_CONF_LOADTIME  1
#define WEBSERVER_CONF_FILESTATS 1
#define WEBSERVER_CONF_TCPSTATS  1
#define WEBSERVER_CONF_PROCESSES 1
#define WEBSERVER_CONF_ADDRESSES 1
#define WEBSERVER_CONF_NEIGHBORS 1
#define WEBSERVER_CONF_NEIGHBOR_STATUS 1
#define WEBSERVER_CONF_ROUTES    1
#define WEBSERVER_CONF_ROUTE_LINKS  1
#define WEBSERVER_CONF_SENSORS   1
#define WEBSERVER_CONF_STATISTICS   1
//#define WEBSERVER_CONF_TICTACTOE 1   //Needs passquery of at least 10 chars
#define WEBSERVER_CONF_AJAX      1
#define WEBSERVER_CONF_SHOW_ROOM 0
#define WEBSERVER_CONF_PASSQUERY 10
#if WEBSERVER_CONF_PASSQUERY
extern char httpd_query[WEBSERVER_CONF_PASSQUERY];
#endif
/* Enable specific file types */
#define WEBSERVER_CONF_JPG       0
#define WEBSERVER_CONF_PNG       0
#define WEBSERVER_CONF_GIF       0
#define WEBSERVER_CONF_TXT       1
#define WEBSERVER_CONF_CSS       0
#define WEBSERVER_CONF_BIN       0

/* Log page accesses */
#define WEBSERVER_CONF_LOG       0
/* Include referrer in log */
#define WEBSERVER_CONF_REFERER   1

/*-----------------------------------------------------------------------------*/
#elif WEBSERVER_CONF_NANO==3
/* webserver-mini having all content */
#define WEBSERVER_CONF_CONNS     6
#define WEBSERVER_CONF_NAMESIZE 20
#define WEBSERVER_CONF_BUFSIZE  40
#define WEBSERVER_CONF_TIMEOUT  20
/* Allow include in .shtml pages, e.g. %!: /header.html */
#define WEBSERVER_CONF_INCLUDE   1
/* Allow cgi in .shtml pages, e.g. %! file-stats . */
#define WEBSERVER_CONF_CGI       1
/* MAX_SCRIPT_NAME_LENGTH should be at least the maximum file name length+2 for %!: includes */
#define MAX_SCRIPT_NAME_LENGTH   WEBSERVER_CONF_NAMESIZE+2
/* Enable specific cgi's */
#define WEBSERVER_CONF_HEADER    1
//#define WEBSERVER_CONF_HEADER_W3C  1 //Proper header
#define WEBSERVER_CONF_HEADER_MENU 1 //with links to other pages
//#define WEBSERVER_CONF_HEADER_ICON 1 //with favicon
#define WEBSERVER_CONF_LOADTIME  1
#define WEBSERVER_CONF_FILESTATS 1
#define WEBSERVER_CONF_TCPSTATS  1
#define WEBSERVER_CONF_PROCESSES 1
#define WEBSERVER_CONF_ADDRESSES 1
#define WEBSERVER_CONF_NEIGHBORS 1
#define WEBSERVER_CONF_ROUTES    1
#define WEBSERVER_CONF_NEIGHBORS 1
#define WEBSERVER_CONF_NEIGHBOR_STATUS 1
#define WEBSERVER_CONF_ROUTES    1
#define WEBSERVER_CONF_ROUTE_LINKS  1
#define WEBSERVER_CONF_SENSORS   1
#define WEBSERVER_CONF_STATISTICS   1
#define WEBSERVER_CONF_TICTACTOE 1   //Needs passquery of at least 10 chars
#define WEBSERVER_CONF_AJAX      1
#define WEBSERVER_CONF_PASSQUERY 10
#if WEBSERVER_CONF_PASSQUERY
extern char httpd_query[WEBSERVER_CONF_PASSQUERY];
#endif
/* Enable specific file types */
#define WEBSERVER_CONF_JPG       1
#define WEBSERVER_CONF_PNG       1
#define WEBSERVER_CONF_GIF       1
#define WEBSERVER_CONF_TXT       1
#define WEBSERVER_CONF_CSS       1
#define WEBSERVER_CONF_BIN       1

/* Log page accesses */
#define WEBSERVER_CONF_LOG       1
/* Include referrer in log */
#define WEBSERVER_CONF_REFERER   1

#else
#error Specified WEBSERVER_CONF_NANO configuration not supported.
#endif /* WEBSERVER_CONF_NANO */

/* Address printing used by cgi's and logging, but it can be turned off if desired */
#if WEBSERVER_CONF_LOG || WEBSERVER_CONF_ADDRESSES || WEBSERVER_CONF_NEIGHBORS || WEBSERVER_CONF_ROUTES
extern uip_ds6_netif_t uip_ds6_if;
#define WEBSERVER_CONF_PRINTADDR 1
#endif
#if WEBSERVER_CONF_PRINTADDR
uint8_t httpd_cgi_sprint_ip6(uip_ip6addr_t addr, char * result);
#else
#define httpd_cgi_sprint_ip6(...) 0
#endif

#include "contiki-net.h"
#include "httpd-fs.h"

#if defined(__AVR__)
/* When using non-ram storage httpd-fsdata.c must be generated with the HTTPD_STRING_ATTR, eg
 *        ../../tools/makefsdata -A HTTPD_STRING_ATTR
 */
#include <avr/pgmspace.h>
#define HTTPD_STRING_ATTR PROGMEM
#define PRINTA(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
/* These will fail if the server strings are above 64K in program flash */
#define httpd_memcpy         memcpy_P
#define httpd_strcpy         strcpy_P
#define httpd_strcmp         strcmp_P
#define httpd_strncmp        strncmp_P
#define httpd_strlen         strlen_P
#define httpd_snprintf       snprintf_P
#define httpd_fs_cpy         memcpy_P
#define httpd_fs_strcmp      strcmp_P
#define httpd_fs_strchr      strchr_P
#define httpd_fs_getchar(x)  pgm_read_byte(x)

#else /* All storage in RAM */
#define HTTPD_STRING_ATTR
#define PRINTA(FORMAT,args...) printf(FORMAT,##args)
#define httpd_snprintf       snprintf
#define httpd_fs_cpy         memcpy
#define httpd_memcpy         memcpy
#define httpd_strcpy         strcpy
#define httpd_strcmp         strcmp
#define httpd_strncmp        strncmp
#define httpd_strlen         strlen
#define httpd_fs_strchr      strchr
#define httpd_fs_strcmp      strcmp
#define httpd_fs_getchar(c)  *(c)
#endif

struct httpd_state {
  unsigned char timer;
  struct psock sin, sout;
  struct pt outputpt;
#if WEBSERVER_CONF_INCLUDE || WEBSERVER_CONF_CGI
  struct pt scriptpt;
#endif
  char inputbuf[WEBSERVER_CONF_BUFSIZE];
  char filename[WEBSERVER_CONF_NAMESIZE];
  char state;
  struct httpd_fs_file file;
  int len;
#if WEBSERVER_CONF_INCLUDE || WEBSERVER_CONF_CGI
  char *scriptptr;
  int scriptlen;
#endif
#if WEBSERVER_CONF_LOADTIME
  clock_time_t pagetime;
#endif
#if WEBSERVER_CONF_AJAX
  uint16_t ajax_timeout;
#endif
#if WEBSERVER_CONF_NEIGHBORS || WEBSERVER_CONF_ROUTES
  uint8_t starti,savei,startj,savej;
#endif
#if WEBSERVER_CONF_CGI
  union {
    unsigned short count;
    void *ptr;
  } u;
#endif
};

void httpd_init(void);
void httpd_appcall(void *state);

/* DEBUGLOGIC is a convenient way to debug without a tcp/ip connection.
 * After initialization, break the program and set the program counter
 * to the beginning of httpd.c::httpd_appcall:
 *   s = sg = (struct httpd_state *)memb_alloc(&conns);
 * The global sg points to the s data to get around "not in scope" optimization.
 * The input file is forced to /index.html and the output directed to TCPBUF.
 * However the socket will hang on acknowledgement when any data is sent.
 * To prevent this just add a break to /core/net/psock.c::psock_generator_send
 * ...
 * // Wait until all data is sent and acknowledged.
 * break;                            //<---add this line
 * PT_YIELD_UNTIL(&s->psockpt, uip_acked() || uip_rexmit());
 * ...
 */
#define DEBUGLOGIC 0
#if DEBUGLOGIC
struct httpd_state *sg;
#define uip_mss(...) 512
#define uip_appdata TCPBUF
char TCPBUF[512];
#endif

#endif /* HTTPD_H_ */


text:
"""Provides Report classes

This module defines various classes representing reports and report sections.
All reports take the form of a report class containing various report
sections.
"""

from cinder.openstack.common.report.views.text import header as header_views

class BasicReport(object):
    """A Basic Report

    A Basic Report consists of a collection of :class:`ReportSection`
    objects, each of which contains a top-level model and generator.
    It collects these sections into a cohesive report which may then
    be serialized by calling :func:`run`.
    """

    def __init__(self):
        self.sections = []
        self._state = 0

    def add_section(self, view, generator, index=None):
        """Add a section to the report

        This method adds a section with the given view and
        generator to the report.  An index may be specified to
        insert the section at a given location in the list;
        If no index is specified, the section is appended to the
        list.  The view is called on the model which results from
        the generator when the report is run.  A generator is simply
        a method or callable object which takes no arguments and
        returns a :class:`openstack.common.report.models.base.ReportModel`
        or similar object.

        :param view: the top-level view for the section
        :param generator: the method or class which generates the model
        :param index: the index at which to insert the section
                      (or None to append it)
        :type index: int or None
        """

        if index is None:
            self.sections.append(ReportSection(view, generator))
        else:
            self.sections.insert(index, ReportSection(view, generator))

    def run(self):
        """Run the report

        This method runs the report, having each section generate
        its data and serialize itself before joining the sections
        together.  The BasicReport accomplishes the joining
        by joining the serialized sections together with newlines.

        :rtype: str
        :returns: the serialized report
        """

        return "\n".join(str(sect) for sect in self.sections)

class ReportSection(object):
    """A Report Section

    A report section contains a generator and a top-level view. When something
    attempts to serialize the section by calling str() on it, the section runs
    the generator and calls the view on the resulting model.

    .. seealso::

       Class :class:`BasicReport`
           :func:`BasicReport.add_section`

    :param view: the top-level view for this section
    :param generator: the generator for this section
      (any callable object which takes no parameters and returns a data model)
    """

    def __init__(self, view, generator):
        self.view = view
        self.generator = generator

    def __str__(self):
        return self.view(self.generator())

class ReportOfType(BasicReport):
    """A Report of a Certain Type

    A ReportOfType has a predefined type associated with it.
    This type is automatically propagated down to the each of
    the sections upon serialization by wrapping the generator
    for each section.

    .. seealso::

       Class :class:`openstack.common.report.models.with_default_view.ModelWithDefaultView` # noqa
          (the entire class)

       Class :class:`openstack.common.report.models.base.ReportModel`
           :func:`openstack.common.report.models.base.ReportModel.set_current_view_type` # noqa

    :param str tp: the type of the report
    """

    def __init__(self, tp):
        self.output_type = tp
        super(ReportOfType, self).__init__()

    def add_section(self, view, generator, index=None):
        def with_type(gen):
            def newgen():
                res = gen()
                try:
                    res.set_current_view_type(self.output_type)
                except AttributeError:
                    pass

                return res
            return newgen

        super(ReportOfType, self).add_section(
            view,
            with_type(generator),
            index
        )

class TextReport(ReportOfType):
    """A Human-Readable Text Report

    This class defines a report that is designed to be read by a human
    being.  It has nice section headers, and a formatted title.

    :param str name: the title of the report
    """

    def __init__(self, name):
        super(TextReport, self).__init__('text')
        self.name = name
        # add a title with a generator that creates an empty result model
        self.add_section(name, lambda: ('|' * 72) + "\n\n")

    def add_section(self, heading, generator, index=None):
        """Add a section to the report

        This method adds a section with the given title, and
        generator to the report.  An index may be specified to
        insert the section at a given location in the list;
        If no index is specified, the section is appended to the
        list.  The view is called on the model which results from
        the generator when the report is run.  A generator is simply
        a method or callable object which takes no arguments and
        returns a :class:`openstack.common.report.models.base.ReportModel`
        or similar object.

        The model is told to serialize as text (if possible) at serialization
        time by wrapping the generator.  The view model's attached view
        (if any) is wrapped in a
        :class:`openstack.common.report.views.text.header.TitledView`

        :param str heading: the title for the section
        :param generator: the method or class which generates the model
        :param index: the index at which to insert the section
                      (or None to append)
        :type index: int or None
        """

        super(TextReport, self).add_section(header_views.TitledView(heading),
                                            generator,
                                            index)


text:
package com.blazebit.persistence.criteria;

import javax.persistence.criteria.AbstractQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.EntityType;
import java.util.List;
import java.util.Set;

/**
 * An extended version of {@link AbstractQuery} that allows setting an alias for {@link javax.persistence.criteria.From} elements.
 *
 * @param <T> the type of the result
 * @author Christian Beikov
 * @since 1.2.0
 */
public interface BlazeAbstractQuery<T> extends AbstractQuery<T>, BlazeCommonAbstractCriteria {

    // TODO: create a fluent builder for clauses, maybe via RestrictionBuilder?
    // TODO: integrate support for SetBuilder, CteBuilder
    // TODO: integrate support for default join nodes?
    // TODO: maybe add explicit support for limit?

    /**
     * Like {@link AbstractQuery#from(Class)} but allows to set the alias of the {@link BlazeRoot}.
     *
     * @param entityClass the entity class
     * @param alias       The alias for the {@link BlazeRoot}
     * @param <X>         The entity type
     * @return query root corresponding to the given entity
     */
    public <X> BlazeRoot<X> from(Class<X> entityClass, String alias);

    /**
     * Like {@link AbstractQuery#from(EntityType)} but allows to set the alias of the {@link BlazeRoot}.
     *
     * @param entityType the entity type
     * @param alias      The alias for the {@link BlazeRoot}
     * @param <X>        The entity type
     * @return query root corresponding to the given entity
     */
    public <X> BlazeRoot<X> from(EntityType<X> entityType, String alias);

    /**
     * Like {@link AbstractQuery#getRoots()} but returns the subtype {@link BlazeRoot} instead.
     *
     * @return the set of query roots
     */
    public Set<BlazeRoot<?>> getBlazeRoots();

    /* Covariant overrides */

    @Override
    <X> BlazeRoot<X> from(Class<X> entityClass);

    @Override
    <X> BlazeRoot<X> from(EntityType<X> entity);

    @Override
    BlazeAbstractQuery<T> where(Expression<Boolean> restriction);

    @Override
    BlazeAbstractQuery<T> where(Predicate... restrictions);

    @Override
    BlazeAbstractQuery<T> groupBy(Expression<?>... grouping);

    @Override
    BlazeAbstractQuery<T> groupBy(List<Expression<?>> grouping);

    @Override
    BlazeAbstractQuery<T> having(Expression<Boolean> restriction);

    @Override
    BlazeAbstractQuery<T> having(Predicate... restrictions);

    @Override
    BlazeAbstractQuery<T> distinct(boolean distinct);
}


text:
package discover

import (
	"fmt"
	"log"
	"sort"
	"strings"
	"sync"

	"github.com/hashicorp/go-discover/provider/aws"
	"github.com/hashicorp/go-discover/provider/azure"
	"github.com/hashicorp/go-discover/provider/gce"
	"github.com/hashicorp/go-discover/provider/softlayer"
)

// Provider has lookup functions for meta data in a
// cloud environment.
type Provider interface {
	// Addrs looks up addresses in the cloud environment according to the
	// configuration provided in args.
	Addrs(args map[string]string, l *log.Logger) ([]string, error)

	// Help provides the configuration help for the command line client.
	Help() string
}

// Providers contains all available providers.
var Providers = map[string]Provider{
	"aws":       &aws.Provider{},
	"azure":     &azure.Provider{},
	"gce":       &gce.Provider{},
	"softlayer": &softlayer.Provider{},
}

// Discover looks up metadata in different cloud environments.
type Discover struct {
	// Providers is the list of address lookup providers.
	// If nil, the default list of providers is used.
	Providers map[string]Provider

	// once is used to initialize the actual list of providers.
	once sync.Once
}

// initProviders sets the list of providers to the
// default list of providers if none are configured.
func (d *Discover) initProviders() {
	if d.Providers == nil {
		d.Providers = Providers
	}
}

// Names returns the names of the configured providers.
func (d *Discover) Names() []string {
	d.once.Do(d.initProviders)

	var names []string
	for n := range d.Providers {
		names = append(names, n)
	}
	sort.Strings(names)
	return names
}

var globalHelp = `The options for discovering ip addresses are provided as a
  single string value in "key=value key=value ..." format where
  the values are URL encoded.

    provider=aws region=eu-west-1 ...

  The options are provider specific and are listed below.
`

// Help describes the format of the configuration string for address discovery
// and the various provider specific options.
func (d *Discover) Help() string {
	d.once.Do(d.initProviders)

	h := []string{globalHelp}
	for _, name := range d.Names() {
		h = append(h, d.Providers[name].Help())
	}
	return strings.Join(h, "\n")
}

// Addrs discovers ip addresses of nodes that match the given filter criteria.
// The config string must have the format 'provider=xxx key=val key=val ...'
// where the keys and values are provider specific. The values are URL encoded.
func (d *Discover) Addrs(cfg string, l *log.Logger) ([]string, error) {
	d.once.Do(d.initProviders)

	args, err := Parse(cfg)
	if err != nil {
		return nil, fmt.Errorf("discover: %s", err)
	}

	name := args["provider"]
	if name == "" {
		return nil, fmt.Errorf("discover: no provider")
	}

	providers := d.Providers
	if providers == nil {
		providers = Providers
	}

	p := providers[name]
	if p == nil {
		return nil, fmt.Errorf("discover: unknown provider " + name)
	}
	l.Printf("[DEBUG] discover: Using provider %q", name)

	return p.Addrs(args, l)
}


text:
<?php

class TranslationController extends Zend_Controller_Action {

    public function init() {

        if (!Aitsu_Adm_User :: getInstance()->isAllowed(array(
                    'area' => 'translation'
                ))) {
            throw new Exception('Access denied');
        }

        $this->_helper->layout->disableLayout();

        $this->_filter = Aitsu_Util_ExtJs :: encodeFilters($this->getRequest()->getParam('filter'));
    }

    public function indexAction() {

    }

    public function storeAction() {

        $refresh = $this->getRequest()->getParam('refresh');

        if ($refresh == 1) {
            Aitsu_Translate :: populate(Aitsu_Registry :: get()->session->currentLanguage);
        }

        $this->_helper->json((object) array(
                    'data' => Aitsu_Persistence_Translate :: getStore(100, 0, $this->_filter)
        ));
    }

    public function editAction() {

        $this->_helper->layout->disableLayout();

        $id = $this->getRequest()->getParam('translationid');

        $form = Aitsu_Forms :: factory('edittranslation', APPLICATION_PATH . '/adm/forms/translation/translation.ini');
        $form->title = Aitsu_Translate :: translate('Edit translation');
        $form->url = $this->view->url();

        $data = Aitsu_Persistence_Translate :: factory($id)->load()->toArray();
        $form->setValues($data);

        if ($this->getRequest()->getParam('loader')) {
            $this->view->form = $form;
            header("Content-type: text/javascript");
            return;
        }

        try {
            if ($form->isValid()) {
                $values = $form->getValues();

                /*
                 * Update config set.
                 */
                Aitsu_Persistence_Translate :: factory($id)->load()->setValues($values)->save();

                $this->_helper->json((object) array(
                            'success' => true
                ));
            } else {
                $this->_helper->json((object) array(
                            'success' => false,
                            'errors' => $form->getErrors()
                ));
            }
        } catch (Exception $e) {
            $this->_helper->json((object) array(
                        'success' => false,
                        'exception' => true,
                        'message' => $e->getMessage()
            ));
        }
    }

    public function deleteAction() {

        $this->_helper->layout->disableLayout();

        Aitsu_Persistence_Translate :: factory($this->getRequest()->getParam('translationid'))->remove();

        $this->_helper->json((object) array(
                    'success' => true
        ));
    }

    public function exportAction() {

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $filename = 'translation.';
        $filename .= Aitsu_Registry :: get()->session->currentClient . '.';
        $filename .= Aitsu_Registry :: get()->session->currentLanguage . '.';
        $filename .= date('Y-m-d-H-i-s') . '.xml';

        header('Content-type: application/xml');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        echo Aitsu_Filter_ToXml :: get(array(
            'info' => array(
                'type' => 'translation',
                'date' => date('Y-m-d H:i:s'),
                'client' => Aitsu_Registry :: get()->session->currentClient,
                'language' => array(
                    'id' => Aitsu_Registry :: get()->session->currentLanguage,
                    'locale' => Aitsu_Persistence_Language :: factory(Aitsu_Registry :: get()->session->currentLanguage)->load()->locale
                ),
                'system' => array(
                    'HTTP_HOST' => $_SERVER['HTTP_HOST'],
                    'SERVER_NAME' => $_SERVER['SERVER_NAME'],
                    'SERVER_ADDR' => $_SERVER['SERVER_ADDR'],
                    'DOCUMENT_ROOT' => $_SERVER['DOCUMENT_ROOT']
                )
            ),
            'data' => Aitsu_Persistence_Translate :: getByLanguage(Aitsu_Registry :: get()->session->currentLanguage)
        ))->saveXML();
    }

}


text:
'use strict';

var gulp  = require('gulp'),
    debug = require('debug')('gulp:watch'),
    lr    = require('gulp-livereload');

var config = require('../../config');

module.exports = function() {
  debug('Start LR server and watch files');

  lr.listen();

  gulp.watch(config.paths.js, ['browserify'], lr.changed);
  gulp.watch(config.paths.templates, ['browserify'], lr.changed);
  gulp.watch('client/**/*.styl', ['stylus']);
  gulp.watch(config.paths.dest + '**/*.css', lr.changed);
};


text:
var React = require('react')

module.exports = React.createClass({
  displayName: 'OtherPage',
  // quick and dirty internal nav handler
  onClick: function (e) {
    e.preventDefault()
    window.router.history.navigate('/')
  },
  render: function () {
    return (

Other page

        go to /

    )
  }
})


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.3.10: http://docutils.sourceforge.net/" />
<title>Boost Pointer Container Library</title>

 Pointer Container Library

Indirected functions

It is quite common that we have two pointers and what to compare the
pointed to objects. Also, we have usually already defined how
to compare the objects. So to avoid some tedious boiler-plate code
this library defines predicates that apply an indirection before comparing.

When the container uses <tt class="docutils literal">void*</tt> internally, we can use the
class <tt class="docutils literal">void_ptr_indirect_fun</tt>; otherwise we use the class
<tt class="docutils literal">indirect_fun</tt>.

Example:

std::string* bar = new std::string("bar");
std::string* foo = new std::string("foo");
BOOST_ASSERT( indirect_fun< std::less<std::string> >()( bar, foo ) == true );
BOOST_ASSERT( make_indirect_fun( std::less<std::string>() )( foo, bar ) == false );

void*       vptr1  = ptr1;
void*       vptr2  = ptr2;
void_ptr_indirect_fun< std::less<std::string>, std::string> cast_fun;
BOOST_CHECK( cast_fun( vptr1, vptr2 ) == true );

See also:

result_of

pointee

ptr_set

ptr_multiset

Navigate

home

reference

Remarks:

The class <tt class="docutils literal">indirect_fun</tt> will work with smart pointers such as boost::shared_ptr<T>
because of the type traits <tt class="docutils literal">pointee<T>::type</tt> from the header <tt class="docutils literal"><boost/pointee.hpp></tt>.

Synopsis:

Since the definition of the predicates is somewhat trivial, only the
first operation is expanded inline.

namespace boost
{

    template< class Fun >
    struct indirect_fun
    {
        indirect_fun() : fun(Fun())
        { }

        indirect_fun( Fun f ) : fun(f)
        { }

        template< class T >
        typename result_of< Fun( typename pointee<T>::type ) >::type
        operator()( const T& r ) const
        {
            return fun( *r );
        }

        template< class T, class U >
        typename result_of< Fun( typename pointee<T>::type,
                                 typename pointee<U>::type ) >::type
        operator()( const T& r, const U& r2 ) const
        {
            return fun( *r, *r2 );
        }

    private:
        Fun fun;
    };

    template< class Fun >
    inline indirect_fun<Fun> make_indirect_fun( Fun f )
    {
        return indirect_fun<Fun>( f );
    }

    template< class Fun, class Arg1, class Arg2 = Arg1 >
    struct void_ptr_indirect_fun
    {
        void_ptr_indirect_fun() : fun(Fun())
        { }

        void_ptr_indirect_fun( Fun f ) : fun(f)
        { }

        typename result_of< Fun( Arg1 ) >::type
        operator()( const void* r ) const
        {
            return fun( * static_cast<const Arg1*>( r ) );
        }

        typename result_of< Fun( Arg1, Arg2 ) >::type
        operator()( const void* l, const void* r ) const
        {
            return fun( * static_cast<const Arg1*>( l ), * static_cast<const Arg2*>( r ) );
        }

    private:
        Fun fun;
    };

    template< class Fun, class Arg >
    inline void_ptr_indirect_fun<Fun,Arg>
    make_void_ptr_indirect_fun( Fun f )
    {
        return void_ptr_indirect_fun<Fun,Arg>( f );
    }

} // namespace 'boost'

<col class="field-name" />
<col class="field-body" />

Copyright:	Thorsten Ottosen 2004-2006. Use, modification and distribution is subject to the Boost Software License, Version 1.0 (see LICENSE_1_0.txt).