text:
package stallone.doubles;

import static stallone.api.API.*;

import stallone.api.doubles.IDoubleIterator;
import stallone.api.doubles.IDoubleArray;
import stallone.api.doubles.IDoubleElement;
import stallone.api.ints.IIntList;

/**
 * Class SparseRealMatrix is an implementation based on a number of sparse row vectors.
 *
 * @author  Martin Senne, Frank Noe
 */
public class SparseRealMatrix extends AbstractDoubleArray
{
    protected SparseRealVector[] rowVectors;
    protected int rows,cols;

    public SparseRealMatrix(final int _rows, final int _cols)
    {
        rows = _rows;
        cols = _cols;
        rowVectors = new SparseRealVector[rows];

        for (int i = 0; i < rows; i++)
        {
            rowVectors[i] = new SparseRealVector(cols);
        }
    }

    private SparseRealMatrix(final SparseRealMatrix source)
    {
        rows = source.rows;
        cols = source.cols;
        this.rowVectors = new SparseRealVector[rows];

        for (int i = 0; i < rows; i++)
        {
            rowVectors[i] = (SparseRealVector)source.rowVectors[i].copy();
        }
    }

    @Override
    public void zero()
    {
        for (int i = 0; i < rows; i++)
        {
            rowVectors[i].zero();
        }
    }

    @Override
    public int rows()
    {
        return(rows);
    }

    @Override
    public int columns()
    {
        return(cols);
    }

    @Override
    public double get(final int i, final int j)
    {
        return rowVectors[i].get(j);
    }

    @Override
    public void set(final int i, final int j, final double real)
    {
        rowVectors[i].set(j, real);
    }

    @Override
    public void copyFrom(final IDoubleArray source)
    {
        zero();

        for (IDoubleIterator it = source.nonzeroIterator(); it.hasNext(); it.advance())
        {
            set(it.row(), it.column(), it.get());
        }
    }

    @Override
    public void copyInto(final IDoubleArray target)
    {
        target.zero();

        for (IDoubleIterator it = nonzeroIterator(); it.hasNext(); it.advance())
        {
            target.set(it.row(), it.column(), it.get());
        }
    }

    @Override
    public IDoubleArray copy()
    {
        return new SparseRealMatrix(this);
    }

    @Override
    public IDoubleArray create(int rows, int cols)
    {
        return (new SparseRealMatrix(rows, cols));
    }

    @Override
    public IDoubleArray create(int size)
    {
        return (new SparseRealMatrix(rows, 1));
    }

    @Override
    public IDoubleArray viewRow(final int r)
    {
        return rowVectors[r];
    }

    @Override
    public boolean isSparse()
    {
        return true;
    }

    @Override
    public IDoubleIterator nonzeroIterator()
    {
        return new SparseRealMatrixNonzeroIterator(this);
    }

}

/**
 *
 * @author noe
 */
class SparseRealMatrixNonzeroIterator implements IDoubleIterator
{
    private SparseRealMatrix M;
    int nrows, ncols;
    private DoubleTableElement de;
    private IIntList nonzeroRows;

    int irow=0, icol=0;
    int row=0, col=0;

    public SparseRealMatrixNonzeroIterator(SparseRealMatrix _M)
    {
        M = _M;
        nrows = _M.rows();
        ncols = _M.columns();
        de = new DoubleTableElement(_M, 0, 0);

        nonzeroRows = intsNew.list(0);
        for (int i=0; i<_M.rows(); i++)
        {
            if (_M.rowVectors[i].getNumberOfNonzero() > 0)
                nonzeroRows.append(i);
        }

        reset();
    }

    @Override
    public void reset()
    {
        irow = 0;
        icol = 0;
        row = nonzeroRows.get(irow);
        col = M.rowVectors[row].getIndexMap().nonZeroIndices[icol];

        this.de = new DoubleTableElement(M, row, col);
    }

    @Override
    public boolean hasNext()
    {
        if (irow >= nonzeroRows.size())
            return false;
        if (icol >= M.rowVectors[row].getIndexMap().usedNonZero)
            return false;
        return true;
    }

    /**
     * Goes to the next value. Does not return anything. You have to get the content with get().
     * Usage Example:
     *
     * for (IDoubleArrayIterator it = arr.iterator(); it.hasNext(); it.next)
     * {
     *      System.out.println("current element: " + it.get());
     * }
     */
    @Override
    public void advance()
    {
        if (icol+1 < M.rowVectors[row].getIndexMap().usedNonZero)
            icol++;
        else
        {
            irow++;
            icol=0;
        }

        // out of bounds: do nothing
        if (irow >= nonzeroRows.size())
            return;

        row = nonzeroRows.get(irow);
        col = M.rowVectors[row].getIndexMap().nonZeroIndices[icol];
    }

    /**
     * Returns the current index. Good to know if this is a sparse vector iterator!
     * @return
     */
    @Override
    public int getIndex()
    {
        return(row*ncols+col);
    }

    /**
     * Returns the current value
     * @return
     */
    @Override
    public double get()
    {
        return M.get(row,col);
    }

    /**
     * Sets the current value
     */
    @Override
    public void set(double newValue)
    {
        M.set(row,col,newValue);
    }

    @Override
    public IDoubleElement next()
    {
        de.setIndex(row,col);
        advance();
        return de;
    }

    @Override
    public void remove()
    {
        throw new UnsupportedOperationException("Remove not supported.");
    }

    @Override
    public int row()
    {
        return row;
    }

    @Override
    public int column()
    {
        return col;
    }

}


text:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Redmine.Net.Api.Exceptions;
using Redmine.Net.Api.Extensions;
using Redmine.Net.Api.Types;

namespace Redmine.Net.Api.Internals
{
    internal sealed class RedmineXmlSerializer : IRedmineSerializer
    {
        public T Deserialize<T>(string response) where T : class
        {
            if (string.IsNullOrEmpty(response))
            {
                throw new RedmineException("Could not deserialize null!");
            }

            try
            {
               return FromXML<T>(response);
            }
            catch (Exception ex)
            {
                throw new RedmineException("Deserialization error", ex);
            }
        }

        public PaginatedResult<T> DeserializeList<T>(string response) where T : class, new()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(response))
                {
                    throw new RedmineException("Could not deserialize empty response!");
                }

                return XmlDeserializeList<T>(response);
            }
            catch (Exception ex)
            {
                throw new RedmineException("Deserialization error", ex);
            }
        }

        public string Serialize<T>(T obj) where T: class
        {
            if(obj == default(T))
            {
                throw new RedmineException("Could not serialize null object.");
            }

            try
            {
                return ToXML(obj);
            }
            catch (Exception ex)
            {
                throw new RedmineException("Serialization error", ex);
            }
        }

        /// <summary>
        /// XMLs the deserialize list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response">The response.</param>
        /// <returns></returns>
        private static PaginatedResult<T> XmlDeserializeList<T>(string response) where T : class, new()
        {
            using (TextReader stringReader = new StringReader(response))
            {
                using (var xmlReader = XmlReader.Create(stringReader))
                {
                    xmlReader.Read();
                    xmlReader.Read();

                    var totalItems = xmlReader.ReadAttributeAsInt(RedmineKeys.TOTAL_COUNT);
                    var offset = xmlReader.ReadAttributeAsInt(RedmineKeys.OFFSET);
                    var result = xmlReader.ReadElementContentAsCollection<T>();
                    return new PaginatedResult<T>(result, totalItems, offset);
                }
            }
        }

        /// <summary>
        /// Serializes the specified System.Object and writes the XML document to a string.
        /// </summary>
        /// <typeparam name="T">The type of objects to serialize.</typeparam>
        /// <param name="obj">The object to serialize.</param>
        /// <returns>
        /// The System.String that contains the XML document.
        /// </returns>
        /// <exception cref="InvalidOperationException"></exception>
        // ReSharper disable once InconsistentNaming
        private static string ToXML<T>(T obj) where T : class
        {
            var xws = new XmlWriterSettings { OmitXmlDeclaration = true };
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, xws))
                {
                    var sr = new XmlSerializer(typeof(T));
                    sr.Serialize(xmlWriter, obj);
                    return stringWriter.ToString();
                }
            }
        }

        /// <summary>
        /// Deserializes the XML document contained by the specific System.String.
        /// </summary>
        /// <typeparam name="T">The type of objects to deserialize.</typeparam>
        /// <param name="xml">The System.String that contains the XML document to deserialize.</param>
        /// <returns>
        /// The T object being deserialized.
        /// </returns>
        /// <exception cref="System.InvalidOperationException">An error occurred during deserialization. The original exception is available
        /// using the System.Exception.InnerException property.</exception>
        // ReSharper disable once InconsistentNaming
        private static T FromXML<T>(string xml) where T : class
        {
            using (var text = new StringReader(xml))
            {
                var sr = new XmlSerializer(typeof(T));
                return sr.Deserialize(text) as T;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# 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.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Gets valid resource name for compute test
#>
function Get-ComputeTestResourceName
{
    $stack = Get-PSCallStack
    $testName = $null;
    foreach ($frame in $stack)
    {
        if ($frame.Command.StartsWith("Test-", "CurrentCultureIgnoreCase"))
        {
            $testName = $frame.Command;
        }
    }

    $oldErrorActionPreferenceValue = $ErrorActionPreference;
    $ErrorActionPreference = "SilentlyContinue";

    try
    {
        $assetName = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::GetAssetName($testName, "crptestps");
    }
    catch
    {
        if (($Error.Count -gt 0) -and ($Error[0].Exception.Message -like '*Unable to find type*'))
        {
            $assetName = Get-RandomItemName;
        }
        else
        {
            throw;
        }
    }
    finally
    {
        $ErrorActionPreference = $oldErrorActionPreferenceValue;
    }

    return $assetName
}

<#
.SYNOPSIS
Gets test mode - 'Record' or 'Playback'
#>
function Get-ComputeTestMode
{
    $oldErrorActionPreferenceValue = $ErrorActionPreference;
    $ErrorActionPreference = "SilentlyContinue";

    try
    {
        $testMode = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::Mode;
        $testMode = $testMode.ToString();
    }
    catch
    {
        if (($Error.Count -gt 0) -and ($Error[0].Exception.Message -like '*Unable to find type*'))
        {
            $testMode = 'Record';
        }
        else
        {
            throw;
        }
    }
    finally
    {
        $ErrorActionPreference = $oldErrorActionPreferenceValue;
    }

    return $testMode;
}

# Get Compute Test Location
function Get-ComputeTestLocation
{
    return $env:AZURE_COMPUTE_TEST_LOCATION;
}

# Cleans the created resource group
function Clean-ResourceGroup($rgname)
{
    Remove-AzureResourceGroup -Name $rgname -Force;
}

# Get Compute Test Tag
function Get-ComputeTestTag
{
    param ([string] $tagname)

    return @{ Name = $tagname; Value = (Get-Date).ToUniversalTime().ToString("u") };
}

######################
#
# Retry the given code block until it succeeds or times out.
#
#    param [ScriptBlock] $script : The code to test
#    param [int] $times          : The times of running the code
#    param [string] $message     : The text of the exception that should be thrown
#######################
function Retry-IfException
{
    param([ScriptBlock] $script, [int] $times = 30, [string] $message = "*")

    if ($times -le 0)
    {
        throw 'Retry time(s) should not be equal to or less than 0.';
    }

    $oldErrorActionPreferenceValue = $ErrorActionPreference;
    $ErrorActionPreference = "SilentlyContinue";

    $iter = 0;
    $succeeded = $false;
    while (($iter -lt $times) -and (-not $succeeded))
    {
        $iter += 1;

        &$script;

        if ($Error.Count -gt 0)
        {
            $actualMessage = $Error[0].Exception.Message;

            Write-Output ("Caught exception: '$actualMessage'");

            if (-not ($actualMessage -like $message))
            {
                $ErrorActionPreference = $oldErrorActionPreferenceValue;
                throw "Expected exception not received: '$message' the actual message is '$actualMessage'";
            }

            $Error.Clear();
            Wait-Seconds 10;
            continue;
        }

        $succeeded = $true;
    }

    $ErrorActionPreference = $oldErrorActionPreferenceValue;
}

<#
.SYNOPSIS
Gets random resource name
#>
function Get-RandomItemName
{
    param([string] $prefix = "crptestps")

    if ($prefix -eq $null -or $prefix -eq '')
    {
        $prefix = "crptestps";
    }

    $str = $prefix + ((Get-Random) % 10000);
    return $str;
}

<#
.SYNOPSIS
Gets default VM size string
#>
function Get-DefaultVMSize
{
    param([string] $location = "westus")

    $vmSizes = Get-AzureVMSize -Location $location | where { $_.NumberOfCores -ge 4 -and $_.MaxDataDiskCount -ge 8 };

    foreach ($sz in $vmSizes)
    {
        if ($sz.Name -eq 'Standard_A3')
        {
            return $sz.Name;
        }
    }

    return $vmSizes[0].Name;
}

<#
.SYNOPSIS
Gets default CRP Image
#>
function Get-DefaultCRPImage
{
    param([string] $loc = "westus", [string] $query = '*Microsoft*Windows*Server')

    $result = (Get-AzureVMImagePublisher -Location $loc) | select -ExpandProperty PublisherName | where { $_ -like $query };
    if ($result.Count -eq 1)
    {
        $defaultPublisher = $result;
    }
    else
    {
        $defaultPublisher = $result[0];
    }

    $result = (Get-AzureVMImageOffer -Location $loc -PublisherName $defaultPublisher) | select -ExpandProperty Offer | where { $_ -like '*Windows*' };
    if ($result.Count -eq 1)
    {
        $defaultOffer = $result;
    }
    else
    {
        $defaultOffer = $result[0];
    }

    $result = (Get-AzureVMImageSku -Location $loc -PublisherName $defaultPublisher -Offer $defaultOffer) | select -ExpandProperty Skus;
    if ($result.Count -eq 1)
    {
        $defaultSku = $result;
    }
    else
    {
        $defaultSku = $result[0];
    }

    $result = (Get-AzureVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku) | select -ExpandProperty Version;
    if ($result.Count -eq 1)
    {
        $defaultVersion = $result;
    }
    else
    {
        $defaultVersion = $result[0];
    }

    $vmimg = Get-AzureVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku -Version $defaultVersion;

    return $vmimg;
}

# Create Image Object
function Create-ComputeVMImageObject
{
    param ([string] $publisherName, [string] $offer, [string] $skus, [string] $version)

    $img = New-Object -TypeName 'Microsoft.Azure.Commands.Compute.Models.PSVirtualMachineImage';
    $img.PublisherName = $publisherName;
    $img.Offer = $offer;
    $img.Skus = $skus;
    $img.Version = $version;

    return $img;
}

# Get Default CRP Windows Image Object Offline
function Get-DefaultCRPWindowsImageOffline
{
    return Create-ComputeVMImageObject 'MicrosoftWindowsServer' 'WindowsServer' '2008-R2-SP1' 'latest';
}

# Get Default CRP Linux Image Object Offline
function Get-DefaultCRPLinuxImageOffline
{
    return Create-ComputeVMImageObject 'SUSE' 'openSUSE' '13.2' 'latest';
}

<#
.SYNOPSIS
Gets VMM Images
#>
function Get-MarketplaceImage
{
    param([string] $location = "westus", [string] $pubFilter = '*', [string] $offerFilter = '*')

    $imgs = Get-AzureVMImagePublisher -Location $location | where { $_.PublisherName -like $pubFilter } | Get-AzureVMImageOffer | where { $_.Offer -like $offerFilter } | Get-AzureVMImageSku | Get-AzureVMImage | Get-AzureVMImageDetail | where { $_.PurchasePlan -ne $null };

    return $imgs;
}

<#
.SYNOPSIS
Gets default VM config object
#>
function Get-DefaultVMConfig
{
    param([string] $location = "westus")

    # VM Profile & Hardware
    $vmsize = Get-DefaultVMSize $location;
    $vmname = Get-RandomItemName 'crptestps';

    $vm = New-AzureVMConfig -VMName $vmname -VMSize $vmsize;

    return $vm;
}

# Assert Output Contains
function Assert-OutputContains
{
    param([string] $cmd, [string[]] $sstr)

    $st = Write-Verbose ('Running Command : ' + $cmd);
    $output = Invoke-Expression $cmd | Out-String;

    $max_output_len = 1500;
    if ($output.Length -gt $max_output_len)
    {
        # Truncate Long Output in Logs
        $st = Write-Verbose ('Output String   : ' + $output.Substring(0, $max_output_len) + '...');
    }
    else
    {
        $st = Write-Verbose ('Output String   : ' + $output);
    }

    $index = 1;
    foreach ($str in $sstr)
    {
        $st = Write-Verbose ('Search String ' + $index++ + " : `'" + $str + "`'");
        Assert-True { $output.Contains($str) }
        $st = Write-Verbose "Found.";
    }
}


text:
require 'spec_helper'
describe 'languages::php' do

  context 'with defaults for all parameters' do
    it { should contain_class('languages::php') }
  end
end


text:
#ifndef QWINDOWSDIRECT2DBACKINGSTORE_H
#define QWINDOWSDIRECT2DBACKINGSTORE_H

#include "qwindowsdirect2dplatformpixmap.h"

#include <QtCore/QScopedPointer>
#include <QtGui/qpa/qplatformbackingstore.h>
#include <QtGui/QPixmap>

QT_BEGIN_NAMESPACE

class QWindowsDirect2DBackingStore : public QPlatformBackingStore
{
    Q_DISABLE_COPY(QWindowsDirect2DBackingStore)

public:
    QWindowsDirect2DBackingStore(QWindow *window);
    ~QWindowsDirect2DBackingStore();

    QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
    void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
    void resize(const QSize &size, const QRegion &staticContents) Q_DECL_OVERRIDE;

private:
    QScopedPointer<QPixmap> m_pixmap;
};

QT_END_NAMESPACE

#endif // QWINDOWSDIRECT2DBACKINGSTORE_H


text:
//
//  AlienNoteImporter.h
//  Notation
//
//  Created by Zachary Schneirov on 11/15/06.

#import <Cocoa/Cocoa.h>

extern NSString *PasswordWasRetrievedFromKeychainKey;
extern NSString *RetrievedPasswordKey;

@class NotationController;
@class NotationPrefs;
@class NoteObject;

@interface AlienNoteImporter : NSObject {
	IBOutlet NSButton *grabCreationDatesButton;
	IBOutlet NSView *importAccessoryView;

	SEL importerSelector;

	//for URL downloading
	id receptionDelegate;

	id source;
	NSMutableDictionary *documentSettings;
	BOOL shouldGrabCreationDates;

    BOOL shouldUseReadability;
}

//a directory containing notes, a custom bundle, or custom file format in which more than one note could be expected
- (id)initWithStoragePaths:(NSArray*)filenames;
- (id)initWithStoragePath:(NSString*)filename;
+ (void)importBlorOrHelpFilesIfNecessaryIntoNotation:(NotationController*)notation;
+ (AlienNoteImporter *)importerWithPath:(NSString*)path;
- (void)importNotesFromDialogAroundWindow:(NSWindow*)mainWindow receptionDelegate:(id)receiver;
- (void)importURLInBackground:(NSURL*)aURL linkTitle:(NSString*)linkTitle receptionDelegate:(id)receiver;
+ (NSString*)blorPath;

+ (NSBundle *)PDFKitBundle;
+ (Class)PDFDocClass;

- (NSView*)accessoryView;
- (NSDictionary*)documentSettings;
- (NSArray*)importedNotes;

- (NSArray*)notesWithPaths:(NSArray*)paths;
//where filename is a file expected to contain a single note (e.g., text, RTF, word)
- (NoteObject*)noteWithFile:(NSString*)filename;

- (NSArray*)notesInDirectory:(NSString*)filename;
- (NSArray*)notesInFile:(NSString*)filename;

- (BOOL)shouldUseReadability;
- (void)setShouldUseReadability:(BOOL)value;

- (NSString*) contentUsingReadability: (NSString *)htmlFile;
- (NSString*) markdownFromSource: (NSString *)htmlString;
- (NSString*) markdownFromHTMLFile: (NSString *)htmlFile;
@end

@interface AlienNoteImporter (DialogDelegate)
- (void)noteImporter:(AlienNoteImporter*)importer importedNotes:(NSArray*)notes;
@end


text:
<?php

namespace spec\Sylius\Component\Core\Resolver;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Core\Model\ShippingMethodInterface;
use Sylius\Component\Shipping\Exception\UnresolvedDefaultShippingMethodException;
use Sylius\Component\Shipping\Repository\ShippingMethodRepositoryInterface;
use Sylius\Component\Shipping\Resolver\DefaultShippingMethodResolverInterface;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
class DefaultShippingMethodResolverSpec extends ObjectBehavior
{
    function let(ShippingMethodRepositoryInterface $shippingMethodRepository)
    {
        $this->beConstructedWith($shippingMethodRepository);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Core\Resolver\DefaultShippingMethodResolver');
    }

    function it_implements_default_shipping_method_resolver_interface()
    {
        $this->shouldImplement(DefaultShippingMethodResolverInterface::class);
    }

    function it_returns_first_enabled_shipping_method_from_shipment_order_channel_as_default(
        ChannelInterface $channel,
        OrderInterface $order,
        ShipmentInterface $shipment,
        ShippingMethodInterface $firstShippingMethod,
        ShippingMethodInterface $secondShippingMethod,
        ShippingMethodInterface $thirdShippingMethod,
        ShippingMethodRepositoryInterface $shippingMethodRepository
    ) {
        $shippingMethodRepository
            ->findBy(['enabled' => true])
            ->willReturn([$firstShippingMethod, $secondShippingMethod, $thirdShippingMethod])
        ;

        $shipment->getOrder()->willReturn($order);
        $order->getChannel()->willReturn($channel);

        $channel->hasShippingMethod($firstShippingMethod)->willReturn(false);
        $channel->hasShippingMethod($secondShippingMethod)->willReturn(true);
        $channel->hasShippingMethod($thirdShippingMethod)->willReturn(true);

        $this->getDefaultShippingMethod($shipment)->shouldReturn($secondShippingMethod);
    }

    function it_throws_exception_if_there_is_no_enabled_shipping_methods(
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShipmentInterface $shipment
    ) {
        $shippingMethodRepository->findBy(['enabled' => true])->willReturn([]);

        $this
            ->shouldThrow(UnresolvedDefaultShippingMethodException::class)
            ->during('getDefaultShippingMethod', [$shipment])
        ;
    }

    function it_throws_exception_if_there_is_no_enabled_shipping_methods_for_channel(
        ChannelInterface $channel,
        OrderInterface $order,
        ShipmentInterface $shipment,
        ShippingMethodInterface $firstShippingMethod,
        ShippingMethodInterface $secondShippingMethod,
        ShippingMethodInterface $thirdShippingMethod,
        ShippingMethodRepositoryInterface $shippingMethodRepository
    ) {
        $shippingMethodRepository
            ->findBy(['enabled' => true])
            ->willReturn([$firstShippingMethod, $secondShippingMethod, $thirdShippingMethod])
        ;

        $shipment->getOrder()->willReturn($order);
        $order->getChannel()->willReturn($channel);

        $channel->hasShippingMethod($firstShippingMethod)->willReturn(false);
        $channel->hasShippingMethod($secondShippingMethod)->willReturn(false);
        $channel->hasShippingMethod($thirdShippingMethod)->willReturn(false);

        $this
            ->shouldThrow(UnresolvedDefaultShippingMethodException::class)
            ->during('getDefaultShippingMethod', [$shipment])
        ;
    }

    function it_throws_exception_if_passed_shipment_is_not_core_shipment_object(
        \Sylius\Component\Shipping\Model\ShipmentInterface $shipment
    ) {
        $this->shouldThrow(\InvalidArgumentException::class)->during('getDefaultShippingMethod', [$shipment]);
    }
}


text:
export function CanvasUtil(){
    function cached(recalculate){
        const data = {}
        return (...args)=>{
            const k = args.join(":")
            return k in data ? data[k] : (data[k] = recalculate.apply(this,args))
        }
    }
    function temp(recalculate){
        const data = {}
        function get(...args){
            const k = args.join(":")
            const value = k in data ? data[k].value : recalculate.apply(this,args)
            return (data[k] = { lastAccess: Date.now(), value }).value
        }
        function clearOlderThan(time){
            Object.keys(data).forEach(k=>{ if(data[k].lastAccess<time) delete data[k] })
        }
        return {get,clearOlderThan}
    }
    function never(){ throw ["not single"] }
    function setup(traits,joiningRules){
        const single = l => l.length === 1 ? l[0] : never()
        const h = {}
        const dst = {}
        traits(dst).forEach(o=>o && Object.keys(o).forEach(k=>(h[k]||(h[k]=[])).push(o[k])))
        Object.keys(h).forEach(k=>(dst[k] = (joiningRules[k]||single)(h[k])))
        return dst
    }
    return {cached,temp,setup}
}

export function CanvasFactory(util, modList){
    const mods = options => canvas => modList.map(f=>f(options)(canvas)).reduce((p,c)=>p.concat(c), [])
    return options => util.setup(mods(options), {
        drag        : l => frame => l.forEach(s=>s(frame)),
        processFrame: l => (frame,prev) => l.map(s=>s(frame,prev)),
        setupContext: l => opt => util.setup(utx=>l.map(s=>s(utx)).concat(opt), {}),
        setupFrame  : l => () => util.setup(frame=>l.map(s=>s()), {})
        //remove      : l => () => l.forEach(s=>s()),
    })
}

export function ExchangeCanvasSetup(canvas){
    function getViewPortRect(){
        return canvas.document().body.getBoundingClientRect()
    }
    return ({getViewPortRect})
}

//state.changedSizes && index >= parseInt(state.changedSizes.sent["X-r-index"]) ? {...state, changedSizes: null} : state
export function ResizeCanvasSetup(canvas){
    function minus(a,b){ return a.map((e,i)=>[e-b[i]]) }
    function isSimilarSizes(a,b){
        if(a == b) return true
        if(!a || !b) return false
        const d = minus(a.split(","), b.split(","))
        return d[0] == 0 && d[1] == 0 && d[2] == 0 && Math.abs(d[3]) < 8
    }
    function processFrame(frame,prev){
        if(!canvas.getSizesSyncEnabled()) return;
        const {zoom,parentPos,zoomIsChanging,pxPerEMZoom} = frame
        if(zoomIsChanging) return;
        const screenScale = canvas.zoomToScale(zoom)
        const cmdUnitsPerEMZoom = (pxPerEMZoom - zoom)|0
        const aspectRatio = canvas.calcPos(dir => parentPos.size[dir]|0)
        const pxMapH = ((canvas.fromServer().height||0)*screenScale)|0
        const sizes = [cmdUnitsPerEMZoom,aspectRatio.x,aspectRatio.y,pxMapH].join(",")
        if(!isSimilarSizes(canvas.fromServer().value, sizes))
            canvas.fromServer().onChange({ target: { value: sizes } })
    }
    return ({processFrame})
}

export function BaseCanvasSetup(log, util, canvas){
    let lastFrame
    let currentState = {}
    let fromServerVersion = 0
    let toRemove = []
    function getSizesSyncEnabled(){ return currentState.sizesSyncEnabled }
    function parentNode(){ return currentState.parentNode }
    function document(){ return canvas.parentNode().ownerDocument }
    function appendChild(el){
        regRemove(()=>el.parentNode && el.parentNode.removeChild(el))
        document().body.appendChild(el)
        el.style.position = "absolute"
    }
    function addEventListener(el,evName,handler,capture){
        regRemove(()=>el.removeEventListener(evName,handler,capture))
        el.addEventListener(evName,handler,capture)
    }

    const fontMeter = util.cached(()=>canvas.document().createElement('div'))
    function setupFontMeter(){
        const el = fontMeter()
        if(el.parentElement) return;
        el.style.cssText = "height:1em;padding:0px;margin:0px"
        appendChild(el)
    }

    function sendToServer(req,evColor){ return currentState.sendToServer({ headers: req },evColor)}

    function fromServer(){ return currentState.parsed }
    function checkActivate(state){
        if(currentState.parsed !== state.parsed) updateFromServerVersion()
        currentState = state

        if(!canvas.parentNode() || !canvas.getViewPortRect()) return state

        setupFontMeter()

        const newFrame = canvas.setupFrame()
        // in setupFrame we gather data from dom and place it to imm frame
        // in processFrame we use gathered data to update dom
        // diff is moved out of setupFrame, to allow merging data from different modules?
        canvas.processFrame(newFrame, lastFrame)
        lastFrame = newFrame
        //console.log("canvas-gen-time",Date.now()-startTime)
        return state
    }
    function regRemove(f){
        toRemove = [f,...toRemove]
    }
    function remove() {
        toRemove.forEach(f=>f())
    }

    ////
    function setupFrame(){
        return {startTime: Date.now(), fromServerVersion}
    }
    function processFrame(frame, prev){
        const canvasElement = canvas.visibleElement()
        if(!canvasElement.parentNode) {
            appendChild(canvasElement)
            if(canvas.setupCanvasElement) canvas.setupCanvasElement(canvasElement)
        }
        const same = canvas.compareFrames(frame,prev)
        const samePos = comparePos(same)
        if(!samePos(p=>p.viewExternalPos)){ //todo m. b. similarPos
            canvasElement.style.left = frame.viewExternalPos.x+"px"
            canvasElement.style.top = frame.viewExternalPos.y+"px"
        }
    }
    /*
	function getWindowScrollOffset(node){
		const w = node.ownerDocument.defaultView
		const x = w.scrollX
		const y = w.scrollY
		return {x,y}
	}
	    const scrollOffset = getWindowScrollOffset(canvasElement)
        const x = ( vExternalPos.x + scrollOffset.x )|0
        const y = ( vExternalPos.y + scrollOffset.y )|0
	*/
    function viewPositions(){
        const parentPos = canvas.elementPos(canvas.parentNode())
        const scrollPos = rectToPos(canvas.getViewPortRect())
        const vExternalPos = canvas.calcPos(dir=>Math.max(parentPos.pos[dir],scrollPos.pos[dir])|0)
        const canvasElement = canvas.visibleElement()
        const canvasPos = canvas.elementPos(canvasElement)
        const bias = canvas.calcPos(dir=>vExternalPos[dir]-canvasPos.pos[dir])
        const x = (parseInt(canvasElement.style.left)|0) + (bias.x|0)
        const y = (parseInt(canvasElement.style.top)|0) + (bias.y|0)
        const viewExternalPos = {x,y}
        //const parentPosEnd = { x: parentPos.end.x|0, y: infinite ? Infinity : parentPos.end.y|0 }
        const vExternalEnd = canvas.calcPos(dir=>Math.min(parentPos.end[dir],scrollPos.end[dir])|0)
        const viewExternalSize = canvas.calcPos(dir=>Math.max(0, vExternalEnd[dir] - vExternalPos[dir])|0)
        //
        const pxPerEMZoom = canvas.scaleToZoom(canvas.elementPos(fontMeter()).size.y)
        const fromServer = canvas.fromServer()
        const maxZoom = pxPerEMZoom - fromServer.minCmdUnitsPerEMZoom
        const mSize = canvas.mapSize()
        const minZooms = canvas.calcPos(dir=>Math.min(
            canvas.scaleToZoom(viewExternalSize[dir]/mSize[dir]),
            maxZoom
        ))
        const minZoom = Math.min(minZooms.x,minZooms.y)
        const initialZoom =
            fromServer.initialFit == "xy" ? minZoom :
            fromServer.initialFit == "x" ? minZooms.x : 0
        //
        return {viewExternalSize,viewExternalPos,scrollPos,parentPos,pxPerEMZoom,maxZoom,minZoom,initialZoom}
    }

    const composingElement = util.cached(name => createCanvas());
    function visibleElement(){ return canvas.composingElement("preparingCtx") }
    ////
    function calcPos(calc){ return { x:calc("x"), y:calc("y") } }
    function elementPos(element){ return rectToPos(element.getBoundingClientRect()) }
        //if(!element) return rectToPos({left:0,right:0,top:0,bottom:0,height:0,width:0})
    function rectToPos(p){
        return {pos:{x:p.left,y:p.top}, size:{x:p.width,y:p.height}, end:{x:p.right,y:p.bottom}}
    }
    function createCanvas(){ return canvas.document().createElement('canvas') }
    function fixCanvasSize(canvasElement,size){
        canvasElement.width = size.x
        canvasElement.height = size.y
    }
    function createCanvasWithSize(sz){
        const canvasElement = createCanvas()
        fixCanvasSize(canvasElement,sz)
        return canvasElement
    }
    function getContext(canvasElement){ return canvasElement.getContext("2d") }
    function cleanContext(ctx){
        ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height)
    }
    ////
    function setupContext(utx){ return {
        set(k,v){ utx.ctx[k] = v },
        definePath(name,commands){ utx[name] = () => utx.run(commands) },
        setMainContext(commands){ utx.ctx = utx.mainContext },
        inContext(name,commands){
            if(name !== utx.mainContextName) return;
            utx.ctx = utx.mainContext
            utx.ctx.save()
            utx.run(commands)
            utx.ctx.restore()
        },
        run(commands){
            for(let i=0; commands[i]; i+=2){
                const cmd = commands[i+1]
                const ctx = cmd in utx ? utx : utx.ctx
                ctx[cmd].apply(ctx, commands[i])
            }
        },
        draw(){
            const {mainScale,mainContext,mainTranslate,commands} = utx
            mainContext.save()
            mainContext.setTransform(mainScale, 0, 0, mainScale, mainTranslate.x, mainTranslate.y) // translate, scale
            utx.run(commands)
            mainContext.restore()
        }
    }}
    ////
    //...commandZoom, maxZoom from server
    function zoomToScale(zoom){
        return Math.exp((zoom||0)/fromServer().zoomSteps)
    }
    function scaleToZoom(scale){
        return Math.log(scale) * fromServer().zoomSteps
    }
    function mapSize(){
        return { x: Math.round(canvas.fromServer().width), y: Math.round(canvas.fromServer().height) }
    }
    function compareFrames(frame,prev){
        return cond => prev && cond(frame)===cond(prev)
    }
    function comparePos(same){
        return toPos => same(p=>toPos(p).x) && same(p=>toPos(p).y)
    }
    const filledElements = util.temp((fromServerVersion,tileZoom,mainContextName,x,y,w,h) => {
        //console.log("filledElements",tileZoom,mainContextName,x,y,w,h)
        const canvasElement = canvas.createCanvasWithSize({x:w,y:h})
        const mainContext = canvas.getContext(canvasElement)
        const commands = canvas.fromServer().commands || []
        const mainScale = canvas.zoomToScale(tileZoom)
        const viewTilePos = {x,y}
        const mainTranslate = canvas.calcPos(dir=>-viewTilePos[dir])
        canvas.setupContext({ mainContextName, mainContext, mainScale, mainTranslate, commands }).draw()
        return canvasElement
    })
    function composeFrameStart(frame,prev,ctxName,sameAdd){//viewPos need integers
        const {startTime,fromServerVersion,viewExternalSize,viewPos,zoom,zoomIsChanging,tileZoom} = frame
        const same = canvas.compareFrames(frame,prev)
        const samePos = comparePos(same)
        if(
            sameAdd && same(p=>p.fromServerVersion) &&
            samePos(p=>p.viewPos) && samePos(p=>p.viewExternalSize) &&
            same(p=>p.zoom) && same(p=>p.tileZoom)
        ) return;

        const canvasElement = canvas.composingElement(ctxName)
        //if(!samePos(p=>p.viewExternalSize)) log({viewExternalSize,ctxName})
        if(!samePos(p=>p.viewExternalSize)) fixCanvasSize(canvasElement,viewExternalSize) //todo: check size
        if(!viewExternalSize.x || !viewExternalSize.y) return;
        const ctx = canvas.getContext(canvasElement)
        canvas.cleanContext(ctx)
        //
        const tileScale = canvas.zoomToScale(tileZoom)
        const screenScale = canvas.zoomToScale(zoom)
        canvas.forTiles(frame, screenScale, tileScale, (tilePos,tileSize)=>{
            const srcElement = filledElements.get(fromServerVersion,tileZoom,ctxName,tilePos.x,tilePos.y,tileSize.x,tileSize.y)
            const dstPos = canvas.calcPos(dir=>tilePos[dir]/tileScale*screenScale-viewPos[dir])
            const dstSize = canvas.calcPos(dir=>tileSize[dir]/tileScale*screenScale)
            ctx.drawImage(srcElement,
                0, 0, tileSize.x, tileSize.y,
                dstPos.x, dstPos.y, dstSize.x, dstSize.y
            )
        })
        filledElements.clearOlderThan(startTime-2000)
        return ctx
    }
    function updateFromServerVersion(){ fromServerVersion++ }
    return {
        setupContext,cleanContext,getContext,calcPos,fromServer,
        composingElement,visibleElement,mapSize,createCanvasWithSize,
        setupFrame,processFrame,viewPositions,composeFrameStart,
        checkActivate, remove, addEventListener,
        zoomToScale, scaleToZoom,
        compareFrames, elementPos, updateFromServerVersion,
        parentNode, sendToServer, document, getSizesSyncEnabled
    }
}

export function ComplexFillCanvasSetup(util, canvas){
    const image = util.cached(url=>{
        const image = canvas.document().createElement("img")
        image.onload = () => canvas.updateFromServerVersion()
        image.src = url
        return image
    })
    const bgCanvas = util.cached((x,y)=>canvas.createCanvasWithSize({x,y}))
    function setupContext(utx){ return {
        definePattern(name,w,h,commands){
            if("preparingCtx" !== utx.mainContextName) return;
            utx.ctx = canvas.getContext(bgCanvas(w,h))
            canvas.cleanContext(utx.ctx)
            utx.run(commands)
            const pattern = utx.mainContext.createPattern(utx.ctx.canvas,"repeat")
            utx[name] = () => {
                if(utx.ctx === utx.mainContext) utx.ctx.fillStyle = pattern
                else throw 'bad ctx'
            }
        },
        linearGradient(x0, y0, x1, y1, stops){
            const grd = utx.ctx.createLinearGradient(x0, y0, x1, y1)
            stops.forEach(s=>grd.addColorStop(s[0], s[1]))
            utx.ctx.fillStyle = grd
        },
        image(name,url,x,y,w,h){
            if(name === utx.mainContextName){
                utx.mainContext.drawImage(image(url),x,y,w,h)
            }
        }
    }}
    return ({setupContext})
}

export function SingleTileCanvasSetup(canvas){
    function forTiles(frame, screenScale, tileScale, compose){
        const mapSize = canvas.mapSize()
        compose({x:0,y:0},canvas.calcPos(dir=>(mapSize[dir]*tileScale)|0))
    }
    return ({forTiles})
}

export function TiledCanvasSetup(canvas){
    function forTiles(frame, screenScale, tileScale, compose){
        const {viewPos,viewExternalSize} = frame
        const tileSize = { x: 2000, y: 1400 } // need to be < 2048 side and < 3M all for some devices
        const viewTilePos = canvas.calcPos(dir=> (viewPos[dir]/screenScale*tileScale)|0)
        const viewTileSize = canvas.calcPos(dir=> viewExternalSize[dir]/screenScale*tileScale)
        const viewEnd = canvas.calcPos(dir=> viewTilePos[dir] + viewTileSize[dir])
        const firstTilePos =
            canvas.calcPos(dir=> viewTilePos[dir] - viewTilePos[dir] % tileSize[dir])
        for(let x = firstTilePos.x; x < viewEnd.x; x+=tileSize.x)
            for(let y = firstTilePos.y; y < viewEnd.y; y+=tileSize.y)
                compose({x,y},tileSize)
    }
    return ({forTiles})
}

export function MouseCanvasSetup(log,canvas){
    let currentDrag = noDrag
    let mousePos = { x:0, y:0, t:0 }
    function mouseMove(ev){ currentDrag(ev,false) }
    function mouseUp(ev){ currentDrag(ev,true) }
    function getMousePos(){ return mousePos }
    function regMousePos(ev, prev){
        mousePos = { prev, x:ev.clientX, y:ev.clientY, t:Date.now() }
    }
    function noDrag(ev,isLast){
        regMousePos(ev, null)
    }
    function setCurrentDrag(f){ currentDrag = f || noDrag }
    function mouseDown(ev){
        regMousePos(ev, null)
        setCurrentDrag((ev,isLast) => {
            regMousePos(ev, canvas.getMousePos())
            canvas.drag({isLast,mousePos})
            //console.log("drag",isLast)
            if(isLast) setCurrentDrag(null)
        })
        ev.preventDefault()
    }
    function processFrame(frame, prev){
        if(prev) return;
        const win = canvas.document().defaultView
        canvas.addEventListener(win,"mousemove",mouseMove,false)
        canvas.addEventListener(win,"mouseup",mouseUp,false) // capture (true) causes popup close to be later
        canvas.addEventListener(canvas.visibleElement(),"mousedown", mouseDown)//ie selectstart?
    }
    function dMousePos(p1,p0){ return { x: p1.x-p0.x, y: p1.y-p0.y, t: p1.t-p0.t } }
    function findMousePos(pLast, cond){
        for(let p=pLast.prev;p;p=p.prev) if(cond(p)) return p
    }
    function relPos(el, pos){
        const rect = canvas.elementPos(el)
        return canvas.calcPos(dir=>pos[dir] - rect.pos[dir])
    }
    return {processFrame,dMousePos,findMousePos,getMousePos,relPos,mouseDown,mouseMove,mouseUp}
}

export function NoOverlayCanvasSetup(canvas){
    function processFrame(frame, prev){
        canvas.composeFrameStart(frame,prev,"preparingCtx",true)
    }
    function setupContext(utx){ return {
        over(evColor,commands){}
    }}
    return {setupContext,processFrame}
}

export function InteractiveCanvasSetup(canvas){
    function getImageData(mousePos){ //private
        const reactiveCanvasElement = canvas.composingElement("reactiveCtx")
        const reactiveContext = canvas.getContext(reactiveCanvasElement)
        const rPos = canvas.relPos(canvas.visibleElement(), mousePos)
        const data = reactiveContext.getImageData(rPos.x-1,rPos.y-1,3,3)
        function getColor(x,y){  //return;
            const p = (x+1)*4 + (y+1)*data.width*4
            return data.data[p+3]===255 ? "rgb("+data.data.slice(p,p+3).join(",")+")" : undefined
        }
        const color = getColor(0,0)
        if(color !== getColor(-1,0) && color !== getColor(1,0)) return;
        if(color !== getColor(0,-1) && color !== getColor(0,1)) return;
        return color
    }
    function drag(dragEvent){
        const mousePos = dragEvent.mousePos
        if(!dragEvent.isLast || canvas.findMousePos(mousePos, p => {
            const d = canvas.dMousePos(mousePos,p)
            //console.log(d)
            return d.t > 200 || d.x*d.x + d.y*d.y > 100
        })) return;
        const color = getImageData(mousePos)
        if(!color) return;
        const rPos = canvas.relPos(canvas.parentNode(), mousePos) // has zk id
        canvas.sendToServer({
            "X-r-canvas-color": color,
            "X-r-canvas-rel-x": rPos.x+"",
            "X-r-canvas-rel-y": rPos.y+"",
            "X-r-action": "clickColor"
        },color)
    }
    function setupFrame(){
        return {color: getImageData(canvas.getMousePos())}
    }
    function processFrame(frame, prev){
        if(frame.zoomIsChanging) return;
        const same = canvas.compareFrames(frame, prev)
        canvas.composeFrameStart(frame,prev,"reactiveCtx",same(p=>p.zoomIsChanging))
    }
    return {setupFrame,processFrame,drag}
}

export function ScrollViewPositionCanvasSetup(canvas){
    function setupFrame(){
        const viewPositions = canvas.viewPositions()
        const {scrollPos,parentPos,initialZoom} = viewPositions
        const viewPos = canvas.calcPos(dir=>Math.max(0, scrollPos.pos[dir] - parentPos.pos[dir])|0)
        //const targetViewPos
        const zoom = initialZoom
        const tileZoom = initialZoom
        return {...viewPositions,viewPos,tileZoom,zoom}
    }
    return ({setupFrame})
}

export function DragViewPositionCanvasSetup(log,canvas){
    let animation
    function setupFrame(){
        return (animation||animateStableZoom(initialZoom=>initialZoom,time=>canvas.calcPos(dir=>0)))(Date.now())
    }
    function dragPos(from,mousePos){
        const dPos = canvas.dMousePos(mousePos, mousePos.prev)
        const viewPos = canvas.calcPos(dir=>from.viewPos[dir] - dPos[dir])
        animation = animateStableZoom(initialZoom=>from.zoom, time=>viewPos)
    }
    function dropPos(from,mousePos){
        const mousePosR = canvas.findMousePos(mousePos, p => mousePos.t-p.t > 50)
        if(!mousePosR) return;
        const d = canvas.dMousePos(mousePos,mousePosR)
        const k = 300
        animation = animateStableZoom(initialZoom=>from.zoom, time => canvas.calcPos(dir => from.viewPos[dir] + d[dir] / d.t * k * (Math.exp((mousePos.t-time)/k)-1)))
    }
    function drag(dragEvent){
        if(canvas.extraDragIsActive && canvas.extraDragIsActive()) return;
        const mousePos = dragEvent.mousePos
        const from = canvas.setupFrame();
        (dragEvent.isLast?dropPos:dragPos)(from, mousePos)
    }
    function handleWheel(ev){
        if(!ev.ctrlKey) return;
        //if(!ev.altKey) return;
        const time = Date.now()
        const mousePos = { x:ev.clientX, y:ev.clientY, t:time }
        const mouseRelPos = canvas.relPos(canvas.visibleElement(), mousePos)
        const from = canvas.setupFrame()
        animation = animateChangingZoom(from, - Math.sign(ev.deltaY)/2, mouseRelPos)
        if(canvas.onZoom) canvas.onZoom() //todo to close popup?
		ev.preventDefault();
    }
    function limit(from, to){
        return value => Math.max(from, Math.min(value, to)) | 0
    }
    function limitPos(zoom, viewExternalSize, pos){
        const mapSize = canvas.mapSize()
        const screenScale = canvas.zoomToScale(zoom)
        const maxViewPos = canvas.calcPos(dir=> mapSize[dir]*screenScale - viewExternalSize[dir])
        return canvas.calcPos(dir => limit(0,maxViewPos[dir])(pos[dir]) )
    }
    function animateStableZoom(getZoom, getPos){//undefined+1 is NaN, NaN!==NaN
        return time => {
            const viewPositions = canvas.viewPositions()
            const {viewExternalSize,initialZoom} = viewPositions
            const zoom = getZoom(initialZoom)
            const viewPos = limitPos(zoom, viewExternalSize, getPos(time))
            return {...viewPositions,time,limitedTargetZoom:zoom,zoom,tileZoom:zoom,viewPos}
        }
    }
    function animateChangingZoom(from,d,mouseRelPos){
        const zoomSteps = canvas.fromServer().zoomSteps
        const targetZoom = from.limitedTargetZoom + d * zoomSteps
        const tempTileZoom = from.tileZoom > targetZoom ? targetZoom - zoomSteps : from.tileZoom
        const mapSize = canvas.mapSize()
        const fromScale = canvas.zoomToScale(from.zoom)
        const pointPos = canvas.calcPos(dir => (from.viewPos[dir]+mouseRelPos[dir])/fromScale)
        return time => {
            const viewPositions = canvas.viewPositions()
            const {viewExternalSize,minZoom,maxZoom} = viewPositions
            const animationPeriod = 200
            const passed = time - from.time
            const done = Math.min(passed/animationPeriod, 1)
            const zoomIsChanging = passed < 500
            const limitZoom = limit(minZoom, maxZoom)
            const zoom = limitZoom(targetZoom*done + from.zoom*(1-done))
            const tileZoom = limitZoom(zoomIsChanging ? tempTileZoom : targetZoom)
            const limitedTargetZoom = limitZoom(targetZoom)
            const scale = canvas.zoomToScale(zoom)
            const viewPos = limitPos(zoom, viewExternalSize, canvas.calcPos(dir => pointPos[dir]*scale - mouseRelPos[dir]))
            //log(d,from.limitedTargetZoom,targetZoom,limitedTargetZoom)
            return {...viewPositions,time,limitedTargetZoom,zoom,tileZoom,zoomIsChanging,viewPos}
        }
    }
    function processFrame(frame, prev){
        if(!prev) canvas.addEventListener(canvas.visibleElement(),"wheel", handleWheel)
    }
    return {drag,setupFrame,processFrame,handleWheel}
}


text:
'''
 this is a "file-blogging" platform copyright adam mathes
 begun 7/26/2010
 bits adapted from endless inkwell unreleased retroblogging platform

 ---
 10/12/2010 picked this up again
 added support for extended attributes from the filesystem (spotlight comments)
 cleaned up templates
 checked into git
'''

import ConfigParser
import sys, os, glob, re, datetime, math, json, Foundation
from Foundation import *
from optparse import OptionParser

deps = ['jinja2', 'markdown2', 'mutagen', 'bleach', 'xattr']
def missing_dependencies():
    missing = False
    for dep in deps:
        try:
            __import__(dep)
        except:
            missing = True
            print 'system is missing the module %s' % (dep)
    return missing

def install_dependencies():
    for dep in deps:
        try:
            __import__(dep)
        except:
            print 'trying to install %s now...' % (dep)
            command = 'sudo easy_install %s' % (dep)
            print(command)
            os.system(command)

class Settings:
    def __init__(self, config_file='settings.cfg', section='eio'):
        self.CONFIG_FILE = os.path.join(os.path.dirname(__file__), config_file)
        self.read_config(section)

    def read_config(self, section='eio'):

        self.config = ConfigParser.ConfigParser()
        config = self.config
        config.read(self.CONFIG_FILE)

        self.BASE_DIR = os.path.abspath(os.path.dirname(__file__))

        try:
            self.DESTINATION =  config.get(section, 'destination')
        except:
            self.DESTINATION = ''
        self.URL =  config.get(section, 'url')
        self.INPUT_DIR =  os.path.join(self.BASE_DIR, config.get(section, 'input'))
        self.OUTPUT_DIR =  os.path.join(self.BASE_DIR, config.get(section, 'output'))
        self.THEME_DIR =  os.path.join(self.BASE_DIR, config.get(section, 'themes'))
        self.LIST_TEMPLATE_DIR = os.path.join(self.THEME_DIR, 'list')

        try:
            self.DEFAULT_THEME = config.get(section, 'theme')
        except:
            self.DEFAULT_THEME = 'default.tpl'

        # set up templates
        self.env = jinja2.Environment(loader=jinja2.FileSystemLoader([self.THEME_DIR, self.LIST_TEMPLATE_DIR], encoding='utf-8'))

        self.DEFAULT_TEMPLATE = self.env.get_template(self.DEFAULT_THEME)

        try:
            self.TITLE = config.get(section, 'title')
        except:
            self.TITLE = 'endless i/o'

        try:
            self.DESCRIPTION = config.get(section, 'description')
        except:
            self.DESCRIPTION = ''

class PostRegistry:
    def __init__(self):
        self.post_types = dict()

    def register(self, extensions, post_type):
        for extension in extensions:
            self.post_types[extension] = post_type
post_registry = PostRegistry()

class Post:
    extensions = []

    def __init__(self, fp, site):
        self.site = site
        self.rp = os.path.relpath(fp, self.site.settings.INPUT_DIR).decode('utf-8')
        self.filename = os.path.basename(fp).decode('utf-8')
        self.directory = os.path.dirname(self.rp)
        self.permafile = self.rp + '.html'
        self.filepath = fp
        self.url = ("%s/%s" % ('files', self.rp))
        self.timestamp = os.path.getmtime(self.filepath)
        self.datetime = datetime.datetime.fromtimestamp(self.timestamp)
        self.prettydate = self.datetime.strftime("%B %e, %Y")
        self.prettytime = self.datetime.strftime("%l:%M %p")
        self.template = self.site.settings.DEFAULT_TEMPLATE
        self.type = 'default'
        self.__init_xattr__()

    def __init_xattr__(self):
        self.attribs = xattr.xattr(self.filepath)

        self.source_url = self.get_x_attr('com.apple.metadata:kMDItemWhereFroms')
        if self.source_url:
            self.source_url = self.source_url.replace('(', '')
            self.source_url = self.source_url.replace(')', '')
            self.source_url = self.source_url.replace('"', '')
            self.source_url = self.source_url.replace(' ', '')

        self.finder_comment = self.get_x_attr('com.apple.metadata:kMDItemFinderComment')
        if self.finder_comment:
            bl = Bleach()
            self.finder_comment = bl.linkify(self.finder_comment, nofollow=False)

    def get_x_attr(self, name):
        if name in self.attribs:
            plstr = self.attribs.get(name)
            pldata = NSData.dataWithBytes_length_(plstr, len(plstr))
            plist, format, error = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(pldata, NSPropertyListImmutable, None, None)
            return unicode(plist)
        else:
            return ''

    def render(self):
        posts = []
        posts.append(self)
        return(self.template.render(posts=posts, site=self.site, base=self.site.base_url(self.directory), directory=self.directory))

    def toast(self):
        out = self.render()
        outfile = os.path.join(self.site.settings.OUTPUT_DIR, self.rp + '.html')
        write_file(outfile, out)

class TextPost(Post):
    extensions = ['text']
    def __init__(self, fp, site):
        Post.__init__(self, fp, site)
        self.type = 'text'
        f = open(self.filepath)
        self.text = f.read()
        f.close()
post_registry.register(TextPost.extensions, TextPost)

class MarkdownPost(TextPost):
    extensions = ['md', 'txt']

    def __init__(self, fp, site):
        TextPost.__init__(self, fp, site)
        self.type = 'text'

        # TODO: this ASCII encoding hack is *not* OK, man! NOT OK
        self.markdown_text = markdown2.markdown(self.text).encode('ascii', 'ignore')
        bl = Bleach()
        self.markdown_text = bl.linkify(self.markdown_text, nofollow=False)
post_registry.register(MarkdownPost.extensions, MarkdownPost)

class ImagePost(Post):
    extensions = ['png', 'jpg', 'gif', 'jpeg', 'bmp', 'tiff']
    sizes = [100, 500, 800]

    def __init__(self, fp, site):
        Post.__init__(self, fp, site)
        self.type = 'image'
        self.resize()
        self.small = "%s/%s/%s" % ('img', '100', self.rp)
        self.medium = "%s/%s/%s" % ('img', '500', self.rp)
        self.large = "%s/%s/%s" % ('img', '800', self.rp)

    def resize(self):
        for size in self.sizes:
            outfile = os.path.join(self.site.settings.OUTPUT_DIR, 'img', str(size), self.rp)
            outdir = os.path.dirname(outfile)
            if not os.path.exists(outdir):
                os.makedirs(outdir)
            infile = os.path.join(self.site.settings.INPUT_DIR, self.rp)

            if(os.path.isfile(outfile)):
                pass
            else:
                try:
                    if size == 100:
                        cmd =  "sips --resampleHeight %d '%s' --out '%s'" % (size, infile, outfile)
                    else:
                        cmd = "sips --resampleWidth %d '%s' --out '%s'" % (size, infile, outfile)
                    os.system(cmd)

                except:
                    print 'uhoh, could not sips resize!'
post_registry.register(ImagePost.extensions, ImagePost)

class WeblocPost(TextPost):
    extensions = ['webloc']

    def __init__(self, fp, site):
        TextPost.__init__(self, fp, site)
        self.type = 'webloc'
        # uh... this is not an ideal way to parse resource forks but i was too lazy to do this properly
        # it almost certainly will not work in some cases. Oops!
        try:
            self.target_url = re.search("(?P<url>https?://[^\s]+)", self.text).group("url").encode('ascii', 'ignore')
        except:
            self.target_url = ''
post_registry.register(WeblocPost.extensions, WeblocPost)

class AudioPost(Post):
    extensions = ['mp3']

    # TODO - flash player instead of relying on HTML5 audio
    def __init__(self, fp, site):
        Post.__init__(self, fp, site)
        self.type = 'audio'

        a = EasyID3(os.path.join(self.site.settings.INPUT_DIR, self.rp))
        try:
            self.audio_title = a["title"][0]
        except:
            self.audio_title = ''
        try:
            self.audio_artist = a["artist"][0]
        except:
            self.audio_artist = ''
        try:
            self.audio_album = a["album"][0]
        except:
            self.audio_album = ''
post_registry.register(AudioPost.extensions, AudioPost)

class VideoPost(Post):
    extensions = ['mp4', 'mpeg']

    def __init__(self, fp, site):
        Post.__init__(self, fp, site)
        self.type = 'video'

post_registry.register(VideoPost.extensions, VideoPost)

class Archive:
    """

    Archive is a reperesentation of a list of posts The simplest
    archive outputs a single file based on a single template with
    access to the Site object

    """
    def __init__(self, template=None, output_filename=None, site=None):
        self.site = site
        self.template = self.site.settings.env.get_template(template)
        self.output_filename = output_filename

    def render(self, directory=''):
        return(self.template.render(site=self.site, posts=self.site.posts_in_directory(directory), directory=directory,
                                    base=self.site.base_url(directory)))

    def toast(self, directory=''):
        outfile = os.path.join(self.site.settings.OUTPUT_DIR, directory, self.output_filename)
        output = self.render(directory)
        write_file(outfile, output)

class PageArchive(Archive):
    """

    PageArchive is a reperesentation of a list of documents in bunches of
    n, or pages. Basically, the arcchive is like the front page of a
    blog that just keeps going on and on. Page 1 is the most recent N
    entries, page 2 is older, etc.

    """

    def render(self, posts, page, last_page, directory=''):
        if directory in self.site.overrides:
            try:
                theme = self.site.overrides[directory].get('overrides', 'theme')
                template = self.site.settings.env.get_template(theme)
            except:
                template = self.template
        else:
            template = self.template

        return(template.render(site=self.site, posts=posts, page=page, last_page=last_page,
                                    directory=directory, base=self.site.base_url(directory)))

    def toast(self, directory=''):
        # TODO: allow this page size to be overriden
        per_page = 15
        if directory in self.site.overrides:
            try:
                per_page = int(self.site.overrides[directory].get('overrides', 'per_page'))
            except:
                pass

        filtered_posts = self.site.posts_in_directory(directory)
        last_page =  int(math.floor(len(filtered_posts)/per_page) + 1)

        for i in range(1, last_page+1):
            outfile = os.path.join(self.site.settings.OUTPUT_DIR, directory, '%d.html' % i)
            page = i
            posts = filtered_posts[(i-1)*per_page:i*per_page]
            output = self.render(posts, page, last_page, directory)
            write_file(outfile, output)
            if i == 1:
                outfile = os.path.join(self.site.settings.OUTPUT_DIR, directory, 'index.html')
                write_file(outfile, output)

class Site:
    BLACKLIST_FILES = ['settings.cfg', 'Interim Note-Changes', '.DS_Store', 'Notes & Settings']

    def __init__(self, site_name='eio'):
        self.settings = Settings(section=site_name)
        self.url = self.settings.URL
        base = os.path.abspath(os.path.dirname(__file__))

        if not os.path.exists(self.settings.INPUT_DIR):
            os.makedirs(self.settings.INPUT_DIR)

        if not os.path.exists(self.settings.OUTPUT_DIR):
            os.makedirs(self.settings.OUTPUT_DIR)

        static = os.path.join(base, 'static')
        if not os.path.exists(os.path.join(self.settings.OUTPUT_DIR, 'static')):
            os.symlink(static, os.path.join(self.settings.OUTPUT_DIR, 'static'))

        if not os.path.exists(os.path.join(self.settings.OUTPUT_DIR, 'files')):
            os.symlink(self.settings.INPUT_DIR, os.path.join(self.settings.OUTPUT_DIR, 'files'))

        self.directories = []
        self.posts = []
        self.overrides = dict()

    def read_files(self, base_dir):
        files = os.listdir(base_dir)
        for f in files:
            fp = os.path.join(base_dir, f)
            rp = os.path.relpath(fp, self.settings.INPUT_DIR)
            if os.path.isdir(fp):
                self.directories.append(rp)
                self.read_files(fp)
            else:
                self.add_file(fp)

        self.posts.sort(key=lambda post: os.path.getmtime(post.filepath))
        self.posts.reverse()

    def add_file(self, fp):
        if os.path.basename(fp) in self.BLACKLIST_FILES:
            return

        extension = os.path.splitext(fp)[1]
        extension = extension.lower()
        extension = extension.replace('.', '')
        if extension in post_registry.post_types:
            p = post_registry.post_types[extension](fp=fp, site=self)
        else:
            p = Post(fp=fp, site=self)
        self.posts.append(p)

    def posts_in_directory(self, directory=None, recursive=False):
        # if directory == None or directory == '':
        #     return self.posts
        # else:
        filtered_posts = []
        for post in self.posts:
            if recursive and post.directory.startswith(directory):
                filtered_posts.append(post)

            if not recursive and post.directory == directory:
                filtered_posts.append(post)

        return filtered_posts

    def read_overrides(self):
        for directory in self.directories:
            override = os.path.join(self.settings.INPUT_DIR, directory, 'settings.cfg')
            if os.path.exists(override):
                config = ConfigParser.ConfigParser()
                config.read(override)
                self.overrides[directory] = config

    def generate(self):
        self.read_files(self.settings.INPUT_DIR)
        self.read_overrides()
        self.read_archives()
        self.generate_posts()
        self.generate_archives()

    def generate_posts(self):
        for p in self.posts:
            p.toast()

    def generate_archives(self):
        for a in self.archives:
            a.toast()
        for directory in self.directories:
            for a in self.archives:
                a.toast(directory)

    def read_archives(self):
        self.archives = []
        list_archive_templates = os.listdir(self.settings.LIST_TEMPLATE_DIR)
        for list_archive_template in list_archive_templates:
            output_filename = re.sub('.tpl', '', list_archive_template)
            template = os.path.join(self.settings.LIST_TEMPLATE_DIR, list_archive_template)
            archive = Archive(output_filename=output_filename, template=list_archive_template, site=self)
            self.archives.append(archive)
        pageArchive = PageArchive(output_filename='x.html', template=self.settings.DEFAULT_TEMPLATE, site=self)
        self.archives.append(pageArchive)

    def base_url(self, directory):
        if directory == '':
            return '.'
        depth = len(directory.split('/'))
        base = '../' * (depth)
        return base

    def sync(self):
        source = self.settings.OUTPUT_DIR
        destination = self.settings.DESTINATION
        if destination:
            rsync_command = 'rsync -auz -L %s/ %s' % (source, destination)
            print 'executing %s' % rsync_command
            os.system(rsync_command)

def write_file(outfile, output):
    try:
        outdir = os.path.dirname(outfile)
        if not os.path.exists(outdir):
            os.makedirs(outdir)

        f = open(outfile, 'w')
        f.write(output.encode('utf-8', 'ignore'))
        f.close()
    except IOError:
        print 'NO!!! could not write to %s' % outfile

def generate():
    site_names = get_site_names()
    for site_name in site_names:
        print 'generating %s' % site_name
        global s
        s = Site(site_name)
        s.generate()

def sync():
    site_names = get_site_names()
    for site_name in site_names:
        print 'generating %s' % site_name
        global s
        s = Site(site_name)
        s.sync()

def auto_launch():
    wd = os.path.abspath(__file__)
    watch_paths = ''
    site_names = get_site_names()
    for site_name in site_names:
        s = Site(site_name)
        files_directory = s.settings.INPUT_DIR
        watch_paths += '<string>%s</string>\n' % files_directory

    plist = '''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<dict>
        <key>Label</key>
        <string>org.trenchant.eio</string>
        <key>LowPriorityIO</key>
        <true/>
        <key>Program</key>
        <string>%s</string>
        <key>ProgramArguments</key>
        <array>
                <string>eio.py</string>
        </array>
        <key>WatchPaths</key>
        <array>
        %s
        </array>
</dict>
</plist>
''' % (wd, watch_paths)
    outfile = os.path.join(os.path.expanduser('~'), 'Library', 'LaunchAgents', 'org.trenchant.eio')
    write_file(outfile, plist)
    os.system('launchctl load -F %s ' % (outfile))

def stop_auto_launch():
    outfile = os.path.join(os.path.expanduser('~'), 'Library', 'LaunchAgents', 'org.trenchant.eio')
    os.system('launchctl unload %s ' % (outfile))

def get_site_names():
    config_file = os.path.join(os.path.dirname(__file__), 'settings.cfg')
    config = ConfigParser.ConfigParser()
    config.read(config_file)
    site_names = []
    for site_name in config.sections():
        if site_name != 'templates':
            site_names.append(site_name)
    return site_names

def main():

    usage ='eio.py [start|stop|generate|sync|bootstrap]'
    parser = OptionParser(usage)
    (options, args) = parser.parse_args()

    try:
        command = args[0]
    except:
        print usage
        command = 'both'

    if command == 'start':
        print 'starting...'
        auto_launch()
    elif command == 'stop':
        print 'stopping autolaunch'
        stop_auto_launch()
    elif command == 'generate':
        print 'generating site...'
        generate()
    elif command == 'sync':
        print 'syncing up...'
        sync()
    elif command == 'bootstrap':
        install_dependencies()
    else:
        print 'generating site...'
        generate()
        print 'syncing up...'
        sync()

if __name__ == "__main__":
    if missing_dependencies():
        confirmation = raw_input( 'you are missing required modules. try to install them now? [y/n]')
        if(confirmation == 'y'):
            install_dependencies()
    else:
        import jinja2
        import markdown2
        from bleach import Bleach
        from mutagen.easyid3 import EasyID3
        import xattr
        main()


text:
import copy

def zero_matrix_w_ds(M, N, given_matrix):
    zero_rows = {}
    zero_columns = {}
    for i in range(M):
        for j in range(N):
            if given_matrix[i][j] == 0:
                zero_rows[i] = True
                zero_columns[j] = True

    for i in zero_rows:
        for j in range(N):
            given_matrix[i][j] = 0

    for j in zero_columns:
        for i in range(M):
            given_matrix[i][j] = 0

    return given_matrix

def zero_matrix_wo_ds(M, N, given_matrix):
    first_col_zero = False
    first_row_zero = False

    for i in range(M):
        if given_matrix[i][0] == 0:
            first_col_zero = True

    for j in range(N):
        if given_matrix[0][j] == 0:
            first_row_zero = True

    for i in range(1, M):
        for j in range(1, N):
            if given_matrix[i][j] == 0:
                given_matrix[i][0] = 0
                given_matrix[0][j] = 0

    for i in range(1, M):
        if given_matrix[i][0] == 0:
            for j in range(N):
                given_matrix[i][j] = 0

    for j in range(1, N):
        if given_matrix[0][j] == 0:
            for i in range(M):
                given_matrix[i][j] = 0

    if first_col_zero:
        for i in range(M):
            given_matrix[i][0] = 0

    if first_row_zero:
        for i in range(N):
            given_matrix[0][j] = 0

    return given_matrix

if __name__ == '__main__':
    M = int(raw_input("Enter value of M in MxN matrix: "))
    N = int(raw_input("Enter value of N in MxN matrix: "))
    given_matrix = []
    for i in range(M):
        given_matrix.append([])
        for j in range(N):
            given_matrix[i].append(int(raw_input("Enter value at index ({}, {}): ".format(i, j))))

    print "Given Matrix: {}".format(given_matrix)

    given_matrix_w_ds = copy.deepcopy(given_matrix)
    given_matrix_wo_ds = copy.deepcopy(given_matrix)

    print "Zero Matrix (with additional data structures) is: {result}".format(result=zero_matrix_w_ds(M, N, given_matrix_w_ds))
    print "Zero Matrix (without additional data structures) is: {result}".format(result=zero_matrix_wo_ds(M, N, given_matrix_wo_ds))


text:
set -euxo pipefail

# Check tar is in PATH
command -v jar

source Version.txt

OUTPUT_DIR="docs/javadoc"
rm -rf ${OUTPUT_DIR}
mkdir -p ${OUTPUT_DIR}

ARCHIVE=$(find "build_make/java/ortools-java/target" -iname "ortools-java-${OR_TOOLS_MAJOR}.${OR_TOOLS_MINOR}.*-javadoc.jar")
(cd ${OUTPUT_DIR} && jar -xvf "../../${ARCHIVE}")


text:
require 'tfl/api/station_locations'

module Tfl
  module API
    include Tfl::API::StationLocations
  end
end


text:
<?php

declare(strict_types = 1);

namespace unreal4u\TelegramBots\Bots\UptimeMonitor\Setup;

use unreal4u\TelegramAPI\Abstracts\TelegramMethods;
use unreal4u\TelegramBots\Bots\UptimeMonitor\Common;

class Step3 extends Common {
    public function generateAnswer(): TelegramMethods
    {
        $this->response->text = sprintf(
            'Now you just have to add in each monitor the recently created Contact. This can be done by going to one '.
            'of the monitors, and selecting the recently created web-hook as a contact.%sYou will now receive any '.
            'notifications on the channel where you configured the notification URL, enjoy!',
            PHP_EOL
        );
        $this->response->disable_web_page_preview = true;
        $this->response->parse_mode = 'Markdown';

        $this->logger->debug('Response ready');
        return $this->response;
    }
}


text:
.quest_info_table {
	display: table;
}

.quest_info_row {
	display: table-row;
	padding: 3px;
	text-decoration: none;
	margin:3px 3px 3px 3px;
}

.quest_info_row_admin {
  background: #cccccc;
}

.quest_info_row_skip {
	display: table-row;
	background: inherit;
	height: 20px;
}

.quest_info_param {
	display: table-cell;
	padding: 8px;
	text-align: right;
}

.quest_info_value {
	display: table-cell;
	padding:8px;
	text-align: left;
}


text:
using System.Collections.Generic;

///This view model class has been referred from example created by Marien Monnier at Soft.it. All credits to Marien for this class
namespace Freelancer.Web.Areas.Admin.ViewModels.DataTable
{
    /// <summary>
    /// A full result, as understood by jQuery DataTables.
    /// </summary>
    /// <typeparam name="T">The data type of each row.</typeparam>
    public class DTResult<T>
    {
        /// <summary>
        /// The draw counter that this object is a response to - from the draw parameter sent as part of the data request.
        /// Note that it is strongly recommended for security reasons that you cast this parameter to an integer, rather than simply echoing back to the client what it sent in the draw parameter, in order to prevent Cross Site Scripting (XSS) attacks.
        /// </summary>
        public int draw { get; set; }

        /// <summary>
        /// Total records, before filtering (i.e. the total number of records in the database)
        /// </summary>
        public int recordsTotal { get; set; }

        /// <summary>
        /// Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).
        /// </summary>
        public int recordsFiltered { get; set; }

        /// <summary>
        /// The data to be displayed in the table.
        /// This is an array of data source objects, one for each row, which will be used by DataTables.
        /// Note that this parameter's name can be changed using the ajaxDT option's dataSrc property.
        /// </summary>
        public List<T> data { get; set; }
    }

}


text:
import xlrd
import sys
from pprint import pprint

def GenerateAFFont():
    """
    Open up the sampler sheet supplied, read in the sizes and determine the factors from there..
    """
    if len(sys.argv) != 2:
        print 'Usage: GenerateAFFont [SampleSheet.xls]'
        sys.exit()

    # Get the workbook file name from the command line
    fileName = sys.argv[1]

    if not fileName.lower().endswith('.xls'):
        fileName = '%s.xls' % fileName

    try:
        sampleBook = xlrd.open_workbook(fileName, formatting_info=True)
    except IOError:
        print 'Failed to open Excel sample sheet %s' % fileName
        sys.exit()

    if sampleBook._all_sheets_count is not 6:
        print 'Invalid Sample Workbook format - must be generated by CreateLearningSheet and contain 6 Sheets'
        sys.exit()

    # Read it in and process it
    charMapping = {}
    gutter = 190
    creepDivisor = 50.00

    # Normal UPPER
    sheet = sampleBook.sheet_by_index(0)
    letterValue = 65
    for col in range(0, 51, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter] = [(round(width10, 4), creepFactor)]
        letterValue += 1

    # Normal lower
    sheet = sampleBook.sheet_by_index(1)
    letterValue = 97
    for col in range(0, 51, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter] = [(round(width10, 4), creepFactor)]
        letterValue += 1

    # Normal Other
    sheet = sampleBook.sheet_by_index(2)
    letterValue = 32
    for col in range(0, 66, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter] = [(round(width10, 4), creepFactor)]
        letterValue += 1

    # Bold UPPER
    sheet = sampleBook.sheet_by_index(3)
    letterValue = 65
    for col in range(0, 51, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter].append((round(width10, 4), creepFactor))
        letterValue += 1

    # Normal lower
    sheet = sampleBook.sheet_by_index(4)
    letterValue = 97
    for col in range(0, 51, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter].append((round(width10, 4), creepFactor))
        letterValue += 1

    # Normal Other
    sheet = sampleBook.sheet_by_index(5)
    letterValue = 32
    for col in range(0, 66, 2):
        width10 = (sheet.colinfo_map[col].width - gutter) / 10.00
        width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00
        creepFactor = round((width10 - width100) / creepDivisor, 4)
        letter = chr(letterValue)
        charMapping[letter].append((round(width10, 4), creepFactor))
        letterValue += 1

    print
    print '=' * 40
    pprint(charMapping)
    print '=' * 40
    print
    print 'CUT the ^above^ dict and paste it into your new AFFont class code where indicated'

if __name__ == '__main__':
    GenerateAFFont()


text:
package com.wut.resources;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.wut.model.Data;
import com.wut.model.map.MessageData;
import com.wut.model.message.ErrorData;
import com.wut.model.scalar.StringData;
import com.wut.pipeline.WutRequest;
import com.wut.resources.common.MissingParameterException;
import com.wut.resources.common.OperationIdentifier;
import com.wut.resources.common.WutOperation;
import com.wut.resources.common.WutResource;
import com.wut.support.ErrorHandler;
import com.wut.support.annotations.ClassPreamble;
import com.wut.support.performance.PerformanceTimer;

// TODO Rename ResourceManager
@ClassPreamble (author = "Russell Palmiter", date="12/2008")
public class ResourceFactory {
	private PerformanceTimer monitor = PerformanceTimer.create(getClass());
	private Map<OperationIdentifier, WutOperation> operations = new HashMap<OperationIdentifier, WutOperation>();
	private Collection<WutResource> resources = new ArrayList<WutResource>();
	private static ResourceFactory singleton = new ResourceFactory();

	// TODO abstract all resources away from the datasource (or provider) of data

	private ResourceFactory() {
		try {
//			addResource(new DiagnosticResource());
//			addResource(new SettingsResource());
//			//addResourceGroup("admin", new ServerInitializationResource());
//			addResource(new PerformanceResource());
//			addResource(new EmailResource());
//			//addResourceGroup("geocode", new GeocodeResource()); // TODO fix
//			addResource(new HelpResource());
//			addResource(new PhotoSearchResource());
//			addResource(new SinglePhotoResource());
//			addResource(new WebSearchResource());
//			addResource(new HashResource());
//			addResource(new PageGenerator());
////		addResource(new AuthenticationResource());
//			addResource(new YetAnotherDatabaseResource());
//			//addResource(new RudResource("schema", new SchemaStore()));
//			addResource(new UsersResource());
//			addResource(new ComponentResource());
//			addResource(new ApplicationResource("application", null));
//			addResource(new CrudResource("application.component", new ApplicationComponentStore()));
//			addResource(new com.wut.resources.application.ComponentResource("component", new ApplicationComponentStore()));
//
//			// STORAGE
//			addResource(new TableResource());
//			addResource(new ScalarResource());
//
//			// PAYMENT
//			//addResource(new OldPaymentResource());
//			addResource(new PaymentResource());
//
//			// TEMPLATE
//			addResource(new TemplateResource());
//
//			// FILE
//			//addResource(new FileBasedResource("file"));
//
//			addResource(new FileResource());

		} catch (Exception e) {
			System.err.println("Error initializing a resource");
			e.printStackTrace();
			ErrorHandler.systemError(e, "Error initializing a resource");
		}
	}

	public static ResourceFactory getInstance() {
		return singleton;
	}

	public void addResource(WutResource resource) {
		// TODO initialize elsewhere????
		boolean initialized = resource.initialize();
		if (!initialized) {
			ErrorHandler.fatalError("resource " + resource.getName() + " failed to initialize");
		}
		resources.add(resource);
		String resName = resource.getName();
		for (WutOperation op : resource.getOperations()) {
			String opName = op.getName();
			OperationIdentifier opId = new OperationIdentifier(resName, opName);
			operations.put(opId, op);
		}
	}

	public WutResource getResource(String name) {
		for (WutResource r : resources) {
			if (r.getName().equals(name)) {
				return r;
			}
		}
		return null;
	}

	public Collection<WutResource> getResources() {
		return resources;
	}

	public WutOperation getOperation(OperationIdentifier opId) {
		return operations.get(opId);
	}

	public boolean checkResourceValid(WutRequest request) {
		String name = request.getResource();
		WutResource resource = getResource(name);
		if (resource == null) {
			return false;
		} else {
			return true;
		}
	}

	public OperationIdentifier getOperationId(WutRequest request) {
		String resource = request.getResource();
		String operation = request.getAction().toLowerCase();
		OperationIdentifier opId = new OperationIdentifier(resource, operation);
		return opId;
	}

	public boolean checkOperationValid(WutRequest request) {
		OperationIdentifier opId = getOperationId(request);

		WutOperation op = getOperation(opId);
		if (op == null) {
			return false;
		} else {
			return true;
		}
	}

	// TODO move this function into the processing pipeline under a new process
	// TODO move this back here?
	public Data performRequest(WutRequest request) {
		boolean isValidResource = checkResourceValid(request);
		if (!isValidResource) {
			return new MessageData("Invalid resource " + request.getResource()
					+ ". Available resources include:"
					+ getResources());
		}

		boolean isValidOperation = checkOperationValid(request);

		if (!isValidOperation) {
			return new MessageData(
					"invalid operation. avaible operation are: "
							+ getResource(request.getResource()).getOperations());
		}

		// start timing request
		String groupPlusName = request.getResource();
		monitor.start(groupPlusName);

		// 2. process request
		Data data = null;
		try {
			OperationIdentifier opId = getOperationId(request);
			WutOperation op = getOperation(opId);
			data = op.perform(request);
		} catch (MissingParameterException e) {
			return new ErrorData(e);
		} catch (Exception e) {
			final String msg = "failed request due to " + e;
			ErrorHandler.userError(request, msg, e);
			MessageData err = ErrorData.error(msg);
			err.setData(new StringData(msg));
			return err;
		} finally {
			monitor.stop(groupPlusName);
		}

		// Logger logger = Logger.getLogger("com.mycompany");

		return data;
	}
}


text:
#!/usr/bin/python
#
# klockstat traces lock events and display locks statistics.
#
# USAGE: klockstat
#

from __future__ import print_function
from bcc import BPF, USDT
import argparse
import subprocess
import ctypes as ct
from time import sleep, strftime
from datetime import datetime, timedelta
import errno
from sys import stderr

examples = """
    klockstat                           # trace system wide
    klockstat -d 5                      # trace for 5 seconds only
    klockstat -i 5                      # display stats every 5 seconds
    klockstat -p 123                    # trace locks for PID 123
    klockstat -t 321                    # trace locks for PID 321
    klockstat -c pipe_                  # display stats only for lock callers with 'pipe_' substring
    klockstat -S acq_count              # sort lock acquired results on acquired count
    klockstat -S hld_total              # sort lock held results on total held time
    klockstat -S acq_count,hld_total    # combination of above
    klockstat -n 3                      # display 3 locks
    klockstat -s 3                      # display 3 levels of stack
"""

# arg validation
def positive_int(val):
    try:
        ival = int(val)
    except ValueError:
        raise argparse.ArgumentTypeError("must be an integer")

    if ival < 0:
        raise argparse.ArgumentTypeError("must be positive")
    return ival

def positive_nonzero_int(val):
    ival = positive_int(val)
    if ival == 0:
        raise argparse.ArgumentTypeError("must be nonzero")
    return ival

def stack_id_err(stack_id):
    # -EFAULT in get_stackid normally means the stack-trace is not available,
    # Such as getting kernel stack trace in userspace code
    return (stack_id < 0) and (stack_id != -errno.EFAULT)

parser = argparse.ArgumentParser(
    description="",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=examples)

time_group = parser.add_mutually_exclusive_group()
time_group.add_argument("-d", "--duration", type=int,
    help="total duration of trace in seconds")
time_group.add_argument("-i", "--interval", type=int,
    help="print summary at this interval (seconds)")
parser.add_argument("-n", "--locks", type=int, default=99999999,
    help="print given number of locks")
parser.add_argument("-s", "--stacks", type=int, default=1,
    help="print given number of stack entries")
parser.add_argument("-c", "--caller",
    help="print locks taken by given caller")
parser.add_argument("-S", "--sort",
    help="sort data on <aq_field,hd_field>, fields: acq_[max|total|count] hld_[max|total|count]")
parser.add_argument("-p", "--pid",
    help="trace this PID only")
parser.add_argument("-t", "--tid",
    help="trace this TID only")
parser.add_argument("--stack-storage-size", default=16384,
    type=positive_nonzero_int,
    help="the number of unique stack traces that can be stored and "
         "displayed (default 16384)")

args = parser.parse_args()

program = """
#include <uapi/linux/ptrace.h>

struct depth_id {
  u64 id;
  u64 depth;
};

BPF_ARRAY(enabled,   u64, 1);
BPF_HASH(track,      u64, u64);
BPF_HASH(time_aq,    u64, u64);
BPF_HASH(lock_depth, u64, u64);
BPF_HASH(time_held,  struct depth_id, u64);
BPF_HASH(stack,      struct depth_id, int);

BPF_HASH(aq_report_count, int, u64);
BPF_HASH(aq_report_max,   int, u64);
BPF_HASH(aq_report_total, int, u64);

BPF_HASH(hl_report_count, int, u64);
BPF_HASH(hl_report_max,   int, u64);
BPF_HASH(hl_report_total, int, u64);

BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);

static bool is_enabled(void)
{
    int key = 0;
    u64 *ret;

    ret = enabled.lookup(&key);
    return ret && *ret == 1;
}

static bool allow_pid(u64 id)
{
    u32 pid = id >> 32; // PID is higher part
    u32 tid = id;       // Cast and get the lower part

    FILTER

    return 1;
}

static int do_mutex_lock_enter(void *ctx, int skip)
{
    if (!is_enabled())
        return 0;

    u64 id = bpf_get_current_pid_tgid();

    if (!allow_pid(id))
        return 0;

    u64 one = 1, zero = 0;

    track.update(&id, &one);

    u64 *depth = lock_depth.lookup(&id);

    if (!depth) {
        lock_depth.update(&id, &zero);

        depth = lock_depth.lookup(&id);
        /* something is wrong.. */
        if (!depth)
            return 0;
    }

    int stackid = stack_traces.get_stackid(ctx, skip);
    struct depth_id did = {
      .id    = id,
      .depth = *depth,
    };
    stack.update(&did, &stackid);

    u64 ts = bpf_ktime_get_ns();
    time_aq.update(&id, &ts);

    *depth += 1;
    return 0;
}

static void update_aq_report_count(int *stackid)
{
    u64 *count, one = 1;

    count = aq_report_count.lookup(stackid);
    if (!count) {
        aq_report_count.update(stackid, &one);
    } else {
        *count += 1;
    }
}

static void update_hl_report_count(int *stackid)
{
    u64 *count, one = 1;

    count = hl_report_count.lookup(stackid);
    if (!count) {
        hl_report_count.update(stackid, &one);
    } else {
        *count += 1;
    }
}

static void update_aq_report_max(int *stackid, u64 time)
{
    u64 *max;

    max = aq_report_max.lookup(stackid);
    if (!max || *max < time)
        aq_report_max.update(stackid, &time);
}

static void update_hl_report_max(int *stackid, u64 time)
{
    u64 *max;

    max = hl_report_max.lookup(stackid);
    if (!max || *max < time)
        hl_report_max.update(stackid, &time);
}

static void update_aq_report_total(int *stackid, u64 delta)
{
    u64 *count, *time;

    count = aq_report_count.lookup(stackid);
    if (!count)
        return;

    time = aq_report_total.lookup(stackid);
    if (!time) {
        aq_report_total.update(stackid, &delta);
    } else {
        *time = *time + delta;
    }
}

static void update_hl_report_total(int *stackid, u64 delta)
{
    u64 *count, *time;

    count = hl_report_count.lookup(stackid);
    if (!count)
        return;

    time = hl_report_total.lookup(stackid);
    if (!time) {
        hl_report_total.update(stackid, &delta);
    } else {
        *time = *time + delta;
    }
}

static int do_mutex_lock_return(void)
{
    if (!is_enabled())
        return 0;

    u64 id = bpf_get_current_pid_tgid();

    if (!allow_pid(id))
        return 0;

    u64 *one = track.lookup(&id);

    if (!one)
        return 0;

    track.delete(&id);

    u64 *depth = lock_depth.lookup(&id);
    if (!depth)
        return 0;

    struct depth_id did = {
      .id    = id,
      .depth = *depth - 1,
    };

    u64 *aq = time_aq.lookup(&id);
    if (!aq)
        return 0;

    int *stackid = stack.lookup(&did);
    if (!stackid)
        return 0;

    int stackid_ = *stackid;
    u64 cur = bpf_ktime_get_ns();

    if (cur > *aq) {
        int val = cur - *aq;
        update_aq_report_count(&stackid_);
        update_aq_report_max(&stackid_, val);
        update_aq_report_total(&stackid_, val);
    }

    time_held.update(&did, &cur);
    return 0;
}

static int do_mutex_unlock_enter(void)
{
    if (!is_enabled())
        return 0;

    u64 id = bpf_get_current_pid_tgid();

    if (!allow_pid(id))
        return 0;

    u64 *depth = lock_depth.lookup(&id);

    if (!depth || *depth == 0)
        return 0;

    *depth -= 1;

    struct depth_id did = {
      .id    = id,
      .depth = *depth,
    };

    u64 *held = time_held.lookup(&did);
    if (!held)
        return 0;

    int *stackid = stack.lookup(&did);
    if (!stackid)
        return 0;

    int stackid_ = *stackid;
    u64 cur = bpf_ktime_get_ns();

    if (cur > *held) {
        u64 val = cur - *held;
        update_hl_report_count(&stackid_);
        update_hl_report_max(&stackid_, val);
        update_hl_report_total(&stackid_, val);
    }

    stack.delete(&did);
    time_held.delete(&did);
    return 0;
}
"""

program_kprobe = """
int mutex_unlock_enter(struct pt_regs *ctx)
{
    return do_mutex_unlock_enter();
}

int mutex_lock_return(struct pt_regs *ctx)
{
    return do_mutex_lock_return();
}

int mutex_lock_enter(struct pt_regs *ctx)
{
    return do_mutex_lock_enter(ctx, 0);
}
"""

program_kfunc = """
KFUNC_PROBE(mutex_unlock, void *lock)
{
    return do_mutex_unlock_enter();
}

KRETFUNC_PROBE(mutex_lock, void *lock, int ret)
{
    return do_mutex_lock_return();
}

KFUNC_PROBE(mutex_lock, void *lock)
{
    return do_mutex_lock_enter(ctx, 3);
}

"""

is_support_kfunc = BPF.support_kfunc()
if is_support_kfunc:
    program += program_kfunc
else:
    program += program_kprobe

def sort_list(maxs, totals, counts):
    if (not args.sort):
        return maxs;

    for field in args.sort.split(','):
        if (field == "acq_max" or field == "hld_max"):
            return maxs
        if (field == "acq_total" or field == "hld_total"):
            return totals
        if (field == "acq_count" or field == "hld_count"):
            return counts

    print("Wrong sort argument: %s", args.sort)
    exit(-1)

def display(sort, maxs, totals, counts):
    global missing_stacks
    global has_enomem

    for k, v in sorted(sort.items(), key=lambda sort: sort[1].value, reverse=True)[:args.locks]:
        missing_stacks += int(stack_id_err(k.value))
        has_enomem      = has_enomem or (k.value == -errno.ENOMEM)

        caller = "[Missed Kernel Stack]"
        stack  = []

        if (k.value >= 0):
            stack  = list(stack_traces.walk(k.value))
            caller = b.ksym(stack[1], show_offset=True)

            if (args.caller and caller.find(args.caller.encode())):
                continue

        avg = totals[k].value / counts[k].value

        print("%40s %10lu %6lu %10lu %10lu" % (caller, avg, counts[k].value, maxs[k].value, totals[k].value))

        for addr in stack[2:args.stacks]:
            print("%40s" %  b.ksym(addr, show_offset=True))

if args.tid:  # TID trumps PID
    program = program.replace('FILTER',
        'if (tid != %s) { return 0; }' % args.tid)
elif args.pid:
    program = program.replace('FILTER',
        'if (pid != %s) { return 0; }' % args.pid)
else:
    program = program.replace('FILTER', '')

program = program.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))

b = BPF(text=program)

if not is_support_kfunc:
    b.attach_kprobe(event="mutex_unlock",  fn_name="mutex_unlock_enter")
    b.attach_kretprobe(event="mutex_lock", fn_name="mutex_lock_return")
    b.attach_kprobe(event="mutex_lock",    fn_name="mutex_lock_enter")

enabled = b.get_table("enabled");

stack_traces = b.get_table("stack_traces")
aq_counts = b.get_table("aq_report_count")
aq_maxs   = b.get_table("aq_report_max")
aq_totals = b.get_table("aq_report_total")

hl_counts = b.get_table("hl_report_count")
hl_maxs   = b.get_table("hl_report_max")
hl_totals = b.get_table("hl_report_total")

aq_sort = sort_list(aq_maxs, aq_totals, aq_counts)
hl_sort = sort_list(hl_maxs, hl_totals, hl_counts)

print("Tracing lock events... Hit Ctrl-C to end.")

# duration and interval are mutualy exclusive
exiting = 0 if args.interval else 1
exiting = 1 if args.duration else 0

seconds = 99999999
if args.interval:
    seconds = args.interval
if args.duration:
    seconds = args.duration

missing_stacks = 0
has_enomem     = False

while (1):
    enabled[ct.c_int(0)] = ct.c_int(1)

    try:
        sleep(seconds)
    except KeyboardInterrupt:
        exiting = 1

    enabled[ct.c_int(0)] = ct.c_int(0)

    print("\n%40s %10s %6s %10s %10s" % ("Caller", "Avg Spin", "Count", "Max spin", "Total spin"))
    display(aq_sort, aq_maxs, aq_totals, aq_counts)

    print("\n%40s %10s %6s %10s %10s" % ("Caller", "Avg Hold", "Count", "Max hold", "Total hold"))
    display(hl_sort, hl_maxs, hl_totals, hl_counts)

    if exiting:
        break;

    stack_traces.clear()
    aq_counts.clear()
    aq_maxs.clear()
    aq_totals.clear()
    hl_counts.clear()
    hl_maxs.clear()
    hl_totals.clear()

if missing_stacks > 0:
    enomem_str = " Consider increasing --stack-storage-size."
    print("WARNING: %d stack traces lost and could not be displayed.%s" %
        (missing_stacks, (enomem_str if has_enomem else "")),
        file=stderr)


text:
<?php

declare(strict_types=1);

use UliCMS\Utils\CacheUtil;

class ExpertSettingsController extends Controller
{
    const LIST_ACTION = "settings";

    public function _save(?string $name = null, $value = null): void
    {
        if (StringHelper::isNotNullOrWhitespace($name) && !is_null($value)) {
            Settings::set($name, $value);
            CacheUtil::clearPageCache();
        }
    }

    public function save(): void
    {
        $name = Request::getVar("name");
        $value = Request::getVar("value");
        $this->_save($name, $value);

        Request::redirect(ModuleHelper::buildActionURL(self::LIST_ACTION));
    }

    public function _delete(?string $name = null): void
    {
        if (!is_null($name)) {
            Settings::delete($name);
            CacheUtil::clearPageCache();
        }
    }

    public function delete(): void
    {
        $name = Request::getVar("name");
        $this->_delete($name);

        Request::redirect(ModuleHelper::buildActionURL(self::LIST_ACTION));
    }
}