text:
<?php

namespace SymphonyCms\Install\Migrations;

use \Exception;
use \SymphonyCms\Symphony;
use \SymphonyCms\Exceptions\DatabaseException;
use \SymphonyCms\Install\Migration;

/**
 * Migration to 2.2.5
 *
 * @package SymphonyCms
 * @subpackage Install
 */
class Migration225 extends Migration
{
    public static function run($function, $existing_version = null)
    {
        self::$existing_version = $existing_version;

        try {
            $canProceed = self::$function();

            return ($canProceed === false) ? false : true;
        } catch (DatabaseException $e) {
            Symphony::Log()->writeToLog('Could not complete upgrading. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getDatabaseErrorMessage(), E_ERROR, true);

            return false;
        } catch (Exception $e){
            Symphony::Log()->writeToLog('Could not complete upgrading because of the following error: ' . $e->getMessage(), E_ERROR, true);

            return false;
        }
    }

    public static function getVersion()
    {
        return '2.2.5';
    }

    public static function getReleaseNotes()
    {
        return 'http://getsymphony.com/download/releases/version/2.2.5/';
    }

    public static function upgrade()
    {
        Symphony::get('Configuration')->set('version', '2.2.5', 'symphony');

        if (Symphony::get('Configuration')->write() === false) {
            throw new Exception('Failed to write configuration file, please check the file permissions.');
        } else {
            return true;
        }
    }
}


text:
title: "Uptime status, new Ruby service, and more!"
description: "First of all, we would like to say thanks for trying WeDeploy! You're shaping the future of this product, so we appreciate you taking the time to provide some feedback."
date: "Oct 10, 2016"
author: "Zeno Rocha"
image: "images/blog/post-1--0.png"
layout: "blog"
---

{$page.description}

> You're shaping the future of this product.

In the last few weeks we've been working day and night to make WeDeploy more stable. Almost two hundred projects have been created since we first launched and dozens of bugs have been fixed.

Today, we would like to show you some of the things we're working on.

#### Uptime Status

Even though this is an alpha version and problems are somewhat expected, we recognize the importance of being transparent about outages. That's why we would like to share with you a new page where you can check [WeDeploy's uptime status](https://status.wedeploy.com/).

#### Ruby Service

Our mission is to create a platform for all kinds of developers. With that in mind, we're introducing a new Ruby service. You can get more information by [reading the docs](/docs/other/ruby/) or checking this [example](https://github.com/wedeploy-examples/ruby-example). Go to [Console](https://console.wedeploy.com) to start using Ruby Service.

> Our mission is to create a platform for all kinds of developers.

If you have any questions, feel free to [contact us](https://chat.wedeploy.com/).

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using Localization.Xliff.OM.Core;
using Localization.Xliff.OM.Serialization;
using NUnit.Framework;

namespace XliffLib.Test
{
    [TestFixture()]
    public class InlineCodeMergerTests
    {

        [Test()]
        public void SingleParagraphPlainTextUnitIsLeftUntouched()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <unit id=""u1"">
            <segment>
                <source>Hello World!</source>
                <target>Hello World!</target>
            </segment>
        </unit>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            Assert.AreEqual(1, newDocument.Files[0].Containers.Count);
            var unit = newDocument.Files[0].Containers[0] as Unit;

            Assert.AreEqual(1, unit.CollapseChildren<Target>()[0].Text.Count);
            var segment = unit.CollapseChildren<Target>()[0].Text[0] as PlainText;
            Assert.IsNotNull(segment);
            Assert.AreEqual("Hello World!", segment.Text);
        }

        [Test()]
        public void TargetWithPcGetConvertedToCDataWithBHtmlTag()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <unit id=""u1"">
            <segment>
                <source>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World</pc>!</source>
                <target>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World</pc>!</target>
            </segment>
        </unit>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            Assert.AreEqual(1, newDocument.Files[0].Containers.Count);
            var unit = newDocument.Files[0].Containers[0] as Unit;

            Assert.AreEqual(1, unit.CollapseChildren<Target>()[0].Text.Count);
            var segment = unit.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment);
            Assert.AreEqual("Hello World!", segment.Text);
        }

        [Test()]
        public void TargetWithPhGetConvertedToCDataWithBrHtmlTag()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <unit id=""u1"">
            <segment>
                <source>Hello <ph id=""1"" subType=""xlf:lb"" type=""fmt""/>World!</source>
                <target>Hello <ph id=""1"" subType=""xlf:lb"" type=""fmt""/>World!</target>
            </segment>
        </unit>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            Assert.AreEqual(1, newDocument.Files[0].Containers.Count);
            var unit = newDocument.Files[0].Containers[0] as Unit;

            Assert.AreEqual(1, unit.CollapseChildren<Target>()[0].Text.Count);
            var segment = unit.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment);
            Assert.AreEqual("Hello
World!", segment.Text);
        }

        [Test()]
        public void TargetWithTwoUnitsWithPcGetConvertedToCDataWithBHtmlTag()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <unit id=""u1"">
            <segment>
                <source>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 1</pc>!</source>
                <target>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 1</pc>!</target>
            </segment>
        </unit>
        <unit id=""u2"">
            <segment>
                <source>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 2</pc>!</source>
                <target>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 2</pc>!</target>
            </segment>
        </unit>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            Assert.AreEqual(2, newDocument.Files[0].Containers.Count);
            var unit1 = newDocument.Files[0].Containers[0] as Unit;
            var unit2 = newDocument.Files[0].Containers[1] as Unit;

            Assert.AreEqual(1, unit1.CollapseChildren<Target>()[0].Text.Count);
            var segment1 = unit1.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment1);
            Assert.AreEqual("Hello World 1!", segment1.Text);

            Assert.AreEqual(1, unit2.CollapseChildren<Target>()[0].Text.Count);
            var segment2 = unit2.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment2);
            Assert.AreEqual("Hello World 2!", segment2.Text);
        }

        [Test()]
        public void TargetWithNestedUnitsWithPcGetConvertedToCDataWithBHtmlTag()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <unit id=""u1"">
            <segment>
                <source>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 1</pc>!</source>
                <target>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 1</pc>!</target>
            </segment>
        </unit>
        <group id=""g1"">
            <unit id=""u2"">
                <segment>
                    <source>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 2</pc>!</source>
                    <target>Hello <pc id=""1"" subType=""xlf:b"" type=""fmt"">World 2</pc>!</target>
                </segment>
            </unit>
        </group>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            Assert.AreEqual(2, newDocument.Files[0].Containers.Count);
            var unit1 = newDocument.Files[0].Containers[0] as Unit;
            var group = newDocument.Files[0].Containers[1] as Group;
            var unit2 = group.Containers[0] as Unit;

            Assert.AreEqual(1, unit1.CollapseChildren<Target>()[0].Text.Count);
            var segment1 = unit1.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment1);
            Assert.AreEqual("Hello World 1!", segment1.Text);

            Assert.AreEqual(1, unit2.CollapseChildren<Target>()[0].Text.Count);
            var segment2 = unit2.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment2);
            Assert.AreEqual("Hello World 2!", segment2.Text);
        }

        [Test()]
        public void TargetWithHrefAndSubflowsConvertedToCDataWithATagWithAttribute()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <group id=""u1-g"">
            <unit id=""u1-1-href"">
                <segment>
                    <source>http://consilium.eu/en</source>
                    <target>http://consilium.eu/it</target>
                </segment>
            </unit>
            <unit id=""u1"">
                <segment>
                    <source>Link to <pc subFlowsStart=""u1-1-href"" id=""1"" type=""link"">Council site in English</pc>!</source>
                    <target>Link to <pc subFlowsStart=""u1-1-href"" id=""1"" type=""link"">Council site in Italian</pc>!</target>
                </segment>
            </unit>
        </group>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            var xliffString = new DefaultExtractor().Write(newDocument, true);
            Assert.AreEqual(1, newDocument.Files[0].Containers.Count);
            var unit = newDocument.Files[0].Containers[0] as Unit;
            Assert.IsNotNull(unit);

            Assert.AreEqual(1, unit.CollapseChildren<Target>()[0].Text.Count);
            var segment = unit.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment);
            Assert.AreEqual("Link to Council site in Italian!", segment.Text);
        }

        [Test()]
        public void TargetWithImgSrcAndSubflowsConvertedToCDataWithImgTagWithAttribute()
        {
            var xliff = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xliff srcLang=""en-GB"" version=""2.0"" trgLang=""it-IT"" xmlns=""urn:oasis:names:tc:xliff:document:2.0"">
    <file id=""f1"">
        <group id=""u1-g"">
            <unit id=""u1-1-src"">
                <segment>
                    <source>http://consilium.eu/en/logo.jpg</source>
                    <target>http://consilium.eu/it/logo.jpg</target>
                </segment>
            </unit>
            <unit id=""u1-1-title"">
                <segment>
                    <source>Council Logo</source>
                    <target>Council Logo Ita</target>
                </segment>
            </unit>
            <unit id=""u1"">
                <segment>
                    <source>Link to <ph subFlows=""u1-1-src u1-1-title"" id=""1"" type=""image""/>Council site in English!</source>
                    <target>Link to <ph subFlows=""u1-1-src u1-1-title"" id=""1"" type=""image""/>Council site in Italian!</target>
                </segment>
            </unit>
        </group>
    </file>
</xliff>";

            XliffDocument document = LoadXliff(xliff);
            var inlineprocessing = new InlineCodeProcessing();

            var newDocument = inlineprocessing.ExecuteMerge(document);

            var xliffString = new DefaultExtractor().Write(newDocument, true);
            Assert.AreEqual(1, newDocument.Files[0].Containers.Count);
            var unit = newDocument.Files[0].Containers[0] as Unit;
            Assert.IsNotNull(unit);

            Assert.AreEqual(1, unit.CollapseChildren<Target>()[0].Text.Count);
            var segment = unit.CollapseChildren<Target>()[0].Text[0] as CDataTag;
            Assert.IsNotNull(segment);
            Assert.AreEqual("Link to Council site in Italian!", segment.Text);
        }

        //Move to actual XliffReader
        private static XliffDocument LoadXliff(string xliff)
        {
            XliffDocument document = null;
            using (Stream stream = GenerateStreamFromString(xliff))
            {
                var reader = new XliffReader();
                document = reader.Deserialize(stream);
            }

            return document;
        }

        private static Stream GenerateStreamFromString(string s)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }
    }
}


text:
{{::vm.translate.get('Clone Product')}}

        <form name="cloneForm" class="form-horizontal">

{{error}}

                {{::vm.translate.get('Product Name')}}

                    <input name="name" ng-model="vm.productClone.name" ng-change="vm.updateSlug()" required class="form-control" />

                {{::vm.translate.get('Slug')}}

                    <input name="slug" ng-model="vm.productClone.slug" required class="form-control" />

                    <button class="btn btn-primary" ng-click="vm.save()"> {{::vm.translate.get('Save')}}</button>
                    <button ui-sref="product-edit({id: vm.productId})" class="btn btn-default">{{::vm.translate.get('Cancel')}}</button>

        </form>


text:
skill: Sublime Text
rating: 5
---


text:
.PHONY: all
all: sphinx

# No -W for doctests because that disallows tests with empty output.
SPHINX_DOCTEST_OPTS=-n -d build/doctress .
SPHINXOPTS=-n -d build/doctrees .

.PHONY: sphinx
sphinx:
	sphinx-build -b html $(SPHINXOPTS) build/html

.PHONY: coverage
coverage:
	sphinx-build -b coverage ${SPHINXOPTS} build/coverage
	cat build/coverage/python.txt

.PHONY: doctest
doctest:
	sphinx-build -b doctest $(SPHINX_DOCTEST_OPTS) build/doctest

clean:
	rm -rf build


text:
package org.jcoderz.phoenix.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBException;

import org.jcoderz.commons.util.IoUtil;
import org.jcoderz.phoenix.checkstyle.jaxb.Checkstyle;
import org.jcoderz.phoenix.report.jaxb.Item;
import org.jcoderz.phoenix.report.jaxb.ObjectFactory;

/**
 * This class is used to read the XML report from checkstyle.
 *
 * The checkstyle report is also transformed to the jCoderZ.org format.
 *
 * @author Michael Griffel
 */
public final class CheckstyleReportReader
      extends AbstractReportReader
{
   /** JAXB context path. */
   public static final String CHECKSTYLE_JAXB_CONTEXT_PATH
      = "org.jcoderz.phoenix.checkstyle.jaxb";

   private static final String CLASSNAME
       = CheckstyleReportReader.class.getName();

   private static final Logger logger = Logger.getLogger(CLASSNAME);

   private Checkstyle mReportDocument;

   CheckstyleReportReader ()
         throws JAXBException
   {
      super(CHECKSTYLE_JAXB_CONTEXT_PATH);
   }

   /** {@inheritDoc} */
   public void parse (File f)
         throws FileNotFoundException, JAXBException
   {
      final FileInputStream is = new FileInputStream(f);
      try
      {
          mReportDocument
              = (Checkstyle) getUnmarshaller().unmarshal(is);
      }
      finally
      {
          IoUtil.close(is);
      }
   }

   protected Map getItems ()
         throws JAXBException
   {
      if (logger.isLoggable(Level.FINE))
      {
         logger.entering(CLASSNAME, "getItems");
      }

      final Map itemMap = new HashMap();

      final List files = mReportDocument.getFileOrErrorOrException();

      for (final Iterator iterator = files.iterator(); iterator.hasNext(); )
      {
         final Object o = iterator.next();

         if (o instanceof org.jcoderz.phoenix.checkstyle.jaxb.File)
         {
            final org.jcoderz.phoenix.checkstyle.jaxb.File f
               = (org.jcoderz.phoenix.checkstyle.jaxb.File) o;
            final String resourceFilename = normalizeFileName(f.getName());

            final List errors = f.getErrorOrException();
            final List items = createReportItems(resourceFilename, errors);

            addItemsToResource(itemMap, resourceFilename, items);
         }
      }

      if (logger.isLoggable(Level.FINE))
      {
         logger.exiting(CLASSNAME, "getItems", itemMap);
      }
      return itemMap;
   }

   private void addItemsToResource (
         Map itemMap, String resourceFilename, List items)
   {
      final ResourceInfo info = ResourceInfo.lookup(resourceFilename);
      if (info != null)
      {
         if (itemMap.get(info) != null)
         {
            final List l = (List) itemMap.get(info);
            l.addAll(items);
         }
         else
         {
            itemMap.put(info, items);
         }
      }
      else
      {
         logger.finer("Ignore findings for resource " + resourceFilename);
      }
   }

   private List createReportItems (String resourceFilename, List errors)
         throws JAXBException
   {
      final List ret = new ArrayList();

      for (final Iterator iterator = errors.iterator(); iterator.hasNext(); )
      {
         final Object o = iterator.next();

         if (o instanceof org.jcoderz.phoenix.checkstyle.jaxb.Error)
         {
            final org.jcoderz.phoenix.checkstyle.jaxb.Error error
               = (org.jcoderz.phoenix.checkstyle.jaxb.Error) o;

            final Item item = new ObjectFactory().createItem();

            if (error.isSetSeverity())
            {
               item.setSeverity(error.getSeverity());
            }
            item.setMessage(error.getMessage());
            item.setLine(error.getLine());
            item.setColumn(error.getColumn());
            item.setOrigin(Origin.CHECKSTYLE);

            final FindingType type = CheckstyleFindingType.
               detectFindingTypeForMessage(error.getMessage());
            if (type == null)
            {
               item.setFindingType(sourceToClass(error.getSource()));
               logger.log(Level.INFO, "Could not find finding type for "
                   + "Checkstyle finding with message '" + error.getMessage()
                   + "'.");
            }
            else
            {
               item.setFindingType(type.getSymbol());
               item.setSeverity(((CheckstyleFindingType) type).getSeverity());
            }

            ret.add(item);
         }
      }

      return ret;
   }

   private static String sourceToClass (String source)
   {
       final int i = source.lastIndexOf('.');
       return source.substring(i + 1);
   }

}


text:
from __future__ import absolute_import
import re
import requests
from geocoder.base import Base
from geocoder.keys import canadapost_key

class Canadapost(Base):
    """
    Addres Complete API
    =======================
    The next generation of address finders, AddressComplete uses
    intelligent, fast searching to improve data accuracy and relevancy.
    Simply start typing a business name, address or Postal Code
    and AddressComplete will suggest results as you go.

    Params
    ------
    :param ``location``: Your search location you want geocoded.
    :param ``key``: (optional) API Key from CanadaPost Address Complete.

    API Reference
    -------------
    https://www.canadapost.ca/pca/
    """
    provider = 'canadapost'
    method = 'geocode'

    def __init__(self, location, **kwargs):
        self.url = 'https://ws1.postescanada-canadapost.ca/AddressComplete' \
                   '/Interactive/RetrieveFormatted/v2.00/json3ex.ws'
        self.location = location
        self.key = kwargs.get('key', canadapost_key)
        self.timeout = kwargs.get('timeout', 5.0)
        self.proxies = kwargs.get('proxies', '')
        self.id = ''

        # Connect to CanadaPost to retrieve API key if none are provided
        if not self.key:
            self._retrieve_key()
        self._retrieve_id()

        if self.key and self.id:
            self.params = {
                'Key': self.key,
                'Id': self.id,
                'Source': '',
            }
            self._initialize(**kwargs)
        else:
            self.json = dict()
            self.parse = self.tree()
            self._json()

    def _retrieve_key(self):
        url = 'http://www.canadapost.ca/cpo/mc/personal/postalcode/fpc.jsf'
        try:
            r = requests.get(url, timeout=self.timeout, proxies=self.proxies)
            text = r.text
        except:
            text = ''
            self.error = 'ERROR - URL Connection'

        expression = r"'(....-....-....-....)';"
        pattern = re.compile(expression)
        match = pattern.search(text)
        if match:
            self.key = match.group(1)
            return self.key
        else:
            self.error = 'ERROR - No API Key'

    def _retrieve_id(self, last_id=''):
        params = {
            'Key': self.key,
            'LastId': last_id,
            'Country': "CAN",
            'SearchFor': 'Everything',
            'SearchTerm': self.location,
        }

        url = 'https://ws1.postescanada-canadapost.ca/AddressComplete' \
              '/Interactive/Find/v2.00/json3ex.ws'
        try:
            r = requests.get(url, params=params,
                             timeout=self.timeout,
                             proxies=self.proxies)
            items = r.json().get('Items')
            self.status_code = 200
        except:
            items = None
            self.status_code = 404
            self.error = 'ERROR - URL Connection'

        if items:
            items = items[0]
            if 'Error' in items:
                self.error = items['Description']
            else:
                item_id = items['Id']
                description = items.get('Description')
                if item_id:
                    if 'results' in description:
                        self._retrieve_id(item_id)
                    elif 'Id' in items:
                        self.id = item_id
                        return self.id

    def _exceptions(self):
        # Build intial Tree with results
        if self.parse['Items']:
            self._build_tree(self.parse['Items'][0])

    @property
    def ok(self):
        return bool(self.postal)

    @property
    def quality(self):
        return self.parse.get('Type')

    @property
    def accuracy(self):
        return self.parse.get('DataLevel')

    @property
    def address(self):
        return self.parse.get('Line1')

    @property
    def postal(self):
        return self.parse.get('PostalCode')

    @property
    def housenumber(self):
        return self.parse.get('BuildingNumber')

    @property
    def street(self):
        return self.parse.get('Street')

    @property
    def city(self):
        return self.parse.get('City')

    @property
    def state(self):
        return self.parse.get('ProvinceName')

    @property
    def country(self):
        return self.parse.get('CountryName')

    @property
    def unit(self):
        return self.parse.get('SubBuilding')

if __name__ == '__main__':
    g = Canadapost("453 Booth Street, ON", key='ea98-jc42-tf94-jk98')
    g.debug()


text:
using GW2PAO.API.Data;
using GW2PAO.API.Data.Entities;
using GW2PAO.Data;
using GW2PAO.Data.UserData;
using GW2PAO.PresentationCore;
using Microsoft.Practices.Prism.Mvvm;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using GW2PAO.Modules.Dungeons.Data;
using GW2PAO.Modules.Dungeons.Interfaces;
using GW2PAO.Modules.WebBrowser.Interfaces;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Collections;

namespace GW2PAO.Modules.Dungeons.ViewModels
{
    public class PathViewModel : BindableBase
    {
        /// <summary>
        /// Default logger
        /// </summary>
        private static Logger logger = LogManager.GetCurrentClassLogger();

        private DungeonsUserData userData;
        private bool isActivePath;

        /// <summary>
        /// The dungeons controller
        /// </summary>
        private IDungeonsController dungeonController;

        /// <summary>
        /// The browser controller used for displaying the dungeon's wiki page
        /// </summary>
        private IWebBrowserController browserController;

        /// <summary>
        /// The primary model object containing the path's information
        /// </summary>
        public DungeonPath PathModel { get; private set; }

        /// <summary>
        /// The paths's ID
        /// </summary>
        public Guid PathId { get { return this.PathModel.ID; } }

        /// <summary>
        /// The paths's display text name
        /// </summary>
        public string DisplayName { get { return this.PathModel.PathDisplayText; } }

        /// <summary>
        /// The paths's nickname
        /// </summary>
        public string NickName { get { return this.PathModel.Nickname; } }

        /// <summary>
        /// The paths's reward Gold component
        /// </summary>
        public int RewardGold { get { return (int)this.PathModel.GoldReward; } }

        /// <summary>
        /// The paths's reward Silver component
        /// </summary>
        public int RewardSilver { get { return (int)((this.PathModel.GoldReward - RewardGold) * 100); } }

        /// <summary>
        /// True if the path has been completed, else false
        /// </summary>
        public bool IsCompleted
        {
            get { return this.userData.CompletedPaths.Contains(this.PathId); }
            set
            {
                if (value && !this.userData.CompletedPaths.Contains(this.PathId))
                {
                    logger.Debug("Adding \"{0}\" to CompletedPaths", this.PathId);
                    this.userData.CompletedPaths.Add(this.PathModel.ID);
                    this.OnPropertyChanged(() => this.IsCompleted);
                }
                else
                {
                    logger.Debug("Removing \"{0}\" from CompletedPaths", this.PathId);
                    if (this.userData.CompletedPaths.Remove(this.PathId))
                        this.OnPropertyChanged(() => this.IsCompleted);
                }
            }
        }

        /// <summary>
        /// True if the path is currently being completed by the player
        /// </summary>
        public bool IsActive
        {
            get { return this.isActivePath; }
            set { this.SetProperty(ref this.isActivePath, value); }
        }

        /// <summary>
        /// The in-game end location for the path
        /// </summary>
        public DetectionPoint EndPoint
        {
            get { return this.PathModel.EndPoint; }
        }

        /// <summary>
        /// Collection of in-game points that identify this path
        /// </summary>
        public List<DetectionPoint> IdentifyingPoints
        {
            get { return this.PathModel.IdentifyingPoints; }
        }

        /// <summary>
        /// Number of cutscenes shown while at the endpoint
        /// </summary>
        public int EndCutsceneCount
        {
            get { return this.PathModel.EndCutsceneCount; }
        }

        /// <summary>
        /// Best completion time for this path
        /// </summary>
        public PathTime BestCompletionTime
        {
            get
            {
                var pathCompletionData = this.userData.PathCompletionData.FirstOrDefault(pt => pt.PathID == this.PathId);
                if (pathCompletionData != null)
                {
                    return pathCompletionData.CompletionTimes.OrderBy((pt) => pt.Time).FirstOrDefault();
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Average completion time for this path
        /// </summary>
        public TimeSpan AverageCompletionTime
        {
            get
            {
                var pathCompletionData = this.userData.PathCompletionData.FirstOrDefault(pt => pt.PathID == this.PathId);
                if (pathCompletionData != null)
                {
                    double totalMs = 0;
                    foreach (var pt in pathCompletionData.CompletionTimes)
                        totalMs += pt.Time.TotalMilliseconds;

                    totalMs /= pathCompletionData.CompletionTimes.Count;

                    if (!double.IsNaN(totalMs))
                    {
                        return TimeSpan.FromMilliseconds(totalMs);
                    }
                }
                return TimeSpan.Zero;
            }
        }

        /// <summary>
        /// Full collection of completion times for this path
        /// </summary>
        public ObservableCollection<PathTime> CompletionTimes
        {
            get
            {
                var pathCompletionData = this.userData.PathCompletionData.FirstOrDefault(pt => pt.PathID == this.PathId);
                return pathCompletionData.CompletionTimes;
            }
        }

        /// <summary>
        /// Command to open the guide for this dungeon
        /// </summary>
        public DelegateCommand OpenGuideCommand { get; private set; }

        /// <summary>
        /// Command to set this path as the active path
        /// </summary>
        public DelegateCommand SetAsActivePathCommand { get; private set; }

        /// <summary>
        /// Command to reset a path's best completion time
        /// </summary>
        public ICommand RemoveTimesCommand
        {
            get;
            private set;
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="path"></param>
        /// <param name="userData"></param>
        public PathViewModel(DungeonPath path, IDungeonsController dungeonController, IWebBrowserController browserController, DungeonsUserData userData)
        {
            this.PathModel = path;
            this.userData = userData;
            this.dungeonController = dungeonController;
            this.browserController = browserController;

            this.OpenGuideCommand = new DelegateCommand(this.OpenGuide);
            this.SetAsActivePathCommand = new DelegateCommand(this.SetAsActivePath);
            this.RemoveTimesCommand = new DelegateCommand<object>(this.RemoveCompletionTimes);

            // Initialize the path completion data in the UserData object
            var existingPathCompletionData = this.userData.PathCompletionData.FirstOrDefault(pt => pt.PathID == this.PathId);
            if (existingPathCompletionData != null)
            {
                existingPathCompletionData.PathData = this;
            }
            else
            {
                this.userData.PathCompletionData.Add(new PathCompletionData(this));
            }

            this.CompletionTimes.CollectionChanged += (o, e) =>
                {
                    this.OnPropertyChanged(() => this.BestCompletionTime);
                    this.OnPropertyChanged(() => this.AverageCompletionTime);
                };
        }

        /// <summary>
        /// Opens the wiki page for this dungeon
        /// </summary>
        private void OpenGuide()
        {
            this.browserController.GoToUrl(this.PathModel.GuideUrl);
        }

        /// <summary>
        /// Sets this path as the active dungeon path in the tracker and timer
        /// </summary>
        private void SetAsActivePath()
        {
            this.dungeonController.SetActivePath(this.PathId);
        }

        /// <summary>
        /// Removes the given path time objects from this path's collection of completion times
        /// </summary>
        /// <param name="completionTimes">The PathTime objects to remove</param>
        private void RemoveCompletionTimes(object completionTimes)
        {
            IList times = (IList)completionTimes;
            var completionTimesToRemove = new List<PathTime>(times.Cast<PathTime>());

            foreach (var time in completionTimesToRemove)
            {
                this.CompletionTimes.Remove(time);
            }
        }
    }
}


text:
function golem-docker() {
  docker_args=""
  if [[ "$1" == *"-dev" ]]; then
    DOCKER_BINARY=$(readlink -f "$GOPATH/src/github.com/docker/docker/bundles/$1/binary/docker")
    if [ ! -f $DOCKER_BINARY ]; then
      current_version=`cat $GOPATH/src/github.com/docker/docker/VERSION`
      echo "$DOCKER_BINARY does not exist"
      echo "Current checked out docker version: $current_version"
      echo "Checkout desired version and run 'make binary' from $GOPATH/src/github.com/docker/docker"
      return 1
    fi
    docker_args="-db=$DOCKER_BINARY"
  elif [ "$1" != "default" ]; then
    docker_args="-docker-version=$1"
  fi
  shift

  golem $docker_args $@
}

function path_save_cd() {
	export GOLEM_SAVED_PATH="$(pwd)"
	cd $1
}

function path_restore() {
	if [ "$GOLEM_SAVED_PATH" != "" ]; then
		cd $GOLEM_SAVED_PATH
		unset GOLEM_SAVED_PATH
	fi
}

# golem-docker-dev is a function to run tests on active docker development directory
function golem-docker-dev() {
  path_save_cd $GOPATH/src/github.com/docker/docker/
  trap path_restore EXIT
  make binary
  version=`cat VERSION`
  path_restore

  binary=$(readlink -f "$GOPATH/src/github.com/docker/docker/bundles/$version/binary/docker")
  if [ ! -f $binary ]; then
    echo "Failed to get binary for $version"
    return 1
  fi

  dir=$(mktemp -d)
  path_save_cd $dir
  trap path_restore EXIT
  cp $binary ./docker
  cat <<DockerFileContent > ./Dockerfile
FROM docker:1.10.1-dind
MAINTAINER distribution@docker.com
COPY docker /usr/local/bin/docker
DockerFileContent
  # Build
  image=$(docker build -q .)
  path_restore

  golem -i "golem-dind:latest,$image,$version" $@
}


text:
using System;

namespace SharpKit.Html.svg
{

using SharpKit.JavaScript;
using SharpKit.Html.fileapi;
using SharpKit.Html.html.shadow;
using SharpKit.Html.html.track;
using SharpKit.Html.inspector;
using SharpKit.Html.loader.appcache;
using SharpKit.Html.battery;
using SharpKit.Html.filesystem;
using SharpKit.Html.gamepad;
using SharpKit.Html.geolocation;
using SharpKit.Html.indexeddb;
using SharpKit.Html.intents;
using SharpKit.Html.mediasource;
using SharpKit.Html.mediastream;
using SharpKit.Html.navigatorcontentutils;
using SharpKit.Html.networkinfo;
using SharpKit.Html.notifications;
using SharpKit.Html.proximity;
using SharpKit.Html.quota;
using SharpKit.Html.speech;
using SharpKit.Html.vibration;
using SharpKit.Html.webaudio;
using SharpKit.Html.webdatabase;
using SharpKit.Html.plugins;
using SharpKit.Html.storage;
using SharpKit.Html.svg;
using SharpKit.Html.workers;

[JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "SVGLength")]
public partial class SvgLength
{
	public  const int SVG_LENGTHTYPE_UNKNOWN = 0;
	public  const int SVG_LENGTHTYPE_NUMBER = 1;
	public  const int SVG_LENGTHTYPE_PERCENTAGE = 2;
	public  const int SVG_LENGTHTYPE_EMS = 3;
	public  const int SVG_LENGTHTYPE_EXS = 4;
	public  const int SVG_LENGTHTYPE_PX = 5;
	public  const int SVG_LENGTHTYPE_CM = 6;
	public  const int SVG_LENGTHTYPE_MM = 7;
	public  const int SVG_LENGTHTYPE_IN = 8;
	public  const int SVG_LENGTHTYPE_PT = 9;
	public  const int SVG_LENGTHTYPE_PC = 10;
	public  int unitType {get; set; }
	public  double value {get; set; }
	public  double valueInSpecifiedUnits {get; set; }
	public  JsString valueAsString {get; set; }
	public  void newValueSpecifiedUnits(int unitType, double valueInSpecifiedUnits) {}
	public  void convertToSpecifiedUnits(int unitType) {}
}

}


text: $(function(){ TodoApp.start() });


text:
if(!EOL) { var EOL = {}; }

// TODO - not all of these are required, if we know we won't use them:
$.ajaxSetup({accepts: {
  '*': "text/javascript, */*",
  html: "text/javascript",
  json: "application/json, text/javascript",
  script: "text/javascript",
  text: "text/plain",
  xml: "application/xml, text/xml"
}});

$(function() {

  $(".heading form.filter, form.select_submit").find(".actions").hide().find(":submit").end().end().find("select")
    .change(function() {
      $(this).closest("form").submit();
    });

  (function($ss) {
    var placeholder = "

";

    $ss.each(function() {
      var $gallery = $(this),
          thumbs = [];
      $("
", { "class": "thumbnails" }).insertBefore($gallery.find("p.all"));
      $gallery.find(".image > a > img").each(function() {
        var $e = $(this),
            li;
        if ($e.is("[data-thumb]")) {
          li = "

";
        }
        else { li = placeholder; }
        thumbs.push(li);
      });
      for (var i = 1, len = 4 - thumbs.length; i <= len; i++) {
        thumbs.push(placeholder);
      }
      $gallery.find(".thumbnails").html(thumbs.join(""));
      $gallery.find(".thumbnails li").not(".placeholder").eq(0).addClass("active");
    });

    $ss.find(".image img").each(function() {
      this.onload = function() {
        $(this).data("height", this.height);
      };
    });

    $ss.find(".thumbnails").delegate("a", "click", function() {
      var $e = $(this).closest("li");
      $e.closest("ul").find(".active").removeClass("active");
      $e.addClass("active");
      return false;
    });

    function toggleImg(idx) {
      var $image = $ss.find(".image:eq(" + idx + ")");
      var $a = $image.find("> a").first();
      var $img = $a.find("img");
      $img.css("paddingTop", ($a.height() / 2 - $img.data("height") / 2) + "px");
      $ss.find(".images").css("height", $image.height());
    }

    if ("cycle" in $.fn) {
      $ss.find(".images").cycle({
        speed: 500,
        timeout: 0,
        onPagerEvent: toggleImg,
        pagerAnchorBuilder: function(idx) {
          return $ss.selector + " .thumbnails a:eq(" + idx + ")";
        }
      });

      if ($ss.find(".image").length > 1) {
        toggleImg(0);
      }

    }

  })($(".gallery"));

  (function($media_list) {
    $media_list.find("li .overlay").click(function() {
      window.location = $(this).parent().find("a").attr("href");
      return false;
    });
  })($("#media_list"));

  (function($language) {
    $language.find("p a").accessibleClick(function() {
      var $e = $(this),
          $ul = $e.closest($language.selector).find("ul");
      if ($ul.is(":visible")) {
        $ul.hide();
        return false;
      }
      $ul.show();
      $(document).click(function(e) {
        if (!$(e.target).closest($language.selector).length) {
          $language.find("ul").hide();
          $(this).unbind(e);
        }
      });
      return false;
    });

  })($(".language"));

  (function($collection) {
    $collection.find("ul.object_list li").each(function() {
      var $li = $(this);
      $li.find("p.edit").show().next().hide().end().find("a").click(function() {
        $(this).parent().hide().next().show();
      });
      $li.find("form a").click(function() {
        $(this).closest("form").hide().prev().show();
      });
    });
  })($("#collections"));

  $("input[placeholder]").each(function() {
    var $e = $(this),
        placeholder = $e.attr("placeholder");
    $e.removeAttr("placeholder").val(placeholder);
    $e.bind("focus blur", function(e) {
      if (e.type === "focus" && $e.val() === placeholder) { $e.val(""); }
      else { if (!$e.val()) { $e.val(placeholder); } }
    });
  });

  // Collecting happens through a modal dialog box:
  $('a.collect').modal({
    beforeSend: function() { $('a.collect').fadeTo(225, 0.3); },
    beforeShow: function() {
      $('#choose_collections form :submit').click(function() {
        if($('#flashes')[0] == undefined) {
          $('#page_heading div.page_actions').after('

');
        }
        EOL.ajax_submit($(this), { update: $('#flashes') });
        $('#choose_collections a.close').click();
        return(false);
      });
      $('#choose_collections a.close_and_go').click(function() { $('#choose_collections a.close').click(); });
    },
    afterClose: function() {
      $('a.collect').delay(25).fadeTo(100, 1, function() {$('a.collect').css({filter:''}); });
    },
    duration: 200
  });

  // Wouldn't it be nice if ratings were Ajaxified?
  $('.media .ratings .rating ul > li > a').click(function() {
    var $update = $(this).closest('div.ratings');
    EOL.ajax_submit($(this), {url: $(this).attr('href'), update: $update, type: 'GET'});
    return(false);
  });

  // initiates march of life on homepage
  $('.thumbnails ul li').each(function() {
    var number_of_slides = $('.thumbnails ul li').length;
    var index = $(this).index();
    var random = new Array(-3, 1, 0, -2, -4, -1);
    var display_time = 5000;
    var transition_time = 1800;
    $(this).cycle({
      fx: 'fade',
      timeout: number_of_slides * display_time,
      delay: random[index] * display_time,
      speed: transition_time
    });
  });

  // properly shows the march of life name on mouseover
  $(".thumbnails li img").unbind().mouseover(function() {
    var $e = $(this).parent().parent();
    $thumbs = $e.closest(".thumbnails");
    // margin = $thumbs.find("li").eq(0).outerWidth(true) - $e.outerWidth();
    var term_p = $thumbs.find(".term p");
    var left_pos = $e.position().left - 100 + 5;
    var right_pos = term_p.outerWidth(true) - $e.position().left - $e.outerWidth(true) - 100;
    if($e.is($(".thumbnails li:last"))) {
      right_pos = right_pos - 15;
    }
    term_p.css({
      textAlign: 'center'
    }).css("margin-left", left_pos+"px").css("margin-right", right_pos+"px").text($(this).attr("alt"));
  }).eq(0).mouseover();

  // removes the homepage march of life name on mouseout
  $(".thumbnails li").mouseout(function() {
    $(".thumbnails .term p").html(" ");
  });

  // uncheck search filter All when other options are selected
  $("#main_search_type_filter input[type=checkbox][value!='all']").click(function() {
    $("#main_search_type_filter input[type=checkbox][value='all']").removeAttr("checked");
  });
  // uncheck all other search filter options when All is selected
  $("#main_search_type_filter input[type=checkbox][value='all']").click(function() {
    $("#main_search_type_filter input[type=checkbox][value!='all']").removeAttr("checked");
  });
  // disable the checkboxes for filter categories with no results
  $("#main_search_type_filter li.no_results input[type=checkbox]").attr("disabled", true);

  // Search should not allow you to search without a term:
  $("#simple_search :submit").click(function() {
    var $q = $("#simple_search :submit").closest('form').find('#q');
    if ($q.val() == $(this).attr('data_unchanged')) {
      $q.css('color', '#aa0000').val($(this).attr('data_error')).click(function() { $(this).val('').css('color', 'black').unbind('click') });
      return(false);
    } else if ($q.val() == $(this).attr('data_error')) {
      var blinkspeed = 160;
      $q.css('color', '#aa0000').fadeOut(blinkspeed).fadeIn(blinkspeed).fadeOut(blinkspeed).fadeIn(blinkspeed).fadeOut(blinkspeed).fadeIn(blinkspeed);
      return(false);
    }
  });

  // uncheck media list filter All when other options are selected
  $("#media_list #sidebar input[type=checkbox][value!='all']").click(function() {
    $("#media_list #sidebar input[type=checkbox][value='all'][name='"+ $(this).attr('name') +"']").removeAttr("checked");
  });
  // uncheck all other media list filter options when All is selected
  $("#media_list #sidebar input[type=checkbox][value='all']").click(function() {
    $("#media_list #sidebar input[type=checkbox][value!='all'][name='"+ $(this).attr('name') +"']").removeAttr("checked");
  });
  // disable the checkboxes for filter categories with no results
  $("#media_list #sidebar li.no_results input[type=checkbox]").attr("disabled", true);

  // Expand the mini-tree on the taxon overview:
  $('#classifications_summary a.show_tree').click(function() {
    var $update = $(this).closest('#classifications_summary > ul > li');
    EOL.ajax_submit($(this), {update: $update, type: 'GET'});
    return(false);
  });
  $('.button.confirm').click(function() {
    if(confirm($(this).attr('data_confirm'))) { return true; } else { return false; }
  });

  // When you select all items, hide the checkboxes (and vice-versa) on collection items:
  $('form.edit_collection #scope').change(function() {
    if ($('form.edit_collection #scope').val() == 'all_items') {
      $('#collection_items :checkbox').parent().hide();
    } else {
      $('#collection_items :checkbox').parent().show();
    }
  });

  (function($content_partner_resources) {
    var $radios = $content_partner_resources.find("dl.resources :radio");
    $radios.change(function() {
      $radios.each(function() {
        var $radio = $(this);
        var $dd = $radio.closest("dt").next("dd");
        $radio.is(":checked") ? $dd.slideDown(200) : $dd.slideUp(200);
      });
    }).not(":checked").closest("dt").next("dd").hide();
  })($("#content_partner_resources"));

});

(function($) {
  $.fn.accessibleClick = function(key_codes, cb) {
    if ("join" in key_codes) { key_codes.push(13); }
    else if (typeof key_codes === "function") { cb = key_codes; }
    else { return this; }
    return this.each(function() {
      $(this).click(function(e) {
        if ((!e.keyCode && e.layerY > 0) || e.layerY === undefined) { return cb.apply(this); }
        else { return false; }
      }).keyup(function(e) {
        if (e.keyCode === 13 || $.inArray(e.keyCode, key_codes) !== -1) {
          return cb.apply(this);
        }
      });
    });
  };

  $.fn.hasAttr = function(attr) {
    return this.is("[" + attr + "]");
  };
})(jQuery);

// trying to generalize Ajax calls for EOL. Parameters:
//   el: The element firing the event.  It helps us find stuff, please pass it.
//   update: where you want the (html) response to go.  Defaults to the closest .editable item.
//   url: where you want the form to subit to.  Defaults to the data_url of the el you pass in, then to the nearest
//        form's action.
//   data: The data to send.  Defaults to the nearest form, serialized.
//   complete: Function to call when complete.  Optional.
//   type: method to use.  Defaults to POST.
EOL.ajax_submit = function(el, args) {
  var form = el.closest('form');
  var cell = '';
  if(typeof(args.update) != 'undefined') { cell = args.update; } else { cell = el.closest('.editable'); }
  var url  = '';
  if(typeof(args.url) != 'undefined') {
    url = args.url;
  } else if(typeof(el.attr('data_url')) != 'undefined') {
    url = el.attr('data_url');
  } else {
    url = form.attr('action');
  }
  var data = '';
  if(typeof(args.data) != 'undefined') { data = args.data; } else { data = form.serialize(); }
  complete = '';
  if(typeof(args.complete) != 'undefined') { complete = args.complete; }
  type = 'POST';
  if(typeof(args.type) != 'undefined') { type = args.type; }
  $.ajax({
    url: url,
    data: data,
    type: type,
    dataType: 'html',
    beforeSend: function(xhr) { cell.fadeTo(225, 0.3); },
    success: function(response) { cell.html(response); },
    error: function(xhr, stat, err) { cell.html('
Sorry, there was an error: '+stat+'
'); },
    complete: function() {
      cell.delay(25).fadeTo(100, 1, function() {cell.css({filter:''});});
      if(complete != '') {
        complete();
      }
    }
  });
  return(false); // stop event... there's a better way to do this?
};

EOL.ajax_get = function(el, args) {
  var cell = '';
  if(typeof(args.update) != 'undefined') { cell = args.update; } else { cell = el.closest('.editable'); }
  complete = '';
  if(typeof(args.complete) != 'undefined') { complete = args.complete; }
  $.ajax({
    url: el.attr('href'),
    dataType: 'html',
    beforeSend: function(xhr) { cell.fadeTo(300, 0.3); },
    success: function(response) { cell.html(response); },
    error: function(xhr, stat, err) { cell.html('
Sorry, there was an error: '+stat+'
'); },
    complete: function() {
      cell.delay(25).fadeTo(100, 1, function() {cell.css({filter:''});});
      if(complete != '') {
        complete();
      }
    }
  });
  return(false); // stop event... there's a better way to do this?
};


text:
using System.Net;
using FluentAssertions;
using Infusion.Desktop.Launcher;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Infusion.Desktop.Tests.Launcher
{
    [TestClass]
    public class LauncherOptionsTests
    {
        [TestMethod]
        public void Can_resolve_ipaddress_and_port()
        {
            var options = new LauncherOptions() { ServerEndpoint = "127.0.0.1,2593" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_ipaddress_and_port_with_leading_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "    127.0.0.1,2593" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_ipaddress_and_port_with_trailing_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "127.0.0.1,2593    " };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_ipaddress_and_port_with_additional_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "127.0.0.1,    2593" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_ipaddress_with_default_port_2593()
        {
            var options = new LauncherOptions() { ServerEndpoint = "127.0.0.1" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_domain_name_and_port()
        {
            var options = new LauncherOptions() { ServerEndpoint = "localhost,2593" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_domain_name_and_port_with_additonal_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "localhost,2593" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_domain_name_with_default_port_2593()
        {
            var options = new LauncherOptions() { ServerEndpoint = "localhost" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_domain_name_with_default_port_2593_with_leading_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "     localhost" };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }

        [TestMethod]
        public void Can_resolve_domain_name_with_default_port_2593_with_trailing_space()
        {
            var options = new LauncherOptions() { ServerEndpoint = "localhost     " };

            options.ResolveServerEndpoint().Result.Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2593));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="CpH1N15amideCALC" author="Agilent" investigator=""
        time_created="20120123T120000" tabname="BioSolidsPack" menu1="Commands" menu2="Calc Values" apptype="solidsseq1d"
        application="BioSolids" scans="CpH1N15amideCALC" seqfil="ahX">
  <protocol title="CpH1N15amideCALC" type="protocol">
    <action  type="CMD" status="Ready" lock="off" title="CpH1N15amideCALC" exp="CpH1N15amideCALC"
        time="1:45" macro="CpH1N15amideCALC" data="" />
  </protocol>
</template>


text:
<?php
/**
 * Created by PhpStorm.
 * User: getju_000
 * Date: 07.05.14
 * Time: 13:18.
 */
namespace getjump\Vk\Exception;

use Exception;

class Error extends Exception
{
    /**
     * @var \getjump\Vk\Response\Error|bool
     */
    public $error = false;

    public function __construct($message, $code, \getjump\Vk\Response\Error $e)
    {
        $this->error = $e;
        $this->message = $message;
        $this->code = $code;
    }
}


text:
class Bar
  include Mongoid::Document
  include Mongoid::Geospatial

  field :name,     type: String

  field :location, type: Point, spatial: true

  has_one :rating, as: :ratable

  spatial_scope :location
end


text:
package org.adonai;

import javafx.application.Application;
import javafx.stage.Stage;
import org.adonai.fx.Mask;
import org.adonai.fx.MaskLoader;
import org.adonai.fx.scripture.ScriptureController;

public class ScriptureDialog extends Application {

  @Override public void start(Stage primaryStage) throws Exception {

    MaskLoader<ScriptureController> maskLoader = new MaskLoader<>();
    Mask<ScriptureController> mask = maskLoader.loadWithStage("scripture");
    primaryStage.setScene(mask.getScene());
    primaryStage.setWidth(800);
    primaryStage.setHeight(1024);
    primaryStage.setResizable(false);

    primaryStage.show();

  }

  public static void main(String[] args) {
    launch(ScriptureDialog.class);
  }
}


text:
export { default as asList } from './as-list';
export { default as get } from './get';
export { default as hasProp } from './has-prop';
export { default as keys } from './keys';
export { default as set } from './set';
export { default as values } from './values';


text:
"""Datasets."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import hashlib
import pickle
from typing import Callable, NamedTuple, Optional, Text, Tuple

from absl import flags
import numpy as np
import tensorflow.compat.v2 as tf

flags.DEFINE_string('german_credit_numeric_path', '/tmp/german.data-numeric',
                    'Path to the numeric German Credit dataset.')
flags.DEFINE_string('stan_item_response_theory_path', '/tmp/irt.data.pkl',
                    'Path to the Stan 1PL Item-Response Theory dataset.')

FLAGS = flags.FLAGS

__all__ = [
    'ClassificationDataset',
    'ItemResponseTheoryDataset',
    'german_credit_numeric',
    'stan_item_response_theory',
]

class ClassificationDataset(
    NamedTuple('ClassificationDataset', [
        ('train_features', np.ndarray),
        ('train_labels', np.ndarray),
        ('test_features', np.ndarray),
        ('test_labels', np.ndarray),
        ('code_name', Text),
        ('human_name', Text),
    ])):
  """Describes a classification dataset.

  Attributes:
    train_features: Floating-point `Tensor` with shape `[num_train_points,
      num_features]`. Training features.
    train_labels: Integer `Tensor` with shape `[num_train_points]`. Training
      labels.
    test_features: Floating-point `Tensor` with shape `[num_test_points,
      num_features]`. Testing features.
    test_labels: Integer `Tensor` with shape `[num_test_points]`. Testing
      labels.
    code_name: Code name of this dataset.
    human_name: Human readable name, suitable for a table in a paper.
  """

class ItemResponseTheoryDataset(
    NamedTuple('ItemResponseTheoryDataset', [
        ('train_student_ids', np.ndarray),
        ('train_question_ids', np.ndarray),
        ('train_correct', np.ndarray),
        ('test_student_ids', np.ndarray),
        ('test_question_ids', np.ndarray),
        ('test_correct', np.ndarray),
        ('code_name', Text),
        ('human_name', Text),
    ])):
  """Describes a regression dataset.

  `*_correct[i] == 1` means that student `*_student_ids[i]` answered question
  `*_question_ids[i]` correctly; `*_correct[i] == 0` means they didn't.

  Attributes:
    train_student_ids: Integer `Tensor` with shape `[num_train_points]`.
    train_question_ids: Integer `Tensor` with shape `[num_train_points]`.
    train_correct: Integer `Tensor` with shape `[num_train_points]`.
    test_student_ids: Integer `Tensor` with shape `[num_test_points]`.
    test_question_ids: Integer `Tensor` with shape `[num_test_points]`.
    test_correct: Integer `Tensor` with shape `[num_test_points]`.
    code_name: Code name of this dataset.
    human_name: Human readable name, suitable for a table in a paper.
  """

def _normalize_zero_mean_one_std(
    train, test):
  """Normalizes the data columnwise to have mean of 0 and std of 1.

  Assumes that the first axis indexes independent datapoints. The mean and
  standard deviation are estimated from the training set and are used
  for both train and test data, to avoid leaking information.

  Args:
    train: A floating point numpy array representing the training data.
    test: A floating point numpy array representing the test data.

  Returns:
    normalized_train: The normalized training data.
    normalized_test: The normalized test data.
  """
  train = np.asarray(train)
  test = np.asarray(test)
  train_mean = train.mean(0, keepdims=True)
  train_std = train.std(0, keepdims=True)
  return (train - train_mean) / train_std, (test - train_mean) / train_std

def german_credit_numeric(
    path = None,
    train_fraction = 1.,
    normalize_fn = _normalize_zero_mean_one_std,
    shuffle = True,
    shuffle_seed = 1337,
    check_hash = True,
):
  """The numeric German Credit dataset [1].

  This dataset contains 1000 data points with 24 features and 1 binary label.

  Args:
    path: Path to the dataset. If `None`, will read this value from the
      `german_credit_numeric_path` flag. The dataset must be a CSV file with
      1000 rows and 25 colums, each with a numeric value.
    train_fraction: What fraction of the data to put in the training set.
    normalize_fn: A callable to normalize the data. This should take the train
      and test datasets and return the normalized versions of them.
    shuffle: Whether to shuffle the dataset.
    shuffle_seed: Seed to use when shuffling.
    check_hash: Whether to check the loaded dataset against a known hash.

  Raises:
    ValueError: If the dataset has an unexpected hash.

  Returns:
    dataset: ClassificationDataset.

  #### References

  1. https://archive.ics.uci.edu/ml/datasets/statlog+(german+credit+data)
  """
  if path is None:
    path = FLAGS.german_credit_numeric_path

  with tf.io.gfile.GFile(path, 'rb') as f:
    data = np.genfromtxt(f)

  data = data.astype(np.float32)

  if check_hash:
    expected_digest = 'f905a324d38659765a0bc234238c1d77'
    actual_hash = hashlib.md5(data)
    actual_hash.update(str(data.shape).encode('ascii'))
    actual_digest = actual_hash.hexdigest()
    if expected_digest != actual_digest:
      raise ValueError('Hash of the dataset is wrong: {}'.format(actual_digest))

  if shuffle:
    np.random.RandomState(shuffle_seed).shuffle(data)

  features = data[:, :-1]
  labels = data[:, -1] - 1

  num_train = int(data.shape[0] * train_fraction)

  train_features = features[:num_train]
  test_features = features[num_train:]

  if normalize_fn is not None:
    train_features, test_features = normalize_fn(train_features, test_features)

  return ClassificationDataset(
      train_features=train_features,
      train_labels=labels[:num_train].astype(np.int32),
      test_features=test_features,
      test_labels=labels[num_train:].astype(np.int32),
      code_name='german_credit_numeric_tf{}'.format(train_fraction),
      human_name='German Credit (Numeric)',
  )

def stan_item_response_theory(
    path = None,
    train_fraction = 1.,
    shuffle = True,
    shuffle_seed = 1337,
    check_hash = True):
  """Synthetic item-response theory dataset from Stan example repo [1].

  This dataset is a simulation of 400 students each answering a subset of
  100 unique questions, with a total of 30105 questions answered.

  The dataset is split into train and test portions by randomly partitioning the
  student-question-response triplets. This has two consequences. First, the
  student and question ids are shared between test and train sets. Second, there
  is a possibility of some students or questions not being present in both sets.

  Args:
    path: Path to the dataset. If `None`, will read this value from the
      `stan_item_response_theory_path` flag. The dataset must be a binary
      pickle file containing a dict with keys `student_ids`, `question_ids`,
      and `correct`, which should map to integer numpy arrays each of length
      30105.
    train_fraction: What fraction of the data to put in the training set.
    shuffle: Whether to shuffle the dataset.
    shuffle_seed: Seed to use when shuffling.
    check_hash: Whether to check the loaded dataset against a known hash.

  Raises:
    ValueError: If the dataset has an unexpected hash.

  Returns:
    dataset: ItemResponseTheoryDataset.

  #### References

  1. https://github.com/stan-dev/example-models/blob/master/misc/irt/irt.data.R
  """
  if path is None:
    path = FLAGS.stan_item_response_theory_path

  data = pickle.load(tf.io.gfile.GFile(path, 'rb'))

  if check_hash:
    expected_digest = 'b5cf5a4ac7e1075a4bb04ae1194e4f2f'
    actual_hash = hashlib.md5(data['student_ids'])
    actual_hash.update(str(data['student_ids'].shape).encode('ascii'))
    actual_hash.update(data['question_ids'])
    actual_hash.update(str(data['question_ids'].shape).encode('ascii'))
    actual_hash.update(data['correct'])
    actual_hash.update(str(data['correct'].shape).encode('ascii'))
    actual_digest = actual_hash.hexdigest()
    if expected_digest != actual_digest:
      raise ValueError('Hash of the dataset is wrong: {}'.format(actual_digest))

  student_ids = data['student_ids']
  question_ids = data['question_ids']
  correct = data['correct']

  if shuffle:
    shuffle_idxs = np.arange(student_ids.shape[0])
    np.random.RandomState(shuffle_seed).shuffle(shuffle_idxs)
    student_ids = student_ids[shuffle_idxs]
    question_ids = question_ids[shuffle_idxs]
    correct = correct[shuffle_idxs]

  num_train = int(student_ids.shape[0] * train_fraction)

  return ItemResponseTheoryDataset(
      train_student_ids=student_ids[:num_train],
      train_question_ids=question_ids[:num_train],
      train_correct=correct[:num_train],
      test_student_ids=student_ids[num_train:],
      test_question_ids=question_ids[num_train:],
      test_correct=correct[num_train:],
      code_name='stan_irt_tf{}'.format(train_fraction),
      human_name='1PL Item-Response Theory',
  )


text:
.class Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;
.super Ljava/lang/Object;
.source "SubscriptionHandlerVisitor.java"

# interfaces
.implements Lcom/upsight/android/internal/persistence/subscription/ClassSubscriptionVisitor;

# instance fields
.field private final mHandlers:Ljava/util/Set;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/Set",
            "<",
            "Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;",
            ">;"
        }
    .end annotation
.end field

.field private final mTarget:Ljava/lang/Object;

# direct methods
.method constructor <init>(Ljava/lang/Object;)V
    .registers 3
    .param p1, "target"    # Ljava/lang/Object;

    .prologue
    .line 23
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 24
    new-instance v0, Ljava/util/HashSet;

    invoke-direct {v0}, Ljava/util/HashSet;-><init>()V

    iput-object v0, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mHandlers:Ljava/util/Set;

    .line 25
    iput-object p1, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mTarget:Ljava/lang/Object;

    .line 26
    return-void
.end method

# virtual methods
.method public getHandlers()Ljava/util/Set;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Set",
            "<",
            "Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;",
            ">;"
        }
    .end annotation

    .prologue
    .line 53
    new-instance v0, Ljava/util/HashSet;

    iget-object v1, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mHandlers:Ljava/util/Set;

    invoke-direct {v0, v1}, Ljava/util/HashSet;-><init>(Ljava/util/Collection;)V

    return-object v0
.end method

.method public visitCreatedSubscription(Ljava/lang/reflect/Method;Ljava/lang/Class;)V
    .registers 9
    .param p1, "method"    # Ljava/lang/reflect/Method;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/reflect/Method;",
            "Ljava/lang/Class",
            "<*>;)V"
        }
    .end annotation

    .prologue
    .line 30
    .local p2, "type":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    const-class v1, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    invoke-virtual {p2, v1}, Ljava/lang/Class;->getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;

    move-result-object v0

    check-cast v0, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    .line 31
    .local v0, "storableType":Lcom/upsight/android/persistence/annotation/UpsightStorableType;
    if-eqz v0, :cond_1c

    .line 32
    iget-object v1, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mHandlers:Ljava/util/Set;

    new-instance v2, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;

    iget-object v3, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mTarget:Ljava/lang/Object;

    sget-object v4, Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;->Created:Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;

    invoke-interface {v0}, Lcom/upsight/android/persistence/annotation/UpsightStorableType;->value()Ljava/lang/String;

    move-result-object v5

    invoke-direct {v2, v3, p1, v4, v5}, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;-><init>(Ljava/lang/Object;Ljava/lang/reflect/Method;Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;Ljava/lang/String;)V

    invoke-interface {v1, v2}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    .line 34
    :cond_1c
    return-void
.end method

.method public visitRemovedSubscription(Ljava/lang/reflect/Method;Ljava/lang/Class;)V
    .registers 9
    .param p1, "method"    # Ljava/lang/reflect/Method;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/reflect/Method;",
            "Ljava/lang/Class",
            "<*>;)V"
        }
    .end annotation

    .prologue
    .line 46
    .local p2, "type":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    const-class v1, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    invoke-virtual {p2, v1}, Ljava/lang/Class;->getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;

    move-result-object v0

    check-cast v0, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    .line 47
    .local v0, "storableType":Lcom/upsight/android/persistence/annotation/UpsightStorableType;
    if-eqz v0, :cond_1c

    .line 48
    iget-object v1, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mHandlers:Ljava/util/Set;

    new-instance v2, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;

    iget-object v3, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mTarget:Ljava/lang/Object;

    sget-object v4, Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;->Removed:Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;

    invoke-interface {v0}, Lcom/upsight/android/persistence/annotation/UpsightStorableType;->value()Ljava/lang/String;

    move-result-object v5

    invoke-direct {v2, v3, p1, v4, v5}, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;-><init>(Ljava/lang/Object;Ljava/lang/reflect/Method;Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;Ljava/lang/String;)V

    invoke-interface {v1, v2}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    .line 50
    :cond_1c
    return-void
.end method

.method public visitUpdatedSubscription(Ljava/lang/reflect/Method;Ljava/lang/Class;)V
    .registers 9
    .param p1, "method"    # Ljava/lang/reflect/Method;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/reflect/Method;",
            "Ljava/lang/Class",
            "<*>;)V"
        }
    .end annotation

    .prologue
    .line 38
    .local p2, "type":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    const-class v1, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    invoke-virtual {p2, v1}, Ljava/lang/Class;->getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;

    move-result-object v0

    check-cast v0, Lcom/upsight/android/persistence/annotation/UpsightStorableType;

    .line 39
    .local v0, "storableType":Lcom/upsight/android/persistence/annotation/UpsightStorableType;
    if-eqz v0, :cond_1c

    .line 40
    iget-object v1, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mHandlers:Ljava/util/Set;

    new-instance v2, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;

    iget-object v3, p0, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandlerVisitor;->mTarget:Ljava/lang/Object;

    sget-object v4, Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;->Updated:Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;

    invoke-interface {v0}, Lcom/upsight/android/persistence/annotation/UpsightStorableType;->value()Ljava/lang/String;

    move-result-object v5

    invoke-direct {v2, v3, p1, v4, v5}, Lcom/upsight/android/internal/persistence/subscription/SubscriptionHandler;-><init>(Ljava/lang/Object;Ljava/lang/reflect/Method;Lcom/upsight/android/internal/persistence/subscription/DataStoreEvent$Action;Ljava/lang/String;)V

    invoke-interface {v1, v2}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    .line 42
    :cond_1c
    return-void
.end method


text:
<div class="data_collection" dcid="<%-ID%>" type="data">

        <a href="<%-APIURL%>/image/id/<%-ID%>/f/1/n/4">

        <a href="<%-APIURL%>/image/id/<%-ID%>/f/1" title="Crystal Snapshot 1">

        <a href="/dc/view/id/<%-ID%>"> Images
         Snapshots
         Data Plot

Wavelength: <%-WAVELENGTH%>Å

Detector Distance: <%-parseFloat(DET).toFixed(1)%>mm

Exposure: <%-EXPOSURETIME%>s

Resolution: <%-RESOLUTION%>Å

Beamsize: <%-BSX%>x<%-BSY%>μm

Comment: <%-COMMENTS%>

        <% if (!STATE) { %>
Status: Stopped
<% } %>

Data Files  <a class="dd" href="<%-APIURL%>/download/dc/id/<%-ID%>" title="Download files">Download


text:
#ifndef TRADERCLIENTSTUB_H
#define TRADERCLIENTSTUB_H
/**
* TraderClientStub.h
*
* This file was auto-generated from WSDL for "TraderClient|http://www.wso2.org" service
* by the Apache Axis2/Java version: #axisVersion# #today#
*/

#include <stdio.h>
#include <OMElement.h>
#include <Stub.h>
#include <ServiceClient.h>

#include <DepositRequest.h>

#include <DepositResponse.h>

#include <GetSymbolsRequest.h>

#include <GetSymbolsResponse.h>

#include <GetQuoteRequest.h>

#include <GetQuoteResponse.h>

#include <CreateAccountRequest.h>

#include <CreateAccountResponse.h>

#include <SellRequest.h>

#include <SellResponse.h>

#include <BuyRequest.h>

#include <BuyResponse.h>

#include <GetPortfolioRequest.h>

#include <GetPortfolioResponse.h>

namespace org_wso2_www
{

#define TRADERCLIENTSTUB_ERROR_CODES_START (AXIS2_ERROR_LAST + 2000)

typedef enum
{
     TRADERCLIENTSTUB_ERROR_NONE = TRADERCLIENTSTUB_ERROR_CODES_START,

    TRADERCLIENTSTUB_ERROR_LAST
} TraderClientStub_error_codes;

 class ITraderClientCallback;

class TraderClientStub : public wso2wsf::Stub
{

        public:
        /**
         *  Constructor of TraderClient class
         *  @param client_home WSF/C home directory
         *
         */
        TraderClientStub(std::string& client_home);

        /**
         *  Constructor of TraderClient class
         *  @param client_home WSF/C home directory
         *  @param endpoint_uri The to endpoint uri,
         */

        TraderClientStub(std::string& client_home, std::string& endpoint_uri);

        /**
         * Populate Services for TraderClientStub
         */
        void WSF_CALL
        populateServicesForTraderClient();

        /**
         * Get the endpoint uri of the TraderClientStub
         */

        std::string WSF_CALL
        getEndpointUriOfTraderClient();

            /**
             * Auto generated function declaration
             * for "deposit|http://www.wso2.org" operation.
             *
             * @param _depositRequest of the org_wso2_www_types::DepositRequest
             *
             * @return org_wso2_www_types::DepositResponse*
             */

            org_wso2_www_types::DepositResponse* WSF_CALL deposit( org_wso2_www_types::DepositRequest*  _depositRequest);

            /**
             * Auto generated function declaration
             * for "getSymbols|http://www.wso2.org" operation.
             *
             * @param _getSymbolsRequest of the org_wso2_www_types::GetSymbolsRequest
             *
             * @return org_wso2_www_types::GetSymbolsResponse*
             */

            org_wso2_www_types::GetSymbolsResponse* WSF_CALL getSymbols( org_wso2_www_types::GetSymbolsRequest*  _getSymbolsRequest);

            /**
             * Auto generated function declaration
             * for "getQuote|http://www.wso2.org" operation.
             *
             * @param _getQuoteRequest of the org_wso2_www_types::GetQuoteRequest
             *
             * @return org_wso2_www_types::GetQuoteResponse*
             */

            org_wso2_www_types::GetQuoteResponse* WSF_CALL getQuote( org_wso2_www_types::GetQuoteRequest*  _getQuoteRequest);

            /**
             * Auto generated function declaration
             * for "createAccount|http://www.wso2.org" operation.
             *
             * @param _createAccountRequest of the org_wso2_www_types::CreateAccountRequest
             *
             * @return org_wso2_www_types::CreateAccountResponse*
             */

            org_wso2_www_types::CreateAccountResponse* WSF_CALL createAccount( org_wso2_www_types::CreateAccountRequest*  _createAccountRequest);

            /**
             * Auto generated function declaration
             * for "sell|http://www.wso2.org" operation.
             *
             * @param _sellRequest of the org_wso2_www_types::SellRequest
             *
             * @return org_wso2_www_types::SellResponse*
             */

            org_wso2_www_types::SellResponse* WSF_CALL sell( org_wso2_www_types::SellRequest*  _sellRequest);

            /**
             * Auto generated function declaration
             * for "buy|http://www.wso2.org" operation.
             *
             * @param _buyRequest of the org_wso2_www_types::BuyRequest
             *
             * @return org_wso2_www_types::BuyResponse*
             */

            org_wso2_www_types::BuyResponse* WSF_CALL buy( org_wso2_www_types::BuyRequest*  _buyRequest);

            /**
             * Auto generated function declaration
             * for "getPortfolio|http://www.wso2.org" operation.
             *
             * @param _getPortfolioRequest of the org_wso2_www_types::GetPortfolioRequest
             *
             * @return org_wso2_www_types::GetPortfolioResponse*
             */

            org_wso2_www_types::GetPortfolioResponse* WSF_CALL getPortfolio( org_wso2_www_types::GetPortfolioRequest*  _getPortfolioRequest);

        /**
         * Auto generated function for asynchronous invocations
         * for "deposit|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _depositRequest of the org_wso2_www_types::DepositRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_deposit(org_wso2_www_types::DepositRequest*  _depositRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "getSymbols|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _getSymbolsRequest of the org_wso2_www_types::GetSymbolsRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_getSymbols(org_wso2_www_types::GetSymbolsRequest*  _getSymbolsRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "getQuote|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _getQuoteRequest of the org_wso2_www_types::GetQuoteRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_getQuote(org_wso2_www_types::GetQuoteRequest*  _getQuoteRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "createAccount|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _createAccountRequest of the org_wso2_www_types::CreateAccountRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_createAccount(org_wso2_www_types::CreateAccountRequest*  _createAccountRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "sell|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _sellRequest of the org_wso2_www_types::SellRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_sell(org_wso2_www_types::SellRequest*  _sellRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "buy|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _buyRequest of the org_wso2_www_types::BuyRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_buy(org_wso2_www_types::BuyRequest*  _buyRequest,ITraderClientCallback* callback);

        /**
         * Auto generated function for asynchronous invocations
         * for "getPortfolio|http://www.wso2.org" operation.
         * @param stub The stub
         *
         * @param _getPortfolioRequest of the org_wso2_www_types::GetPortfolioRequest
         * @param ICallback callback handler
         */

        void WSF_CALL
        start_getPortfolio(org_wso2_www_types::GetPortfolioRequest*  _getPortfolioRequest,ITraderClientCallback* callback);

};

/** we have to reserve some error codes for adb and for custom messages */

}

#endif


text:
// Copyright 2022 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Tests that blog post search service gets correct results.
 */

import { EventEmitter } from '@angular/core';
import { HttpClientTestingModule } from
  '@angular/common/http/testing';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';

import { BlogPostSearchService, UrlSearchQuery } from 'services/blog-search.service';
import { BlogHomePageBackendApiService, SearchResponseData } from 'domain/blog/blog-homepage-backend-api.service';
import { Subscription } from 'rxjs';

describe('Blog Post Search Service', () => {
  let searchService: BlogPostSearchService;
  let blogHomePageBackendApiService: BlogHomePageBackendApiService;
  let response: UrlSearchQuery;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        BlogPostSearchService,
        BlogHomePageBackendApiService,
      ]
    });
    searchService = TestBed.inject(BlogPostSearchService);
    blogHomePageBackendApiService = TestBed.inject(
      BlogHomePageBackendApiService);
  });

  describe('updateSearchFieldsBasedOnUrlQuery', () => {
    let urlSearchQuery: string;

    // eslint-disable-next-line max-len
    it('should identify two tags given in url search query', () => {
      urlSearchQuery = '?q=testBlogSearch&tags=("News"%20OR%20"Mathematics")';
      response = searchService.updateSearchFieldsBasedOnUrlQuery(
        urlSearchQuery);
      expect(response.selectedTags.sort()).toEqual(['Mathematics', 'News']);
      expect(response.searchQuery).toEqual('testBlogSearch');
    });

    it('should find one tag if given in url search without query',
      () => {
        urlSearchQuery = '?q=&tags=("News"%20OR%20"Mathematics")';
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags.sort()).toEqual(['Mathematics', 'News']);
        expect(response.searchQuery).toBe('');
      }
    );
    it('should find no tags if not given in url search',
      () => {
        urlSearchQuery = '?q=test';
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags.length).toBe(0);
        expect(response.searchQuery).toEqual('test');
      }
    );

    it('should find as many keywords as provided in search query',
      () => {
        urlSearchQuery = '?q=protractor%20blog%20test&tags=("News"%20OR%20' +
        '"Mathematics")';
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags.sort()).toEqual(['Mathematics', 'News']);
        expect(response.searchQuery).toEqual('protractor blog test');
      }
    );

    it('should not find tags when ampersand is escaped',
      () => {
        urlSearchQuery = '?q=protractor%20test%26tags=("Mathematics")';
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags.length).toBe(0);
        expect(response.searchQuery).toEqual(
          'protractor test&tags=("Mathematics")');
      }
    );

    it('should only use correct fields when ampersand is not escaped anywhere',
      () => {
        urlSearchQuery = '?q=protractor&test&tags=("Mathematics")';
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags).toEqual(['Mathematics']);
        expect(response.searchQuery).toEqual(
          'protractor');
      }
    );

    it('should omit url component if it is malformed',
      () => {
        // In the search query below tags param are not wrapped in parentheses.
        // updateSearchFieldsBasedOnUrlQuery is expected to clean tags from url.
        urlSearchQuery = (
          '?q=protractor%20test&tags="Mathematics"');
        response = searchService.updateSearchFieldsBasedOnUrlQuery(
          urlSearchQuery);
        expect(response.selectedTags.length).toBe(0);
        expect(response.searchQuery).toEqual('protractor test');
      }
    );
  });

  describe('getSearchUrlQueryString', () => {
    it('should successfully get search url query string', () => {
      const searchQuery = 'blog search';
      const tags = ['tag1', 'tag2'];

      expect(searchService.getSearchUrlQueryString(searchQuery, tags)).toBe(
        'blog%20search&tags=("tag1" OR "tag2")');
    });

    it('should successfully get search url query string when there is no' +
      'tags query params', () => {
      const searchQuery: string = 'blog search';
      const tags: string[] = [];

      expect(searchService.getSearchUrlQueryString(searchQuery, tags)).toBe(
        'blog%20search');
    });

    it('should successfully get search url query string when there is no' +
    ' query params', () => {
      const searchQuery = '';
      const tags = ['tag1', 'tag2'];

      expect(searchService.getSearchUrlQueryString(searchQuery, tags)).toBe(
        '&tags=("tag1" OR "tag2")');
    });
  });

  describe('executeSearchQuery', () => {
    let successHandler: jasmine.Spy<jasmine.Func>;
    let errorHandler: jasmine.Spy<jasmine.Func>;
    let searchQuery: string;
    let tags: string[];
    let initialSearchResultsLoadedSpy: jasmine.Spy<jasmine.Func>;
    let testSubscriptions: Subscription;
    let sampleResponse: SearchResponseData;
    beforeEach(() => {
      searchQuery = 'example';
      tags = ['tag1', 'tag2'];
      initialSearchResultsLoadedSpy = jasmine.createSpy(
        'initialSearchResultsLoadedSpy');
      successHandler = jasmine.createSpy('success');
      errorHandler = jasmine.createSpy('error');
      sampleResponse = {
        searchOffset: 2,
        blogPostSummariesList: [],
        listOfDefaultTags: [],
      };
      testSubscriptions = new Subscription();
      testSubscriptions.add(
        searchService.onInitialSearchResultsLoaded.subscribe(
          initialSearchResultsLoadedSpy
        ));
    });

    it('should successfully execute search query', fakeAsync(() => {
      spyOn(blogHomePageBackendApiService, 'fetchBlogPostSearchResultAsync')
        .and.returnValue(Promise.resolve(sampleResponse));

      searchService.executeSearchQuery(
        searchQuery, tags, () => {});
      expect(searchService.isSearchInProgress()).toBe(true);

      tick();

      expect(blogHomePageBackendApiService.fetchBlogPostSearchResultAsync)
        .toHaveBeenCalled();
      expect(searchService.isSearchInProgress()).toBe(false);
      expect(initialSearchResultsLoadedSpy).toHaveBeenCalled();
    }));

    it('should use reject handler if fetching data fails while search exec',
      fakeAsync(() => {
        spyOn(blogHomePageBackendApiService, 'fetchBlogPostSearchResultAsync')
          .and.returnValue(Promise.reject({
            error: {error: 'Some error in the backend.'}
          }));

        searchService.executeSearchQuery(
          searchQuery, tags, () => {}, errorHandler);
        expect(searchService.isSearchInProgress()).toBe(true);

        tick();

        expect(searchService.isSearchInProgress()).toBe(false);
        expect(blogHomePageBackendApiService.fetchBlogPostSearchResultAsync)
          .toHaveBeenCalled();
        expect(errorHandler).toHaveBeenCalledWith(
          'Some error in the backend.');
      }));

    describe('loadMoreData', () => {
      let moreSampleResponse: SearchResponseData = {
        searchOffset: 1,
        blogPostSummariesList: [],
        listOfDefaultTags: [],
      };

      it('should successfully load more data', fakeAsync(() => {
        spyOn(blogHomePageBackendApiService, 'fetchBlogPostSearchResultAsync')
          .and.returnValues(
            Promise.resolve(sampleResponse),
            Promise.resolve(moreSampleResponse)
          );

        searchService.executeSearchQuery(searchQuery, tags, () => {});
        tick();
        expect(initialSearchResultsLoadedSpy).toHaveBeenCalled();

        searchService.loadMoreData(successHandler, errorHandler);
        tick();

        expect(successHandler).toHaveBeenCalledWith(moreSampleResponse);
        expect(errorHandler).not.toHaveBeenCalled();
      }));

      it('should not load more data when a new query is still being sent',
        fakeAsync(() => {
          spyOn(blogHomePageBackendApiService, 'fetchBlogPostSearchResultAsync')
            .and.returnValues(
              Promise.resolve(sampleResponse),
              Promise.resolve(moreSampleResponse)
            );

          searchService.executeSearchQuery(searchQuery, tags, () => {});
          tick();
          expect(initialSearchResultsLoadedSpy).toHaveBeenCalled();

          searchService.loadMoreData(successHandler);
          searchService.loadMoreData(successHandler, errorHandler);
          tick();
          expect(errorHandler).toHaveBeenCalledWith(false);
        }));

      it('should not load more data when the end of page has been reached',
        fakeAsync(() => {
          let lastSampleResponse: SearchResponseData = {
            searchOffset: null,
            blogPostSummariesList: [],
            listOfDefaultTags: [],
          };
          spyOn(blogHomePageBackendApiService, 'fetchBlogPostSearchResultAsync')
            .and.returnValues(
              Promise.resolve(sampleResponse),
              Promise.resolve(lastSampleResponse),
            );

          searchService.executeSearchQuery(searchQuery, tags, () => {});
          tick();
          expect(initialSearchResultsLoadedSpy).toHaveBeenCalled();

          searchService.loadMoreData(successHandler);
          tick();
          expect(successHandler).toHaveBeenCalledWith(lastSampleResponse);
          expect(errorHandler).not.toHaveBeenCalled();

          searchService.loadMoreData(successHandler, errorHandler);
          tick();
          expect(errorHandler).toHaveBeenCalledWith(true);
        }));
    });
  });

  it('should fetch searchBarLoaded EventEmitter', () => {
    let searchBarLoadedEmitter = new EventEmitter();
    expect(searchService.onSearchBarLoaded).toEqual(searchBarLoadedEmitter);
  });
});


text:
using System;
using System.Text;

namespace Rocinante.Types.Extensions
{
    public static class ExceptionExtensions
    {
        public static string AllInnerMessages(this Exception ex, string seperator = "\n-----\n")
        {
            if(seperator.IsNullOrEmpty()) throw new ArgumentException("The seperator cannot be null or empty", nameof(seperator));

            var sb = new StringBuilder();

            var e = ex;
            while(e != null)
            {
                sb.Append(e.Message).Append(seperator);
                e = e.InnerException;
            }

            var result = sb.ToString();

            return result.Length > 0 ? result.Substring(0, result.Length - seperator.Length) : string.Empty;
        }
    }
}