text:
package subtitleFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FormatTTML implements TimedTextFileFormat {

	public TimedTextObject parseFile(String fileName, InputStream is) throws IOException, FatalParsingException {

		TimedTextObject tto = new TimedTextObject();
		tto.fileName = fileName;

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(is);
			doc.getDocumentElement().normalize();

			//we recover the metadata
			Node node = doc.getElementsByTagName("ttm:title").item(0);
			if (node != null) tto.title = node.getTextContent();
			node = doc.getElementsByTagName("ttm:copyright").item(0);
			if (node != null) tto.copyrigth = node.getTextContent();
			node = doc.getElementsByTagName("ttm:desc").item(0);
			if (node != null) tto.description = node.getTextContent();

			//we recover the styles
			NodeList styleN = doc.getElementsByTagName("style");
			//we recover the timed text elements
			NodeList captionsN = doc.getElementsByTagName("p");
			//regions of the layout could also be recovered this way

			tto.warnings += "Styling attributes are only recognized inside a style definition, to be referenced later in the captions.\n\n";
			//we parse the styles
			for (int i = 0; i < styleN.getLength(); i++) {
				Style style = new Style(Style.defaultID());
				node = styleN.item(i);
				NamedNodeMap attr = node.getAttributes();
				//we get the id
				Node currentAtr = attr.getNamedItem("id");
				if (currentAtr != null)
					style.iD = currentAtr.getNodeValue();
				currentAtr = attr.getNamedItem("xml:id");
				if (currentAtr != null)
					style.iD = currentAtr.getNodeValue();

				//we get the style it may be based upon
				currentAtr = attr.getNamedItem("style");
				if (currentAtr != null)
					if(tto.styling.containsKey(currentAtr.getNodeValue()))
							style = new Style (style.iD,tto.styling.get(currentAtr.getNodeValue()));

				//we check for background color
				currentAtr = attr.getNamedItem("tts:backgroundColor");
				if (currentAtr != null)
					style.backgroundColor = parseColor(currentAtr.getNodeValue(),tto);

				//we check for color
				currentAtr = attr.getNamedItem("tts:color");
				if (currentAtr != null)
					style.color = parseColor(currentAtr.getNodeValue(),tto);

				//we check for font family
				currentAtr = attr.getNamedItem("tts:fontFamily");
				if (currentAtr != null)
					style.font = currentAtr.getNodeValue();

				//we check for font size
				currentAtr = attr.getNamedItem("tts:fontSize");
				if (currentAtr != null)
					style.fontSize = currentAtr.getNodeValue();

				//we check for italics
				currentAtr = attr.getNamedItem("tts:fontStyle");
				if (currentAtr != null)
					if (currentAtr.getNodeValue().equalsIgnoreCase("italic") || currentAtr.getNodeValue().equalsIgnoreCase("oblique"))
						style.italic = true;
					else if  (currentAtr.getNodeValue().equalsIgnoreCase("normal"))
						style.italic = false;

				//we check for bold
				currentAtr = attr.getNamedItem("tts:fontWeight");
				if (currentAtr != null)
					if (currentAtr.getNodeValue().equalsIgnoreCase("bold"))
						style.bold = true;
					else if  (currentAtr.getNodeValue().equalsIgnoreCase("normal"))
						style.bold = false;

				//we check opacity (to set the alpha)
				currentAtr = attr.getNamedItem("tts:opacity");
				if (currentAtr != null){
					try {
						//a number between 1.0 and 0
						float alpha = Float.parseFloat(currentAtr.getNodeValue());
						if (alpha > 1)
							alpha = 1;
						else if (alpha < 0)
							alpha = 0;

						String aa = Integer.toHexString((int) (alpha*255));
						if (aa.length()<2)
							aa = "0"+aa;

						style.color = style.color.substring(0, 6)+aa;
						style.backgroundColor = style.backgroundColor.substring(0, 6)+aa;

					} catch (NumberFormatException e){
						//ignore the alpha
					}
				}

				//we check for text align
				currentAtr = attr.getNamedItem("tts:textAlign");
				if (currentAtr != null)
					if (currentAtr.getNodeValue().equalsIgnoreCase("left") || currentAtr.getNodeValue().equalsIgnoreCase("start"))
						style.textAlign = "bottom-left";
					else if  (currentAtr.getNodeValue().equalsIgnoreCase("right") || currentAtr.getNodeValue().equalsIgnoreCase("end"))
						style.textAlign = "bottom-right";

				//we check for underline
				currentAtr = attr.getNamedItem("tts:textDecoration");
				if (currentAtr != null)
					if (currentAtr.getNodeValue().equalsIgnoreCase("underline"))
						style.underline = true;
					else if  (currentAtr.getNodeValue().equalsIgnoreCase("noUnderline"))
						style.underline = false;

				//we add the style
				tto.styling.put(style.iD, style);
			}

			//we parse the captions
			for (int i = 0; i < captionsN.getLength(); i++) {
				Caption caption = new Caption();
				caption.content = "";
				boolean validCaption = true;
				node = captionsN.item(i);

				NamedNodeMap attr = node.getAttributes();
				//we get the begin time
				Node currentAtr = attr.getNamedItem("begin");
				//if no begin is present, 0 is assumed
				caption.start = new Time("", "");
				caption.end = new Time("", "");
				if (currentAtr != null)
					caption.start.mseconds = parseTimeExpression(currentAtr.getNodeValue(), tto, doc);

				//we get the end time, if present, duration is ignored, otherwise end is calculated from duration
				currentAtr = attr.getNamedItem("end");
				if (currentAtr != null)
					caption.end.mseconds = parseTimeExpression(currentAtr.getNodeValue(), tto, doc);
				else {
					currentAtr = attr.getNamedItem("dur");
					if (currentAtr != null)
						caption.end.mseconds = caption.start.mseconds + parseTimeExpression(currentAtr.getNodeValue(), tto, doc);
					else
						//no end or duration, invalid format, caption is discarded
						validCaption = false;
				}

				//we get the style
				currentAtr = attr.getNamedItem("style");
				if (currentAtr != null){
					Style style = tto.styling.get(currentAtr.getNodeValue());
					if (style != null)
						caption.style = style;
					else
						//unrecognized style
						tto.warnings += "unrecoginzed style referenced: "+currentAtr.getNodeValue()+"\n\n";
				}

				//we save the text
				NodeList textN = node.getChildNodes();
				for (int j = 0; j < textN.getLength(); j++) {
					if(textN.item(j).getNodeName().equals("#text"))
						caption.content+=textN.item(j).getTextContent().trim();
					else if (textN.item(j).getNodeName().equals("br"))
						caption.content+="
";

				}
				//is this check worth it?
				if (caption.content.replaceAll("
","").trim().isEmpty())
					validCaption = false;

				//and save the caption
				if (validCaption){
					int key = caption.start.mseconds;
					//in case the key is already there, we increase it by a millisecond, since no duplicates are allowed
					while (tto.captions.containsKey(key)) key++;
					tto.captions.put(key, caption);
				}

			}

		}catch(Exception e){
			e.printStackTrace();
			//this could be a fatal error...
			throw new FatalParsingException("Error during parsing: "+e.getMessage());
		}

		tto.built = true;
		return tto;
	}

	public String[] toFile(TimedTextObject tto) {

		//first we check if the TimedTextObject had been built, otherwise...
		if(!tto.built)
			return null;

		//we will write the lines in an ArrayList
		int index = 0;
		//the minimum size of the file is the number of captions and styles + lines for sections and formats and the metadata, so we'll take some extra space.
		ArrayList<String> file = new ArrayList<String>(30+tto.styling.size()+tto.captions.size());

		//identification line is placed
		file.add(index++,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		//root element is placed
		file.add(index++,"<tt xml:lang=\""+tto.language+"\" xmlns=\"http://www.w3.org/ns/ttml\" xmlns:tts=\"http://www.w3.org/ns/ttml#styling\">");
		//head
		file.add(index++,"\t");
		//metadata
		file.add(index++,"\t\t<metadata xmlns:ttm=\"http://www.w3.org/ns/ttml#metadata\">");
		//title
		String title;
		if (tto.title == null || tto.title.isEmpty())
			title = tto.fileName;
		else title = tto.title;
		file.add(index++,"\t\t\t<ttm:title>"+title+"</ttm:title>");
		//Copyright
		if (tto.copyrigth != null && !tto.copyrigth.isEmpty())
			file.add(index++,"\t\t\t<ttm:copyright>"+tto.copyrigth+"</ttm:copyright>");
		//additional info
		String desc = "Converted by the Online Subtitle Converter developed by J. David Requejo\n";
		if (tto.author != null && !tto.author.isEmpty())
			desc+="\n Original file by: "+tto.author+"\n";
		if (tto.description != null && !tto.description.isEmpty())
			desc+=tto.description+"\n";
		file.add(index++,"\t\t\t<ttm:desc>"+desc+"\t\t\t</ttm:desc>");

		//metadata closes
		file.add(index++,"\t\t</metadata>");
		//styling opens
		file.add(index++,"\t\t<styling>");

		String line;
		//Next we iterate over the styles
		Iterator


text:
@interface MOBProjectionEPSG2273 : MOBProjection

@end

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Build.Engine
{
    using System;
    using System.Collections.Immutable;
    using System.IO;
    using System.Linq;

    using Microsoft.DocAsCode.Build.Engine.Incrementals;
    using Microsoft.DocAsCode.Common;
    using Microsoft.DocAsCode.Exceptions;
    using Microsoft.DocAsCode.Plugins;

    internal class IncrementalPostProcessorHost : IPostProcessorHost
    {
        private readonly IncrementalPostProcessorsContext _increContext;
        private readonly string _postProcessorName;

        public IncrementalPostProcessorHost(IncrementalPostProcessorsContext increContext, string postProcessorName, IImmutableList<SourceFileInfo> sourceFileInfos)
        {
            if (increContext == null)
            {
                throw new ArgumentNullException(nameof(increContext));
            }
            if (postProcessorName == null)
            {
                throw new ArgumentNullException(nameof(postProcessorName));
            }

            _increContext = increContext;
            _postProcessorName = postProcessorName;
            SourceFileInfos = sourceFileInfos;
            ShouldTraceIncrementalInfo = _increContext.ShouldTraceIncrementalInfo;
            IsIncremental = _increContext.IsIncremental;
        }

        #region IPostProcessorHost

        public IImmutableList<SourceFileInfo> SourceFileInfos { get; }

        public bool ShouldTraceIncrementalInfo { get; }

        public bool IsIncremental { get; }

        public Stream LoadContextInfo()
        {
            if (_increContext.LastInfo == null)
            {
                Logger.LogVerbose("Could not load last context info since last build has no incremental information.");
                return null;
            }

            var lastPostProcessorInfo = FindPostProcessorInfo(_increContext.LastInfo, _postProcessorName);
            if (lastPostProcessorInfo.ContextInfoFile == null)
            {
                Logger.LogVerbose("Could not load last context info since last build has no context file information.");
                return null;
            }

            return EnvironmentContext.FileAbstractLayer.OpenRead(Path.Combine(_increContext.LastBaseDir, lastPostProcessorInfo.ContextInfoFile));
        }

        public Stream SaveContextInfo()
        {
            if (!_increContext.ShouldTraceIncrementalInfo)
            {
                Logger.LogVerbose("Could not save current context info since should not trace incremental information.");
                return null;
            }

            var currentPostProcessorInfo = FindPostProcessorInfo(_increContext.CurrentInfo, _postProcessorName);
            currentPostProcessorInfo.ContextInfoFile = IncrementalUtility.CreateRandomFileName(_increContext.CurrentBaseDir);

            return EnvironmentContext.FileAbstractLayer.Create(Path.Combine(_increContext.CurrentBaseDir, currentPostProcessorInfo.ContextInfoFile));
        }

        #endregion

        private static PostProcessorInfo FindPostProcessorInfo(PostProcessInfo postProcessInfo, string postProcessorName)
        {
            var postProcessorInfo = postProcessInfo.PostProcessorInfos.SingleOrDefault(p => p.Name == postProcessorName);
            if (postProcessorInfo == null)
            {
                throw new DocfxException($"Could not find post processor info with name {postProcessorName}.");
            }

            return postProcessorInfo;
        }
    }
}


text:
package org.wildfly.swarm.netflix.ribbon.secured;

import com.netflix.loadbalancer.reactive.ExecutionContext;
import com.netflix.loadbalancer.reactive.ExecutionInfo;
import com.netflix.loadbalancer.reactive.ExecutionListener;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import org.keycloak.KeycloakSecurityContext;
import org.wildfly.swarm.runtime.keycloak.KeycloakSecurityContextAssociation;

/**
 * @author Bob McWhirter
 */
public class BearerHeaderAdder implements ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>> {
    @Override
    public void onExecutionStart(ExecutionContext<HttpClientRequest<ByteBuf>> context) throws AbortExecutionException {
    }

    @Override
    public void onStartWithServer(ExecutionContext<HttpClientRequest<ByteBuf>> context, ExecutionInfo info) throws AbortExecutionException {
        KeycloakSecurityContext securityContext = KeycloakSecurityContextAssociation.get();
        if ( securityContext != null ) {
            HttpClientRequest<ByteBuf> request = context.getRequest();
            request.withHeader( "Authorization", "Bearer " + securityContext.getTokenString() );
        }
    }

    @Override
    public void onExceptionWithServer(ExecutionContext<HttpClientRequest<ByteBuf>> context, Throwable exception, ExecutionInfo info) {

    }

    @Override
    public void onExecutionSuccess(ExecutionContext<HttpClientRequest<ByteBuf>> context, HttpClientResponse<ByteBuf> response, ExecutionInfo info) {

    }

    @Override
    public void onExecutionFailed(ExecutionContext<HttpClientRequest<ByteBuf>> context, Throwable finalException, ExecutionInfo info) {

    }
}


text:
This topic lists localized versions of the Angular documentation.

* [Español](http://docs.angular.lat/)
* [简体中文版](https://angular.cn/)
* [正體中文版](https://angular.tw/)
* [日本語版](https://angular.jp/)
* [한국어](https://angular.kr/)

For information on localizing Angular documentation, see [Angular localization guidelines](guide/localizing-angular).


text:
"""Problem 33: Digit cancelling fractions.

Weird that it's 100"""
import unittest
from functools import reduce
from utils.primes import find_prime_factors

def is_curious(num, den):
    """Returns if fraction is of curious type"""
    num_d = [int(d) for d in str(num)]
    den_d = [int(d) for d in str(den)]
    intersection = [d for d in num_d if d in den_d]
    if len(intersection) in [0, 2]:
        return False
    int_d = intersection[0]
    if int_d == 0:
        return False
    num_d.remove(int_d)
    den_d.remove(int_d)
    if den_d == [0]:
        return False
    return num/den == num_d[0]/den_d[0]

def solution():
    fractions = [(num, den) for den in range(10, 100)
                            for num in range(10, den)
                            if is_curious(num, den)]
    numerator = reduce(lambda x, y: x * y, [f[0] for f in fractions])
    denominator = reduce(lambda x, y: x * y, [f[1] for f in fractions])
    print(fractions)
    print(numerator, denominator)
    i = 2
    while i < denominator:
        if (not numerator%i) and (not denominator%i):
            numerator //= i
            denominator //= i
            i = 2
        else:
            i += 1
    return denominator

class TestFunction(unittest.TestCase):
    def test_is_curious(self):
        self.assertTrue(is_curious(49, 98))
        self.assertFalse(is_curious(34, 75))
        self.assertFalse(is_curious(20, 22))

if __name__ == "__main__":
    print(solution())
    unittest.main()


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearning.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.core.management.SystemData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.machinelearning.models.ModelVersionProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Azure Resource Manager resource envelope. */
@Fluent
public final class ModelVersionInner extends ProxyResource {
    /*
     * [Required] Additional attributes of the entity.
     */
    @JsonProperty(value = "properties", required = true)
    private ModelVersionProperties properties;

    /*
     * Azure Resource Manager metadata containing createdBy and modifiedBy information.
     */
    @JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY)
    private SystemData systemData;

    /** Creates an instance of ModelVersionInner class. */
    public ModelVersionInner() {
    }

    /**
     * Get the properties property: [Required] Additional attributes of the entity.
     *
     * @return the properties value.
     */
    public ModelVersionProperties properties() {
        return this.properties;
    }

    /**
     * Set the properties property: [Required] Additional attributes of the entity.
     *
     * @param properties the properties value to set.
     * @return the ModelVersionInner object itself.
     */
    public ModelVersionInner withProperties(ModelVersionProperties properties) {
        this.properties = properties;
        return this;
    }

    /**
     * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information.
     *
     * @return the systemData value.
     */
    public SystemData systemData() {
        return this.systemData;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (properties() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property properties in model ModelVersionInner"));
        } else {
            properties().validate();
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(ModelVersionInner.class);
}


text:
{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) - 2017 Róman Joost <roman@bromeco.de>

This file is part of gtfsschedule.

gtfsschedule is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

gtfsschedule is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with gtfsschedule.  If not, see <http://www.gnu.org/licenses/>.
-}
module CSV.Import.Calendar where

import           Control.Monad         (mzero)
import           Data.Csv              (DefaultOrdered, FromField,
                                        FromNamedRecord (..), parseField, (.:))
import           Data.Time.Format      (defaultTimeLocale, parseTimeM)
import           Data.Time.Calendar    (Day)
import           GHC.Generics

import qualified Data.ByteString.Char8 as B
import qualified Data.Text             as T
import           Database.Persist      (PersistValue (..))

data Calendar = Calendar { service_id :: !T.Text
                         , monday     :: !Int
                         , tuesday    :: !Int
                         , wednesday  :: !Int
                         , thursday   :: !Int
                         , friday     :: !Int
                         , saturday   :: !Int
                         , sunday     :: !Int
                         , start_date :: CSVDay
                         , end_date   :: CSVDay
                         }
  deriving (Eq, Generic, Show)

instance FromNamedRecord Calendar where
    parseNamedRecord m =
        Calendar <$> m .: "service_id" <*> m .: "monday" <*> m .: "tuesday" <*>
        m .: "wednesday" <*>
        m .: "thursday" <*>
        m .: "friday" <*>
        m .: "saturday" <*>
        m .: "sunday" <*>
        m .: "start_date" <*>
        m .: "end_date"

instance DefaultOrdered Calendar

-- Wrapper to avoid orphaned instances (see #29)
-- Format: 20160912
newtype CSVDay = CSVDay { unWrapDay :: Day } deriving (Eq, Show)

instance FromField CSVDay where
  parseField str = case parseTimeM True defaultTimeLocale "%Y%m%d" (B.unpack str) of
    Just d -> return $ CSVDay d
    Nothing -> mzero

toBool ::
  Int
  -> Bool
toBool 0 = False
toBool _ = True

prepareSQL ::
  T.Text
prepareSQL = "insert into calendar (service_id, monday, tuesday, wednesday, thursday, friday, saturday, sunday, start_date, end_date) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

convertToValues ::
  Calendar
  -> [PersistValue]
convertToValues r = [ PersistText $ service_id r
                    , PersistBool $ toBool $ monday r
                    , PersistBool $ toBool $ tuesday r
                    , PersistBool $ toBool $ wednesday r
                    , PersistBool $ toBool $ thursday r
                    , PersistBool $ toBool $ friday r
                    , PersistBool $ toBool $ saturday r
                    , PersistBool $ toBool $ sunday r
                    , PersistDay $ unWrapDay $ start_date r
                    , PersistDay $ unWrapDay $ end_date r
                    ]


text:
package com.xtra.api.command.base;

import java.lang.reflect.ParameterizedType;

import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;

import com.xtra.api.command.Command;
import com.xtra.api.util.command.CommandBaseExecutor;

/**
 * Provides a base for commands. Support for many XtraCore command features are
 * provided through this default implementation. It is highly recommended to use
 * this base class, over implementing your own {@link Command} or using
 * {@link CommandBaseLite}.
 *
 * @param <T> The {@link CommandSource} required to execute this command. If a
 *        {@link CommandSource} not of the same type as the one specified in
 *        this generic attempts to execute this command, they will receive an
 *        error message. Note that if you wish for any {@link CommandSource} to
 *        execute this command, specify CommandSource in the
 *        generic.
 */
public abstract class CommandBase<T extends CommandSource> implements Command {

    // NOTE: this is overridden by the implementation
    private static CommandBaseExecutor BASE = null;

    public abstract CommandResult executeCommand(T src, CommandContext args) throws Exception;

    public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
        // Get the generic type
        @SuppressWarnings("rawtypes")
        Class<?> o = ((Class) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0]);
        // Let the implementation handle the rest of the logic
        return BASE.execute(this, o, src, args);
    }
}


text: [https://www.npmjs.com/package/trello](Node-trello) packaged for meteor.


text:
namespace TranslateManagerMetrics {

// An indexing type to query each UMA entry name via GetMetricsName() function.
// Note: |kMetricsEntries| should be updated when a new entry is added here.
enum MetricsNameIndex {
  UMA_INITIATION_STATUS,
  UMA_LANGUAGE_DETECTION_ERROR,
  UMA_SERVER_REPORTED_UNSUPPORTED_LANGUAGE,
  UMA_MAX,
};

// When Chrome Translate is ready to translate a page, one of following reason
// decide the next browser action.
enum InitiationStatusType {
  INITIATION_STATUS_DISABLED_BY_PREFS,
  INITIATION_STATUS_DISABLED_BY_SWITCH,
  INITIATION_STATUS_DISABLED_BY_CONFIG,
  INITIATION_STATUS_LANGUAGE_IS_NOT_SUPPORTED,
  INITIATION_STATUS_URL_IS_NOT_SUPPORTED,
  INITIATION_STATUS_SIMILAR_LANGUAGES,
  INITIATION_STATUS_ACCEPT_LANGUAGES,

  INITIATION_STATUS_AUTO_BY_CONFIG,
  INITIATION_STATUS_AUTO_BY_LINK,
  INITIATION_STATUS_SHOW_INFOBAR,

  INITIATION_STATUS_MAX,
};

// Called when Chrome Translate is initiated to report a reason of the next
// browser action.
void ReportInitiationStatus(InitiationStatusType type);

// Called when Chrome opens the URL so that the user sends an error feedback.
void ReportLanguageDetectionError();

// Called when it turns out that translating page is in unsupported language.
void ReportUnsupportedLanguage();

// Provides UMA entry names for unit tests.
const char* GetMetricsName(MetricsNameIndex index);

}  // namespace TranslateManagerMetrics

#endif  // CHROME_BROWSER_TRANSLATE_TRANSLATE_MANAGER_METRICS_H_


text:
find $DATA_DIR -type d -exec chmod 775 {} \;
find $DATA_DIR -type f -exec chmod 644 {} \;
chown -R root:root $DATA_DIR

# Start grunt process
cd $DATA_DIR

# Install NPM packages only if not present
if [ ! -d "$DATA_DIR/node_modules" ]; then
  npm install
fi

# Check if we are running the docker in DEV mode
if [ $PRODUCTION = true ]; then
  # Build the mockup
  grunt build_deploy

  # Serve it via HTTP
  grunt server
else
  # Restore run.sh execution permissions
  chmod +x run.sh

  # Build, Serve via HTTP and Watch for changes
  grunt build
fi


text:
  <form name="update_ship_status" method="POST" >

Shipping Type <?php echo $ship_data['shipping_type']; ?>

      Carrier
      <select name="carrier" class="form-group">
        <option value="">Select Carrier</option>
        <?php if(count($carrier)>0){ foreach($carrier as $ckey => $cvalue){ ?>
         <option value="<?php echo $cvalue['id'];?>" <?php echo set_select('carrier',$cvalue['id'],(($ship_data['ship_company'] == $cvalue['id'])?true:false));?> ><?php echo $cvalue['name']; ?></option>
        <?php }} ?>
      </select>

      Status
      <select name="status" class="form-group">
        <option value="">Select Status</option>
        <?php if(count($status)>0){ foreach($status as $ckey => $cvalue){ ?>
         <option value="<?php echo $cvalue['name']; ?>" <?php echo set_select('status',$cvalue['name'],(($ship_data['order_status'] == $cvalue['name'])?true:false));?> ><?php echo $cvalue['name']; ?></option>
        <?php }} ?>
      </select>

        <input type="submit" name="update_shp_type" class="btn btn-default" value="SAVE" />

  </form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace valentines.Helpers
{
    //from: http://stackoverflow.com/questions/1607832/writing-a-compareto-dataannotation-attribute
    /// <summary>
    /// Compares a property to a given comparison value. Applied to a property.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
    public class CompareValueAttribute : ValidationAttribute
    {
        public CompareValueAttribute() : base()
        {
            if(ErrorMessage.IsNullOrEmpty())
                ErrorMessage = "The value failed validation.";
        }
        /// <summary>
        /// Gets or sets the comparison value.
        /// </summary>
        /// <value>The comparison value.</value>
        public object ComparisonValue
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets a value indicating whether the first property can be less than the second property.
        /// </summary>
        /// <value><c>true</c> if less than is allowed; otherwise, <c>false</c>.</value>
        public bool LessThanAllowed
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets a value indicating whether the first property can be equal to the second property.
        /// </summary>
        /// <value><c>true</c> if equal to is allowed; otherwise, <c>false</c>.</value>
        public bool EqualToAllowed
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets a value indicating whether the first property can be greater than the second property.
        /// </summary>
        /// <value><c>true</c> if greater than is allowed; otherwise, <c>false</c>.</value>
        public bool GreaterThanAllowed
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets a value indicating whether null values are allowed.
        /// </summary>
        /// <value><c>true</c> if null values are allowed; otherwise, <c>false</c>.</value>
        public bool AllowNullValues
        {
            get;
            set;
        }
        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        /// 	<c>true</c> if the specified value is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return AllowNullValues;
            }
            if(ComparisonValue==null)
            {
                throw new ArgumentNullException("ComparisonValue");
            }

            int result = 0;

            if(ComparisonValue as string == "DateTime.Now")
            {
                result = (value as IComparable).CompareTo((DateTime.Now as IComparable));
            }
            else
            {
                result = (value as IComparable).CompareTo((ComparisonValue as IComparable));
            }

            switch (result)
            {
                case -1: return LessThanAllowed;
                case 0: return EqualToAllowed;
                case 1: return GreaterThanAllowed;
                default: throw new ApplicationException("Something just failed in ComparePropertiesAttribute");
            }
        }
    }
}


text:
/**
 * @class Oskari.mapframework.bundle.personaldata.PersonalDataBundle
 *
 * Definition for bundle. See source for details.
 */
Oskari.clazz.define("Oskari.mapframework.bundle.personaldata.PersonalDataBundle", function () {

}, {
    "create": function () {
        var me = this;
        var inst = Oskari.clazz.create("Oskari.mapframework.bundle.personaldata.PersonalDataBundleInstance");
        return inst;

    },
    "update": function (manager, bundle, bi, info) {

    }
}, {

    "protocol": ["Oskari.bundle.Bundle", "Oskari.mapframework.bundle.extension.ExtensionBundle"],
    "source": {

        "scripts": [{
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/instance.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/Flyout.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/Tile.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/events/PersonaldataLoadedEvent.js"
        },{
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/MyViewsTab.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/service/ViewService.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/PublishedMapsTab.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/AccountTab.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/request/AddTabRequest.js"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/request/AddTabRequestHandler.js"
        }, {
            "type": "text/css",
            "src": "../../../../resources/framework/bundle/personaldata/css/personaldata.css"
        }, {
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/myplaces2/MyPlacesTab.js"
        }],

        "locales": [{
            "lang": "hy",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/hy.js"
        }, {
            "lang": "bg",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/bg.js"
        }, {
            "lang": "cs",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/cs.js"
        }, {
            "lang": "da",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/da.js"
        }, {
            "lang": "de",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/de.js"
        }, {
            "lang": "en",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/en.js"
        }, {
            "lang": "es",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/es.js"
        }, {
            "lang": "et",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/et.js"
        }, {
            "lang": "fi",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/fi.js"
        }, {
            "lang": "ka",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/ka.js"
        }, {
            "lang": "el",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/el.js"
        }, {
            "lang": "hr",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/hr.js"
        }, {
            "lang": "hu",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/hu.js"
        }, {
            "lang": "lv",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/lv.js"
        }, {
            "lang": "nl",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/nl.js"
        }, {
            "lang": "pl",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/pl.js"
        }, {
            "lang": "pt",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/pt.js"
        }, {
            "lang": "ro",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/ro.js"
        }, {
            "lang": "sr",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/sr.js"
        }, {
            "lang": "sl",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/sl.js"
        }, {
            "lang": "sk",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/sk.js"
        }, {
            "lang": "sq",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/sq.js"
        }, {
            "lang": "sv",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/sv.js"
        }, {
            "lang": "uk",
            "type": "text/javascript",
            "src": "../../../../bundles/framework/bundle/personaldata/locale/uk.js"
        }]
    },
    "bundle": {
        "manifest": {
            "Bundle-Identifier": "personaldata",
            "Bundle-Name": "personaldata",
            "Bundle-Author": [{
                "Name": "ejv",
                "Organisation": "nls.fi",
                "Temporal": {
                    "Start": "2009",
                    "End": "2011"
                },
                "Copyleft": {
                    "License": {
                        "License-Name": "EUPL",
                        "License-Online-Resource": "http://www.paikkatietoikkuna.fi/license"
                    }
                }
            }],
            "Bundle-Name-Locale": {
                "fi": {
                    "Name": " style-1",
                    "Title": " style-1"
                },
                "en": {}
            },
            "Bundle-Version": "1.0.0",
            "Import-Namespace": ["Oskari"],
            "Import-Bundle": {}
        }
    },

    /**
     * @static
     * @property {String[]} dependencies
     */
    "dependencies": ["jquery"]

});

Oskari.bundle_manager.installBundleClass("personaldata", "Oskari.mapframework.bundle.personaldata.PersonalDataBundle");


text:
<?xml version="1.0" encoding="utf-8" ?>
<!--Created:cb85b80c-f585-40ff-8bfc-12ff4d0e34a9-->
<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
     Name="OAuthAddinDemo"
     ProductID="{08b663af-b62e-4865-a5a4-290aaf6e8082}"
     Version="1.0.0.0"
     SharePointMinVersion="16.0.0.0"
>
  <Properties>
    <Title>OAuth SharePoint Addin Demo</Title>
    <StartPage>~remoteAppUrl/Pages/Default.aspx?{StandardTokens}</StartPage>
  </Properties>

  <AppPrincipal>
    <RemoteWebApplication ClientId="*" />
  </AppPrincipal>
  <AppPermissionRequests AllowAppOnlyPolicy="true" >
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
  </AppPermissionRequests>
</App>


text:
$(document).ready(function(){
    var canvas, ctx,
        PENCIL_TOOL = 1, BRUSH_TOOL = 2, LINE_TOOL = 3, RECTANGLE_TOOL = 4,
        CIRCLE_TOOL = 5, ERASER_TOOL = 10;
    var activeTool = 0;

    // Clears the temporary canvas
    function clrScreen(){
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    // since we use drawImage to the base canvas, fillRect isn't just gonna cut it
    function wipeCanvas(){
        baseCtx.fillStyle = "white";
        clrScreen();
        baseCtx.fillRect(0,0, baseCanvas.width, baseCanvas.height);
    }

    function getStrokeWidth(){
        var stroke = $("#outline-choose-slider").slider("value");
        return stroke;
    }

    function getStrokeColor(){
        var strokeColor = $("#stroke-swatch").css("background-color");
        return strokeColor;
    }

    function getFillColor(){
        var fillColor = $("#fill-swatch").css("background-color");
        return fillColor;
    }

    // given rgb values, convert them to hex
    function hexFromRGB(red, green, blue){
        var hex = [
            red.toString(16),
            green.toString(16),
            blue.toString(16)
        ];

        $.each(hex, function(nr, val){
            if (val.length === 1){
                hex[nr] = "0" + val;
            }
        });
        return hex.join("").toUpperCase();
    }

    function refreshStrokeSwatch(){
        var red = $("#stroke-red").slider("value"),
            green = $("#stroke-green").slider("value"),
            blue = $("#stroke-blue").slider("value");

        // convert to hex
        var hex = hexFromRGB(red, green, blue);
        $("#stroke-swatch").css("background", "#" + hex);
    }

    function refreshFillSwatch(){
        var red = $("#fill-red").slider("value"),
            green = $("#fill-green").slider("value"),
            blue = $("#fill-blue").slider("value");

        // convert to hex
        var hex = hexFromRGB(red, green, blue);
        $("#fill-swatch").css("background", "#" + hex);
    }

    function canvasDraw(e){
        if (e.type === 'mousedown'){
            x = e.pageX;
            y = e.pageY;

            if (activeTool === LINE_TOOL || activeTool === PENCIL_TOOL ||
                activeTool === CIRCLE_TOOL || activeTool === BRUSH_TOOL){
                ctx.beginPath();
            }
            else if (activeTool === RECTANGLE_TOOL){
                ctx.fillRect(x,y,0,0);
            }
            canvas.addEventListener('mousemove', canvasDraw, false);
        }
        else if (e.type === 'mouseup'){
            // stop the drawing and transfer to the background
            canvas.removeEventListener('mousemove', canvasDraw, false);
            baseCtx.drawImage(canvas, 0, 0);

            // TODO -- allow resizing before transferring to the background
        }
        else if (e.type === 'mousemove'){
            clrScreen();

            x2 = e.pageX;
            y2 = e.pageY;

            // get the properties based on the sliders and/or swatches
            ctx.lineWidth = getStrokeWidth();
            ctx.fillStyle = getFillColor();
            ctx.strokeStyle = getStrokeColor();

            if (activeTool === PENCIL_TOOL){
                ctx.moveTo(x, y);
                ctx.lineTo(x2, y2);
                ctx.lineWidth = 1;
                ctx.stroke();
                x = e.pageX;
                y = e.pageY;
            }
            else if (activeTool === BRUSH_TOOL){
                ctx.moveTo(x, y);
                ctx.lineTo(x2, y2);
                ctx.stroke();
                x = e.pageX;
                y = e.pageY;
            }
            else if (activeTool === LINE_TOOL){
                ctx.beginPath();
                ctx.moveTo(x, y);
                ctx.lineTo(x2, y2);

                ctx.stroke();
            }
            else if (activeTool === RECTANGLE_TOOL){
                ctx.strokeRect(x,y, (x2-x), (y2-y));
                ctx.fillRect(x,y, (x2-x), (y2-y));
            }
            else if (activeTool === CIRCLE_TOOL){
                ctx.beginPath();
                if (x2 > x){
                    ctx.arc(x,y,x2-x,0,2*Math.PI);
                }
                else{
                    ctx.arc(x,y,x-x2,0,2*Math.PI);
                }
                ctx.fill();
                ctx.stroke();
            }
        }
    }

    function setActiveTool(tool){
        if (activeTool === 0 && tool >= 1 && tool <= 5){
            canvas.addEventListener('mousedown', canvasDraw, false);
            canvas.addEventListener('mouseup', canvasDraw, false);
        }
        activeTool = tool;
    }

    // TOOL DECLARATIONS
    $(".tool").click(function(){
        $(".tool").css("background", "#555");
        var id = parseInt($(this).attr("data-tid"));
        setActiveTool(id);
        $(this).css("background", "#34495e");
    });

    // --JQUERY-UI STUFF--
    $("#outline-choose").click(function(){
        $("#stroke-width").slideToggle('50');
    });

    $("#outline-color-choose").click(function(){
        $("#stroke-color").slideToggle('50');
        if($("#fill-color").is(":visible")){
            $("#fill-color").toggle();
        }
    });

    $("#fill-color-choose").click(function(){
        $("#fill-color").slideToggle('50');
        if($("#stroke-color").is(":visible")){
            $("#stroke-color").toggle();
        }
    });

    // sliders for width and color swatch
    $("#outline-choose-slider").slider({
        orientation: "vertical",
        range: "min",
        min: 0,
        max: 15,
        value: 1,
        slide: function( event, ui ) {
                $( "#stroke-val").html( ui.value );
            }
    });

    $( "#stroke-red, #stroke-green, #stroke-blue" ).slider({
      orientation: "horizontal",
      range: "min",
      max: 255,
      value: 127,
      slide: refreshStrokeSwatch,
      change: refreshStrokeSwatch
    });

    $( "#fill-red, #fill-green, #fill-blue" ).slider({
      orientation: "horizontal",
      range: "min",
      max: 255,
      value: 127,
      slide: refreshFillSwatch,
      change: refreshFillSwatch
    });
    $( ".red, .blue, .green" ).slider( "value", 50 );

    $("#clear").click(function(){
        wipeCanvas();
    });

    canvas = document.getElementById("canvas");
    baseCanvas = document.getElementById("baseCanvas");
    ctx = canvas.getContext("2d");
    baseCtx = baseCanvas.getContext("2d");

    baseCanvas.height = window.innerHeight;
    baseCanvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;

    var x, y, x2, y2;

     $("#stroke-width, #fill-color, #stroke-color").hide();

});


text:
using namespace rek;

int main() {

  srand((unsigned int)time(nullptr));
  unsigned int m = 100, n = 10;
  long ITERS = 10000;

  Matrix<double, Dynamic, Dynamic> A(m, n);
  RowVector xopt(n);
  xopt.setRandom();
  A.setRandom();
  RowVector b = A * xopt;

  auto solver = Solver();
  RowVector x = solver.solve(A, b, ITERS);

  // Error should be small
  RowVector residual = (x - xopt) / std::sqrt(n);
  std::cout << "Error is " << residual.norm() << std::endl;
  assert(residual.norm() <= 0.01);
  std::cout << "Success..." << std::endl;

  return 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Log in</title>

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">

    <link href="assets/css/main.css" rel="stylesheet">
    <link href="assets/css/login.css" rel="stylesheet">

Admin login

                    <form role="form", action="/awesome", method="post">

                            Username
                            <input type="text" name="username" class="form-control" placeholder="Username" autofocus="">

                            Password
                            <input type="password" name="password" class="form-control" placeholder="Password">

                                <button class="btn btn-lg btn-primary btn-block" type="submit">Log in</button>

                    </form>


text:
package router

import (
	"math"
	"time"
)

const (
	EthernetOverhead    = 14
	UDPOverhead         = 28 // 20 bytes for IPv4, 8 bytes for UDP
	Port                = 6783
	HTTPPort            = Port + 1
	DefaultPMTU         = 65535
	MaxUDPPacketSize    = 65536
	ChannelSize         = 16
	FragTestSize        = 60001
	PMTUDiscoverySize   = 60000
	TCPHeartbeat        = 30 * time.Second
	FastHeartbeat       = 500 * time.Millisecond
	SlowHeartbeat       = 10 * time.Second
	FragTestInterval    = 5 * time.Minute
	GossipInterval      = 30 * time.Second
	PMTUVerifyAttempts  = 8
	PMTUVerifyTimeout   = 10 * time.Millisecond // gets doubled with every attempt
	MaxDuration         = time.Duration(math.MaxInt64)
	MaxMissedHeartbeats = 6
	HeaderTimeout       = 10 * time.Second
	HeartbeatTimeout    = MaxMissedHeartbeats * SlowHeartbeat
)

var (
	FragTest      = make([]byte, FragTestSize)
	PMTUDiscovery = make([]byte, PMTUDiscoverySize)
)


text:
.class Lcom/android/server/wifi/WifiServiceImpl$LockList;
.super Ljava/lang/Object;
.source "WifiServiceImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/wifi/WifiServiceImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "LockList"
.end annotation

# instance fields
.field private mList:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Lcom/android/server/wifi/WifiServiceImpl$WifiLock;",
            ">;"
        }
    .end annotation
.end field

.field final synthetic this$0:Lcom/android/server/wifi/WifiServiceImpl;

# direct methods
.method private constructor <init>(Lcom/android/server/wifi/WifiServiceImpl;)V
    .locals 1

    .prologue
    .line 2260
    iput-object p1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

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

    .line 2261
    new-instance v0, Ljava/util/ArrayList;

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

    iput-object v0, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    .line 2262
    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/wifi/WifiServiceImpl;Lcom/android/server/wifi/WifiServiceImpl$1;)V
    .locals 0
    .param p1, "x0"    # Lcom/android/server/wifi/WifiServiceImpl;
    .param p2, "x1"    # Lcom/android/server/wifi/WifiServiceImpl$1;

    .prologue
    .line 2257
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;-><init>(Lcom/android/server/wifi/WifiServiceImpl;)V

    return-void
.end method

.method static synthetic access$1100(Lcom/android/server/wifi/WifiServiceImpl$LockList;Ljava/io/PrintWriter;)V
    .locals 0
    .param p0, "x0"    # Lcom/android/server/wifi/WifiServiceImpl$LockList;
    .param p1, "x1"    # Ljava/io/PrintWriter;

    .prologue
    .line 2257
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->dump(Ljava/io/PrintWriter;)V

    return-void
.end method

.method static synthetic access$1700(Lcom/android/server/wifi/WifiServiceImpl$LockList;Lcom/android/server/wifi/WifiServiceImpl$WifiLock;)V
    .locals 0
    .param p0, "x0"    # Lcom/android/server/wifi/WifiServiceImpl$LockList;
    .param p1, "x1"    # Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    .prologue
    .line 2257
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->addLock(Lcom/android/server/wifi/WifiServiceImpl$WifiLock;)V

    return-void
.end method

.method static synthetic access$1800(Lcom/android/server/wifi/WifiServiceImpl$LockList;Landroid/os/IBinder;)I
    .locals 1
    .param p0, "x0"    # Lcom/android/server/wifi/WifiServiceImpl$LockList;
    .param p1, "x1"    # Landroid/os/IBinder;

    .prologue
    .line 2257
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->findLockByBinder(Landroid/os/IBinder;)I

    move-result v0

    return v0
.end method

.method static synthetic access$1900(Lcom/android/server/wifi/WifiServiceImpl$LockList;)Ljava/util/List;
    .locals 1
    .param p0, "x0"    # Lcom/android/server/wifi/WifiServiceImpl$LockList;

    .prologue
    .line 2257
    iget-object v0, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    return-object v0
.end method

.method static synthetic access$2000(Lcom/android/server/wifi/WifiServiceImpl$LockList;Landroid/os/IBinder;)Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    .locals 1
    .param p0, "x0"    # Lcom/android/server/wifi/WifiServiceImpl$LockList;
    .param p1, "x1"    # Landroid/os/IBinder;

    .prologue
    .line 2257
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->removeLock(Landroid/os/IBinder;)Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    move-result-object v0

    return-object v0
.end method

.method private addLock(Lcom/android/server/wifi/WifiServiceImpl$WifiLock;)V
    .locals 1
    .param p1, "lock"    # Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    .prologue
    .line 2291
    iget-object v0, p1, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;->mBinder:Landroid/os/IBinder;

    invoke-direct {p0, v0}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->findLockByBinder(Landroid/os/IBinder;)I

    move-result v0

    if-gez v0, :cond_0

    .line 2292
    iget-object v0, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 2294
    :cond_0
    return-void
.end method

.method private dump(Ljava/io/PrintWriter;)V
    .locals 3
    .param p1, "pw"    # Ljava/io/PrintWriter;

    .prologue
    .line 2317
    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v2}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v0

    .local v0, "i$":Ljava/util/Iterator;
    :goto_0
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_0

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    .line 2318
    .local v1, "l":Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    const-string v2, "    "

    invoke-virtual {p1, v2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    .line 2319
    invoke-virtual {p1, v1}, Ljava/io/PrintWriter;->println(Ljava/lang/Object;)V

    goto :goto_0

    .line 2321
    .end local v1    # "l":Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    :cond_0
    return-void
.end method

.method private findLockByBinder(Landroid/os/IBinder;)I
    .locals 3
    .param p1, "binder"    # Landroid/os/IBinder;

    .prologue
    .line 2308
    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v2}, Ljava/util/List;->size()I

    move-result v1

    .line 2309
    .local v1, "size":I
    add-int/lit8 v0, v1, -0x1

    .local v0, "i":I
    :goto_0
    if-ltz v0, :cond_1

    .line 2310
    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v2, v0}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    iget-object v2, v2, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;->mBinder:Landroid/os/IBinder;

    if-ne v2, p1, :cond_0

    .line 2313
    .end local v0    # "i":I
    :goto_1
    return v0

    .line 2309
    .restart local v0    # "i":I
    :cond_0
    add-int/lit8 v0, v0, -0x1

    goto :goto_0

    .line 2313
    :cond_1
    const/4 v0, -0x1

    goto :goto_1
.end method

.method private removeLock(Landroid/os/IBinder;)Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    .locals 3
    .param p1, "binder"    # Landroid/os/IBinder;

    .prologue
    .line 2297
    invoke-direct {p0, p1}, Lcom/android/server/wifi/WifiServiceImpl$LockList;->findLockByBinder(Landroid/os/IBinder;)I

    move-result v0

    .line 2298
    .local v0, "index":I
    if-ltz v0, :cond_0

    .line 2299
    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v2, v0}, Ljava/util/List;->remove(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    .line 2300
    .local v1, "ret":Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    invoke-virtual {v1}, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;->unlinkDeathRecipient()V

    .line 2303
    .end local v1    # "ret":Lcom/android/server/wifi/WifiServiceImpl$WifiLock;
    :goto_0
    return-object v1

    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

# virtual methods
.method declared-synchronized getStrongestLockMode()I
    .locals 3

    .prologue
    const/4 v0, 0x1

    .line 2269
    monitor-enter p0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v1}, Ljava/util/List;->isEmpty()Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v1

    if-eqz v1, :cond_1

    .line 2281
    :cond_0
    :goto_0
    monitor-exit p0

    return v0

    .line 2273
    :cond_1
    :try_start_1
    iget-object v1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    # getter for: Lcom/android/server/wifi/WifiServiceImpl;->mFullHighPerfLocksAcquired:I
    invoke-static {v1}, Lcom/android/server/wifi/WifiServiceImpl;->access$1300(Lcom/android/server/wifi/WifiServiceImpl;)I

    move-result v1

    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    # getter for: Lcom/android/server/wifi/WifiServiceImpl;->mFullHighPerfLocksReleased:I
    invoke-static {v2}, Lcom/android/server/wifi/WifiServiceImpl;->access$1400(Lcom/android/server/wifi/WifiServiceImpl;)I

    move-result v2

    if-le v1, v2, :cond_2

    .line 2274
    const/4 v0, 0x3

    goto :goto_0

    .line 2277
    :cond_2
    iget-object v1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    # getter for: Lcom/android/server/wifi/WifiServiceImpl;->mFullLocksAcquired:I
    invoke-static {v1}, Lcom/android/server/wifi/WifiServiceImpl;->access$1500(Lcom/android/server/wifi/WifiServiceImpl;)I

    move-result v1

    iget-object v2, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    # getter for: Lcom/android/server/wifi/WifiServiceImpl;->mFullLocksReleased:I
    invoke-static {v2}, Lcom/android/server/wifi/WifiServiceImpl;->access$1600(Lcom/android/server/wifi/WifiServiceImpl;)I
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    move-result v2

    if-gt v1, v2, :cond_0

    .line 2281
    const/4 v0, 0x2

    goto :goto_0

    .line 2269
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method declared-synchronized hasLocks()Z
    .locals 1

    .prologue
    .line 2265
    monitor-enter p0

    :try_start_0
    iget-object v0, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v0}, Ljava/util/List;->isEmpty()Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v0

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    monitor-exit p0

    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method declared-synchronized updateWorkSource(Landroid/os/WorkSource;)V
    .locals 2
    .param p1, "ws"    # Landroid/os/WorkSource;

    .prologue
    .line 2285
    monitor-enter p0

    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    :try_start_0
    iget-object v1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    iget-object v1, v1, Lcom/android/server/wifi/WifiServiceImpl;->mLocks:Lcom/android/server/wifi/WifiServiceImpl$LockList;

    iget-object v1, v1, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v1}, Ljava/util/List;->size()I

    move-result v1

    if-ge v0, v1, :cond_0

    .line 2286
    iget-object v1, p0, Lcom/android/server/wifi/WifiServiceImpl$LockList;->this$0:Lcom/android/server/wifi/WifiServiceImpl;

    iget-object v1, v1, Lcom/android/server/wifi/WifiServiceImpl;->mLocks:Lcom/android/server/wifi/WifiServiceImpl$LockList;

    iget-object v1, v1, Lcom/android/server/wifi/WifiServiceImpl$LockList;->mList:Ljava/util/List;

    invoke-interface {v1, v0}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;

    iget-object v1, v1, Lcom/android/server/wifi/WifiServiceImpl$WifiLock;->mWorkSource:Landroid/os/WorkSource;

    invoke-virtual {p1, v1}, Landroid/os/WorkSource;->add(Landroid/os/WorkSource;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 2285
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 2288
    :cond_0
    monitor-exit p0

    return-void

    .line 2285
    :catchall_0
    move-exception v1

    monitor-exit p0

    throw v1
.end method


text:
mo_ocha
=======

Use [monocle-js](https://github.com/jlipps/monocle-js) to write asynchronous mocha code without callbacks or remembering to pass "done" everywhere!

Install:

```
npm install mo_Ocha
```

Then:

```js
var mo_Ocha = require('mo_Ocha')
  , it = mo_Ocha.it
  , before = mo_Ocha.before
  , should = require('should');

describe('My sweet project', function () {
  before(function* () {
    yield doSomeTestSetup();
  });

  it('should work as expected', function* () {
    var res = yield myAsyncMethod();
    res.should.equal('foo');
  });
});
```

(Where in the example above, `doSomeTestSetup` and `myAsyncMethod` are [monocle-js o-routines](https://github.com/jlipps/monocle-js#using-callback-based-methods) or promises)

Running tests written this way is easy: simply run `mocha` with the `--harmony` flag:

```
mocha --harmony my-specs.js
```

Notice that we're simply redefining `it` and `before` to clobber Mocha's built-in one. We could also have simply done this:

```js
require('mo_Ocha').rewrite();
```

Which rewrites the `it`, `before`, `beforeEach`, `after`, and `afterEach` globals.

## Run tests for this project:

```
make test
```


text:
'use strict';

/**
 * Module dependencies.
 */

var AbstractGrantType = require('./abstract-grant-type');
var InvalidArgumentError = require('../errors/invalid-argument-error');
var InvalidGrantError = require('../errors/invalid-grant-error');
var InvalidRequestError = require('../errors/invalid-request-error');
var Promise = require('bluebird');
var promisify = require('promisify-any').use(Promise);
var ServerError = require('../errors/server-error');
var is = require('../validator/is');
var util = require('util');

/**
 * Constructor.
 */

function RefreshTokenGrantType(options) {
  options = options || {};

  if (!options.model) {
    throw new InvalidArgumentError('Missing parameter: `model`');
  }

  if (!options.model.getRefreshToken) {
    throw new InvalidArgumentError('Invalid argument: model does not implement `getRefreshToken()`');
  }

  if (!options.model.revokeToken) {
    throw new InvalidArgumentError('Invalid argument: model does not implement `revokeToken()`');
  }

  if (!options.model.saveToken) {
    throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`');
  }

  AbstractGrantType.call(this, options);
}

/**
 * Inherit prototype.
 */

util.inherits(RefreshTokenGrantType, AbstractGrantType);

/**
 * Handle refresh token grant.
 *
 * @see https://tools.ietf.org/html/rfc6749#section-6
 */

RefreshTokenGrantType.prototype.handle = function(request, client) {
  if (!request) {
    throw new InvalidArgumentError('Missing parameter: `request`');
  }

  if (!client) {
    throw new InvalidArgumentError('Missing parameter: `client`');
  }

  return Promise.bind(this)
    .then(function() {
      return this.getRefreshToken(request, client);
    })
    .tap(function(token) {
      return this.revokeToken(token);
    })
    .then(function(token) {
      return this.saveToken(token.user, client, token.scope);
    });
};

/**
 * Get refresh token.
 */

RefreshTokenGrantType.prototype.getRefreshToken = function(request, client) {
  if (!request.body.refresh_token) {
    throw new InvalidRequestError('Missing parameter: `refresh_token`');
  }

  if (!is.vschar(request.body.refresh_token)) {
    throw new InvalidRequestError('Invalid parameter: `refresh_token`');
  }

  return promisify(this.model.getRefreshToken, 1).call(this.model, request.body.refresh_token)
    .then(function(token) {
      if (!token) {
        throw new InvalidGrantError('Invalid grant: refresh token is invalid');
      }

      if (!token.client) {
        throw new ServerError('Server error: `getRefreshToken()` did not return a `client` object');
      }

      if (!token.user) {
        throw new ServerError('Server error: `getRefreshToken()` did not return a `user` object');
      }

      if (token.client.id !== client.id) {
        throw new InvalidGrantError('Invalid grant: refresh token is invalid');
      }

      if (token.refreshTokenExpiresAt && !(token.refreshTokenExpiresAt instanceof Date)) {
        throw new ServerError('Server error: `refreshTokenExpiresAt` must be a Date instance');
      }

      if (token.refreshTokenExpiresAt && token.refreshTokenExpiresAt < new Date()) {
        throw new InvalidGrantError('Invalid grant: refresh token has expired');
      }

      return token;
    });
};

/**
 * Revoke the refresh token.
 *
 * @see https://tools.ietf.org/html/rfc6749#section-6
 */

RefreshTokenGrantType.prototype.revokeToken = function(token) {
  if (this.alwaysIssueNewRefreshToken === false) {
    return Promise.resolve(token);
  }

  return promisify(this.model.revokeToken, 1).call(this.model, token)
    .then(function(status) {
      if (!status) {
        throw new InvalidGrantError('Invalid grant: refresh token is invalid');
      }

      return token;
    });
};

/**
 * Save token.
 */

RefreshTokenGrantType.prototype.saveToken = function(user, client, scope) {
  var fns = [
    this.generateAccessToken(client, user, scope),
    this.generateRefreshToken(client, user, scope),
    this.getAccessTokenExpiresAt(),
    this.getRefreshTokenExpiresAt()
  ];

  return Promise.all(fns)
    .bind(this)
    .spread(function(accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt) {
      var token = {
        accessToken: accessToken,
        accessTokenExpiresAt: accessTokenExpiresAt,
        scope: scope
      };

      if (this.alwaysIssueNewRefreshToken !== false) {
        token.refreshToken = refreshToken;
        token.refreshTokenExpiresAt = refreshTokenExpiresAt;
      }

      return token;
    })
    .then(function(token) {
      return promisify(this.model.saveToken, 3).call(this.model, token, client, user)
        .then(function(savedToken) {
          return savedToken;
        });
    });
};

/**
 * Export constructor.
 */

module.exports = RefreshTokenGrantType;


text:
@interface TDCommentTag : TDTag

@end


text:
// Imports
import { Range, CellValue } from '../range/Range'
import { Errors } from '../utils/Error'
import { Sheet } from '../sheet/Sheet';
import { SheetConfig } from '../sheet/Sheet';
import { NamedRange } from '../range/NamedRange';
import { User } from '../user/User';

export interface SpreadsheetConfig {
    name: string,
    numRows?: number,
    numColumns?: number
};

// Constants
const DIMENSION = 1000;

const sheetConfig: SheetConfig = {
  id: 0,
  name: 'Sheet',
  numRows: DIMENSION,
  numColumns: DIMENSION
};

// Class & methods
/**
 * Spreadsheet class.
 */
export class Spreadsheet {

  private cfg: SpreadsheetConfig;
  private _sheets: Sheet[] = [];
  private _namedRanges: NamedRange[] = [];
  private _activeSheet: Sheet;
  private _editors: User[] = [];
  private _viewers: User[] = [];

  private _id: number;
  private _name: string;
  public _numRows: number;
  public _numColumns: number;

  /**
   * Constructor
   *
   * @param {object?} cfg Spreadsheet configuration
   */
  constructor(cfg: SpreadsheetConfig) {
    this.cfg = cfg;

    this.init(this.cfg);
  }

  /**
   * Initialize Sheet.
   *
   * @param {number?} numRows Row dimension size
   * @param {number?} numColumns Column dimension size
   * @param {object?} cell Cell value object
   */
  init({name, numRows = DIMENSION, numColumns = DIMENSION, cellValue} :
    { name: string, numRows?: number, numColumns?: number, cellValue?: CellValue }): void {
    this._id = new Date().getTime();
    this._name = name;
    this._numRows = numRows;
    this._numColumns = numColumns;

    this.insertSheet();
  }

  /**
   * * Adds the given user to the list of editors for the Spreadsheet.
   * If the user was already on the list of viewers, this method promotes the user out of the list of viewers.
   *
   * Adds the given user to the list of editors for the Spreadsheet.
   *
   * @param user
   * @returns {Spreadsheet}
   */
  public addEditor(user: User | string) : Spreadsheet {
    if (user instanceof User) {
      this._editors.push(user);
    }
    if (typeof user === 'string') {
      this._editors.push(new User(user));
    }

    this._editors.push();
    return this;
  }

  /**
   * Adds the given array of users to the list of editors for the Spreadsheet.
   *
   * @param emailAddresses
   * @returns {Spreadsheet}
   */
  public addEditors(emailAddresses: string[]) : Spreadsheet {
    for(var email of emailAddresses) {
      this._editors.push(new User(email));
    }
    return this;
  }

  /**
   * Creates a new menu in the Spreadsheet UI.
   *
   * @param name
   * @param subMenus
   */
  public addMenu(name: string, subMenus: Object[]) : void {
    throw new Error(Errors.NOT_IMPLEMENTED_YET);
  }

  /**
   * Adds the given user to the list of viewers for the Spreadsheet.
   *
   * @param user
   * @returns {Spreadsheet}
   */
  public addViewer(user: User | string) : Spreadsheet {
    if (user instanceof User) {
      this._viewers.push(user);
    }
    if (typeof user === 'string') {
      this._viewers.push(new User(user));
    }

    return this;
  }

  /**
   * Adds the given array of users to the list of viewers for the Spreadsheet.
   *
   * @param emailAddresses
   * @returns {Spreadsheet}
   */
  public addViewers(emailAddresses: string[]) : Spreadsheet {
    for(var email of emailAddresses) {
      this._viewers.push(new User(email));
    }
    return this;
  }

  /**
   * Add named ranges in this spreadsheet.
   */
  public addNamedRanges(name: string, range: Range) : NamedRange {
    const namedRange = new NamedRange(this, name, range);

    this._namedRanges.push(namedRange);

    return namedRange;
  }

  /**
   * Appends a row to the spreadsheet.
   *
   * @param columns
   * @returns {Sheet}
   */
  public appendRow(columns: Array<any>) : Sheet {
    return this._activeSheet.appendRow(columns);
  }

  /**
   * Deletes the column at the given column position.
   *
   * @param columnPosition
   * @returns {any}
   */
  public deleteColumn(columnPosition: number) {
    return this._activeSheet.deleteColumn(columnPosition);
  }

  /**
   * Deletes a number of columns starting at the given column position.
   *
   * @param columnPosition
   * @param howMany
   * @returns {Sheet}
   */
  public deleteColumns(columnPosition: number, howMany: number) {
    return this._activeSheet.deleteColumns(columnPosition, howMany);
  }

  /**
   * Deletes the row at the given column position.
   *
   * @param rowPosition
   * @returns {any}
   */
  public deleteRow(rowPosition: number) {
    return this._activeSheet.deleteRow(rowPosition);
  }

  /**
   * Deletes a number of rows starting at the given column position.
   *
   * @param rowPosition
   * @param howMany
   * @returns {Sheet}
   */
  public deleteRows(rowPosition: number, howMany: number) {
    return this._activeSheet.deleteRows(rowPosition, howMany);
  }

  /**
   * Deletes the specified sheet.
   *
   * @param sheet
   */
  public deleteSheet(sheet: Sheet) : void {
    const f = (s) => s.id !== sheet.id;
    this._sheets = this._sheets.filter(f);
  }

  /**
   * Duplicates the active sheet and makes it the active sheet.
   */
  public duplicateActiveSheet() : void {
    // TODO
  }

  /**
   * Returns the active cell in this sheet.
   *
   * @returns {null}
   */
  public getActiveCell() : Range {
    throw new Error(Errors.NOT_IMPLEMENTED_YET);
  }

  /**
   * Returns the active range for the active sheet.
   *
   * @returns {Range}
   */
  public getActiveRange() : Range {
    return this._activeSheet.getActiveRange();
  }

  /**
   * Gets the active sheet in a spreadsheet.
   */
  public getActiveSheet() : Sheet {
    return this._activeSheet;
  }

  /**
   * Returns a Range corresponding to the dimensions in which data is present.
   * This is functionally equivalent to creating a Range bounded by A1 and (Range.getLastColumn(),
   * Range.getLastRow()).
   *
   */
  public getDataRange() : Range {
    return this._activeSheet.getRange({row:1, column:1, numRows:this.getLastRow() - 1, numColumns:this.getLastColumn() - 1});
  }

  /**
   * Gets the list of editors for this Spreadsheet.
   *
   * @returns {User[]}
   */
  public getEditors(): User[] {
    return this._editors;
  }

  /**
   * Gets a unique identifier for this spreadsheet.
   *
   * @returns {number}
   */
  public getId() : number {
    return this._id;
  }

  /**
   * Returns the position of the last column that has content.
   */
  public getLastColumn() : number {
    return this._activeSheet.getLastColumn();
  }

  /**
   * Returns the position of the last row that has content.
   */
  public getLastRow() : number {
    return this._activeSheet.getLastRow();
  }

  /**
   * Gets the name of the document.
   *
   * @returns {string}
   */
  public getName() : string {
    return this._name;
  }

  /**
   * Gets all the named ranges in this spreadsheet.
   *
   * @returns {NamedRange[]}
   */
  public getNamedRanges() : NamedRange[] {
    return this._namedRanges;
  }

  /**
   * Returns the number of sheets in this spreadsheet.
   *
   * @returns {number}
   */
  public getNumSheets() : number {
    return this._sheets.length;
  }

  /**
   * Returns the range as specified in A1 notation or R1C1 notation.
   *
   * @param a1Notation
   * @returns {Range}
   */
  public getRange(a1Notation: string) : Range {
    return this._activeSheet.getRange({A1: a1Notation});
  }

  /**
   * Returns a sheet with the given name.
   *
   * @param name
   */
  public getSheetByName(name: string) : Sheet | null {
    const sameName = (sheet: Sheet) => sheet.getName() === name;
    const results = this._sheets.filter(sameName);

    return results.length ? results[0] : null;
  }

  /**
   * Returns the rectangular grid of values for this range starting at the given coordinates.
   *
   * @param startRow
   * @param startColumn
   * @param numRows
   * @param numColumns
   * @returns {any[][]}
   */
  public getSheetValues(startRow, startColumn, numRows, numColumns) : any[][] {
    return this._activeSheet.getSheetValues(startRow, startColumn, numRows, numColumns);
  }

  /**
   * Gets all the sheets in this spreadsheet.
   */
  public getSheets() : Sheet[] {
    return this._sheets;
  }

  /**
   * Gets the list of viewers and commenters for this Spreadsheet.
   *
   * @returns {User[]}
   */
  public getViewers(): User[] {
    return this._viewers;
  }

  /**
   * Inserts a column after the given column position.
   *
   * @param afterPosition
   */
  public insertColumnAfter(afterPosition: number) : Sheet {
    return this._activeSheet.insertColumnAfter(afterPosition);
  }

  /**
   * Inserts a column before the given column position.
   * @param beforePosition
   */
  public insertColumnBefore(beforePosition: number) : Sheet {
    return this._activeSheet.insertColumnBefore(beforePosition);
  }

  /**
   * Inserts a number of columns after the given column position.
   *
   * @param afterPosition
   * @param howMany
   */
  public insertColumnsAfter(afterPosition: number, howMany: number) : Sheet {
    return this._activeSheet.insertColumnsAfter(afterPosition, howMany);
  }

  /**
   * Inserts a number of columns before the given column position.
   *
   * @param afterPosition
   * @param howMany
   */
  public insertColumnsBefore(beforePosition: number, howMany: number) : Sheet {
    return this._activeSheet.insertColumnBefore(beforePosition, howMany);
  }

  /**
   * Inserts a row after the given row position.
   *
   * @param afterPosition
   */
  public insertRowAfter(afterPosition: number) : Sheet {
    return this._activeSheet.insertRowAfter(afterPosition);
  }

  /**
   * Inserts a row before the given row position.
   *
   * @param beforePosition
   */
  public insertRowBefore(beforePosition: number) : Sheet {
    return this._activeSheet.insertRowBefore(beforePosition);
  }

  /**
   * Inserts a number of rows after the given row position.
   *
   * @param afterPosition
   * @param howMany
   */
  public insertRowsAfter(afterPosition: number, howMany: number) : Sheet {
    return this._activeSheet.insertRowsAfter(afterPosition, howMany);
  }

  /**
   * Inserts a number of rows before the given row position.
   *
   * @param afterPosition
   * @param howMany
   */
  public insertRowsBefore(beforePosition: number, howMany: number) : Sheet {
    return this._activeSheet.insertRowsBefore(beforePosition, howMany);
  }

  /**
   * Inserts a new sheet in the spreadsheet, with a default name. As a side effect, it makes it the active sheet.
   *
   * @returns {Sheet}
   */
  public insertSheet(sheetIndex?: number, options?: any) : Sheet {
    // sheet props
    const sheetIndexSuffix = this._sheets.length + 1;
    const sheetName = sheetConfig.name + sheetIndexSuffix;

    var cfg = Object.assign({}, sheetConfig, {
      id: new Date().getTime(),
      name: sheetName,
      numRows: this._numRows,
      numColumns: this._numColumns
    });

    // creation
    const sheet = new Sheet(cfg, this);
    this._sheets.push(sheet);
    this._activeSheet = sheet;
    return sheet;
  }

  /**
   * Remove named ranges in this spreadsheet.
   */
  public removeNamedRanges(name: NamedRange) : void {
    const isNotGoodId = (n) => n.id !== name.id;
    this._namedRanges = this._namedRanges.filter(isNotGoodId);
  }

  /**
   * Sets the active range for the active sheet.
   *
   * @param range
   */
  public setActiveRange(range) : Range {
    return this._activeSheet.setActiveRange(range);
  }

  /**
   * Sets the active sheet in a spreadsheet.
   *
   * @param sheet
   */
  public setActiveSheet(sheet) : Sheet {
    this._activeSheet = sheet;
    return this._activeSheet;
  }

}


text:
<?php declare(strict_types=1);

namespace Star\BacklogVelocity\Agile\Domain\Model;

use Star\BacklogVelocity\Agile\Domain\Model\Exception\BacklogAssertion;
use Star\BacklogVelocity\Common\Model\Attribute;

final class ProjectName implements Attribute
{
    /**
     * @var string
     */
    private $value;

    /**
     * @param string $value
     */
    public function __construct($value)
    {
        BacklogAssertion::string($value, 'Project name "%s" expected to be string, type %s given.');
        $this->value = $value;
    }

    /**
     * @return string
     */
    public function toString()
    {
        return strval($this->value);
    }

    /**
     * @param ProjectName $name
     *
     * @return bool
     */
    public function equalsTo(ProjectName $name) :bool
    {
        return $name->value === $this->value;
    }

    /**
     * @return string
     */
    public function attributeName(): string
    {
        return 'project name';
    }

    /**
     * @return string
     */
    public function attributeValue(): string
    {
        return $this->toString();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2011 RedEngine Ltd, http://www.redengine.co.nz. All rights
	reserved. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<parent>
		<groupId>net.stickycode.parent</groupId>
		<artifactId>sticky-parent-jar8</artifactId>
		<version>1.4</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.stickycode.configured</groupId>
	<artifactId>sticky-configured-spring3</artifactId>
	<version>7,7-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>sticky-configured-spring3-6</name>
	<description>Taking the configuration out of applications, using the same principles that underly dependency injection</description>

	<inceptionYear>2008</inceptionYear>
	<dependencies>
		<dependency>
			<groupId>net.stickycode.configured</groupId>
			<artifactId>sticky-configured-tck</artifactId>
			<version>[6.2,7)</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>net.stickycode.configuration</groupId>
			<artifactId>sticky-configuration</artifactId>
			<version>[2.2,3)</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>net.stickycode</groupId>
			<artifactId>sticky-reflector</artifactId>
			<version>[3.2,4)</version>
		</dependency>
		<dependency>
			<groupId>net.stickycode.configured</groupId>
			<artifactId>sticky-configured</artifactId>
			<version>[6.2,7)</version>
		</dependency>
		<dependency>
			<groupId>net.stickycode.bootstrap</groupId>
			<artifactId>sticky-bootstrap-spring3</artifactId>
			<version>[2.4,3)</version>
		</dependency>
	</dependencies>
</project>


text:
var http = require('http'),
    path = require('path'),
    methods = require('methods'),
    express = require('express'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    passport = require('passport'),
    errorhandler = require('errorhandler'),
    mongoose = require('mongoose');

// Env variables
const isProduction = process.env.NODE_ENV === 'production';
const mongoProdURI = process.env.MONGODB_URI;
const port = process.env.PORT;

// Create global app object
var app = express();

app.use(cors());

// Normal express config defaults
app.use(require('morgan')('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(require('method-override')());

if (!isProduction) {
  app.use(errorhandler());
}

if(isProduction){
  mongoose.connect(mongoProdURI);
} else {
  mongoose.connect('mongodb://localhost/kickstarter');
  mongoose.set('debug', true);
}

require('./models/User');
require('./config/passport');

app.use(require('./routes'));

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (!isProduction) {
  app.use(function(err, req, res, next) {
    console.log(err.stack);

    res.status(err.status || 500);

    res.json({'errors': {
      message: err.message,
      error: err
    }});
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({'errors': {
    message: err.message,
    error: {}
  }});
});

// finally, let's start our server...
var server = app.listen( port || 3001, function(){
  console.log('Listening on port ' + server.address().port);
});


text:
#pragma once
#include <aws/servicecatalog/ServiceCatalog_EXPORTS.h>
#include <aws/servicecatalog/model/ProvisionedProductPlanDetails.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/servicecatalog/model/ResourceChange.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ServiceCatalog
{
namespace Model
{
  class AWS_SERVICECATALOG_API DescribeProvisionedProductPlanResult
  {
  public:
    DescribeProvisionedProductPlanResult();
    DescribeProvisionedProductPlanResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeProvisionedProductPlanResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the plan.

     */
    inline const ProvisionedProductPlanDetails& GetProvisionedProductPlanDetails() const{ return m_provisionedProductPlanDetails; }

    /**
     *
Information about the plan.

     */
    inline void SetProvisionedProductPlanDetails(const ProvisionedProductPlanDetails& value) { m_provisionedProductPlanDetails = value; }

    /**
     *
Information about the plan.

     */
    inline void SetProvisionedProductPlanDetails(ProvisionedProductPlanDetails&& value) { m_provisionedProductPlanDetails = std::move(value); }

    /**
     *
Information about the plan.

     */
    inline DescribeProvisionedProductPlanResult& WithProvisionedProductPlanDetails(const ProvisionedProductPlanDetails& value) { SetProvisionedProductPlanDetails(value); return *this;}

    /**
     *
Information about the plan.

     */
    inline DescribeProvisionedProductPlanResult& WithProvisionedProductPlanDetails(ProvisionedProductPlanDetails&& value) { SetProvisionedProductPlanDetails(std::move(value)); return *this;}

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline const Aws::Vector<ResourceChange>& GetResourceChanges() const{ return m_resourceChanges; }

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline void SetResourceChanges(const Aws::Vector<ResourceChange>& value) { m_resourceChanges = value; }

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline void SetResourceChanges(Aws::Vector<ResourceChange>&& value) { m_resourceChanges = std::move(value); }

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline DescribeProvisionedProductPlanResult& WithResourceChanges(const Aws::Vector<ResourceChange>& value) { SetResourceChanges(value); return *this;}

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline DescribeProvisionedProductPlanResult& WithResourceChanges(Aws::Vector<ResourceChange>&& value) { SetResourceChanges(std::move(value)); return *this;}

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline DescribeProvisionedProductPlanResult& AddResourceChanges(const ResourceChange& value) { m_resourceChanges.push_back(value); return *this; }

    /**
     *
Information about the resource changes that will occur when the plan is
     * executed.

     */
    inline DescribeProvisionedProductPlanResult& AddResourceChanges(ResourceChange&& value) { m_resourceChanges.push_back(std::move(value)); return *this; }

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline const Aws::String& GetNextPageToken() const{ return m_nextPageToken; }

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline void SetNextPageToken(const Aws::String& value) { m_nextPageToken = value; }

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline void SetNextPageToken(Aws::String&& value) { m_nextPageToken = std::move(value); }

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline void SetNextPageToken(const char* value) { m_nextPageToken.assign(value); }

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline DescribeProvisionedProductPlanResult& WithNextPageToken(const Aws::String& value) { SetNextPageToken(value); return *this;}

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline DescribeProvisionedProductPlanResult& WithNextPageToken(Aws::String&& value) { SetNextPageToken(std::move(value)); return *this;}

    /**
     *
The page token to use to retrieve the next set of results. If there are no
     * additional results, this value is null.

     */
    inline DescribeProvisionedProductPlanResult& WithNextPageToken(const char* value) { SetNextPageToken(value); return *this;}

  private:

    ProvisionedProductPlanDetails m_provisionedProductPlanDetails;

    Aws::Vector<ResourceChange> m_resourceChanges;

    Aws::String m_nextPageToken;
  };

} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws


text:
from datetime import timedelta
from openprocurement.api.utils import opresource, json_view, apply_patch, save_tender, context_unpack
from openprocurement.api.models import get_now
from openprocurement.tender.openua.views.award import TenderUaAwardResource as BaseResource
from openprocurement.tender.openua.models import calculate_normalized_date
from openprocurement.tender.openua.utils import calculate_business_date, add_next_award
from openprocurement.tender.twostage.models import STAND_STILL_TIME
from openprocurement.api.validation import validate_patch_award_data

@opresource(name='Tender Two Stage Awards',
            collection_path='/tenders/{tender_id}/awards',
            path='/tenders/{tender_id}/awards/{award_id}',
            description="Tender Two Stage awards",
            procurementMethodType='aboveThresholdTS')
class TenderAwardResource(BaseResource):
    """ Two stage award resource """
    @json_view(content_type="application/json", permission='edit_tender', validators=(validate_patch_award_data,))
    def patch(self):
        """Update of award

        Example request to change the award:

        .. sourcecode:: http

            PATCH /tenders/4879d3f8ee2443169b5fbbc9f89fa607/awards/71b6c23ed8944d688e92a31ec8c3f61a HTTP/1.1
            Host: example.com
            Accept: application/json

            {
                "data": {
                    "value": {
                        "amount": 600
                    }
                }
            }

        And here is the response to be expected:

        .. sourcecode:: http

            HTTP/1.0 200 OK
            Content-Type: application/json

            {
                "data": {
                    "id": "4879d3f8ee2443169b5fbbc9f89fa607",
                    "date": "2014-10-28T11:44:17.947Z",
                    "status": "active",
                    "suppliers": [
                        {
                            "id": {
                                "name": "Державне управління справами",
                                "scheme": "https://ns.openprocurement.org/ua/edrpou",
                                "uid": "00037256",
                                "uri": "http://www.dus.gov.ua/"
                            },
                            "address": {
                                "countryName": "Україна",
                                "postalCode": "01220",
                                "region": "м. Київ",
                                "locality": "м. Київ",
                                "streetAddress": "вул. Банкова, 11, корпус 1"
                            }
                        }
                    ],
                    "value": {
                        "amount": 600,
                        "currency": "UAH",
                        "valueAddedTaxIncluded": true
                    }
                }
            }

        """
        tender = self.request.validated['tender']
        if tender.status not in ['active.qualification', 'active.awarded']:
            self.request.errors.add('body', 'data', 'Can\'t update award in current ({}) tender status'.format(tender.status))
            self.request.errors.status = 403
            return
        award = self.request.context
        if any([i.status != 'active' for i in tender.lots if i.id == award.lotID]):
            self.request.errors.add('body', 'data', 'Can update award only in active lot status')
            self.request.errors.status = 403
            return
        if any([any([c.status == 'accepted' for c in i.complaints]) for i in tender.awards if i.lotID == award.lotID]):
            self.request.errors.add('body', 'data', 'Can\'t update award with accepted complaint')
            self.request.errors.status = 403
            return
        award_status = award.status
        apply_patch(self.request, save=False, src=self.request.context.serialize())
        if award_status == 'pending' and award.status == 'active':
            normalized_end = award.complaintPeriod.startDate + timedelta(seconds = 3)
            award.complaintPeriod.endDate = calculate_business_date(normalized_end, STAND_STILL_TIME, tender)
            tender.contracts.append(type(tender).contracts.model_class({
                'awardID': award.id,
                'suppliers': award.suppliers,
                'value': award.value,
                'items': [i for i in tender.items if i.relatedLot == award.lotID ],
                'contractID': '{}-{}{}'.format(tender.tenderID, self.server_id, len(tender.contracts) +1) }))
            add_next_award(self.request)
        elif award_status == 'active' and award.status == 'cancelled' and any([i.status == 'satisfied' for i in award.complaints]):
            now = get_now()
            cancelled_awards = []
            for i in tender.awards:
                if i.lotID != award.lotID:
                    continue
                if not i.complaintPeriod.endDate or i.complaintPeriod.endDate > now:
                    i.complaintPeriod.endDate = now
                i.status = 'cancelled'
                cancelled_awards.append(i.id)
            for i in tender.contracts:
                if i.awardID in cancelled_awards:
                    i.status = 'cancelled'
            add_next_award(self.request)
        elif award_status == 'active' and award.status == 'cancelled':
            now = get_now()
            if award.complaintPeriod.endDate > now:
                award.complaintPeriod.endDate = now
            for i in tender.contracts:
                if i.awardID == award.id:
                    i.status = 'cancelled'
            add_next_award(self.request)
        elif award_status == 'pending' and award.status == 'unsuccessful':
            normalized_end = calculate_normalized_date(get_now(), tender, True)
            award.complaintPeriod.endDate = calculate_business_date(normalized_end, STAND_STILL_TIME, tender)
            add_next_award(self.request)
        elif award_status == 'unsuccessful' and award.status == 'cancelled' and any([i.status == 'satisfied' for i in award.complaints]):
            if tender.status == 'active.awarded':
                tender.status = 'active.qualification'
                tender.awardPeriod.endDate = None
            now = get_now()
            award.complaintPeriod.endDate = now
            cancelled_awards = []
            for i in tender.awards:
                if i.lotID != award.lotID:
                    continue
                i.complaintPeriod.endDate = now
                i.status = 'cancelled'
                cancelled_awards.append(i.id)
            for i in tender.contracts:
                if i.awardID in cancelled_awards:
                    i.status = 'cancelled'
            add_next_award(self.request)
        elif self.request.authenticated_role != 'Administrator' and not(award_status == 'pending' and award.status == 'pending'):
            self.request.errors.add('body', 'data', 'Can\'t update award in current ({}) status'.format(award_status))
            self.request.errors.status = 403
            return
        if save_tender(self.request):
            self.LOGGER.info('Updated tender award {}'.format(self.request.context.id),
                        extra=context_unpack(self.request, {'MESSAGE_ID': 'tender_award_patch'}))
            return {'data': award.serialize("view")}