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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NLog;
using Summer.Batch.Common.IO;
using Summer.Batch.Common.Settings;
using Summer.Batch.Core.Scope.Context;
using Summer.Batch.Infrastructure.Item;

namespace Summer.Batch.Extra.IO
{
    ///
    /// Resource loader that supports generation data groups (GDG) with the "gdg:" URI protocol.
    /// Other URIs or paths without protocol are delegated to <see cref="ResourceLoader"/>.
    ///
    /// Generation data groups are supported with the following syntax:
    ///
    ///
    /// gdg:path/to/file(<number>)[.<extension>]
    ///
    ///
    /// <number> refers to a file in the group. The latest version existing before the job
    /// is start is version 0. The previous one is -1, and so on. The version that has being written
    /// in the current job can be referenced with 1 (or +1).
    ///
    /// It is possible to limit the number of files in a group by using a setting named "gdg-options".
    /// This setting must be a string containing comma separated values with the following repeatable
    /// pattern:
    ///
    ///
    /// path/to/file.txt,limit=<limit>[,mode=<mode>]
    ///
    ///
    /// <limit> is the maximum number of files in the group and <mode> is either "empty"
    /// or "noempty". If no mode is specified, "noempty" is the default. In the "empty" mode, all
    /// previous files are moved when the limit is reached, whereas in "noempty" mode the oldest files
    /// are removed to keep the number of files at the limit.
    ///
    public class GdgResourceLoader : ResourceLoader
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private const int Max = 10000;
        private const string OptionsSetting = "gdg-options";
        private const string LimitOption = "limit=";
        private const string ModeOption = "mode=";
        private const string ContextSuffix = "_gdg";

        private static readonly string GdgProtocol = @"gdg" + Uri.SchemeDelimiter;

        private static readonly Regex GdgRegex =
            new Regex(@"^gdg:\/\/(?<fullPath>[^\(]*?(?<name>[\w-.]+))\((?<parameter>[+-]?\d+|\*)\)(?<extension>\.\w+)?$");

        private static readonly Regex GenerationNumbeRegex = new Regex(@"[\w-.]+G(?<G>\d{4})V(?<V>\d{2})(?:\.\w+)?");

        private readonly SettingsManager _settings;

        private readonly IDictionary<string, GdgOptions> _gdgOptions = new Dictionary<string, GdgOptions>();

        private readonly Dictionary<GdgPath, IDictionary<int, IResource>> _startingResources =
            new Dictionary<GdgPath, IDictionary<int, IResource>>();

        private ExecutionContext _jobContext;

        ///
        /// Default constructor. Checks the options in the settings manager.
        ///
        public GdgResourceLoader(SettingsManager settings)
        {
            _settings = settings;
            ParseOptions();
        }

        ///
        /// Destructor that deletes the obsolete files.
        ///
        ~GdgResourceLoader()
        {
            foreach (var resource in GetResourcesToDelete().Where(resource => resource.Exists()))
            {
                try
                {
                    resource.GetFileInfo().Delete();
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Could not delete GDG resource " + resource.GetDescription());
                }
            }
        }

        ///
        /// Resolves a single path to resources.
        ///
        /// <param name="path">the path to resolve</param>
        /// <returns>the matched resources</returns>
        protected override IEnumerable<IResource> DoGetResources(string path)
        {
            if (!path.StartsWith(GdgProtocol))
            {
                return base.DoGetResources(path);
            }
            var gdgPath = GetPath(path);
            return gdgPath.Wildcard
                ? GetResources(gdgPath)
                : new[] { GetGdgResource(gdgPath) };
        }

        // Gets a resource from a GDG path
        private IResource GetGdgResource(GdgPath path)
        {
            var number = GetGenerationNumber(path.FullPath);
            if (number == int.MinValue)
            {
                var resources = GetResourcesDictionary(path);
                number = GetGenerationNumber(resources);
                _startingResources[path] = resources;
                SaveGenerationNumber(path.FullPath, number);
            }
            var resource = GetResource(path, number);
            if (path.N <= 0 && !resource.Exists())
            {
                Logger.Warn("GDG resource accessed with negative reference does not exist: {0}({1}){2}",
                    path.FullPath, path.N, path.Extension);
            }
            return resource;
        }

        // Retrieves the current generation number from a collection of the existing resources in the group
        private int GetGenerationNumber(SortedDictionary<int, IResource> resources)
        {
            int number;
            if (!resources.Any())
            {
                number = 0;
            }
            else if (resources.ContainsKey(Max - 1) && resources.ContainsKey(0))
            {
                number = 0;
                while (resources.ContainsKey(number + 1))
                {
                    number++;
                }
            }
            else
            {
                number = resources.Last().Key;
            }
            return number;
        }

        // Retrieves the generation number of a path from the job context.
        private int GetGenerationNumber(string path)
        {
            var key = path + ContextSuffix;
            var jobContext = GetJobContext();
            return jobContext.ContainsKey(key)
                ? jobContext.GetInt(key)
                : int.MinValue;
        }

        // Saves the generation number in the job context.
        private void SaveGenerationNumber(string path, int number)
        {
            GetJobContext().PutInt(path + ContextSuffix, number);
        }

        // Retrieves the job context.
        private ExecutionContext GetJobContext()
        {
            if (_jobContext == null)
            {
                _jobContext = JobSynchronizationManager.GetContext().JobExecution.ExecutionContext;
            }
            return _jobContext;
        }

        // Retrieves a resource from its GDG path and number
        private IResource GetResource(GdgPath path, int currentNumber)
        {
            var number = currentNumber + path.N;
            if (number < 0)
            {
                number += Max;
            }
            if (number >= Max)
            {
                number -= Max;
            }
            return GetResource(string.Format("file://{0}G{1:0000}V00{2}", path.FullPath, number, path.Extension ?? ""));
        }

        // Retrieves all the existing resources for a GDG and puts them in a
        // sorted dictionary with the generation numbers as keys.
        private SortedDictionary<int, IResource> GetResourcesDictionary(GdgPath path)
        {
            var result = new SortedDictionary<int, IResource>();
            foreach (var resource in GetResources(path))
            {
                result[GetGenerationNumber(resource)] = resource;
            }
            return result;
        }

        // Retrieves existing resources for a GDG path.
        private IEnumerable<IResource> GetResources(GdgPath path)
        {
            return base.DoGetResources(string.Format("file://{0}G*V*{1}", path.FullPath, (path.Extension ?? "")));
        }

        // Extract the generation number from a file name.
        private int GetGenerationNumber(IResource resource)
        {
            var match = GenerationNumbeRegex.Match(resource.GetFilename());
            return match.Success
                ? int.Parse(match.Groups["G"].Value)
                : int.MinValue;
        }

        // Creates an instance of GdgPath from a gdg URI
        private static GdgPath GetPath(string path)
        {
            var match = GdgRegex.Match(path);
            if (!match.Success)
            {
                throw new ArgumentException("Invalid GDG path: " + path);
            }
            var name = match.Groups["name"].Value;
            var fullPath = match.Groups["fullPath"].Value;
            var extension = match.Groups["extension"].Value;
            var parameter = match.Groups["parameter"].Value;
            var n = parameter == "*" ? int.MaxValue : int.Parse(parameter);

            return new GdgPath(name, fullPath, extension, n);
        }

        // Parses the options in the settings
        private void ParseOptions()
        {
            var optionsSetting = _settings[OptionsSetting];
            if (optionsSetting != null)
            {
                var split = optionsSetting.Split(',');
                var i = 0;
                while (i < split.Length)
                {
                    var name = split[i++];
                    var limit = 0;
                    var empty = false;
                    while (i < split.Length)
                    {
                        if (split[i].StartsWith(LimitOption, StringComparison.OrdinalIgnoreCase))
                        {
                            limit = int.Parse(split[i++].Substring(LimitOption.Length));
                        }
                        else if (split[i].StartsWith(ModeOption, StringComparison.OrdinalIgnoreCase))
                        {
                            empty = string.Equals("empty", split[i++].Substring(ModeOption.Length),
                                StringComparison.OrdinalIgnoreCase);
                        }
                        else
                        {
                            break;
                        }
                    }
                    _gdgOptions.Add(name, new GdgOptions(limit, empty));
                }
            }
        }

        // Computes the resources that need to be deleted at the end of the job
        private IEnumerable<IResource> GetResourcesToDelete()
        {
            var toDelete = new HashSet<IResource>();
            foreach (var path in _startingResources.Keys)
            {
                GdgOptions options;
                if (_gdgOptions.TryGetValue(path.Name + "(*)" + path.Extension, out options))
                {
                    try
                    {
                        var resources = GetResources(path).ToArray();
                        var startingResources = _startingResources[path];
                        if (options.Empty && resources.Length > options.Limit)
                        {
                            foreach (var resource in startingResources.Values)
                            {
                                toDelete.Add(resource);
                            }
                        }
                        else if (!options.Empty)
                        {
                            foreach (var resource in GetResourcesToDelete(path, options, resources))
                            {
                                toDelete.Add(resource);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Could not get resources for path : " + path.FullPath + path.Extension);
                    }
                }
            }
            return toDelete;
        }

        private IEnumerable<IResource> GetResourcesToDelete(GdgPath path, GdgOptions options, IEnumerable<IResource> resources)
        {
            var toDelete = new HashSet<IResource>();
            var startingResources = _startingResources[path];
            var newResources = resources.Except(startingResources.Values).ToList();
            foreach (var resource in newResources)
            {
                var numberToDelete = GetGenerationNumber(resource) - options.Limit;
                if (numberToDelete < 0)
                {
                    numberToDelete += Max;
                }
                if (startingResources.ContainsKey(numberToDelete))
                {
                    toDelete.Add(startingResources[numberToDelete]);
                }
            }
            return toDelete;
        }

        #region Internal structs

        private struct GdgPath
        {
            private readonly string _name;
            private readonly string _fullPath;
            private readonly string _extension;
            private readonly int _n;

            public GdgPath(string name, string fullPath, string extension, int n)
            {
                _name = name;
                _fullPath = fullPath;
                _extension = extension;
                _n = n;
            }

            public string Name
            {
                get { return _name; }
            }

            public string FullPath
            {
                get { return _fullPath; }
            }

            public string Extension
            {
                get { return _extension; }
            }

            public int N
            {
                get { return _n; }
            }

            public bool Wildcard
            {
                get { return _n == int.MaxValue; }
            }
        }

        private struct GdgOptions
        {
            private readonly int _limit;
            private readonly bool _empty;

            public GdgOptions(int limit, bool empty)
            {
                _limit = limit;
                _empty = empty;
            }

            public int Limit
            {
                get { return _limit; }
            }

            public bool Empty
            {
                get { return _empty; }
            }
        }

        #endregion
    }
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Threading.Tasks;
using Orleans;

namespace Squidex.Infrastructure.Orleans
{
    public interface IBackgroundGrain : IGrainWithStringKey
    {
        Task ActivateAsync();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Formapro\Values\Tests\Model;

interface ObjectInterface
{
}


text:
<?php

class SingleFileSet implements ezcMailParserSet
{
    private $fp = null;

    public function __construct( $file )
    {
        $fp = fopen( dirname( __FILE__ ). '../../' . $file, 'r' );
        if ( $fp == false )
        {
            throw new Exception( "Could not open file '{$file}' for testing." );
        }
        $this->fp = $fp;

//        while (!feof($fp)) {
//        $buffer = fgets($fp, 4096);
//        echo $buffer;
//    }
    }

    public function hasData()
    {
        return !feof( $this->fp );
    }

    public function getNextLine()
    {
        if ( feof( $this->fp ) )
        {
            if ( $this->fp != null )
            {
                fclose( $this->fp );
                $this->fp = null;
            }
            return null;
        }
        $next =  fgets( $this->fp );
        if ( $next == "" && feof( $this->fp ) ) // eat last linebreak
        {
            return null;
        }
        return $next;
    }

    public function nextMail()
    {
        return false;
    }
}

class ExtendedMail extends ezcMail
{

}

class myConverter
{
    public static function convertToUTF8Iconv( $text, $originalCharset )
    {
        if ( $originalCharset === 'unknown-8bit' || $originalCharset === 'x-user-defined' )
        {
            $originalCharset = "latin1";
        }
        // '@' is to avoid notices on broken input - see issue #8369
        return @iconv( $originalCharset, 'utf-8', $text );
    }

    public static function convertToUTF8IconvIgnore( $text, $originalCharset )
    {
        if ( $originalCharset === 'unknown-8bit' || $originalCharset === 'x-user-defined' )
        {
            $originalCharset = "latin1";
        }
        // '@' is to avoid notices on broken input - see issue #8369
        return @iconv( $originalCharset, 'utf-8//IGNORE', $text );
    }

    public static function convertToUTF8IconvTranslit( $text, $originalCharset )
    {
        if ( $originalCharset === 'unknown-8bit' || $originalCharset === 'x-user-defined' )
        {
            $originalCharset = "latin1";
        }
        // '@' is to avoid notices on broken input - see issue #8369
        return @iconv( $originalCharset, 'utf-8//TRANSLIT', $text );
    }

    public static function convertToUTF8Mbstring( $text, $originalCharset )
    {
        return mb_convert_encoding( $text, "UTF-8", $originalCharset );
    }
}
class myCustomFileClass extends ezcMailFile
{
}
?>


text:
var KeyNumberLayout = [
  '1234567890'
].map(function(v) {
  return v.split('');
});

var KeyLayout = [
  'qwert', 'asdfg', 'zxcvb'
].map(function(v) {
  return v.split('');
});

var KeyShiftLayout = [
  'qwertQWERT', 'asdfgASDFG', 'zxcvbZXCVBN'
].map(function(v) {
  return v.split('');
});

var EditorKeyMapping = {
  'q': ['arrow', 'none'],
  'w': ['arrow', 'up'],
  'e': ['command', 'none'],
  'r': ['command', 'select'],
  't': ['command', 'move'],
  'a': ['arrow', 'left'],
  's': ['arrow', 'down'],
  'd': ['arrow', 'right'],
  'f': ['command', 'push'],
  'g': ['command', 'pop'],
  'z': ['command', 'subtract'],
  'x': ['command', 'divide'],
  'c': ['command', 'add'],
  'v': ['command', 'multiply'],
  'b': ['command', 'mod'],
  'Q': ['arrow', 'reverse'],
  'W': ['arrow', 'skip-up'],
  'E': ['command', 'end'],
  'R': ['command', 'condition'],
  'T': ['command', 'compare'],
  'A': ['arrow', 'skip-left'],
  'S': ['arrow', 'skip-down'],
  'D': ['arrow', 'skip-right'],
  'F': ['command', 'copy'],
  'G': ['command', 'flip'],
  'Z': ['arrow', 'horizontal'],
  'X': ['arrow', 'vertical'],
  'C': ['command', 'pop-number'],
  'V': ['command', 'pop-unicode'],
  'B': ['command', 'push-unicode'],
  'N': ['command', 'push-number']
};

function Keyboard() {
  this.stack = [];
  this.registerEvents();
}

Keyboard.prototype.push = function(entry) {
  this.stack.push(entry);
}

Keyboard.prototype.pop = function() {
  return this.stack.pop();
}

Keyboard.prototype.registerEvents = function() {
  var self = this;
  document.addEventListener('keypress', function(e) {
    var keyPressed = e.key || String.fromCharCode(e.charCode);
    for(var i = self.stack.length - 1; i >= 0; --i) {
      var entry = self.stack[i];
      // Act differently if Ctrl is pressed.
      if(e.ctrlKey) entry = self.stack[0];
      if(!entry || !entry.map) continue;
      if(entry.map[keyPressed] != undefined) {
        entry.callback(entry.map[keyPressed]);
        return false;
      } else if(entry.map[keyPressed.toUpperCase()] != undefined) {
        // Quick dirty method to use uppercase if lowercase is not available
        entry.callback(entry.map[keyPressed.toUpperCase()]);
        return false;
      }
    }
  });
}

Keyboard.KeyNumberLayout = KeyNumberLayout;
Keyboard.KeyLayout = KeyLayout;
Keyboard.KeyShiftLayout = KeyShiftLayout;
Keyboard.EditorKeyMapping = EditorKeyMapping;

// An utility function to create keybinding map from 2D array.
Keyboard.createKeyMap = function(binding, layout) {
  if(layout == null) layout = KeyShiftLayout;
  var map = {};
  for(var y = 0; y < binding.length; ++y) {
    for(var x = 0; x < binding[y].length; ++x) {
      // It's completely fine to use keyShiftLayout.
      map[layout[y][x]] = binding[y][x];
    }
  }
  return map;
}

module.exports = Keyboard;


text:
package org.grain.tcp;

import java.lang.reflect.Method;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.google.protobuf.Message;

public class MinaDecoder extends ProtocolDecoderAdapter {

	private static final String BUFFER = ".Buffer";
	private static final int U = 85;
	private static final int A = 65;

	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		IoBuffer buf = (IoBuffer) session.getAttribute(BUFFER);
		if (buf != null) {
			buf.put(in);
			buf.flip();
		} else {
			buf = in;
		}
		for (;;) {
			if (buf.remaining() > 6) {
				int pos = buf.position();

				int head1 = buf.get();
				int head2 = buf.get();
				if (head1 == U && head2 == A) {
					int len = buf.getInt();
					if (buf.remaining() >= (len - 6)) {
						int tOpCode = buf.getInt();
						int lockedId = buf.getInt();
						int unlockedId = buf.getInt();
						byte[] bytes = new byte[len - 18];
						buf.get(bytes);
						Class<?> className = TcpManager.tOpCodeMap.get(tOpCode);
						Message data = null;
						Method m = className.getDeclaredMethod("parseFrom", new Class[] { byte[].class });
						data = (Message) m.invoke(null, bytes);
						TcpPacket packet = new TcpPacket(tOpCode, data);
						packet.lockedId = lockedId;
						packet.unlockedId = unlockedId;
						packet.session = session;
						out.write(packet);
					} else {
						buf.position(pos);
						break;
					}
				} else {

					session.setAttribute(BUFFER, null);
					if (MinaConfig.log != null) {
						MinaConfig.log.error("头消息错误,客户端或服务器不合法", null);
					}
					throw new Exception("头消息错误,客户端或服务器不合法");
				}

			} else {
				break;
			}
		}
		if (buf.hasRemaining()) {
			storeRemainingInSession(buf, session);
		} else {
			session.setAttribute(BUFFER, null);
		}
	}

	private void storeRemainingInSession(IoBuffer buf, IoSession session) {
		IoBuffer remainingBuf = IoBuffer.allocate(buf.capacity());
		remainingBuf.setAutoExpand(true);
		remainingBuf.order(buf.order());
		remainingBuf.put(buf);
		session.setAttribute(BUFFER, remainingBuf);
	}

}


text:
![travis](https://api.travis-ci.org/tmpvar/vec2.js.png)

[![browser support](https://ci.testling.com/tmpvar/vec2.js.png)](http://ci.testling.com/tmpvar/vec2.js)

  A generic library useful when you need to work with points/vectors in 2d space.

## Use

```javascript
  var a = new Vec2(10, 10), // new keyword
      b = Vec2(100, 10); // call the constructor directly

  console.log(a.distance(b)); // 90
```

**Stuff to Note**: most of the Vec2's methods take a `returnNew` as the last parameter.  If passed a truthy value, a new vector will be returned to you.  Otherwise the operation will be applied to `this` and `this` will be returned.

Also, since `Infinity`and `NaN` are so insidious, this library will throw as soon as it detects either of these so you can take action to fix your data/algorithm.

## Supported operations

__change__([fn])

Add an observer `fn` that will be called whenever this vector changes.  Calling this method without a function causes it to notify observers.

`fn` signature: `function(vec, prev) {}` - where `prev` is a clone of the vector before the last operation.

this function returns the passed `fn`

_returns_: `Vec2`

__ignore__([fn])

Pass a `fn` to remove it from the observers list. Calling this function without a `fn` will remove all observers.

_returns_: `Vec2`

__set__(x, y [, notify]) or __set__(vec2 [, notify])

Sets the `x` and `y` coordinates of this vector.  If `false` is passed for `notify`, none of the observers will be called.

_returns_: `Vec2`

__zero__()

Sets the `x` and `y` of this vector to `0`

_returns_: `Vec2`

__clone__()

Returns a clone of this vector.

_Note_: this does not clone observers

_returns_: `Vec2`

__negate__([returnNew])

Negate the `x` and `y` coords of this vector.  If `returnNew` is truthy, a new vector with the negated coordinates will be returned.

_returns_: `Vec2`

__add__(x, y [, returnNew]) or __add__(array, [, returnNew]) or __add__(vec2 [, returnNew])

Add the `x` and `y` to this vector's coordinates.

If `returnNew` is truthy, return a new vector containing the resulting coordinates. Otherwise apply them to this vector and return it.

_returns_: `Vec2`

__subtract__(x, y [, returnNew]) or __subtract__(array, [, returnNew]) or __subtract__(vec2 [, returnNew])

_returns_: `Vec2`

__multiply__(scalar [, returnNew]) or __multiply__(x, y [, returnNew]) or __multiply__(array, [, returnNew]) or __multiply__(vec2 [, returnNew])

Multiply this vectors components with the incoming, returning a clone if `returnNew` is truthy.

_returns_: `Vec2`

__divide__(scalar [, returnNew]) or __divide__(x, y [, returnNew]) or __divide__(array, [, returnNew]) or __divide__(vec2 [, returnNew])

Divide this vectors components by the incoming, returning a clone if `returnNew` is truthy.

_note_: this method will throw if you attempt to divide by zero or pass values that cause NaNs

_returns_: `Vec2`

__rotate__(radians [, inverse [, returnNew]])

Rotate this vector's cordinates around `(0,0)`.  If `returnNew` is specified, a new `Vec2` will be created and populated with the result and returned.  Otherwise the result is applied to this vector and `this` is returned.

`inverse` - inverts the direction of the rotation

`returnNew` - causes the result to be applied to a new `Vec2`, otherwise the result is applied to `this`

_returns_: `Vec2`

__length__()

Returns the length of this vector from `(0,0)`

_returns_: `double`

__lengthSquared__()

Returns the length of this vector prior to the `Math.sqrt` call.

This is usefull when you don't need to know the actual distance, but need a normalized value to compare with another `Vec2#lengthSquared` or similar.

_returns_: `double`

__distance__(vec2)

_returns_: the distance between this vector and the incoming

__nearest__(array)

_returns_: closest vector in array to this vector.

__normalize__([returnNew])

Normalizes this vector.  If `returnNew` is truthy, a new vector populated with the normalized coordinates will be returned.

_returns_: `Vec2`

__equal__(vec2) or __equal__(x, y) or __equal__(array)

returns true if the incoming coordinates are the same as this vector's

_returns_: `boolean`

__abs__([returnNew])

Return a `Vec2` that contains the absolute value of each of this vector's parts.

If `returnNew` is truthy, create a new `Vec2` and return it. Otherwise apply the absolute values to to `this`.

_returns_: `Vec2`

__min__(vec)

Return a `Vec2` consisting of the smallest values from this vector and the incoming

When returnNew is truthy, a new `Vec2` will be returned otherwise the minimum values in either this or `vec` will be applied to this vector.

_returns_: `Vec2`

__max__(vec)

Return a `Vec2` consisting of the largest values from this vector and the incoming

When returnNew is truthy, a new `Vec2` will be returned otherwise the maximum values in either `this` or `vec` will be applied to this vector.

_returns_: `Vec2`

__clamp__(low, high [, returnNew])

Clamp the coordinates of this vector to the high/low of the incoming vec2s.  If `returnNew` apply the result to the new vector and return.  Otherwise apply to this vector.

_returns_: `Vec2`

__lerp__(vec, amount [, returnNew])

Perform linear interpolation between this vector and the incoming.

`amount` - the percentage along the path to place the vector

`returnNew` - if `truthy`, apply the result to a new vector and return it, otherwise return `this`

_returns_: `Vec2`

__skew__([returnNew])

Returns a vector set with the `(-y,x)` coordinates of this vector.  If `returnNew` a new vector is created and the operation is applied to the new vector.

_returns_: `Vec2`

__dot__()

_returns_: `double`

__perpDot__()

_returns_: `double`

__angleTo__(vec)

returns the angle from this vector to the incoming.

_returns_: `double`

__isPointOnLine__(start, end)

where `start` and `end` are vec2-like (e.g. `start.x` and `start.y`)

_returns_: `boolean`

__toArray__()

_returns_: `[x, y]`

__fromArray__(array)

Applies the `[0]` to `this.x` and `[1]` to `this.y`

_returns_: `Vec2`

__toJSON__()

_returns_: `{ x: ..., y: ...}`

__toString__()

_returns_: `'(x, y)'`

## Install

### Browser

```html
<script type="text/javascript" src="https://raw.github.com/tmpvar/vec2.js/master/vec2.min.js"></script>
<script type="text/javascript">
   var v = new Vec2();
</script>
```

### Node

install with npm

    npm install vec2

and then require it!

    var Vec2 = require('vec2');

## License

MIT (see [LICENSE.txt](LICENSE.txt))


text:
// BridgeDb,
// An abstraction layer for identifier mapping services, both local and online.
//
// Copyright 2006-2009  BridgeDb developers
// Copyright 2012-2013  Christian Y. A. Brenninkmeijer
// Copyright 2012-2013  OpenPhacts
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.bridgedb.ws;

import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.bridgedb.utils.BridgeDBException;
import org.bridgedb.ws.bean.MappingSupportedBean;

/**
 *
 * @author Christian
 */
public class WSCoreClientFactory extends org.bridgedb.utils.IDMapperTestBase{

    static final Logger logger = Logger.getLogger( WSCoreClientFactory.class);

    public static WSCoreInterface createTestWSClient() throws BridgeDBException{
        //ystem.out.println("in WSCoreInterface 1");
        WSCoreInterface webService = new WSCoreClient("http://localhost:8080/BridgeDb");
        //ystem.out.println("in WSCoreInterface 2");
        try {
            webService.isFreeSearchSupported();
            //ystem.out.println("in WSCoreInterface 3");
        } catch (Exception ex) {
            logger.error("Unable to create WS Client", ex);
            logger.fatal("***** SKIPPING BridgeDB WSClientTest ******");
            System.err.println("***** SKIPPING BridgeDB WSClientTest ******");
            System.err.println("These test are repeated in the OPS client so normally not needed here.");
            System.err.println("Please make sure the specicifc bridgeDB.war based server is running");
            org.junit.Assume.assumeTrue(false);
        }
        //ystem.out.println("in WSCoreInterface 4");
        boolean ok;
        try{
            Response response = webService.isMappingSupported(DataSource1.getSystemCode(), DataSource2.getSystemCode());
            MappingSupportedBean bean = (MappingSupportedBean)response.getEntity();
            ok = bean.isMappingSupported();
        } catch (Exception ex){
            ok = false;
        }
        if (!ok){
            logger.error("Unable to get test data from WS Client");
            logger.fatal("***** SKIPPING BridgeDB WSClientTest ******");
            System.err.println("***** SKIPPING WSClientTest ******");
            System.err.println("It appears the Test data is not loaded");
            System.err.println("remove ignore in TestDataToMainServerTest (org.bridgedb.ws.sqlserver) ");
            org.junit.Assume.assumeTrue(false);
        }
        //ystem.out.println("in WSCoreInterface 5b");
        return webService;
    }
}


text:
var core = require('../../core');
var math = core.create();

// Configure to use fractions by default
math.config({number: 'fraction'});

// Add a conversion from Faction -> BigNumber
// this conversion:
// - must be inserted in the conversions list before the conversion Fraction -> number
// - must be added to the conversions before loading functions into math.js
math.typed.conversions.unshift({
  from: 'Fraction',
  to: 'BigNumber',
  convert: function (value) {
    return new math.type.BigNumber(value);
  }
});

// Import all data types, functions, constants, the expression parser, etc.
math.import(require('../../lib'));

// Operators `add` and `divide` have support for Fractions. The result will be a Fraction
var ans1 = math.eval('1/3 + 1/4');
console.log(math.typeof(ans1), math.format(ans1));
    // outputs "Fraction 7/12"

// function sqrt doesn't have Fraction support, will fall back to BigNumber
var ans2 = math.eval('sqrt(4)');
console.log(math.typeof(ans2), math.format(ans2));
    // outputs "BigNumber 2"


text:
const ObjectKeyword = require('./Object');
const ArrayKeyword = require('./Array');
const StringKeyword = require('./String');
const IntegerKeyword = require('./Integer');
const NumberKeyword = require('./Number');
const BooleanKeyword = require('./Boolean');
const TypeKeyword = require('./Type');
const EnumKeyword = require('./Enum');
const ConstKeyword = require('./Const');
const OneOfKeyword = require('./OneOf');
const AnyOfKeyword = require('./AnyOf');

module.exports = {
  object: () => new ObjectKeyword(),
  array: () => new ArrayKeyword(),
  string: () => new StringKeyword(),
  integer: () => new IntegerKeyword(),
  number: () => new NumberKeyword(),
  boolean: () => new BooleanKeyword(),

  type: value => new TypeKeyword(value),
  enum: value => new EnumKeyword(value),
  const: value => new ConstKeyword(value),
  oneOf: value => new OneOfKeyword(value),
  anyOf: value => new AnyOfKeyword(value),
};


text:
package org.kie.pmml.pmml_4_2.predictive.models;

import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.kie.api.io.Resource;
import org.kie.api.pmml.PMMLRequestData;
import org.kie.internal.io.ResourceFactory;
import org.kie.pmml.pmml_4_2.PMML4ExecutionHelper;
import org.kie.pmml.pmml_4_2.PMMLRequestDataBuilder;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class DecisionTreeWithSurrogateTest {

    private static final String DECISION_TREES_FOLDER = "org/kie/pmml/pmml_4_2/";
    private static final String treeWithSurrogate = DECISION_TREES_FOLDER + "test_tree_with_surrogate.pmml";

    private Optional<Double> temperature;
    private Optional<Double> humidity;
    private String decision;
    private String correlationId;

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                 { Optional.of(34.0), Optional.empty(), "sunglasses", "1234" }, //bug - RHPAM-1492
                { Optional.of(34.0), Optional.of(15.0), "sunglasses", "5678" },
                { Optional.empty(), Optional.of(15.0), "sunglasses", "9012" },
                { Optional.empty(), Optional.of(85.0), "umbrella", "3456" }, //bug - RHPAM-1492
                { Optional.of(22.0), Optional.of(85.0), "umbrella", "7890" },
                { Optional.of(22.0), Optional.of(35.0), "nothing", "4321" },
                { Optional.empty(), Optional.of(35.0), "nothing", "0987" }, //bug - RHPAM-1492
                { Optional.of(22.0), Optional.empty(), "nothing", "6543" },
        });
    }

    public DecisionTreeWithSurrogateTest(Optional<Double> temperature, Optional<Double> humidity, String decision, String correlationId) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.decision = decision;
        this.correlationId = correlationId;
    }

    @Test
    public void testTreeWithSurrogatePredicate() {
        Resource res = ResourceFactory.newClassPathResource(treeWithSurrogate);
        PMML4ExecutionHelper helper = PMML4ExecutionHelper.PMML4ExecutionHelperFactory
                .getExecutionHelper("SampleMine", res, null, false);
        helper.initModel();

        PMMLRequestDataBuilder rdb = new PMMLRequestDataBuilder(correlationId, "SampleMine");
        temperature.ifPresent( t -> rdb.addParameter("temperature", t, Double.class));
        humidity.ifPresent( h -> rdb.addParameter("humidity", h, Double.class));
        PMMLRequestData request = rdb.build();
        helper.submitRequest(request);
        helper.getResultData().iterator().forEachRemaining(rd -> {
            assertEquals("OK",rd.getResultCode());
            assertEquals(correlationId,rd.getCorrelationId());
            String value = rd.getResultValue("Decision", "value", String.class).orElse(null);
            assertEquals(decision, value);
        });
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.secretmanager.v1.model;

/**
 * The rotation time and period for a Secret. At next_rotation_time, Secret Manager will send a
 * Pub/Sub notification to the topics configured on the Secret. Secret.topics must be set to
 * configure rotation.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Secret Manager API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Rotation extends com.google.api.client.json.GenericJson {

  /**
   * Optional. Timestamp in UTC at which the Secret is scheduled to rotate. Cannot be set to less
   * than 300s (5 min) in the future and at most 3153600000s (100 years). next_rotation_time MUST be
   * set if rotation_period is set.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String nextRotationTime;

  /**
   * Input only. The Duration between rotation notifications. Must be in seconds and at least 3600s
   * (1h) and at most 3153600000s (100 years). If rotation_period is set, next_rotation_time must be
   * set. next_rotation_time will be advanced by this period when the service automatically sends
   * rotation notifications.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String rotationPeriod;

  /**
   * Optional. Timestamp in UTC at which the Secret is scheduled to rotate. Cannot be set to less
   * than 300s (5 min) in the future and at most 3153600000s (100 years). next_rotation_time MUST be
   * set if rotation_period is set.
   * @return value or {@code null} for none
   */
  public String getNextRotationTime() {
    return nextRotationTime;
  }

  /**
   * Optional. Timestamp in UTC at which the Secret is scheduled to rotate. Cannot be set to less
   * than 300s (5 min) in the future and at most 3153600000s (100 years). next_rotation_time MUST be
   * set if rotation_period is set.
   * @param nextRotationTime nextRotationTime or {@code null} for none
   */
  public Rotation setNextRotationTime(String nextRotationTime) {
    this.nextRotationTime = nextRotationTime;
    return this;
  }

  /**
   * Input only. The Duration between rotation notifications. Must be in seconds and at least 3600s
   * (1h) and at most 3153600000s (100 years). If rotation_period is set, next_rotation_time must be
   * set. next_rotation_time will be advanced by this period when the service automatically sends
   * rotation notifications.
   * @return value or {@code null} for none
   */
  public String getRotationPeriod() {
    return rotationPeriod;
  }

  /**
   * Input only. The Duration between rotation notifications. Must be in seconds and at least 3600s
   * (1h) and at most 3153600000s (100 years). If rotation_period is set, next_rotation_time must be
   * set. next_rotation_time will be advanced by this period when the service automatically sends
   * rotation notifications.
   * @param rotationPeriod rotationPeriod or {@code null} for none
   */
  public Rotation setRotationPeriod(String rotationPeriod) {
    this.rotationPeriod = rotationPeriod;
    return this;
  }

  @Override
  public Rotation set(String fieldName, Object value) {
    return (Rotation) super.set(fieldName, value);
  }

  @Override
  public Rotation clone() {
    return (Rotation) super.clone();
  }

}


text:
extern crate easy_plugin;

extern crate crustacean;
extern crate rustc_plugin;
extern crate syntax;

use crustacean::{Filter, Generator};

use easy_plugin::{PluginResult, PluginResultExt, ToError};
use easy_plugin::extractor::*;

use rustc_plugin::{Registry};

use syntax::ast::*;
use syntax::codemap::{Span};
use syntax::ext::base::{ExtCtxt, MacEager, MacResult};
use syntax::ptr::{P};
use syntax::util::small_vector::{SmallVector};

fn get_expr_addr_of_vec(expr: P<Expr>) -> PluginResult<Vec<P<Expr>>> {
    expr_to_vec(&expr).map_err_message("expected `[...]`")
}

fn get_bool(expr: P<Expr>) -> PluginResult<bool> {
    expr_to_lit(&expr).and_then(|l| lit_to_bool(&l)).map_err_message("expected `true` or `false`")
}

fn get_string(expr: P<Expr>) -> PluginResult<String> {
    expr_to_lit(&expr).and_then(|l| {
        lit_to_str(&l.unwrap()).map(|(s, _)| s)
    }).map_err_message("expected \"...\"")
}

fn get_strings(expr: P<Expr>) -> PluginResult<Vec<String>> {
    get_expr_addr_of_vec(expr).and_then(|es| es.into_iter().map(get_string).collect())
}

fn get_string_set(expr: P<Expr>) -> PluginResult<(String, Vec<String>)> {
    let mut tup = try!(expr_to_tup(&expr).map_err_message("expected `(\"...\", [...])`"));
    if tup.len() != 2 {
        return expr.to_error("expected `(\"...\", [...])`");
    }
    let name = try!(get_string(tup.remove(0)));
    let values = try!(get_strings(tup.remove(0)));
    Ok((name, values))
}

fn get_string_sets(expr: P<Expr>) -> PluginResult<Vec<(String, Vec<String>)>> {
    get_expr_addr_of_vec(expr).and_then(|es| es.into_iter().map(get_string_set).collect())
}

easy_plugin! {
    struct KeyValuePair {
        $key:ident: $value:expr
    }

    struct Arguments {
        $($header:lit_str $(: $arguments:expr)?), + $(,)? $(=> { $($kvp:$KeyValuePair), * $(,)? })?
    }

    pub fn expand_crustacean(
        _: &mut ExtCtxt, span: Span, arguments: Arguments
    ) -> PluginResult<Box<MacResult>> {
        let mut generator = Generator::new();
        for (header, arguments) in arguments.header.iter().zip(arguments.arguments.iter()) {
            let arguments = if let Some(ref arguments) = *arguments {
                try!(get_strings(arguments.clone()))
            } else {
                vec![]
            };
            generator.header(header.0.clone(), &arguments);
        }
        if let Some(kvps) = arguments.kvp {
            for KeyValuePair { key, value } in kvps {
                match &key.node.name.as_str()[..] {
                    "ALLOW_UNSUPPORTED_TYPES" => {
                        generator.allow_unsupported_types(try!(get_bool(value)));
                    },
                    "DERIVE_ENUM" => {
                        let value = try!(get_strings(value));
                        generator.derive_enum(&value[..]);
                    },
                    "DERIVE_STRUCT" => {
                        let value = try!(get_strings(value));
                        generator.derive_struct(&value[..]);
                    },
                    "DISPLAY_DIAGNOSTICS" => {
                        generator.display_diagnostics(try!(get_bool(value)));
                    },
                    "FILTER" => {
                        let span = value.span;
                        let filter = match &try!(get_string(value))[..] {
                            "none" => Filter::None,
                            "system" => Filter::System,
                            "non-main" => Filter::NonMain,
                            _ => return span.to_error("invalid filter"),
                        };
                        generator.filter(filter);
                    },
                    "IGNORE_ENUM_VARIANTS" => {
                        let value = try!(get_string_sets(value));
                        generator.ignore_enum_variants(&value[..]);
                    },
                    "NESTED_MOD" => {
                        let value = try!(get_string(value));
                        generator.nested_mod(value);
                    },
                    "PRIMITIVE" => {
                        let value = try!(get_strings(value));
                        generator.primitive(&value[..]);
                    },
                    _ => return key.to_error("invalid option"),
                }
            }
        }
        generator.span(span);
        let items = try!(generator.generate().map_err(|m| (span, m))).items;
        Ok(MacEager::items(SmallVector::many(items)))
    }
}

#[plugin_registrar]
pub fn plugin_registrar(registry: &mut Registry) {
    registry.register_macro("crustacean", expand_crustacean);
}


text:
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

from lib.core.settings import WAF_ATTACK_VECTORS

__product__ = "SEnginx (Neusoft Corporation)"

def detect(get_page):
    retval = False

    for vector in WAF_ATTACK_VECTORS:
        page, headers, code = get_page(get=vector)
        retval = "SENGINX-ROBOT-MITIGATION" in page
        if retval:
            break

    return retval


text:
<?php

namespace Magium\Configuration\Tests\Config;

use Magium\Configuration\Config\Storage\CallbackInterface;

class InsufficientCallback implements CallbackInterface
{

    public function __construct($stringParam)
    {
    }

    public function filter($value)
    {
        return strtoupper($value);
    }
}


text:
static os_timer_t sntp_check_timer;

uint64_t init_time = 0;
uint64_t current_unix_time;
uint64_t ntp_offline_second_counter = 0;

static os_timer_t ntp_offline_second_counter_timer;

ICACHE_FLASH_ATTR void static sntp_check_timer_func(void *arg) {
	current_unix_time = sntp_get_current_timestamp();	// DEBUG: possible wrapping error here, when casting from 32 bit to 64 bit variable

	if (current_unix_time == 0) {
		os_timer_disarm(&sntp_check_timer);
		os_timer_arm(&sntp_check_timer, 2000, 0);
	} else {
		os_timer_disarm(&sntp_check_timer);
		// save init time for use in get_uptime()
		os_timer_disarm(&ntp_offline_second_counter_timer);		// stop offline second counter
		if (init_time == 0) {		// only set init_time at boot
			init_time = current_unix_time;							// save the unix time stamp we go ntp time
		}
	}
}

ICACHE_FLASH_ATTR void static ntp_offline_second_counter_timer_func(void *arg) {
	ntp_offline_second_counter++;
}

ICACHE_FLASH_ATTR void init_unix_time(void) {
	// init sntp
	sntp_setservername(0, NTP_SERVER_1); // set server 0 by domain name
	sntp_setservername(1, NTP_SERVER_2); // set server 1 by domain name
	sntp_set_timezone(0);	// UTC time
	sntp_init();

	// start timer to make sure we go ntp reply
	os_timer_disarm(&sntp_check_timer);
	os_timer_setfn(&sntp_check_timer, (os_timer_func_t *)sntp_check_timer_func, NULL);
	os_timer_arm(&sntp_check_timer, 2000, 0);

	ntp_offline_second_counter = 0;
	os_timer_disarm(&ntp_offline_second_counter_timer);
	os_timer_setfn(&ntp_offline_second_counter_timer, (os_timer_func_t *)ntp_offline_second_counter_timer_func, NULL);
	os_timer_arm(&ntp_offline_second_counter_timer, 1000, 1);		// every seconds
}

ICACHE_FLASH_ATTR uint64_t get_unix_time(void) {
	current_unix_time = sntp_get_current_timestamp();	// DEBUG: possible wrapping error here, when casting from 32 bit to 64 bit variable

	return current_unix_time;
}

ICACHE_FLASH_ATTR uint64_t get_uptime(void) {
	current_unix_time = sntp_get_current_timestamp();	// DEBUG: possible wrapping error here, when casting from 32 bit to 64 bit variable
	if (init_time == 0) {	// just booted
		return ntp_offline_second_counter;
	}
	else {
		return current_unix_time - init_time + ntp_offline_second_counter;
	}
}

ICACHE_FLASH_ATTR void destroy_unix_time(void) {
	// only call this before restarting system_restart() to stop all timers
	os_timer_disarm(&sntp_check_timer);
	os_timer_disarm(&ntp_offline_second_counter_timer);
	sntp_stop();		// stop ntp client
}


text:
namespace Poco {

class Exception;

class Foundation_API Logger: public Channel
	/// Logger is a special Channel that acts as the main
	/// entry point into the logging framework.
	///
	/// An application uses instances of the Logger class to generate its log messages
	/// and send them on their way to their final destination. Logger instances
	/// are organized in a hierarchical, tree-like manner and are maintained by
	/// the framework. Every Logger object has exactly one direct ancestor, with
	/// the exception of the root logger. A newly created logger inherits its properties -
	/// channel and level - from its direct ancestor. Every logger is connected
	/// to a channel, to which it passes on its messages. Furthermore, every logger
	/// has a log level, which is used for filtering messages based on their priority.
	/// Only messages with a priority equal to or higher than the specified level
	/// are passed on. For example, if the level of a logger is set to three (PRIO_ERROR),
	/// only messages with priority PRIO_ERROR, PRIO_CRITICAL and PRIO_FATAL will
	/// propagate. If the level is set to zero, the logger is effectively disabled.
	///
	/// The name of a logger determines the logger's place within the logger hierarchy.
	/// The name of the root logger is always "", the empty string. For all other
	/// loggers, the name is made up of one or more components, separated by a period.
	/// For example, the loggers with the name HTTPServer.RequestHandler and HTTPServer.Listener
	/// are descendants of the logger HTTPServer, which itself is a descendant of
	/// the root logger. There is not limit as to how deep
	/// the logger hierarchy can become. Once a logger has been created and it has
	/// inherited the channel and level from its ancestor, it loses the connection
	/// to it. So changes to the level or channel of a logger do not affect its
	/// descendants. This greatly simplifies the implementation of the framework
	/// and is no real restriction, because almost always levels and channels are
	/// set up at application startup and never changed afterwards. Nevertheless,
	/// there are methods to simultaneously change the level and channel of all
	/// loggers in a certain hierarchy.
{
public:
	const std::string& name() const;
		/// Returns the name of the logger, which is set as the
		/// message source on all messages created by the logger.

	void setChannel(Channel* pChannel);
		/// Attaches the given Channel to the Logger.

	Channel* getChannel() const;
		/// Returns the Channel attached to the logger.

	void setLevel(int level);
		/// Sets the Logger's log level.

	int getLevel() const;
		/// Returns the Logger's log level.

	void setLevel(const std::string& level);
		/// Sets the Logger's log level using a symbolic value.
		///
		/// Valid values are:
		///   - fatal
		///   - critical
		///   - error
		///   - warning
		///   - notice
		///   - information
		///   - debug
		///   - trace

	void setProperty(const std::string& name, const std::string& value);
		/// Sets or changes a configuration property.
		///
		/// Only the "channel" and "level" properties are supported, which allow
		/// setting the target channel and log level, respectively, via the LoggingRegistry.
		/// The "channel" and "level" properties are set-only.

	void log(const Message& msg);
		/// Logs the given message if its priority is
		/// greater than or equal to the Logger's log level.

	void log(const Exception& exc);
		/// Logs the given exception with priority PRIO_ERROR.

	void fatal(const std::string& msg);
		/// If the Logger's log level is at least PRIO_FATAL,
		/// creates a Message with priority PRIO_FATAL
		/// and the given message text and sends it
		/// to the attached channel.

	void critical(const std::string& msg);
		/// If the Logger's log level is at least PRIO_CRITICAL,
		/// creates a Message with priority PRIO_CRITICAL
		/// and the given message text and sends it
		/// to the attached channel.

	void error(const std::string& msg);
		/// If the Logger's log level is at least PRIO_ERROR,
		/// creates a Message with priority PRIO_ERROR
		/// and the given message text and sends it
		/// to the attached channel.

	void warning(const std::string& msg);
		/// If the Logger's log level is at least PRIO_WARNING,
		/// creates a Message with priority PRIO_WARNING
		/// and the given message text and sends it
		/// to the attached channel.

	void notice(const std::string& msg);
		/// If the Logger's log level is at least PRIO_NOTICE,
		/// creates a Message with priority PRIO_NOTICE
		/// and the given message text and sends it
		/// to the attached channel.

	void information(const std::string& msg);
		/// If the Logger's log level is at least PRIO_INFORMATION,
		/// creates a Message with priority PRIO_INFORMATION
		/// and the given message text and sends it
		/// to the attached channel.

	void debug(const std::string& msg);
		/// If the Logger's log level is at least PRIO_DEBUG,
		/// creates a Message with priority PRIO_DEBUG
		/// and the given message text and sends it
		/// to the attached channel.

	void trace(const std::string& msg);
		/// If the Logger's log level is at least PRIO_TRACE,
		/// creates a Message with priority PRIO_TRACE
		/// and the given message text and sends it
		/// to the attached channel.

	void dump(const std::string& msg, const void* buffer, std::size_t length, Message::Priority prio = Message::PRIO_DEBUG);
		/// Logs the given message, followed by the data in buffer.
		///
		/// The data in buffer is written in canonical hex+ASCII form:
		/// Offset (4 bytes) in hexadecimal, followed by sixteen
		/// space-separated, two column, hexadecimal bytes,
		/// followed by the same sixteen bytes as ASCII characters.
		/// For bytes outside the range 32 .. 127, a dot is printed.

	bool is(int level) const;
		/// Returns true if at least the given log level is set.

	bool fatal() const;
		/// Returns true if the log level is at least PRIO_FATAL.

	bool critical() const;
		/// Returns true if the log level is at least PRIO_CRITICAL.

	bool error() const;
		/// Returns true if the log level is at least PRIO_ERROR.

	bool warning() const;
		/// Returns true if the log level is at least PRIO_WARNING.

	bool notice() const;
		/// Returns true if the log level is at least PRIO_NOTICE.

	bool information() const;
		/// Returns true if the log level is at least PRIO_INFORMATION.

	bool debug() const;
		/// Returns true if the log level is at least PRIO_DEBUG.

	bool trace() const;
		/// Returns true if the log level is at least PRIO_TRACE.

	static std::string format(const std::string& fmt, const std::string& arg);
		/// Replaces all occurences of $0 in fmt with the string given in arg and
		/// returns the result. To include a dollar sign in the result string,
		/// specify two dollar signs ($$) in the format string.

	static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1);
		/// Replaces all occurences of $<n> in fmt with the string given in arg<n> and
		/// returns the result. To include a dollar sign in the result string,
		/// specify two dollar signs ($$) in the format string.

	static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2);
		/// Replaces all occurences of $<n> in fmt with the string given in arg<n> and
		/// returns the result. To include a dollar sign in the result string,
		/// specify two dollar signs ($$) in the format string.

	static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3);
		/// Replaces all occurences of $<n> in fmt with the string given in arg<n> and
		/// returns the result. To include a dollar sign in the result string,
		/// specify two dollar signs ($$) in the format string.

	static void setLevel(const std::string& name, int level);
		/// Sets the given log level on all loggers that are
		/// descendants of the Logger with the given name.

	static void setChannel(const std::string& name, Channel* pChannel);
		/// Attaches the given Channel to all loggers that are
		/// descendants of the Logger with the given name.

	static void setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value);
		/// Sets or changes a configuration property for all loggers
		/// that are descendants of the Logger with the given name.

	static Logger& get(const std::string& name);
		/// Returns a reference to the Logger with the given name.
		/// If the Logger does not yet exist, it is created, based
		/// on its parent logger.

	static Logger& unsafeGet(const std::string& name);
		/// Returns a reference to the Logger with the given name.
		/// If the Logger does not yet exist, it is created, based
		/// on its parent logger.
		///
		/// WARNING: This method is not thread safe. You should
		/// probably use get() instead.
		/// The only time this method should be used is during
		/// program initialization, when only one thread is running.

	static Logger& create(const std::string& name, Channel* pChannel, int level = Message::PRIO_INFORMATION);
		/// Creates and returns a reference to a Logger with the
		/// given name. The Logger's Channel and log level as set as
		/// specified.

	static Logger& root();
		/// Returns a reference to the root logger, which is the ultimate
		/// ancestor of all Loggers.

	static Logger* has(const std::string& name);
		/// Returns a pointer to the Logger with the given name if it
		/// exists, or a null pointer otherwse.

	static void destroy(const std::string& name);
		/// Destroys the logger with the specified name. Does nothing
		/// if the logger is not found.
		///
		/// After a logger has been destroyed, all references to it
		/// become invalid.

	static void shutdown();
		/// Shuts down the logging framework and releases all
		/// Loggers.

	static void names(std::vector<std::string>& names);
		/// Fills the given vector with the names
		/// of all currently defined loggers.

	static const std::string ROOT; /// The name of the root logger ("").

protected:
	typedef std::map<std::string, Logger*> LoggerMap;

	Logger(const std::string& name, Channel* pChannel, int level);
	~Logger();

	void log(const std::string& text, Message::Priority prio);

	static std::string format(const std::string& fmt, int argc, std::string argv[]);
	static void formatDump(std::string& message, const void* buffer, std::size_t length);
	static Logger& parent(const std::string& name);
	static void add(Logger* pLogger);
	static Logger* find(const std::string& name);

private:
	Logger();
	Logger(const Logger&);
	Logger& operator = (const Logger&);

	std::string _name;
	Channel*    _pChannel;
	int         _level;

	static LoggerMap* _pLoggerMap;
	static Mutex      _mapMtx;
};

//
// convenience macros
//
#define poco_fatal(logger, msg) \
	if ((logger).fatal()) (logger).fatal(msg) else (void) 0

#define poco_critical(logger, msg) \
	if ((logger).critical()) (logger).critical(msg) else (void) 0

#define poco_error(logger, msg) \
	if ((logger).error()) (logger).error(msg) else (void) 0

#define poco_warning(logger, msg) \
	if ((logger).warning()) (logger).warning(msg) else (void) 0

#define poco_notice(logger, msg) \
	if ((logger).notice()) (logger).notice(msg) else (void) 0

#define poco_information(logger, msg) \
	if ((logger).information()) (logger).information(msg) else (void) 0

#if defined(_DEBUG)
	#define poco_debug(logger, msg) \
		if ((logger).debug()) (logger).debug(msg) else (void) 0

	#define poco_trace(logger, msg) \
		if ((logger).trace()) (logger).trace(msg) else (void) 0
#else
	#define poco_debug(logger, msg)
	#define poco_trace(logger, msg)
#endif

//
// inlines
//
inline const std::string& Logger::name() const
{
	return _name;
}

inline int Logger::getLevel() const
{
	return _level;
}

inline void Logger::log(const std::string& text, Message::Priority prio)
{
	if (_level >= prio && _pChannel)
	{
		_pChannel->log(Message(_name, text, prio));
	}
}

inline void Logger::fatal(const std::string& msg)
{
	log(msg, Message::PRIO_FATAL);
}

inline void Logger::critical(const std::string& msg)
{
	log(msg, Message::PRIO_CRITICAL);
}

inline void Logger::error(const std::string& msg)
{
	log(msg, Message::PRIO_ERROR);
}

inline void Logger::warning(const std::string& msg)
{
	log(msg, Message::PRIO_WARNING);
}

inline void Logger::notice(const std::string& msg)
{
	log(msg, Message::PRIO_NOTICE);
}

inline void Logger::information(const std::string& msg)
{
	log(msg, Message::PRIO_INFORMATION);
}

inline void Logger::debug(const std::string& msg)
{
	log(msg, Message::PRIO_DEBUG);
}

inline void Logger::trace(const std::string& msg)
{
	log(msg, Message::PRIO_TRACE);
}

inline bool Logger::is(int level) const
{
	return _level >= level;
}

inline bool Logger::fatal() const
{
	return _level >= Message::PRIO_FATAL;
}

inline bool Logger::critical() const
{
	return _level >= Message::PRIO_CRITICAL;
}

inline bool Logger::error() const
{
	return _level >= Message::PRIO_ERROR;
}

inline bool Logger::warning() const
{
	return _level >= Message::PRIO_WARNING;
}

inline bool Logger::notice() const
{
	return _level >= Message::PRIO_NOTICE;
}

inline bool Logger::information() const
{
	return _level >= Message::PRIO_INFORMATION;
}

inline bool Logger::debug() const
{
	return _level >= Message::PRIO_DEBUG;
}

inline bool Logger::trace() const
{
	return _level >= Message::PRIO_TRACE;
}

} // namespace Poco

#endif // Foundation_Logger_INCLUDED


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                    http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Entities\User" table="users">
        <id name="id" type="integer">
            <generator strategy="AUTO"/>
        </id>
        <field name="name" type="string" length="50"/>
        <one-to-one field="address" target-entity="Address">
            <join-column name="address_id" referenced-column-name="id"/>
        </one-to-one>
    </entity>

</doctrine-mapping>


text:
#pragma once

using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;

// Prototype
class MediaEngineManager;

namespace Microsoft {
	namespace Maker {
		namespace Media {
			namespace UniversalMediaEngine
			{
				public enum class MediaEngineInitializationResult
				{
					Success,
					Fail
				};

				public delegate void MediaStateChangedHandler(MediaState state);

				public ref class MediaEngine sealed
				{
				private:
					~MediaEngine();
				public:

					/// <summary>
					/// Asynchronously initializes the media engine
					/// </summary>
					/// <returns> A task with a value that indicates whether Initialization was
					/// successful</returns>
					IAsyncOperation<MediaEngineInitializationResult>^ InitializeAsync();

					/// <summary>
					/// Plays the media stream at the given URL
					/// </summary>
					void Play(Platform::String^ url);

					void PlayStream(IRandomAccessStream^ stream);

					/// <summary>
					/// Pauses playback
					/// </summary>
					void Pause();

					/// <summary>
					/// Stops playback
					/// </summary>
					void Stop();

					property double Volume
					{
						/// <summary>
						/// Gets the current volume
						/// </summary>
						/// <returns>The current volume</returns>
						double get();

						/// <summary>
						/// Sets the current volume
						/// </summary>
						/// <param name="value">The new volume</param>
						void set(double value);
					}

					/// <summary>
					/// Gets the current volume
					/// </summary>
					event MediaStateChangedHandler^ MediaStateChanged;

				internal:

					/// <summary>
					/// Used by internal components to trigger the MediaStateChanged event
					/// </summary>
					void TriggerMediaStateChanged(MediaState state);

				private:

					/// <summary>
					/// Used by internal components to trigger the MediaStateChanged event
					/// </summary>
					ComPtr<MediaEngineManager> spMediaEngineManager;
				};
			}
		}
	}
}


text:
// Originally from UpdatedComponentTests/Authentication/SOAP/SOAP_Authentication_UnknownCred.xls;
package uk.co.exemel.disco.tests.updatedcomponenttests.authentication.soap;

import uk.co.exemel.testing.utils.disco.misc.XMLHelpers;
import uk.co.exemel.testing.utils.disco.assertions.AssertionUtils;
import uk.co.exemel.testing.utils.disco.beans.HttpCallBean;
import uk.co.exemel.testing.utils.disco.beans.HttpResponseBean;
import uk.co.exemel.testing.utils.disco.enums.DiscoMessageProtocolResponseTypeEnum;
import uk.co.exemel.testing.utils.disco.manager.AccessLogRequirement;
import uk.co.exemel.testing.utils.disco.manager.DiscoManager;
import uk.co.exemel.testing.utils.disco.manager.RequestLogRequirement;

import org.testng.annotations.Test;
import org.w3c.dom.Document;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * Verify that an unknown pareameter added to Credentials auth header is ignored
 */
public class SOAPAuthenticationUnknownCredTest {
    @Test
    public void doTest() throws Exception {

        XMLHelpers xMLHelpers1 = new XMLHelpers();
        Document createAsDocument1 = xMLHelpers1.getXMLObjectFromString("<TestIdentityChainRequest/>");

        DiscoManager discoManager2 = DiscoManager.getInstance();
        HttpCallBean getNewHttpCallBean2 = discoManager2.getNewHttpCallBean("87.248.113.14");
        discoManager2 = discoManager2;

        discoManager2.setDiscoFaultControllerJMXMBeanAttrbiute("DetailedFaults", "false");

        getNewHttpCallBean2.setServiceName("Baseline", "discoBaseline");

        getNewHttpCallBean2.setVersion("v2");

        Map map3 = new HashMap();
        map3.put("Username","foo");
        map3.put("Unknown","bar");
        getNewHttpCallBean2.setAuthCredentials(map3);

        getNewHttpCallBean2.setPostObjectForRequestType(createAsDocument1, "SOAP");

        Timestamp getTimeAsTimeStamp9 = new Timestamp(System.currentTimeMillis());

        discoManager2.makeSoapDiscoHTTPCalls(getNewHttpCallBean2);

        XMLHelpers xMLHelpers5 = new XMLHelpers();
        Document createAsDocument11 = xMLHelpers5.getXMLObjectFromString("<response><identities><Ident><principal>PRINCIPAL: Username</principal><credentialName>CREDENTIAL: Username</credentialName><credentialValue>foo</credentialValue></Ident></identities></response>");

        HttpResponseBean getResponseObjectsByEnum13 = getNewHttpCallBean2.getResponseObjectsByEnum(DiscoMessageProtocolResponseTypeEnum.SOAP);
        AssertionUtils.multiAssertEquals(createAsDocument11, getResponseObjectsByEnum13.getResponseObject());

        Map<String, String> map7 = getResponseObjectsByEnum13.getFlattenedResponseHeaders();
        AssertionUtils.multiAssertEquals("Username:foo", map7.get("Credentials"));

        // generalHelpers.pauseTest(1000L);

        discoManager2.verifyRequestLogEntriesAfterDate(getTimeAsTimeStamp9, new RequestLogRequirement("2.8", "testIdentityChain") );

        discoManager2.verifyAccessLogEntriesAfterDate(getTimeAsTimeStamp9, new AccessLogRequirement(null, null, "Ok") );
    }

}


text:
package org.jetbrains.plugins.scala.lang.parser.scala3

import org.jetbrains.plugins.scala.util.PsiSelectionUtil
import org.jetbrains.plugins.scala.util.assertions.AssertionMatchers

class EndParserTest_InTemplateDefinition extends SimpleScala3ParserTestBase with PsiSelectionUtil with AssertionMatchers {

  def test_end_class_empty_template_body(): Unit = checkTree(
    """class A
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScClass: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(class)('class')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    PrimaryConstructor
      |      AnnotationsList
      |        <empty list>
      |      Modifiers
      |        <empty list>
      |      Parameters
      |        <empty list>
      |    ExtendsBlock
      |      <empty list>
      |    PsiWhiteSpace('\n')
      |    End: A
      |      PsiElement(end)('end')
      |      PsiWhiteSpace(' ')
      |      PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_class_empty_template_body_with_colon(): Unit = checkTree(
    """class A:
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScClass: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(class)('class')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    PrimaryConstructor
      |      AnnotationsList
      |        <empty list>
      |      Modifiers
      |        <empty list>
      |      Parameters
      |        <empty list>
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_class_non_empty_template_body_with_colon(): Unit = checkTree(
    """class A:
      |  def foo = ???
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScClass: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(class)('class')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    PrimaryConstructor
      |      AnnotationsList
      |        <empty list>
      |      Modifiers
      |        <empty list>
      |      Parameters
      |        <empty list>
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n  ')
      |        ScFunctionDefinition: foo
      |          AnnotationsList
      |            <empty list>
      |          Modifiers
      |            <empty list>
      |          PsiElement(def)('def')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('foo')
      |          Parameters
      |            <empty list>
      |          PsiWhiteSpace(' ')
      |          PsiElement(=)('=')
      |          PsiWhiteSpace(' ')
      |          ReferenceExpression: ???
      |            PsiElement(identifier)('???')
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_object_empty_template_body(): Unit = checkTree(
    """object A
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScObject: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(object)('object')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    ExtendsBlock
      |      <empty list>
      |    PsiWhiteSpace('\n')
      |    End: A
      |      PsiElement(end)('end')
      |      PsiWhiteSpace(' ')
      |      PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_object_empty_template_body_with_colon(): Unit = checkTree(
    """object A:
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScObject: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(object)('object')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_object_non_empty_template_body_with_colon(): Unit = checkTree(
    """object A:
      |  def foo = ???
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScObject: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(object)('object')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n  ')
      |        ScFunctionDefinition: foo
      |          AnnotationsList
      |            <empty list>
      |          Modifiers
      |            <empty list>
      |          PsiElement(def)('def')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('foo')
      |          Parameters
      |            <empty list>
      |          PsiWhiteSpace(' ')
      |          PsiElement(=)('=')
      |          PsiWhiteSpace(' ')
      |          ReferenceExpression: ???
      |            PsiElement(identifier)('???')
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_enum_empty_template_body_with_colon(): Unit = checkTree(
    """enum A:
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScEnum: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(enum)('enum')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    PrimaryConstructor
      |      AnnotationsList
      |        <empty list>
      |      Modifiers
      |        <empty list>
      |      Parameters
      |        <empty list>
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_enum_non_empty_template_body_with_colon(): Unit = checkTree(
    """enum A:
      |  case X
      |end A
      |""".stripMargin,
    """ScalaFile
      |  ScEnum: A
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(enum)('enum')
      |    PsiWhiteSpace(' ')
      |    PsiElement(identifier)('A')
      |    PrimaryConstructor
      |      AnnotationsList
      |        <empty list>
      |      Modifiers
      |        <empty list>
      |      Parameters
      |        <empty list>
      |    ExtendsBlock
      |      ScTemplateBody
      |        PsiElement(:)(':')
      |        PsiWhiteSpace('\n  ')
      |        ScEnumCases: X
      |          AnnotationsList
      |            <empty list>
      |          Modifiers
      |            <empty list>
      |          PsiElement(case)('case')
      |          PsiWhiteSpace(' ')
      |          ScEnumCase: X
      |            PsiElement(identifier)('X')
      |            ExtendsBlock
      |              <empty list>
      |        PsiWhiteSpace('\n')
      |        End: A
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('A')
      |  PsiWhiteSpace('\n')""".stripMargin
  )

  def test_end_given_with_empty_template_body(): Unit = checkTree(
    """given Conversion[Int, String] with
      |end given""".stripMargin,
    """ScalaFile
      |  ScGivenDefinition: given_Conversion_Int_String
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(given)('given')
      |    PsiWhiteSpace(' ')
      |    ExtendsBlock
      |      TemplateParents
      |        ConstructorInvocation
      |          ParametrizedType: Conversion[Int, String]
      |            SimpleType: Conversion
      |              CodeReferenceElement: Conversion
      |                PsiElement(identifier)('Conversion')
      |            TypeArgumentsList
      |              PsiElement([)('[')
      |              SimpleType: Int
      |                CodeReferenceElement: Int
      |                  PsiElement(identifier)('Int')
      |              PsiElement(,)(',')
      |              PsiWhiteSpace(' ')
      |              SimpleType: String
      |                CodeReferenceElement: String
      |                  PsiElement(identifier)('String')
      |              PsiElement(])(']')
      |      PsiWhiteSpace(' ')
      |      PsiElement(with)('with')
      |      PsiWhiteSpace('\n')
      |      ScTemplateBody
      |        End: given
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(given)('given')""".stripMargin
  )

  def test_end_given_with_non_empty_template_body(): Unit = checkTree(
    """given Conversion[Int, String] with
      |  def foo = ???
      |end given""".stripMargin,
    """ScalaFile
      |  ScGivenDefinition: given_Conversion_Int_String
      |    AnnotationsList
      |      <empty list>
      |    Modifiers
      |      <empty list>
      |    PsiElement(given)('given')
      |    PsiWhiteSpace(' ')
      |    ExtendsBlock
      |      TemplateParents
      |        ConstructorInvocation
      |          ParametrizedType: Conversion[Int, String]
      |            SimpleType: Conversion
      |              CodeReferenceElement: Conversion
      |                PsiElement(identifier)('Conversion')
      |            TypeArgumentsList
      |              PsiElement([)('[')
      |              SimpleType: Int
      |                CodeReferenceElement: Int
      |                  PsiElement(identifier)('Int')
      |              PsiElement(,)(',')
      |              PsiWhiteSpace(' ')
      |              SimpleType: String
      |                CodeReferenceElement: String
      |                  PsiElement(identifier)('String')
      |              PsiElement(])(']')
      |      PsiWhiteSpace(' ')
      |      PsiElement(with)('with')
      |      PsiWhiteSpace('\n  ')
      |      ScTemplateBody
      |        ScFunctionDefinition: foo
      |          AnnotationsList
      |            <empty list>
      |          Modifiers
      |            <empty list>
      |          PsiElement(def)('def')
      |          PsiWhiteSpace(' ')
      |          PsiElement(identifier)('foo')
      |          Parameters
      |            <empty list>
      |          PsiWhiteSpace(' ')
      |          PsiElement(=)('=')
      |          PsiWhiteSpace(' ')
      |          ReferenceExpression: ???
      |            PsiElement(identifier)('???')
      |        PsiWhiteSpace('\n')
      |        End: given
      |          PsiElement(end)('end')
      |          PsiWhiteSpace(' ')
      |          PsiElement(given)('given')""".stripMargin
  )
}


text:
import Comp from './index.vue'

import { mount } from 'vue-test-utils'
import { expect } from 'chai'

describe('Clocker', () => {
  it('basic', () => {
    const wrapper = mount(Comp)
    expect(wrapper.name()).to.equal('clocker')
  })
})


text:
package io.cdap.plugin.zuora.objects;

import com.google.gson.annotations.SerializedName;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectFieldDefinition;
import io.cdap.plugin.zuora.restobjects.objects.BaseObject;

import javax.annotation.Nullable;

/**
* Object name: UpdateCustomObjectCusotmFieldDefinitionItem (UpdateCustomObjectCusotmFieldDefinitionItem).
* Related objects:
**/
@SuppressWarnings("unused")
@ObjectDefinition(
  Name = "UpdateCustomObjectCusotmFieldDefinitionItem",
  ObjectType = ObjectDefinition.ObjectDefinitionType.NESTED
)
public class UpdateCustomObjectCusotmFieldDefinitionItem extends BaseObject {

  @Override
  public void addFields() {
  }
}


text:
def parse_options(usage=None, parser_fnr=None, num_args=None, args=None):
    """ parser_fnr - to add options for parser
    num_args - required number of args
    args - if not None then use them instead of sys.argv[1:] """
    from optparse import OptionParser
    import sys
    parser = OptionParser(usage=usage)

    if parser_fnr:
        parser_fnr(parser)
    options, args = parser.parse_args(args)

    if num_args != None and len(args) != num_args:
        parser.print_help()
        sys.exit(1)

    return options, args

def parse_opts_args(parser_fnr, *args):
    return parse_options("usage: %prog [options] " + " ".join(args), parser_fnr=parser_fnr, num_args=len(args))

def parse_args(*args):
    return parse_opts_args(None, *args)[1]

def parse_one_arg(arg_name):
    return parse_args(arg_name)[0]

def add_bool_option(parser, name, var_name, help_str):
    """ name - "-s" либо "--long_bool_option" """
    parser.add_option(name, action="store_true", dest=var_name, default=False,
                      help=help_str)

def parse_1bool_args(b_name, b_var_name, b_help_str, *args):
    def add_options(parser):
        add_bool_option(parser, b_name, b_var_name, b_help_str)
    return parse_opts_args(add_options, *args)


text:
package base

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"strings"

	common_http "github.com/goharbor/harbor/src/common/http"
	"github.com/goharbor/harbor/src/pkg/reg/filter"
	"github.com/goharbor/harbor/src/pkg/reg/model"
	"net/url"
)

type label struct {
	Name string `json:"name"`
}

type chartVersion struct {
	Version string   `json:"version"`
	Labels  []*label `json:"labels"`
}

type chartVersionDetail struct {
	Metadata *chartVersionMetadata `json:"metadata"`
}

type chartVersionMetadata struct {
	URLs []string `json:"urls"`
}

// FetchCharts fetches charts
func (a *Adapter) FetchCharts(filters []*model.Filter) ([]*model.Resource, error) {
	projects, err := a.ListProjects(filters)
	if err != nil {
		return nil, err
	}

	resources := []*model.Resource{}
	for _, project := range projects {
		url := fmt.Sprintf("%s/api/chartrepo/%s/charts", a.Client.GetURL(), project.Name)
		repositories := []*model.Repository{}
		if err := a.httpClient.Get(url, &repositories); err != nil {
			return nil, err
		}
		if len(repositories) == 0 {
			continue
		}
		for _, repository := range repositories {
			repository.Name = fmt.Sprintf("%s/%s", project.Name, repository.Name)
		}
		repositories, err = filter.DoFilterRepositories(repositories, filters)
		if err != nil {
			return nil, err
		}

		for _, repository := range repositories {
			name := strings.SplitN(repository.Name, "/", 2)[1]
			url := fmt.Sprintf("%s/api/chartrepo/%s/charts/%s", a.Client.GetURL(), project.Name, name)
			versions := []*chartVersion{}
			if err := a.httpClient.Get(url, &versions); err != nil {
				return nil, err
			}
			if len(versions) == 0 {
				continue
			}
			var artifacts []*model.Artifact
			for _, version := range versions {
				var labels []string
				for _, label := range version.Labels {
					labels = append(labels, label.Name)
				}
				artifacts = append(artifacts, &model.Artifact{
					Tags:   []string{version.Version},
					Labels: labels,
				})
			}
			artifacts, err = filter.DoFilterArtifacts(artifacts, filters)
			if err != nil {
				return nil, err
			}
			if len(artifacts) == 0 {
				continue
			}

			for _, artifact := range artifacts {
				resources = append(resources, &model.Resource{
					Type:     model.ResourceTypeChart,
					Registry: a.Registry,
					Metadata: &model.ResourceMetadata{
						Repository: &model.Repository{
							Name:     repository.Name,
							Metadata: project.Metadata,
						},
						Artifacts: []*model.Artifact{artifact},
					},
				})
			}
		}
	}
	return resources, nil
}

// ChartExist checks the existence of the chart
func (a *Adapter) ChartExist(name, version string) (bool, error) {
	_, err := a.getChartInfo(name, version)
	if err == nil {
		return true, nil
	}
	if httpErr, ok := err.(*common_http.Error); ok && httpErr.Code == http.StatusNotFound {
		return false, nil
	}
	return false, err
}

func (a *Adapter) getChartInfo(name, version string) (*chartVersionDetail, error) {
	project, name, err := parseChartName(name)
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s/api/chartrepo/%s/charts/%s/%s", a.Client.GetURL(), project, name, version)
	info := &chartVersionDetail{}
	if err = a.httpClient.Get(url, info); err != nil {
		return nil, err
	}
	return info, nil
}

// DownloadChart downloads the specific chart
func (a *Adapter) DownloadChart(name, version, contentURL string) (io.ReadCloser, error) {
	info, err := a.getChartInfo(name, version)
	if err != nil {
		return nil, err
	}
	if info.Metadata == nil || len(info.Metadata.URLs) == 0 || len(info.Metadata.URLs[0]) == 0 {
		return nil, fmt.Errorf("cannot got the download url for chart %s:%s", name, version)
	}

	url, err := url.Parse(info.Metadata.URLs[0])
	if err != nil {
		return nil, err
	}
	// relative URL
	urlStr := url.String()
	if !(url.Scheme == "http" || url.Scheme == "https") {
		project, _, err := parseChartName(name)
		if err != nil {
			return nil, err
		}
		urlStr = fmt.Sprintf("%s/chartrepo/%s/%s", a.Client.GetURL(), project, urlStr)
	}
	req, err := http.NewRequest(http.MethodGet, urlStr, nil)
	if err != nil {
		return nil, err
	}
	resp, err := a.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("failed to download the chart %s: %d %s", req.URL.String(), resp.StatusCode, string(body))
	}
	return resp.Body, nil
}

// UploadChart uploads the chart
func (a *Adapter) UploadChart(name, version string, chart io.Reader) error {
	project, name, err := parseChartName(name)
	if err != nil {
		return err
	}

	buf := &bytes.Buffer{}
	w := multipart.NewWriter(buf)
	fw, err := w.CreateFormFile("chart", name+".tgz")
	if err != nil {
		return err
	}
	if _, err = io.Copy(fw, chart); err != nil {
		return err
	}
	w.Close()

	url := fmt.Sprintf("%s/api/chartrepo/%s/charts", a.Client.GetURL(), project)

	req, err := http.NewRequest(http.MethodPost, url, buf)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", w.FormDataContentType())
	resp, err := a.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return &common_http.Error{
			Code:    resp.StatusCode,
			Message: string(data),
		}
	}
	return nil
}

// DeleteChart deletes the chart
func (a *Adapter) DeleteChart(name, version string) error {
	project, name, err := parseChartName(name)
	if err != nil {
		return err
	}
	url := fmt.Sprintf("%s/api/chartrepo/%s/charts/%s/%s", a.Client.GetURL(), project, name, version)
	return a.httpClient.Delete(url)
}

// TODO merge this method and utils.ParseRepository?
func parseChartName(name string) (string, string, error) {
	strs := strings.Split(name, "/")
	if len(strs) == 2 && len(strs[0]) > 0 && len(strs[1]) > 0 {
		return strs[0], strs[1], nil
	}
	return "", "", fmt.Errorf("invalid chart name format: %s", name)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2013-2017 microG Project Team
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:tint="?attr/colorAccent"
    android:viewportWidth="24"
    android:viewportHeight="24">

    <path
        android:fillColor="#FF000000"
        android:pathData="M14,10H2V12H14V10M14,6H2V8H14V6M2,16H10V14H2V16M21.5,11.5L23,13L16,20L11.5,15.5L13,14L16,17L21.5,11.5Z" />
</vector>


text:
title: "Main Content Figures (half)"
type: media
scss: _assets/stylesheets/_base.scss
usage: "For displaying two related images side by side."
---

Images in two columns.


text:
.core-spread-sheet table tbody thead th {

}
.core-spread-sheet-data {
    display: block;
}

.core-spread-sheet-site-name {
    padding:15px;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SPR.Blog.Services
{
    public class ExcerptGenerator
    {
        private readonly int _maxLength;

        public ExcerptGenerator(int maxLength)
        {
            _maxLength = maxLength;
        }

        public string CreateExcerpt(string body)
        {
            string excerpt;
            if (body.Length > _maxLength)
            {
                excerpt = body.Substring(0, _maxLength) + "...";
            }
            else
            {
                excerpt = body;
            }
            return excerpt;
        }
    }
}