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

namespace Cube.Net.Rss.Reader
{
    /* --------------------------------------------------------------------- */
    ///
    /// SharedSetting
    ///
    /// <summary>
    /// ユーザ設定を保持するためのクラスです。
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    [DataContract]
    public class SharedSetting : SerializableBase
    {
        #region Properties

        /* ----------------------------------------------------------------- */
        ///
        /// FileName
        ///
        /// <summary>
        /// Get the name of the file that will hold the configuration.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public static string FileName => "Settings.json";

        /* ----------------------------------------------------------------- */
        ///
        /// StartUri
        ///
        /// <summary>
        /// Gets or sets the URL of the RssEntry object to be displayed at
        /// startup.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember(Name = "Start")]
        public Uri StartUri
        {
            get => Get<Uri>();
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// Capacity
        ///
        /// <summary>
        /// Gets or sets the maximum number of RSS feed items to be retained
        /// in memory.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public int Capacity
        {
            get => Get(() => 100);
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// LightMode
        ///
        /// <summary>
        /// Gets or sets a value indicating whether to apply the lightweight
        /// mode.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public bool LightMode
        {
            get => Get(() => false);
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// EnableNewWindow
        ///
        /// <summary>
        /// Gets or sets a value indicating whether Open in new window is
        /// enabled.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public bool EnableNewWindow
        {
            get => Get(() => false);
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// EnableMonitorMessage
        ///
        /// <summary>
        /// Gets or sets a value indicating whether the status of RSS feed
        /// acquisition is displayed in the status bar.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public bool EnableMonitorMessage
        {
            get => Get(() => true);
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// CheckUpdate
        ///
        /// <summary>
        /// Gets or sets a value indicating whether or not to check for
        /// software updates.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public bool CheckUpdate
        {
            get => Get(() => true);
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// HighInterval
        ///
        /// <summary>
        /// Gets or sets the check interval of the high frequency monitor.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public TimeSpan HighInterval
        {
            get => Get(() => TimeSpan.FromHours(1));
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// LowInterval
        ///
        /// <summary>
        /// Gets or sets the check interval of the low frequency monitor.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [DataMember]
        public TimeSpan LowInterval
        {
            get => Get(() => TimeSpan.FromHours(24));
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// InitialDelay
        ///
        /// <summary>
        /// Gets or sets the initial delay time for monitoring.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public TimeSpan InitialDelay
        {
            get => Get(() => TimeSpan.FromSeconds(3));
            set => Set(value);
        }

        /* ----------------------------------------------------------------- */
        ///
        /// LastCheckUpdate
        ///
        /// <summary>
        /// Get or set the date and time of the last software update
        /// confirmation.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public DateTime? LastCheckUpdate
        {
            get => Get<DateTime?>();
            set => Set(value);
        }

        #endregion

        #region Methods

        /* ----------------------------------------------------------------- */
        ///
        /// Load
        ///
        /// <summary>
        /// Loads the settings from the specified arguments.
        /// </summary>
        ///
        /// <param name="directory">Dicretory path.</param>
        ///
        /// <returns>SharedSetting object.</returns>
        ///
        /* ----------------------------------------------------------------- */
        public static SharedSetting Load(string directory)
        {
            try
            {
                var src = Io.Combine(directory, FileName);
                return Io.Exists(src) ? Format.Json.Deserialize<SharedSetting>(src) : new();
            }
            catch { return new(); }
        }

        /* ----------------------------------------------------------------- */
        ///
        /// Save
        ///
        /// <summary>
        /// Saves the current settings to the specified path.
        /// </summary>
        ///
        /// <param name="directory">Dicretory path.</param>
        ///
        /* ----------------------------------------------------------------- */
        public void Save(string directory) => Format.Json.Serialize(Io.Combine(directory, FileName), this);

        #endregion
    }
}


text:
//
//  CLTGetUserInfoResult.h
//
//  Created by CAI on 2015/4/24
//  Copyright (c) 2015年 CAI. All rights reserved.
//

/*
     用户信息结构
*/

#import "Mantle.h"
#import "CLTStatus.h"
#import "CLTUserInfo.h"

@interface CLTGetUserInfoResult : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong)CLTStatus *status;
@property (nonatomic, strong)CLTUserInfo *data;

@end

redpajama_set_name: RedPajamaGithub


text:
namespace {

// MEMBER FUNCTIONS - Body may be edited by hand.

void CEF_CALLBACK display_handler_on_address_change(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    struct _cef_frame_t* frame, const cef_string_t* url) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Verify param: frame; type: refptr_diff
  DCHECK(frame);
  if (!frame)
    return;
  // Verify param: url; type: string_byref_const
  DCHECK(url);
  if (!url)
    return;

  // Execute
  CefDisplayHandlerCppToC::Get(self)->OnAddressChange(
      CefBrowserCToCpp::Wrap(browser),
      CefFrameCToCpp::Wrap(frame),
      CefString(url));
}

void CEF_CALLBACK display_handler_on_title_change(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    const cef_string_t* title) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Unverified params: title

  // Execute
  CefDisplayHandlerCppToC::Get(self)->OnTitleChange(
      CefBrowserCToCpp::Wrap(browser),
      CefString(title));
}

void CEF_CALLBACK display_handler_on_favicon_urlchange(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    cef_string_list_t icon_urls) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Unverified params: icon_urls

  // Translate param: icon_urls; type: string_vec_byref_const
  std::vector<CefString> icon_urlsList;
  transfer_string_list_contents(icon_urls, icon_urlsList);

  // Execute
  CefDisplayHandlerCppToC::Get(self)->OnFaviconURLChange(
      CefBrowserCToCpp::Wrap(browser),
      icon_urlsList);
}

void CEF_CALLBACK display_handler_on_fullscreen_mode_change(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    int fullscreen) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;

  // Execute
  CefDisplayHandlerCppToC::Get(self)->OnFullscreenModeChange(
      CefBrowserCToCpp::Wrap(browser),
      fullscreen?true:false);
}

int CEF_CALLBACK display_handler_on_tooltip(struct _cef_display_handler_t* self,
    cef_browser_t* browser, cef_string_t* text) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return 0;
  // Unverified params: text

  // Translate param: text; type: string_byref
  CefString textStr(text);

  // Execute
  bool _retval = CefDisplayHandlerCppToC::Get(self)->OnTooltip(
      CefBrowserCToCpp::Wrap(browser),
      textStr);

  // Return type: bool
  return _retval;
}

void CEF_CALLBACK display_handler_on_status_message(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    const cef_string_t* value) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Unverified params: value

  // Execute
  CefDisplayHandlerCppToC::Get(self)->OnStatusMessage(
      CefBrowserCToCpp::Wrap(browser),
      CefString(value));
}

int CEF_CALLBACK display_handler_on_console_message(
    struct _cef_display_handler_t* self, cef_browser_t* browser,
    const cef_string_t* message, const cef_string_t* source, int line) {
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return 0;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return 0;
  // Unverified params: message, source

  // Execute
  bool _retval = CefDisplayHandlerCppToC::Get(self)->OnConsoleMessage(
      CefBrowserCToCpp::Wrap(browser),
      CefString(message),
      CefString(source),
      line);

  // Return type: bool
  return _retval;
}

}  // namespace

// CONSTRUCTOR - Do not edit by hand.

CefDisplayHandlerCppToC::CefDisplayHandlerCppToC() {
  GetStruct()->on_address_change = display_handler_on_address_change;
  GetStruct()->on_title_change = display_handler_on_title_change;
  GetStruct()->on_favicon_urlchange = display_handler_on_favicon_urlchange;
  GetStruct()->on_fullscreen_mode_change =
      display_handler_on_fullscreen_mode_change;
  GetStruct()->on_tooltip = display_handler_on_tooltip;
  GetStruct()->on_status_message = display_handler_on_status_message;
  GetStruct()->on_console_message = display_handler_on_console_message;
}

template<> CefRefPtr<CefDisplayHandler> CefCppToC<CefDisplayHandlerCppToC,
    CefDisplayHandler, cef_display_handler_t>::UnwrapDerived(
    CefWrapperType type, cef_display_handler_t* s) {
  NOTREACHED() << "Unexpected class type: " << type;
  return NULL;
}

#ifndef NDEBUG
template<> base::AtomicRefCount CefCppToC<CefDisplayHandlerCppToC,
    CefDisplayHandler, cef_display_handler_t>::DebugObjCt = 0;
#endif

template<> CefWrapperType CefCppToC<CefDisplayHandlerCppToC, CefDisplayHandler,
    cef_display_handler_t>::kWrapperType = WT_DISPLAY_HANDLER;


text:
"use strict";

var child_process = require('child_process');
const fs = require("fs-extra");
const nunjucks = require("nunjucks");
const path = require("path");

const projectRootDir = process.cwd();
const projectConfigPath = path.join(projectRootDir, "package.json");
const projectConfig = fs.readJsonSync(projectConfigPath);

var productInfo = {
  version: parseVersion(projectConfig.version),
  commit: gitLatestCommit()
};

var context = {
  product: productInfo,
  version: productInfo.version,
  commit: productInfo.commit
};

renderTemplateFile(
    path.join(__dirname, 'templates/CommonAssemblyInfo.cs.nunjucks'),
    path.join(__dirname, 'templates/Common/Properties/CommonAssemblyInfo.cs'),
    context
  );
renderTemplateFile(
    path.join(__dirname, 'templates/ProductInfo.cs.nunjucks'),
    path.join(__dirname, '../assets/Source/ProductInfo.cs'),
    context
  );

//-----------------------------------------------------------------------------
// Nunjucks Helpers
//-----------------------------------------------------------------------------

function renderTemplateFile(sourceFile, outputFile, context) {
	nunjucks.configure(path.dirname(sourceFile), { watch: false });
  var result = nunjucks.render(path.basename(sourceFile), context);

  fs.ensureDirSync(path.dirname(outputFile));
	fs.writeFileSync(outputFile, result);
}

//-----------------------------------------------------------------------------
// Version Helpers
//-----------------------------------------------------------------------------

function parseVersion(versionTag) {
	var matches = versionTag.match(/^([0-9]+)\.([0-9]+)\.([0-9]+)(-(.+))?/);
	return {
		'major': matches[1],
		'minor': matches[2],
		'patch': matches[3],
		'label': matches[5],
		'informational': versionTag
	};
}

//-----------------------------------------------------------------------------
// Git Helpers
//-----------------------------------------------------------------------------

function gitLatestCommitHash() {
  try {
    return child_process.execSync('git rev-parse HEAD').toString().trim();
  }
  catch (err) {
    console.error(err.toString());
    return "unknown";
  }
}

function gitLatestCommit() {
	var latestCommitHash = gitLatestCommitHash();
	if (!latestCommitHash) {
    return { };
  }
	return {
		longHash: latestCommitHash,
		shortHash: latestCommitHash.substr(0, 7)
	};
}


text:
This is a fork project from the tomo2d, created by Jun Korenaga at Yale university, aimed for helping seismic project(s) of the Institute of Petroleum, the Heriot Watt University

## ACKNOWLEDGEMENT
The project was originally forked from tomo2d repository at the Yale university, website: [http://people.earth.yale.edu/software/jun-korenaga](http://people.earth.yale.edu/software/jun-korenaga). It is created for supporting the work of Ms. Kim Phung Nguyen, a research assistant at the Institute of Petroleum, the Heriot Watt University. All changes and contribution should be reported back to the mentioned 2 parties.

## TECHNICAL REVIEW

There are changes of source code in order to make the code be possibly compiled by the GNU Compiler Collection (gcc) version 4.9.2:
* the iostream.h declared in several "error.cc" were replace by iostream, which is a newer library
* Added the library cstdlib, and declared "using namespace std;" in some source files:
 * util.cc
 * corrlen.cc
 * lsqr.cc
* in "heap_deque.h", any of push\_back actions were replaced by this->push\_back


text:
  Peyrusse est
       un village
       géographiquement positionné dans le département de Cantal en Auvergne. On dénombrait 177 habitants en 2008.

Si vous pensez demenager à Peyrusse, vous pourrez facilement trouver une maison à acheter.

La ville propose quelques  équipements sportifs, elle propose entre autres une boucle de randonnée.

À coté de Peyrusse sont localisées les communes de
Molompize localisée à 8 km, 292 habitants,
Vèze à 7 km, 71 habitants,
Ferrières-Saint-Mary localisée à 3 km, 255 habitants,
Valjouze à 5 km, 26 habitants,
Joursac située à 6 km, 155 habitants,
Molèdes à 6 km, 104 habitants,
 entre autres. De plus, Peyrusse est située à seulement 29 km de Brioude.

Le nombre d'habitations, à Peyrusse, était réparti en 2011 en huit appartements et 161 maisons soit
 un marché relativement équilibré.


text:
 interface Expression {
    conditionType?: "OR" | "AND";
    category?: string;
    operator?: string;
    value?: string;
    expressions?:Expression[];
}

export default Expression;


text:
layout: post
title: Welcome
comments: true
---

I plan to use this blog to share some of my thoughts on doing data analyses. I'm not a statistician or a computer scientist by training, but hopefully my physics background can provide a slightly different angle for these discussions.

This blog is called *Uncertainties*, as I think estimating and reducing uncertainties are the most essential part (and the hardest part) of a data analysis. They deserve more attention from us.

I'm very excited about what I may write in the coming days and months!


text:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Castle.Core.Logging;
using SOURCE.Infrastructure.Services.Depots;
using SOURCE.Infrastructure.Services.Encryption;
using SOURCE.BackOffice.Web.Controllers.Modularity;
using SOURCE.BackOffice.Web.Controllers.Helpers;
using SOURCE.Infrastructure.Constant;
using SOURCE.BackOffice.Web.Controllers.Filters;
using System.Net;
using SOURCE.BackOffice.Web.Controllers.ActionResults;
using SOURCE.Infrastructure.Extensions;
using SOURCE.Domaine.Composite;
using SOURCE.Domaine.Results;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Common;
using System.Text;
using System;
using SOURCE.BackOffice.Web.ViewModels.ModelBuilders.Recherche.Recherche;
using SOURCE.Infrastructure.Attributes.Modularity;
using SOURCE.Domaine;
using AutoMapper;
using System.Transactions;
using SOURCE.BackOffice.Web.ViewModels.Pages.Recherche.Criteres;
using SOURCE.BackOffice.Web.ViewModels.Pages.Common;
using SOURCE.BackOffice.Web.ViewModels.Pages.Recherche.Selection;
using SOURCE.Infrastructure.Services.Caching;
using SOURCE.Infrastructure.Services.Exports;
using SOURCE.Infrastructure.Exceptions;

namespace SOURCE.BackOffice.Web.Controllers.Recherche
{
    public class RechercheController : ModularController
    {
        private readonly IRechercheModelBuilder _rechercheModelBuilder;

        public RechercheController(
            ILogger logger,
            ICryptography encryption,
            IDepotFactory depotFactory,
            IRechercheModelBuilder rechercheModelBuilder,
            ICommonModelBuilder commonModelBuilder,
            ICaching cachingService,
            IExcelExport exportService)
            : base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
        {
            _rechercheModelBuilder = rechercheModelBuilder;
            Page = PageEnum.Recherche;
        }

        public ActionResult Index()
        {
            return ProcessPage();
        }

        public ActionResult ComparePlanning(long[] ids)
        {
            Page = PageEnum.ComparePlanning;
            ViewBag.ids = string.Join(",", ids);
            return ProcessPage();
        }

        [HttpGet]
        public ActionResult Recherche(long? demandeID)
        {
            var vm = _commonModelBuilder.BuildDetailsViewModel(Context, (long)ActionModeAffichageEnum.Consultation, (long)GroupeVueEnum.RechercheRecherche, null, null);

            foreach (var item in vm.GroupeVue.Vues)
            {
                item.Url = RoutesHelper.GetUrl(item.CodeRoute, new { demandeID = demandeID });
            }

            return View("~/Views/Common/Details.cshtml", vm);
        }

        [HttpGet]
        public ActionResult Criteres(long? demandeID)
        {
            BuildActionContext(VueEnum.RechercheCriteres);

            var vm = _rechercheModelBuilder.BuildCriteresViewModel(Context, demandeID);

            return View(vm);
        }

        [HttpGet]
        public ActionResult Sauvegardes(long? demandeID)
        {
            BuildActionContext(VueEnum.RechercheSauvegarde);

            var vm = _rechercheModelBuilder.BuildSauvegardesViewModel(Context, demandeID);

            return View(vm);
        }

        [HttpGet]
        public ActionResult Selection(long demandeID)
        {
            BuildActionContext(VueEnum.RechercheSelection);

            var vm = _rechercheModelBuilder.BuildSelectionViewModel(Context, demandeID);

            return View(vm);
        }

        [HttpPost]
        public ActionResult ModificationMultiple(ModificationMultipleViewModel model)
        {
            BuildActionContext(VueEnum.RechercheSelection);

            var intervenantCompetence = AutoMapper.Mapper.Map<ModificationMultipleViewModel, IntervenantCompetenceDto>(model);
            var res = _depotFactory.RechercheDepot.ModificationMultiple(Context.User.ID, intervenantCompetence);

            if (res.Any(x => x.ErreurNumber < 0))
            {
                throw new ValidationException(res.Where(x => x.ErreurNumber < 0).Select(x => Tuple.Create(x.ErreurCode, x.ErreurLib)));
            }

            return new JsonHttpStatusResult((int) HttpStatusCode.OK, res);
        }

        [HttpPost]
        public ActionResult SaveSelectionElement(RechercheSelectionItemViewModel model)
        {
            BuildActionContext(VueEnum.RechercheSelection);
            //todo time stamp
            var element = AutoMapper.Mapper.Map<RechercheSelectionItemViewModel, SelectionElementDto>(model);
            var res = _depotFactory.RechercheDepot.SaveSelectionElement(element);

            _depotFactory.PlanningDepot.UpdateStatutPlanningFromElementSelection(element.ID, Context.User.ID);

            return new JsonHttpStatusResult((int)HttpStatusCode.OK, res.ID);
        }

        [HttpGet]
        public ActionResult Resultat(long rechercheID, long? demandeID)
        {
            BuildActionContext(VueEnum.RechercheResults);

            var vm = _rechercheModelBuilder.BuildResultsViewModel(Context, rechercheID, demandeID);

            var recherche = _depotFactory.RechercheDepot.GetById(rechercheID);
            if (vm != null && vm.JqGridModel != null && recherche.ExportExcel)
            {
                vm.ExportUrl = CreateExportFile(vm.JqGridModel.Data, "ExportRecherche.xls", FileDownloadTypes.ExportRecherche);
            }

            return View(vm);
        }

        [HttpPost]
        [ValidateModelState]
        public ActionResult Recherche(RechercheCriteresViewModel rechercheVM)
        {
            var rechercheComposite = Mapper.Map<RechercheCriteresViewModel, RechercheComposite>(rechercheVM);

            using (var transaction = new TransactionScope())
            {
                var id = _depotFactory.RechercheDepot.Search(Context.User.ID, rechercheComposite);

                transaction.Complete();

                return new JsonHttpStatusResult((int)HttpStatusCode.OK, id);
            }
        }

        [HttpPost]
        [ValidateModelState]
        public ActionResult CreerSauvegarde(RechercheCriteresViewModel rechercheVM)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                if (rechercheVM != null && rechercheVM.Recherche != null && string.IsNullOrWhiteSpace(rechercheVM.Recherche.Libelle))
                {
                    rechercheVM.Recherche.Libelle = string.Format("{0}-{1}", _cachingService.Translate("SAVE_RECHERCHE_DEFAULT_LIB"), DateTime.Now.ToString("MM_dd_yyyy_h:mm:ss"));
                }
                var rechercheComposite = Mapper.Map<RechercheCriteresViewModel, RechercheComposite>(rechercheVM);
                _depotFactory.RechercheDepot.CreerSauvegarde(Context.User.ID, rechercheComposite);

                transaction.Complete();

                return new JsonHttpStatusResult((int)HttpStatusCode.OK);
            }
        }

        [HttpPost]
        public ActionResult LoadSauvegarde(long id, long? demandeID)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                _depotFactory.RechercheDepot.LoadSauvegarde(Context.User.ID, id, demandeID);
                transaction.Complete();
                return new JsonHttpStatusResult((int)HttpStatusCode.OK);
            }
        }

        [HttpPost]
        public ActionResult AddToSelection(RechercheAddSelectionViewModel model)
        {
            if (model.ListIntervenantID == null || !model.ListIntervenantID.Any(x => x > 0))
            {
                return new JsonHttpStatusResult((int)HttpStatusCode.BadRequest, new { error = "VALIDATION_SELECTION_NO_ITEMS_SELECTED" });
            }
            using (TransactionScope transaction = new TransactionScope())
            {
                _depotFactory.RechercheDepot.AddToSelection(Context.User.ID, model.RechercheID, model.DemandeID, model.ListIntervenantID);
                transaction.Complete();
                return new JsonHttpStatusResult((int)HttpStatusCode.OK);
            }
        }

        public ActionResult PlanningCompare(long[] ids)
        {
            BuildActionContext(VueEnum.RecherchePlanningCompare);

            var vm = _rechercheModelBuilder.BuildPlanningCompareViewModel(Context, ids.AsEnumerable());

            return View(vm);
        }

        [HttpPost]
        public ActionResult GetPoolData(long id)
        {
            if (id <= 0)
            {
                return new JsonHttpStatusResult((int)HttpStatusCode.BadRequest, new { error = "VALIDATION_POOL_ID_INVALID" });
            }

            var vm = _rechercheModelBuilder.BuildPoolDataViewModel(Context, id);

            return new JsonHttpStatusResult((int)HttpStatusCode.OK, vm);
        }

        public override void ProcessGroupeVues(PageViewModel page)
        {
            page.GroupeVues = _commonModelBuilder.BuildPageGroupeVuesViewModel(Context, (long)Page.Value, page.IdFonctionnel);

            if (page.GroupeVues != null)
            {
                foreach (var groupeVue in page.GroupeVues)
                {
                    var idFonctionnel = groupeVue.IdFonctionnel.HasValue ? groupeVue.IdFonctionnel.Value : page.IdFonctionnel;

                    groupeVue.Url = RoutesHelper.GetUrl(groupeVue.CodeRoute, new { id = idFonctionnel, demandeID = idFonctionnel, ids = ViewBag.ids  });
                }
            }
        }

        [HttpPost]
        public ActionResult ReinitialiseRecherche(long? demandeID)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                _depotFactory.RechercheDepot.ReinitialiseRecherche(Context.User.ID, Context.User.LangueID, demandeID);
                transaction.Complete();
                return new JsonHttpStatusResult((int)HttpStatusCode.OK);
            }
        }
    }
}


text:
using System;
using FlubuCore.Tasks.Utils;
using Xunit;

namespace FlubuCore.Tests.Tasks
{
    public class QueryServiceTests : TaskUnitTestBase
    {
        private readonly ServiceStatusTask _task;

        public QueryServiceTests()
        {
            _task = new ServiceStatusTask("eventlog");
            Tasks.Setup(x => x.RunProgramTask("sc")).Returns(RunProgramTask.Object);
        }

        [Fact]
        public void QueryRunningService()
        {
            Properties.Setup(i => i.Set("eventlog.status", ServiceStatus.Running, true));
            RunProgramTask.Setup(i => i.GetOutput()).Returns(@"SERVICE_NAME: eventlog
        TYPE               : 30  WIN32
        STATE              : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0
        PID                : 2928
        FLAGS              :");

            _task.ExecuteVoid(Context.Object);

            Properties.VerifyAll();
        }

        [Fact]
        public void QueryStoppedService()
        {
            Properties.Setup(i => i.Set("eventlog.status", ServiceStatus.Stopped, true));
            RunProgramTask.Setup(i => i.GetOutput()).Returns(@"SERVICE_NAME: AppIDSvc
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0");

            _task.ExecuteVoid(Context.Object);

            Properties.VerifyAll();
        }

        [Fact]
        public void WaitForStopServiceTimeout()
        {
            Properties.Setup(i => i.Get<ServiceStatus>("eventlog.status", ServiceStatus.Unknown, string.Empty)).Returns(ServiceStatus.Running);
            var task = new WaitForServiceStopTask("eventlog");
            Tasks.Setup(x => x.RunProgramTask("sc")).Returns(RunProgramTask.Object);
            RunProgramTask.Setup(i => i.GetOutput()).Returns(@"SERVICE_NAME: AppIDSvc
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 4  RUN
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0");

            var res = task.Execute(Context.Object);
            Assert.Equal(1, res);
        }

        [Fact]
        public void WaitForStopService()
        {
            Properties.Setup(i => i.Get<ServiceStatus>("eventlog.status", true, string.Empty)).Returns(ServiceStatus.Stopped);
            var task = new WaitForServiceStopTask("eventlog");
            Tasks.Setup(x => x.RunProgramTask("sc")).Returns(RunProgramTask.Object);
            RunProgramTask.Setup(i => i.GetOutput()).Returns(@"SERVICE_NAME: AppIDSvc
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 1  ST
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0");

            var res = task.Execute(Context.Object);
            Assert.Equal(1, res);
        }
    }
}


text:
import java.awt.Point;
import java.awt.geom.Point2D;

public class Zombie implements Comparable<Object> {
	private Point position;
	private int animatesAt;
	private int diesAt;
	private int LONGEVITY = 1000;

	// If Smashed or Expired
	boolean isDead = false;

	public Zombie(Point position, int animatesAt) {
		this.setPosition(position);
		this.setAnimatesAt(animatesAt);
		this.setDeathTime();
	}

	public static Zombie FactoryFromInput(String inputString) {
		String[] parts = inputString.split(" ");
		Point position = new Point(Integer.parseInt(parts[0]) * 100, Integer.parseInt(parts[1]) * 100);
		int animatesAt = Integer.parseInt(parts[2]);

		return new Zombie(position, animatesAt);
	}

	public int distanceFrom(Point p) {
		return (int) this.getPosition().distance((Point2D) p);
	}

	public boolean canBeReachedAndSmashedFromPoint(Point p, int nextFullChargedAt) {
		int distance = this.distanceFrom(p);
		int trueDistance = nextFullChargedAt > distance ? nextFullChargedAt : distance;

		return (this.getAnimatesAt() <= trueDistance && this.getDiesAt() >= trueDistance);
	}

	@Override
	public int compareTo(Object z) {
		return (this.getAnimatesAt() - ((Zombie) z).getAnimatesAt());
	}

	// Getters / Setters

	public Point getPosition() {
		return position;
	}

	public void setPosition(Point position) {
		this.position = position;
	}

	private void setDeathTime() {
		this.setDiesAt(this.getAnimatesAt() + this.LONGEVITY);
	}

	public int getAnimatesAt() {
		return animatesAt;
	}

	public void setAnimatesAt(int animatesAt) {
		this.animatesAt = animatesAt;
	}

	public int getDiesAt() {
		return diesAt;
	}

	public void setDiesAt(int diesAt) {
		this.diesAt = diesAt;
	}

}


text:
module ReportsHtmlHelper
  # Write a report in HTML format. Writes a header, then each table in the report, including each table's title if it has one.
  def html_report(report=@report)
    header = content_tag(:h2, report.title)

    body = ""

    report.tables.each do |table|
      body += html_table(table)
    end

    (header + body.html_safe)
  end

  def html_table(table)
    format_table(table)
    html_class = "report #{table.name}"
    html_class += " sortable" if table.sortable
    html_class += " #{table.font_size}"
    if table.is_a?(Report::Table::Map)
      table_output = html_map(table)
    else
      table_output = content_tag(:table, html_inner_table(table), :class => html_class, :table_name => table.name)
    end
    (table_title(table) + table_output)
  end

  def html_map(table)
    @html_map_div_count ||= 1
    map = Mapstraction.new("map_div_#{@html_map_div_count}", SimpleReports::MAP[:service])
    @html_map_div_count += 1

    map.control_init(:small => true)
    map.center_zoom_init(table.center, table.zoom)

    marker_array = []
    table.rows.each do |row|
      marker_array << Marker.new([row.at("LAT"),row.at("LNG")], :label => row.at("LABEL"), :info_bubble => row.at("INFO"))
    end

    clusterer = Clusterer.new(marker_array)
    map.clusterer_init(clusterer)

    content_for(:map_header) do
      # javascript_include_tag('clusterer')
      Mapstraction.header(SimpleReports::MAP[:service]) + map.to_html
    end

    map.div(:width => 600, :height => 400).html_safe
  end

  def table_title(table)
    return content_tag(:h3, table.title) if table.title
    return "" # return empty string if there is no title
  end

  def html_inner_table(table=@table)
    html_header_row(table) + html_data_rows(table)
  end

  def html_data_rows(table=@table)
    rows = "
"
    tbody_ended = false
    table.rows.each do |row|
      inner_row_html = ""
      row.data.each_with_index do |column, index|
        html_class = table.align[index].to_s
        inner_row_html << content_tag(:td, column, :class => html_class)
      end
      tbody_end = ''
      # TODO: instead of relying on summary/total rows being bolded, come up with a row divider instead
      if !tbody_ended and row.has_row_format?(:bold)
        tbody_ended = true
        tbody_end = '

'
      end
      rows << tbody_end + content_tag(:tr, inner_row_html)
    end

    rows + (tbody_ended ? '
' : '
')
  end

  def html_header_row(table=@table)
    start_row = "

"
    header_cells = ''
    table.header.each do |column|
      header_cells += html_header_cell(column, table)
    end
    end_row = "

"

    start_row + header_cells + end_row
  end

  def html_header_cell(column, table=@table)
    options = {}
    if table.sortable and column == table.sort_by
      options.merge!(:class => "sort#{table.sort_order ? "asc" : "desc"}")
    end

    content_tag(:th, column, options)
  end

end


text:
	<title>Chris Hollins's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Chris Hollins's panel show appearances

Chris Hollins (born 1971-03-20[ref]) has appeared in 3 episodes between 2010-2011.  Chris Hollins on IMDB. Chris Hollins on Wikipedia.

2010

2011

2011-10-27 / Loose Women

2011-05-10 / Loose Women

2010-01-02 / Fighting Talk


text:
from oslo_policy import policy

COMPUTE_API = 'os_compute_api'

RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner'
RULE_ADMIN_API = 'rule:admin_api'
RULE_ANY = '@'

# NOTE(johngarbutt) The base rules here affect so many APIs the list
# of related API operations has not been populated. It would be
# crazy hard to manually maintain such a list.
rules = [
    policy.RuleDefault(
        "context_is_admin",
        "role:admin",
        "Decides what is required for the 'is_admin:True' check to succeed."),
    policy.RuleDefault(
        "admin_or_owner",
        "is_admin:True or project_id:%(project_id)s",
        "Default rule for most non-Admin APIs."),
    policy.RuleDefault(
        "admin_api",
        "is_admin:True",
        "Default rule for most Admin APIs.")
]

def list_rules():
    return rules


text:
package example

import java.sql.Timestamp
import java.util.Calendar

import com.folio_sec.example.domain.issue003.scala_api._
import com.folio_sec.reladomo.scala_api.TransactionProvider.withTransaction
import com.folio_sec.reladomo.scala_api.configuration.DatabaseManager
import com.folio_sec.reladomo.scala_api.util.TimestampUtil
import org.scalatest.{ FunSpec, Matchers }
import unit.DatabasePreparation

class Issue003Spec extends FunSpec with Matchers with DatabasePreparation {

  initializeIssue003Database()
  DatabaseManager.loadRuntimeConfig("ReladomoRuntimeConfig.xml")

  describe("Related object with non existent condition") {
    it("should return None") {
      withTransaction { implicit tx =>
        NewParentObject(name = "name1").insert()
      }

      val maybeParent = ParentObjectFinder.findOneWith(_.name.eq("name1"))

      maybeParent match {
        case Some(parent) =>
          //since there is no child object inserted, it should return None.
          parent.relatedObject(TimestampUtil.now()) should equal(None)
        case _ =>
          fail()
      }
    }
  }

  describe("Bi-temporal object") {
    it("updates attributes with non-infinite businessTo attribute without touching primary key") {
      withTransaction { implicit tx =>
        val parentObject = NewParentObject(name = "name2").insert()
        NewBitemporalChildObject(name = "name", state = 1, parentObject.id)
          .insertUntil(createTimestamp(9000, 1, 1)) //using long time away so that the test is practically deterministic
      }

      ParentObjectFinder.findOneWith(_.name.eq("name2")) match {
        case Some(parent) =>
          parent.relatedObject(TimestampUtil.now()) match {
            case Some(child: BitemporalChildObject) =>
              withTransaction { implicit tx =>
                child.copy(name = "updated name").update()
              }
            case _ => fail()
          }
        case _ => fail()
      }

      val maybeUpdatedChild = BitemporalChildObjectFinder.findOneWith(_.businessDate.eq(TimestampUtil.now()))

      maybeUpdatedChild match {
        case Some(child) =>
          child.name should equal("updated name")
        case _ =>
          fail()
      }
    }

  }

  private[this] def createTimestamp(year: Int, month: Int, dayOfMonth: Int): Timestamp = {
    val cal = Calendar.getInstance
    cal.set(Calendar.YEAR, year)
    cal.set(Calendar.MONTH, month - 1)
    cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
    cal.set(Calendar.AM_PM, Calendar.AM)
    cal.set(Calendar.HOUR_OF_DAY, 0)
    cal.set(Calendar.MINUTE, 0)
    cal.set(Calendar.SECOND, 0)
    cal.set(Calendar.MILLISECOND, 0)
    new Timestamp(cal.getTimeInMillis)
  }

}


text:
package cloudphoto

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DeletePhotos invokes the cloudphoto.DeletePhotos API synchronously
// api document: https://help.aliyun.com/api/cloudphoto/deletephotos.html
func (client *Client) DeletePhotos(request *DeletePhotosRequest) (response *DeletePhotosResponse, err error) {
	response = CreateDeletePhotosResponse()
	err = client.DoAction(request, response)
	return
}

// DeletePhotosWithChan invokes the cloudphoto.DeletePhotos API asynchronously
// api document: https://help.aliyun.com/api/cloudphoto/deletephotos.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeletePhotosWithChan(request *DeletePhotosRequest) (<-chan *DeletePhotosResponse, <-chan error) {
	responseChan := make(chan *DeletePhotosResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DeletePhotos(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DeletePhotosWithCallback invokes the cloudphoto.DeletePhotos API asynchronously
// api document: https://help.aliyun.com/api/cloudphoto/deletephotos.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeletePhotosWithCallback(request *DeletePhotosRequest, callback func(response *DeletePhotosResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DeletePhotosResponse
		var err error
		defer close(result)
		response, err = client.DeletePhotos(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DeletePhotosRequest is the request struct for api DeletePhotos
type DeletePhotosRequest struct {
	*requests.RpcRequest
	StoreName string    `position:"Query" name:"StoreName"`
	LibraryId string    `position:"Query" name:"LibraryId"`
	PhotoId   *[]string `position:"Query" name:"PhotoId"  type:"Repeated"`
}

// DeletePhotosResponse is the response struct for api DeletePhotos
type DeletePhotosResponse struct {
	*responses.BaseResponse
	Code      string   `json:"Code" xml:"Code"`
	Message   string   `json:"Message" xml:"Message"`
	RequestId string   `json:"RequestId" xml:"RequestId"`
	Action    string   `json:"Action" xml:"Action"`
	Results   []Result `json:"Results" xml:"Results"`
}

// CreateDeletePhotosRequest creates a request to invoke DeletePhotos API
func CreateDeletePhotosRequest() (request *DeletePhotosRequest) {
	request = &DeletePhotosRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("CloudPhoto", "2017-07-11", "DeletePhotos", "cloudphoto", "openAPI")
	return
}

// CreateDeletePhotosResponse creates a response to parse from DeletePhotos response
func CreateDeletePhotosResponse() (response *DeletePhotosResponse) {
	response = &DeletePhotosResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
This is the JavaScript summary.

You'll find all the script related in the current directory.

Just in case, here's a link to the docs :)
[Official Adobe docs & guides for AppleScript/Javascript/VBScript](http://www.adobe.com/devnet/illustrator/scripting.html)


text:
import { Types, reflect } from 'tsruntime'
import { expectUnion } from '../utils'

describe('union types', () => {
    it('string | null', () => {
        const type = reflect<string | null>()
        expectUnion(type, {kind: Types.TypeKind.Null}, { kind: Types.TypeKind.String});
    });

    it('string | undefined', () => {
        const type = reflect<string | undefined>()
        expectUnion(type, {kind: Types.TypeKind.Undefined}, {kind: Types.TypeKind.String});
    });

})


text:
class DropDatasetContributorsTable < ActiveRecord::Migration[4.2]
  def up
    drop_table :dataset_contributors
  end

  def down
    create_table :dataset_contributors do |t|
      t.integer :dataset_id
      t.integer :user_id

      t.timestamps
    end
  end
end


text:
<?php
$config = CheckmydriveHelper::getConfigs();
?>

            <a href="<?php echo Checkmydrive::root(); ?>" class="brand pull-left">
                    <img alt="<?php echo $config->get('sitename'); ?>" src="<?php echo Checkmydrive::root() . $config->get('logo'); ?> ">

<?php $message = Checkmydrive::getMessage(); ?>


text:
/****************************************************************************
 * apps/system/utils/utils_free.c
 *
 *   Copyright (C) 2013 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/
#include <tinyara/config.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(CONFIG_BUILD_PROTECTED) && defined(CONFIG_MM_KERNEL_HEAP)
#include <fcntl.h>
#include <errno.h>

#include <tinyara/fs/ioctl.h>
#include <tinyara/mminfo.h>
#endif

/****************************************************************************
 * Public Functions
 ****************************************************************************/
int utils_free(int argc, char **args)
{
	struct mallinfo data;
#if defined(CONFIG_BUILD_PROTECTED) && defined(CONFIG_MM_KERNEL_HEAP)
	int fd;
	int ret;

	fd = open(MMINFO_DRVPATH, O_RDWR);
	if (fd < 0) {
		printf("Open %s Fail, errno %d\n", MMINFO_DRVPATH, get_errno());
		return ERROR;
	}

	ret = ioctl(fd, MMINFOIOC_HEAP, (int)&data);
	close(fd);
	if (ret != OK) {
		printf("Mminfo ioctl Fail, ret %d\n", ret);
		return ERROR;
	}
#else
#ifdef CONFIG_CAN_PASS_STRUCTS
	data = mallinfo();
#else
	(void)mallinfo(&data);
#endif
#endif
	printf("              total       used       free    largest\n");
	printf(" Mem:	%11d%11d%11d%11d\n", data.arena, data.uordblks, data.fordblks, data.mxordblk);

	return OK;
}


text:
require 'abstract_unit'

class DurationTest < Test::Unit::TestCase
  def test_inspect
    assert_equal '1 month',                         1.month.inspect
    assert_equal '1 month and 1 day',               (1.month + 1.day).inspect
    assert_equal '6 months and -2 days',            (6.months - 2.days).inspect
    assert_equal '10 seconds',                      10.seconds.inspect
    assert_equal '10 years, 2 months, and 1 day',   (10.years + 2.months + 1.day).inspect
    assert_equal '7 days',                          1.week.inspect
    assert_equal '14 days',                         1.fortnight.inspect
  end

  def test_minus_with_duration_does_not_break_subtraction_of_date_from_date
    assert_nothing_raised { Date.today - Date.today }
  end

  def test_plus_with_time
    assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
  end

  def test_argument_error
    begin
      1.second.ago('')
      flunk("no exception was raised")
    rescue ArgumentError => e
      assert_equal 'expected a time or date, got ""', e.message, "ensure ArgumentError is not being raised by dependencies.rb"
    rescue Exception
      flunk("ArgumentError should be raised, but we got #{$!.class} instead")
    end
  end

  def test_fractional_weeks
    assert_equal((86400 * 7) * 1.5, 1.5.weeks)
    assert_equal((86400 * 7) * 1.7, 1.7.weeks)
  end

  def test_fractional_days
    assert_equal 86400 * 1.5, 1.5.days
    assert_equal 86400 * 1.7, 1.7.days
  end

  uses_mocha 'TestDurationSinceAndAgoWithCurrentTime' do
    def test_since_and_ago_with_fractional_days
      Time.stubs(:now).returns Time.local(2000)
      # since
      assert_equal 36.hours.since, 1.5.days.since
      assert_equal((24 * 1.7).hours.since, 1.7.days.since)
      # ago
      assert_equal 36.hours.ago, 1.5.days.ago
      assert_equal((24 * 1.7).hours.ago, 1.7.days.ago)
    end

    def test_since_and_ago_with_fractional_weeks
      Time.stubs(:now).returns Time.local(2000)
      # since
      assert_equal((7 * 36).hours.since, 1.5.weeks.since)
      assert_equal((7 * 24 * 1.7).hours.since, 1.7.weeks.since)
      # ago
      assert_equal((7 * 36).hours.ago, 1.5.weeks.ago)
      assert_equal((7 * 24 * 1.7).hours.ago, 1.7.weeks.ago)
    end

    def test_deprecated_fractional_years
      years_re = /Fractional years are not respected\. Convert value to integer before calling #years\./
      assert_deprecated(years_re){1.0.years}
      assert_deprecated(years_re){1.5.years}
      assert_not_deprecated{1.years}
      assert_deprecated(years_re){1.0.year}
      assert_deprecated(years_re){1.5.year}
      assert_not_deprecated{1.year}
    end

    def test_deprecated_fractional_months
      months_re = /Fractional months are not respected\. Convert value to integer before calling #months\./
      assert_deprecated(months_re){1.5.months}
      assert_deprecated(months_re){1.0.months}
      assert_not_deprecated{1.months}
      assert_deprecated(months_re){1.5.month}
      assert_deprecated(months_re){1.0.month}
      assert_not_deprecated{1.month}
    end

    def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
      Time.zone_default = nil
      with_env_tz 'US/Eastern' do
        Time.stubs(:now).returns Time.local(2000)
        # since
        assert_equal false, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
        assert_equal Time.local(2000,1,1,0,0,5), 5.seconds.since
        # ago
        assert_equal false, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
        assert_equal Time.local(1999,12,31,23,59,55), 5.seconds.ago
      end
    end

    def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
      silence_warnings do # silence warnings raised by tzinfo gem
        Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
        with_env_tz 'US/Eastern' do
          Time.stubs(:now).returns Time.local(2000)
          # since
          assert_equal true, 5.seconds.since.is_a?(ActiveSupport::TimeWithZone)
          assert_equal Time.utc(2000,1,1,0,0,5), 5.seconds.since.time
          assert_equal 'Eastern Time (US & Canada)', 5.seconds.since.time_zone.name
          # ago
          assert_equal true, 5.seconds.ago.is_a?(ActiveSupport::TimeWithZone)
          assert_equal Time.utc(1999,12,31,23,59,55), 5.seconds.ago.time
          assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
        end
      end
    ensure
      Time.zone_default = nil
    end
  end

  protected
    def with_env_tz(new_tz = 'US/Eastern')
      old_tz, ENV['TZ'] = ENV['TZ'], new_tz
      yield
    ensure
      old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
    end
end


text:
/*
 * Licensed under the GPL License. You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://probe.jstripe.com/d/license.shtml
 *
 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

function inverse($f) {
    for ($i = 0; $i < $f.elements.length; $i++) {
        if ($f.elements[$i].type == "checkbox") {
            $f.elements[$i].checked = !$f.elements[$i].checked;
        }
    }
    return false;
}

function checkAll($f) {
    for ($i = 0; $i < $f.elements.length; $i++) {
        if ($f.elements[$i].type == "checkbox") {
            $f.elements[$i].checked = true;
        }
    }
    return false;
}

/**
 * Requires prototype.js (http://prototype.conio.net/)
 */
Ajax.ImgUpdater = Class.create();
Ajax.ImgUpdater.prototype = {
    initialize: function(imgID, timeout, newSrc) {
        this.img = document.getElementById(imgID);
        if (newSrc) {
            this.src = newSrc;
        } else {
            this.src = this.img.src;
        }
        this.timeout = timeout;
        this.start();
    },

    start: function() {
        var now = new Date();
        this.img.src = this.src + '&t=' + now.getTime();
        this.timer = setTimeout(this.start.bind(this), this.timeout * 1000);
    },

    stop: function() {
        if (this.timer) clearTimeout(this.timer);
    }
}

function togglePanel(container, remember_url) {
    if (Element.getStyle(container, "display") == 'none') {
        if (remember_url) {
            new Ajax.Request(remember_url, {method:'get',asynchronous:true, parameters: 'state=on'});
        }
        if (document.getElementById('invisible_' + container)) {
            Element.hide('invisible_' + container);
        }
        if (document.getElementById('visible_' + container)) {
            Element.show('visible_' + container);
        }

        Effect.Grow(container);
    } else {
        if (remember_url) {
            new Ajax.Request(remember_url, {method:'get',asynchronous:true, parameters: 'state=off'});
        }
        if (document.getElementById('visible_' + container)) {
            Element.hide('visible_' + container);
        }
        if (document.getElementById('invisible_' + container)) {
            Element.show('invisible_' + container);
        }
        Effect.Shrink(container);
    }
    return false;
}

function scaleImage(v, min, max) {
    var images = document.getElementsByClassName('scale-image');
    w = (max - min) * v + min;
    for (i = 0; i < images.length; i++) {
        images[i].style.width = w + 'px';
    }
}

function toggleAndReloadPanel(container, url) {
    if (Element.getStyle(container, "display") == 'none') {
        new Ajax.Updater(container, url);
        Effect.BlindDown(container);
    } else {
        Effect.Shrink(container);
    }
}

function getWindowHeight() {
    var myHeight = 0;
    if (typeof( window.innerHeight ) == 'number') {
        //Non-IE
        myHeight = window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

function getWindowWidth() {
    var myWidth = 0;
    if (typeof( window.innerWidth ) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
    }
    return myWidth;
}

var helpTimerID;

function setupHelpToggle(url) {
    rules = {
        'li#abbreviations': function(element) {
            element.onclick = function() {
                help_container = 'help';
                if (Element.getStyle(help_container, "display") == 'none') {
                    new Ajax.Updater(help_container, url);
                }
                Effect.toggle(help_container, 'appear');
                if (helpTimerID) clearTimeout(helpTimerID)
                helpTimerID = setTimeout('Effect.Fade("' + help_container + '")', 15000);
                return false;
            }
        }
    }
    Behaviour.register(rules);
}

function addAjaxTooltip(activator, tooltip, url) {
    Tooltip.closeText = null;
    Tooltip.autoHideTimeout = null;
    Tooltip.showMethod = function(e) {
        Effect.Appear(e, {to: 0.9});
    }

    Tooltip.add(activator, tooltip);
    tt_container = $$('#' + tooltip + ' .tt_content')[0];
    Event.observe(activator, 'click', function(e) {

        t_title = $('tt_title');

        if (t_title) t_title.hide();

        tt_container.style.width = '300px';

        tt_container.innerHTML = '

';
        new Ajax.Updater(tt_container, url, {method: 'get'}).onComplete = function () {
            tt_container.style.width = null;
            the_title = $('tooltip_title');
            t_title = $('tt_title');

            if (the_title && t_title) {
                the_title.hide();
                t_title.innerHTML = the_title.innerHTML;
                t_title.show();
            }
        };
    });
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Samuel
 * Date: 24/07/2015
 * Time: 15:10
 */

namespace Samcrosoft\MultiAuth\Manager\Resolver\Session;

use Illuminate\Contracts\Config\Repository;

/**
 * Class MultiAuthSessionResolver
 * @package Samcrosoft\MultiAuth\Manager\Resolver\Session
 */
class MultiAuthSessionResolver
{
    /**
     * @var
     */
    var $app;

    function __construct($app)
    {
        $this->app = $app;
    }

    /**
     * this method will resolve the appropriate session cookie key name
     * @return string
     */
    public function resolveAppropriateSessionCookieName()
    {
        $sDefaultSessionCookie = $this->app['config']['session.cookie'];
        $sReturn = $sDefaultSessionCookie;

        /** @var Repository $oConfig */
        $oConfig = $this->app['config'];
        $aResolverClosures = $oConfig->get("multiauth.session_cookie_resolver");
        if($aResolverClosures && is_array($aResolverClosures)){
            $oCurrentRequest = $this->app['request'];
            foreach ($aResolverClosures as $sKey=>$oClosure) {
                if(!($oClosure instanceof \Closure))
                    continue;
                else{
                    $bReturn = $oClosure($oCurrentRequest);
                    if($bReturn) {
                        $sReturn = $sKey;
                        break;      // break out of the loop check
                    }
                }
            }
        }

        return $sReturn;
    }

}