text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.ComponentModel;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using static OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreConstants;
using Properties = OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreConstants.Properties;

namespace OpenIddict.Server.AspNetCore;

/// <summary>
/// Provides the logic necessary to extract, validate and handle OpenID Connect requests.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<OpenIddictServerAspNetCoreOptions>,
    IAuthenticationRequestHandler,
    IAuthenticationSignInHandler,
    IAuthenticationSignOutHandler
{
    private readonly IOpenIddictServerDispatcher _dispatcher;
    private readonly IOpenIddictServerFactory _factory;

    /// <summary>
    /// Creates a new instance of the <see cref="OpenIddictServerAspNetCoreHandler"/> class.
    /// </summary>
    public OpenIddictServerAspNetCoreHandler(
        IOpenIddictServerDispatcher dispatcher,
        IOpenIddictServerFactory factory,
        IOptionsMonitor<OpenIddictServerAspNetCoreOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
        _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
        _factory = factory ?? throw new ArgumentNullException(nameof(factory));
    }

    /// <inheritdoc/>
    public async Task<bool> HandleRequestAsync()
    {
        // Note: the transaction may be already attached when replaying an ASP.NET Core request
        // (e.g when using the built-in status code pages middleware with the re-execute mode).
        var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction;
        if (transaction is null)
        {
            // Create a new transaction and attach the HTTP request to make it available to the ASP.NET Core handlers.
            transaction = await _factory.CreateTransactionAsync();
            transaction.Properties[typeof(HttpRequest).FullName!] = new WeakReference<HttpRequest>(Request);

            // Attach the OpenIddict server transaction to the ASP.NET Core features
            // so that it can retrieved while performing sign-in/sign-out operations.
            Context.Features.Set(new OpenIddictServerAspNetCoreFeature { Transaction = transaction });
        }

        var context = new ProcessRequestContext(transaction);
        await _dispatcher.DispatchAsync(context);

        if (context.IsRequestHandled)
        {
            return true;
        }

        else if (context.IsRequestSkipped)
        {
            return false;
        }

        else if (context.IsRejected)
        {
            var notification = new ProcessErrorContext(transaction)
            {
                Error = context.Error ?? Errors.InvalidRequest,
                ErrorDescription = context.ErrorDescription,
                ErrorUri = context.ErrorUri,
                Response = new OpenIddictResponse()
            };

            await _dispatcher.DispatchAsync(notification);

            if (notification.IsRequestHandled)
            {
                return true;
            }

            else if (notification.IsRequestSkipped)
            {
                return false;
            }

            throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
        }

        return false;
    }

    /// <inheritdoc/>
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ??
            throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));

        // Note: in many cases, the authentication token was already validated by the time this action is called
        // (generally later in the pipeline, when using the pass-through mode). To avoid having to re-validate it,
        // the authentication context is resolved from the transaction. If it's not available, a new one is created.
        var context = transaction.GetProperty<ProcessAuthenticationContext>(typeof(ProcessAuthenticationContext).FullName!);
        if (context is null)
        {
            context = new ProcessAuthenticationContext(transaction);
            await _dispatcher.DispatchAsync(context);

            // Store the context object in the transaction so it can be later retrieved by handlers
            // that want to access the authentication result without triggering a new authentication flow.
            transaction.SetProperty(typeof(ProcessAuthenticationContext).FullName!, context);
        }

        if (context.IsRequestHandled || context.IsRequestSkipped)
        {
            return AuthenticateResult.NoResult();
        }

        else if (context.IsRejected)
        {
            // Note: the missing_token error is special-cased to indicate to ASP.NET Core
            // that no authentication result could be produced due to the lack of token.
            // This also helps reducing the logging noise when no token is specified.
            if (string.Equals(context.Error, Errors.MissingToken, StringComparison.Ordinal))
            {
                return AuthenticateResult.NoResult();
            }

            var properties = new AuthenticationProperties(new Dictionary<string, string?>
            {
                [Properties.Error] = context.Error,
                [Properties.ErrorDescription] = context.ErrorDescription,
                [Properties.ErrorUri] = context.ErrorUri
            });

            return AuthenticateResult.Fail(SR.GetResourceString(SR.ID0113), properties);
        }

        else
        {
            // A single main claims-based principal instance can be attached to an authentication ticket.
            // To return the most appropriate one, the principal is selected based on the endpoint type.
            // Independently of the selected main principal, all principals resolved from validated tokens
            // are attached to the authentication properties bag so they can be accessed from user code.
            var principal = context.EndpointType switch
            {
                OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.Logout
                    => context.IdentityTokenPrincipal,

                OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.Revocation
                    => context.AccessTokenPrincipal       ??
                       context.RefreshTokenPrincipal      ??
                       context.IdentityTokenPrincipal     ??
                       context.AuthorizationCodePrincipal ??
                       context.DeviceCodePrincipal        ??
                       context.UserCodePrincipal,

                OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType()
                    => context.AuthorizationCodePrincipal,
                OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
                    => context.DeviceCodePrincipal,
                OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType()
                    => context.RefreshTokenPrincipal,

                OpenIddictServerEndpointType.Userinfo => context.AccessTokenPrincipal,

                OpenIddictServerEndpointType.Verification => context.UserCodePrincipal,

                _ => null
            };

            if (principal is null)
            {
                return AuthenticateResult.NoResult();
            }

            // Restore or create a new authentication properties collection and populate it.
            var properties = CreateProperties(principal);
            properties.ExpiresUtc = principal.GetExpirationDate();
            properties.IssuedUtc = principal.GetCreationDate();

            List<AuthenticationToken>? tokens = null;

            // Attach the tokens to allow any ASP.NET Core component (e.g a controller)
            // to retrieve them (e.g to make an API request to another application).

            if (!string.IsNullOrEmpty(context.AccessToken))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.AccessToken,
                    Value = context.AccessToken
                });
            }

            if (!string.IsNullOrEmpty(context.AuthorizationCode))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.AuthorizationCode,
                    Value = context.AuthorizationCode
                });
            }

            if (!string.IsNullOrEmpty(context.DeviceCode))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.DeviceCode,
                    Value = context.DeviceCode
                });
            }

            if (!string.IsNullOrEmpty(context.IdentityToken))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.IdentityToken,
                    Value = context.IdentityToken
                });
            }

            if (!string.IsNullOrEmpty(context.RefreshToken))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.RefreshToken,
                    Value = context.RefreshToken
                });
            }

            if (!string.IsNullOrEmpty(context.UserCode))
            {
                tokens ??= new(capacity: 1);
                tokens.Add(new AuthenticationToken
                {
                    Name = Tokens.UserCode,
                    Value = context.UserCode
                });
            }

            if (context.AccessTokenPrincipal is not null)
            {
                properties.SetParameter(Properties.AccessTokenPrincipal, context.AccessTokenPrincipal);
            }

            if (context.AuthorizationCodePrincipal is not null)
            {
                properties.SetParameter(Properties.AuthorizationCodePrincipal, context.AuthorizationCodePrincipal);
            }

            if (context.DeviceCodePrincipal is not null)
            {
                properties.SetParameter(Properties.DeviceCodePrincipal, context.DeviceCodePrincipal);
            }

            if (context.IdentityTokenPrincipal is not null)
            {
                properties.SetParameter(Properties.IdentityTokenPrincipal, context.IdentityTokenPrincipal);
            }

            if (context.RefreshTokenPrincipal is not null)
            {
                properties.SetParameter(Properties.RefreshTokenPrincipal, context.RefreshTokenPrincipal);
            }

            if (context.UserCodePrincipal is not null)
            {
                properties.SetParameter(Properties.UserCodePrincipal, context.UserCodePrincipal);
            }

            if (tokens is { Count: > 0 })
            {
                properties.StoreTokens(tokens);
            }

            return AuthenticateResult.Success(new AuthenticationTicket(principal, properties,
                OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
        }

        static AuthenticationProperties CreateProperties(ClaimsPrincipal? principal)
        {
            // Note: the principal may be null if no value was extracted from the corresponding token.
            if (principal is not null)
            {
                var value = principal.GetClaim(Claims.Private.HostProperties);
                if (!string.IsNullOrEmpty(value))
                {
                    var dictionary = new Dictionary<string, string?>(comparer: StringComparer.Ordinal);
                    using var document = JsonDocument.Parse(value);

                    foreach (var property in document.RootElement.EnumerateObject())
                    {
                        dictionary[property.Name] = property.Value.GetString();
                    }

                    return new AuthenticationProperties(dictionary);
                }
            }

            return new AuthenticationProperties();
        }
    }

    /// <inheritdoc/>
    protected override async Task HandleChallengeAsync(AuthenticationProperties? properties)
    {
        var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ??
            throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));

        transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();

        var context = new ProcessChallengeContext(transaction)
        {
            Response = new OpenIddictResponse()
        };

        await _dispatcher.DispatchAsync(context);

        if (context.IsRequestHandled || context.IsRequestSkipped)
        {
            return;
        }

        else if (context.IsRejected)
        {
            var notification = new ProcessErrorContext(transaction)
            {
                Error = context.Error ?? Errors.InvalidRequest,
                ErrorDescription = context.ErrorDescription,
                ErrorUri = context.ErrorUri,
                Response = new OpenIddictResponse()
            };

            await _dispatcher.DispatchAsync(notification);

            if (notification.IsRequestHandled || context.IsRequestSkipped)
            {
                return;
            }

            throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
        }
    }

    /// <inheritdoc/>
    protected override Task HandleForbiddenAsync(AuthenticationProperties? properties)
        => HandleChallengeAsync(properties);

    /// <inheritdoc/>
    public async Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties)
    {
        if (user is null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ??
            throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));

        transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();

        var context = new ProcessSignInContext(transaction)
        {
            Principal = user,
            Response = new OpenIddictResponse()
        };

        await _dispatcher.DispatchAsync(context);

        if (context.IsRequestHandled || context.IsRequestSkipped)
        {
            return;
        }

        else if (context.IsRejected)
        {
            var notification = new ProcessErrorContext(transaction)
            {
                Error = context.Error ?? Errors.InvalidRequest,
                ErrorDescription = context.ErrorDescription,
                ErrorUri = context.ErrorUri,
                Response = new OpenIddictResponse()
            };

            await _dispatcher.DispatchAsync(notification);

            if (notification.IsRequestHandled || context.IsRequestSkipped)
            {
                return;
            }

            throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
        }
    }

    /// <inheritdoc/>
    public async Task SignOutAsync(AuthenticationProperties? properties)
    {
        var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ??
            throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));

        var context = new ProcessSignOutContext(transaction)
        {
            Response = new OpenIddictResponse()
        };

        transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();

        await _dispatcher.DispatchAsync(context);

        if (context.IsRequestHandled || context.IsRequestSkipped)
        {
            return;
        }

        else if (context.IsRejected)
        {
            var notification = new ProcessErrorContext(transaction)
            {
                Error = context.Error ?? Errors.InvalidRequest,
                ErrorDescription = context.ErrorDescription,
                ErrorUri = context.ErrorUri,
                Response = new OpenIddictResponse()
            };

            await _dispatcher.DispatchAsync(notification);

            if (notification.IsRequestHandled || context.IsRequestSkipped)
            {
                return;
            }

            throw new InvalidOperationException(SR.GetResourceString(SR.ID0111));
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
HttpClient 3.0.1 API: Uses of Class org.apache.commons.httpclient.cookie.CookieSpecBase
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

Uses of Class
org.apache.commons.httpclient.cookie.CookieSpecBase

Packages that use CookieSpecBase

org.apache.commons.httpclient.cookie
Provides cookie handling in conjunction with Cookie.

Uses of CookieSpecBase in org.apache.commons.httpclient.cookie

Subclasses of CookieSpecBase in org.apache.commons.httpclient.cookie

 class
NetscapeDraftSpec

          Netscape cookie draft specific cookie management functions

 class
RFC2109Spec

          RFC 2109 specific cookie management functions

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

Copyright © 2001-2006 Apache Software Foundation. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
define(['mac/roman'], function(macRoman) {

  'use strict';

  function open(item) {
    return item.getBytes().then(function(bytes) {
      item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
    });
  };

  function TextView(buffer, byteOffset, byteLength) {
    this.dataView = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  };
  TextView.prototype = {
    toJSON: function() {
      return {
        top: this.top,
        left: this.left,
        bottom: this.bottom,
        right: this.right,
        fontType: this.fontType,
        fontSize: this.fontSize,
        text: this.text,
      };
    },
    get top() {
      return this.dataView.getInt16(0, false);
    },
    get left() {
      return this.dataView.getInt16(2, false);
    },
    get bottom() {
      return this.dataView.getInt16(4, false);
    },
    get right() {
      return this.dataView.getInt16(6, false);
    },
    get fontType() {
      return this.dataView.getUint16(8, false);
    },
    get fontSize() {
      return this.dataView.getUint16(10, false);
    },
    get text() {
      return macRoman(this.bytes, 12);
    },
  };

  return open;

});


text:
layout: post
title: TDD and legacy code
date: 2010-01-14T07:53:00.001Z
author: Marcus Hammarberg
tags:
  - .NET
  - Life of a consultant
  - Agile
  - TDD
modified_time: 2010-01-14T07:53:17.653Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-372874052836303505
blogger_orig_url: http://www.marcusoft.net/2010/01/tdd-and-legacy-code.html
---

I have been doing some presentations on
TDD and one thing that always happen is that you get
some tricky questions in the beginning of the presentation.

As you're introducing a new concept it of course starts very small and
easy but most people directly try to put into their context, their
normal situation.

And let's admit it – there not very often we start off in a void, aka. a
green field project. No – it's mostly brown field - there is always code that exists that
needs to be handled. What's worse – that code is not written to be
tested – Not Designed for Testability.

I think this is a very interesting subject and it touches on other
subjects that I'm interesting on surrounding why it's worth "clean up your room" (as Uncle Bob would have put it…)

There's a lot written on this subject, most notable and my next read,
Michael
Feathers Working Effectively with Legacy Code.

But from my good friend Calle Lindelöf I've got a tip for two great
articles by David Laribee. Here you go, thank you Calle:

- 9 Useful Tactics for Paying Back Technical Debt
- Using Agile Techniques to Pay Back Technical Debt


text:
<!DOCTYPE html>

        <title>Logtoeye Dashbaord</title>

        <link rel="stylesheet" type="text/css" media="screen" href="/static/themes/ui-darkness/jquery-ui.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="/static/themes/ui.jqgrid.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="/static/css/dashboard.css" />

                Logtoeye Dashbaord
                V0.1 for Nginx

Home

Report

Config

runbytech.com all copyright reserved


text:
<md-toolbar>

Project Assets

    <md-button class="md-raised md-accent"
      ngf-select ng-multiple="true"
      ngf-change="upload_single_asset($files)"
      ng-model="files">
      + Add new
  </md-button>

</md-toolbar>

{{asset_upload_message}}

  <md-input-container class="md-icon-float" flex="33" style="margin-bottom: -15px;">

    Search Asset
    <md-icon class="md-primary" md-font-set="material-icons">search</md-icon>
    <input ng-model="assetSearch" type="text">
  </md-input-container>

    <md-card flex="100" class="asset_card">
      <md-card-title>

          <md-icon class="asset_icon" md-font-set="material-icons">{{asset.icon}}</md-icon>

 {{asset.name}}

          <md-icon class="asset_download" ng-click="downloadAsset(asset.path)" md-font-set="material-icons">file_download</md-icon>
          <md-icon class="md-primary asset_trash" ng-click="removeAsset(asset.path)" md-font-set="material-icons">delete</md-icon>

      </md-card-title>
    </md-card>


text:
KeyManager::Engine.routes.draw do

  resources :secrets, only: [:index, :show, :new, :create, :destroy] do
    get 'type_update', :on => :collection
    get 'payload', :on => :member
  end

  resources :containers, only: [:index, :show, :new, :create, :destroy]

end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>U3: Netzwerkkomponenten</title>
    <link rel="stylesheet" href="../stylesheets/main.css" type="text/css">

    « Zurück

Netzwerkkomponenten

Hier sollte man mal etwas hinschreiben.

    « U2: Tonwertveränderung
    U4: Fontformate »


text:
#include "VCv.h"
#include "Input_Reader.h"
#include <vector>
#include <stdlib.h>
#include <math.h>

class Cv_Rational: public VCv
{
public:
  Cv_Rational(const Input_Reader& input_reader,
  const int mat_num);
  virtual ~Cv_Rational(){}

  double get_cv(const double position, const double temperature) override;
private:
  /// \f$ C_v = m_{const} \f$
  const double m_const;
  const int m_power;
  const double m_offset;
};

#endif


text:
package com.raizlabs.android.debugmodule.database;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.LayoutRes;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.raizlabs.android.debugmodule.Critter;
import com.raizlabs.android.debugmodule.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Description: Displays a row in editable format.
 */
public class RowCritter implements Critter {

    public interface ColumnChangeListener {

        /**
         * Called when a column's value changes for a specific row
         *
         * @param column The column changed.
         */
        void onColumnChanged(Column column);
    }

    private LinearLayout rowLayout;
    private Button saveButton;

    private Map<String, Column> columnDataMap;
    private Map<String, Column> originalColumnMap;
    private List<String> columnNameSet;
    private String tableName;
    private SQLiteDatabase database;

    private RowEditAdapter adapter;

    @Override
    public int getLayoutResId() {
        return R.layout.view_debug_module_row;
    }

    @Override
    public void handleView(@LayoutRes int layoutResource, View view) {
        rowLayout = ((LinearLayout) view.findViewById(R.id.rowLayout));
        saveButton = (Button) view.findViewById(R.id.view_debug_module_row_save);
        saveButton.setOnClickListener(clickListener);

        adapter = new RowEditAdapter();

        rowLayout.removeAllViews();
        for (int i = 0; i < adapter.getCount(); i++) {
            rowLayout.addView(adapter.getView(i, null, rowLayout));
        }
    }

    /**
     * Sets the data that we will display in this {@link Critter}
     *
     * @param tableName The name of the table to display.
     * @param database  The database to use.
     * @param map       The map of data for a specific row.
     */
    void setColumnDataMap(String tableName, SQLiteDatabase database, Map<String, Column> map) {
        this.tableName = tableName;
        this.database = database;
        Set<String> keys = map.keySet();
        columnDataMap = new HashMap<>();
        for (String key : keys) {
            Column column = new Column(map.get(key));
            columnDataMap.put(key, column);
        }
        originalColumnMap = map;
        columnNameSet = new ArrayList<>(columnDataMap.keySet());
    }

    @Override
    public void cleanup() {
        columnDataMap = null;
    }

    private final ColumnChangeListener changeListener = new ColumnChangeListener() {
        @Override
        public void onColumnChanged(Column column) {
            columnDataMap.put(column.columnName, column);
        }
    };

    private final View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues contentValues = DatabaseCritterUtils.toContentValues(columnDataMap);
            int count = database.updateWithOnConflict(tableName, contentValues,
                                                      DatabaseCritterUtils.toWhere(originalColumnMap), null,
                                                      SQLiteDatabase.CONFLICT_FAIL);
            Toast.makeText(v.getContext(), count == 1 ? "Row updated successfully" :
                    (count > 1 ? "Update touched more than one row" : "Row update failed"), Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Displays row editing on screen.
     */
    private class RowEditAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return columnDataMap.size();
        }

        @Override
        public String getItem(int position) {
            return columnNameSet.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            RowEditView rowEditView;
            if (convertView == null) {
                rowEditView = new RowEditView(parent.getContext());
            } else {
                rowEditView = (RowEditView) convertView;
            }
            String columnName = getItem(position);
            rowEditView.populate(columnDataMap.get(columnName), changeListener);
            return rowEditView;
        }
    }
}


text:
/* gxtype1.c */
/* Adobe Type 1 font interpreter support */
#include "math_.h"
#include "gx.h"
#include "gserrors.h"
#include "gsccode.h"
#include "gsline.h"
#include "gsstruct.h"
#include "gxarith.h"
#include "gxfixed.h"
#include "gxistate.h"
#include "gxmatrix.h"
#include "gxcoord.h"
#include "gxfont.h"
#include "gxfont1.h"
#include "gxtype1.h"
#include "gzpath.h"

/*
 * The routines in this file are used for both Type 1 and Type 2
 * charstring interpreters.
 */

/*
 * Define whether or not to force hints to "big pixel" boundaries
 * when rasterizing at higher resolution.  With the current algorithms,
 * a value of 1 is better for devices without alpha capability,
 * but 0 is better if alpha is available.
 */
#define FORCE_HINTS_TO_BIG_PIXELS 1

/* Structure descriptor */
public_st_gs_font_type1();

/* Encrypt a string. */
int
gs_type1_encrypt(byte *dest, const byte *src, uint len, crypt_state *pstate)
{	register crypt_state state = *pstate;
	register const byte *from = src;
	register byte *to = dest;
	register uint count = len;
	while ( count )
	   {	encrypt_next(*from, state, *to);
		from++, to++, count--;
	   }
	*pstate = state;
	return 0;
}
/* Decrypt a string. */
int
gs_type1_decrypt(byte *dest, const byte *src, uint len, crypt_state *pstate)
{	register crypt_state state = *pstate;
	register const byte *from = src;
	register byte *to = dest;
	register uint count = len;
	while ( count )
	   {	/* If from == to, we can't use the obvious */
		/*	decrypt_next(*from, state, *to);	*/
		register byte ch = *from++;
		decrypt_next(ch, state, *to);
		to++, count--;
	   }
	*pstate = state;
	return 0;
}

/* Define the structure type for a Type 1 interpreter state. */
public_st_gs_type1_state();
/* GC procedures */
#define pcis ((gs_type1_state *)vptr)
private ENUM_PTRS_BEGIN(gs_type1_state_enum_ptrs) {
	if ( index < pcis->ips_count + 3 )
	  {	ENUM_RETURN_CONST_STRING_PTR(gs_type1_state,
					     ipstack[index - 3].char_string);
	  }
	return 0;
	}
	ENUM_PTR(0, gs_type1_state, pfont);
	ENUM_PTR(1, gs_type1_state, pis);
	ENUM_PTR(2, gs_type1_state, path);
ENUM_PTRS_END
private RELOC_PTRS_BEGIN(gs_type1_state_reloc_ptrs) {
	int i;
	RELOC_PTR(gs_type1_state, pfont);
	RELOC_PTR(gs_type1_state, pis);
	RELOC_PTR(gs_type1_state, path);
	for ( i = 0; i < pcis->ips_count; i++ )
	  {	ip_state *ipsp = &pcis->ipstack[i];
		int diff = ipsp->ip - ipsp->char_string.data;
		gs_reloc_const_string(&ipsp->char_string, gcst);
		ipsp->ip = ipsp->char_string.data + diff;
	  }
} RELOC_PTRS_END
#undef pcis

/* ------ Interpreter entry point ------ */

private int
gs_no_charstring_interpret(gs_type1_state *pcis, const gs_const_string *str,
  int *pindex)
{	return_error(gs_error_rangecheck);
}
int (*gs_charstring_interpreter[3])
     (P3(gs_type1_state *pcis, const gs_const_string *str, int *pindex)) = {
       gs_no_charstring_interpret,
       gs_no_charstring_interpret,
       gs_no_charstring_interpret
};

/*
 * Continue interpreting a Type 1 charstring.  If str != 0, it is taken as
 * the byte string to interpret.  Return 0 on successful completion, <0 on
 * error, or >0 when client intervention is required (or allowed).  The int*
 * argument is where the othersubr # is stored for callothersubr.
 */
int
gs_type1_interpret(gs_type1_state *pcis, const gs_const_string *str,
  int *pindex)
{	return (*gs_charstring_interpreter[pcis->pfont->data.CharstringType])
	  (pcis, str, pindex);
}

/* ------ Interpreter services ------ */

#define s (*ps)

/* We export this for the Type 2 charstring interpreter. */
void
accum_xy_proc(register is_ptr ps, fixed dx, fixed dy)
{	ptx += c_fixed(dx, xx),
	pty += c_fixed(dy, yy);
	if ( sfc.skewed )
	  ptx += c_fixed(dy, yx),
	  pty += c_fixed(dx, xy);
}

/* Initialize a Type 1 interpreter. */
/* The caller must supply a string to the first call of gs_type1_interpret. */
int
gs_type1_interp_init(register gs_type1_state *pcis, gs_imager_state *pis,
  gx_path *ppath, const gs_log2_scale_point *pscale, bool charpath_flag,
  int paint_type, gs_font_type1 *pfont)
{	static const gs_log2_scale_point no_scale = { 0, 0 };
	const gs_log2_scale_point *plog2_scale =
	  (FORCE_HINTS_TO_BIG_PIXELS ? pscale : &no_scale);

	pcis->pfont = pfont;
	pcis->pis = pis;
	pcis->path = ppath;
	/*
	 * charpath_flag controls coordinate rounding, hinting, and
	 * flatness enhancement.  If we allow it to be set to true,
	 * charpath may produce results quite different from show.
	 */
	pcis->charpath_flag = false /*charpath_flag*/;
	pcis->paint_type = paint_type;
	pcis->os_count = 0;
	pcis->ips_count = 1;
	pcis->ipstack[0].ip = 0;
	pcis->ipstack[0].char_string.data = 0;
	pcis->ipstack[0].char_string.size = 0;
	pcis->ignore_pops = 0;
	pcis->init_done = -1;
	pcis->sb_set = false;
	pcis->width_set = false;

	/* Set the sampling scale. */
	set_pixel_scale(&pcis->scale.x, plog2_scale->x);
	set_pixel_scale(&pcis->scale.y, plog2_scale->y);

	return 0;
}
/* Preset the left side bearing and/or width. */
void
gs_type1_set_lsb(gs_type1_state *pcis, const gs_point *psbpt)
{	pcis->lsb.x = float2fixed(psbpt->x);
	pcis->lsb.y = float2fixed(psbpt->y);
	pcis->sb_set = true;
}
void
gs_type1_set_width(gs_type1_state *pcis, const gs_point *pwpt)
{	pcis->width.x = float2fixed(pwpt->x);
	pcis->width.y = float2fixed(pwpt->y);
	pcis->width_set = true;
}
/* Finish initializing the interpreter if we are actually rasterizing */
/* the character, as opposed to just computing the side bearing and width. */
void
gs_type1_finish_init(gs_type1_state *pcis, gs_op1_state _ss *ps)
{	gs_imager_state *pis = pcis->pis;

	/* Set up the fixed version of the transformation. */
	gx_matrix_to_fixed_coeff(&ctm_only(pis), &pcis->fc, max_coeff_bits);
	sfc = pcis->fc;

	/* Set the current point of the path to the origin, */
	/* in anticipation of the initial [h]sbw. */
	{ gx_path *ppath = pcis->path;
	  ptx = pcis->origin.x = ppath->position.x;
	  pty = pcis->origin.y = ppath->position.y;
	}

	/* Initialize hint-related scalars. */
	pcis->have_hintmask = false;
	pcis->seac_base = -1;
	pcis->asb_diff = pcis->adxy.x = pcis->adxy.y = 0;
	pcis->flex_count = flex_max;		/* not in Flex */
	pcis->dotsection_flag = dotsection_out;
	pcis->vstem3_set = false;
	pcis->vs_offset.x = pcis->vs_offset.y = 0;
	pcis->hints_initial = 0;		/* probably not needed */
	pcis->hint_next = 0;
	pcis->hints_pending = 0;

	/* Assimilate the hints proper. */
	{ gs_log2_scale_point log2_scale;
	  log2_scale.x = pcis->scale.x.log2_unit;
	  log2_scale.y = pcis->scale.y.log2_unit;
	  if ( pcis->charpath_flag )
	    reset_font_hints(&pcis->fh, &log2_scale);
	  else
	    compute_font_hints(&pcis->fh, &pis->ctm, &log2_scale,
			       &pcis->pfont->data);
	}
	reset_stem_hints(pcis);

	/*
	 * Set the flatness to a value that is likely to produce reasonably
	 * good-looking curves, regardless of its current value in the
	 * graphics state.  If the character is very small, set the flatness
	 * to zero, which will produce very accurate curves.
	 */
	   {	float cxx = fabs(pis->ctm.xx), cyy = fabs(pis->ctm.yy);
		if ( cyy < cxx )
		  cxx = cyy;
		if ( !is_xxyy(&pis->ctm) )
		   {	float cxy = fabs(pis->ctm.xy), cyx = fabs(pis->ctm.yx);
			if ( cxy < cxx )
			  cxx = cxy;
			if ( cyx < cxx )
			  cxx = cyx;
		   }
		/* Don't let the flatness be worse than the default. */
		if ( cxx > pis->flatness )
		  cxx = pis->flatness;
		/* If the character is tiny, force accurate curves. */
		if ( cxx < 0.2 )
		  cxx = 0;
		pcis->flatness = cxx;
	   }

	/* Move to the side bearing point. */
	accum_xy(pcis->lsb.x, pcis->lsb.y);
	pcis->position.x = ptx;
	pcis->position.y = pty;

	pcis->init_done = 1;
}

/* ------ Operator procedures ------ */

/* We put these before the interpreter to save having to write */
/* prototypes for all of them. */

int
gs_op1_closepath(register is_ptr ps)
{	/* Note that this does NOT reset the current point! */
	gx_path *ppath = sppath;
	subpath *psub;
	segment *pseg;
	fixed dx, dy;
	int code;

	/* Check for and suppress a microscopic closing line. */
	if ( (psub = ppath->current_subpath) != 0 &&
	     (pseg = psub->last) != 0 &&
	     (dx = pseg->pt.x - psub->pt.x,
	      any_abs(dx) < float2fixed(0.1)) &&
	     (dy = pseg->pt.y - psub->pt.y,
	      any_abs(dy) < float2fixed(0.1))
	   )
	  switch ( pseg->type )
	    {
	    case s_line:
	      code = gx_path_pop_close_subpath(sppath);
	      break;
	    case s_curve:
	      /*
	       * Unfortunately, there is no "s_curve_close".  (Maybe there
	       * should be?)  Just adjust the final point of the curve so it
	       * is identical to the closing point.
	       */
	      pseg->pt = psub->pt;
#define pcseg ((curve_segment *)pseg)
	      pcseg->p2.x -= dx;
	      pcseg->p2.y -= dy;
#undef pcseg
	      /* falls through */
	    default:
	      /* What else could it be?? */
	      code = gx_path_close_subpath(sppath);
	    }
	else
	  code = gx_path_close_subpath(sppath);
	if ( code < 0 )
	  return code;
	return gx_path_add_point(ppath, ptx, pty);	/* put the point where it was */
}

int
gs_op1_rrcurveto(register is_ptr ps, fixed dx1, fixed dy1,
  fixed dx2, fixed dy2, fixed dx3, fixed dy3)
{	gs_fixed_point pt1, pt2;
	fixed ax0 = sppath->position.x - ptx;
	fixed ay0 = sppath->position.y - pty;
	accum_xy(dx1, dy1);
	pt1.x = ptx + ax0, pt1.y = pty + ay0;
	accum_xy(dx2, dy2);
	pt2.x = ptx, pt2.y = pty;
	accum_xy(dx3, dy3);
	return gx_path_add_curve(sppath, pt1.x, pt1.y, pt2.x, pt2.y, ptx, pty);
}

#undef s

/* Record the side bearing and character width. */
int
gs_type1_sbw(gs_type1_state *pcis, fixed lsbx, fixed lsby, fixed wx, fixed wy)
{	if ( !pcis->sb_set )
	  pcis->lsb.x = lsbx, pcis->lsb.y = lsby,
	    pcis->sb_set = true;	/* needed for accented chars */
	if ( !pcis->width_set )
	  pcis->width.x = wx, pcis->width.y = wy,
	    pcis->width_set = true;
	if_debug4('1',"[1]sb=(%g,%g) w=(%g,%g)\n",
		  fixed2float(pcis->lsb.x), fixed2float(pcis->lsb.y),
		  fixed2float(pcis->width.x), fixed2float(pcis->width.y));
	return 0;
}

/* Handle the end of a character. */
int
gs_type1_endchar(gs_type1_state *pcis)
{	gs_imager_state *pis = pcis->pis;
	gx_path *ppath = pcis->path;

	if ( pcis->hint_next != 0 || path_is_drawing(ppath) )
	  apply_path_hints(pcis, true);
	/* Set the current point to the character origin */
	/* plus the width. */
	{ gs_fixed_point pt;

	  gs_point_transform2fixed(&pis->ctm,
				   fixed2float(pcis->width.x),
				   fixed2float(pcis->width.y),
				   &pt);
	  gx_path_add_point(ppath, pt.x, pt.y);
	}
	if ( pcis->scale.x.log2_unit + pcis->scale.y.log2_unit == 0 )
	{	/*
		 * Tweak up the fill adjustment.  This is a hack for when
		 * we can't oversample.  The values here are based entirely
		 * on experience, not theory, and are designed primarily
		 * for displays and low-resolution fax.
		 */
		gs_fixed_rect bbox;
		int dx, dy, dmax;

		gx_path_bbox(ppath, &bbox);
		dx = fixed2int_ceiling(bbox.q.x - bbox.p.x);
		dy = fixed2int_ceiling(bbox.q.y - bbox.p.y);
		dmax = max(dx, dy);
		if ( pcis->fh.snap_h.count || pcis->fh.snap_v.count ||
		     pcis->fh.a_zone_count
		   )
		{	/* We have hints.  Only tweak up a little at */
			/* very small sizes, to help nearly-vertical */
			/* or nearly-horizontal diagonals. */
			pis->fill_adjust.x = pis->fill_adjust.y =
				(dmax < 15 ? float2fixed(0.15) :
				 dmax < 25 ? float2fixed(0.1) :
				 fixed_0);
		}
		else
		{	/* No hints.  Tweak a little more to compensate */
			/* for lack of snapping to pixel grid. */
			pis->fill_adjust.x = pis->fill_adjust.y =
				(dmax < 10 ? float2fixed(0.2) :
				 dmax < 25 ? float2fixed(0.1) :
				 float2fixed(0.05));
		}
	}
	else
	{	/* Don't do any adjusting. */
		pis->fill_adjust.x = pis->fill_adjust.y = fixed_0;
	}
	/* Set the flatness for curve rendering. */
	if ( !pcis->charpath_flag )
	  gs_imager_setflat(pis, pcis->flatness);
	return 0;
}


text:
package hayago.game.tests

import org.specs2.mutable._
import org.specs2.specification.core._
import hayago.game._
import scala.collection.immutable.HashSet

class SessionSpec extends Specification { sequential
  import scala.util._

  "A fresh game session" should {
    "know who's turn it is" in {
      val startState1 = Session (Configuration.default)
      startState1.colourToPlay must_== Colour.Black
      startState1.playerToPlay must_== Player.Montague

      val startState2 = Session (Configuration.default.copy(firstTurn = Player.Capulet))
      startState2.colourToPlay must_== Colour.Black
      startState2.playerToPlay must_== Player.Capulet
    }
  }

  "The game session" should {
    val turns =
        Turn.create ("C:4") ::
        Turn.create ("D:4") ::
        Turn.create ("C:6") ::
        Turn.create ("D:6") ::
        Turn.create ("B:5") ::
        Turn.create ("E:5") ::
        Turn.create ("D:5") ::
        Turn.create ("C:5") ::
        Nil

    "know about the game end conditions" in {
      val t0  = turns
      val t1  = turns :+ Turn.create ("RESIGN")
      val t2a = turns :+ Turn.create ("PASS")
      val t2b = t2a   :+ Turn.create ("PASS")
      val t2c = t2b   :+ Turn.create (Signal.Evaluation (HashSet ()))
      val t2d = t2c   :+ Turn.create (Signal.Evaluation (HashSet ()))

      val s0  = Session (Configuration.default, t0)
      val s1  = Session (Configuration.default, t1)
      val s2a = Session (Configuration.default, t2a)
      val s2b = Session (Configuration.default, t2b)
      val s2c = Session (Configuration.default, t2c)
      val s2d = Session (Configuration.default, t2d)

      s0.isAgreementPhase must_== false
      s0.isComplete must_== false

      s1.isAgreementPhase must_== false
      s1.isComplete must_== true

      s2a.isAgreementPhase must_== false
      s2a.isComplete must_== false

      s2b.isAgreementPhase must_== true
      s2b.isComplete must_== false

      s2c.isAgreementPhase must_== true
      s2c.isComplete must_== false

      s2d.isAgreementPhase must_== false
      s2d.isComplete must_== true

      val turn = Turn.create ("F:8")

      s0.applyTurn (turn).isSuccess must_== true
      s1.applyTurn (turn) must_== Failure (IllegalTurnException (IllegalTurnReason.GameComplete))
      s2a.applyTurn (turn).isSuccess must_== true
      s2b.applyTurn (turn) must_== Failure (IllegalTurnException (IllegalTurnReason.EvaluationExpected))
      s2c.applyTurn (turn) must_== Failure (IllegalTurnException (IllegalTurnReason.EvaluationExpected))
      s2d.applyTurn (turn) must_== Failure (IllegalTurnException (IllegalTurnReason.GameComplete))
    }

    "know about illegal moves due to Ko" in {
      val s = Session (Configuration.default, turns)
      val b = s.currentBoard
      b.stones.size must_== 7
      b ("C:4") must_== Success (Some (Colour.Black))
      b ("D:4") must_== Success (Some (Colour.White))
      b ("C:6") must_== Success (Some (Colour.Black))
      b ("D:6") must_== Success (Some (Colour.White))
      b ("B:5") must_== Success (Some (Colour.Black))
      b ("E:5") must_== Success (Some (Colour.White))
      b ("D:5") must_== Success (None)
      b ("C:5") must_== Success (Some (Colour.White))

      s.applyTurn (Turn.create ("D:5")) must_== Failure (IllegalTurnException (IllegalTurnReason.Ko))
      s.applyTurn (Turn.create ("D:8"))
        .flatMap (_.applyTurn (Turn.create ("F:8")))
        .flatMap (_.applyTurn (Turn.create ("D:5"))) match { case Success (sn) => ok; case _ => ko }

      s.applyTurn (Turn.create ("PASS"))
        .flatMap (_.applyTurn (Turn.create ("F:8")))
        .flatMap (_.applyTurn (Turn.create ("D:5"))) match { case Success (sn) => ok; case _ => ko }
    }

    val examples = Data.example9x9 :: Data.second_hayago_championship :: Nil

    Fragment.foreach (examples) { example =>

      s"When scoring ${example.description}, the game session" should {
        "calculate black captures correctly" in {
          example.completeSession.captureCount(Colour.Black) must_== example.expectedScoreBlack.captures
        }

        "calculate white captures correctly" in {
          example.completeSession.captureCount(Colour.White) must_== example.expectedScoreWhite.captures
        }

        val scores = example.completeSession.score (example.expectedDeadStones).get

        "calculate black score correctly, given a list of dead stones" in {
          scores (example.completeSession.player (Colour.Black)) must_== example.expectedScoreBlack
        }

        "calculate white score correctly, given a list of dead stones" in {
          scores (example.completeSession.player (Colour.White)) must_== example.expectedScoreWhite
        }
      }
    }
  }
}


text:
<?php

namespace CTask;

class Result
{
    const SUCCESS = 0;
    const FAIL = 1;

    private $exit;
    private $data;
    private $error;

    function __construct($exit, $data, $error)
    {
        Preconditions::assertNumeric($exit);

        $this->exit = $exit;
        $this->data = $data;
        $this->error = $error;
    }

    /**
     * @return mixed
     */
    public function getExit()
    {
        return $this->exit;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    public function hasError()
    {
        return $this->$exit > 0;
    }

    public function deconstruct()
    {
        return array($this->exit, $this->data, $this->error);
    }

    public static function success($data = null)
    {
        return new Result(self::SUCCESS, $data, null);
    }

    public static function error($error)
    {
        return new Result(self::FAIL, null, $error);
    }
}

?>


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
  /* Includes ------------------------------------------------------------------*/

/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private define ------------------------------------------------------------*/

#define WS2812_OUTPUT_Pin GPIO_PIN_1
#define WS2812_OUTPUT_GPIO_Port GPIOA
#define UART_ESP8266_TX_Pin GPIO_PIN_2
#define UART_ESP8266_TX_GPIO_Port GPIOA
#define UART_ESP8266_RX_Pin GPIO_PIN_3
#define UART_ESP8266_RX_GPIO_Port GPIOA
#define LCD1_RESET_Pin GPIO_PIN_4
#define LCD1_RESET_GPIO_Port GPIOA
#define SPI1_SCK_LCD_Pin GPIO_PIN_5
#define SPI1_SCK_LCD_GPIO_Port GPIOA
#define LCD1_BACKLIGHT_Pin GPIO_PIN_6
#define LCD1_BACKLIGHT_GPIO_Port GPIOA
#define SPI1_MOSI_LCD_Pin GPIO_PIN_7
#define SPI1_MOSI_LCD_GPIO_Port GPIOA
#define LCD1_DATA_CMD1_Pin GPIO_PIN_0
#define LCD1_DATA_CMD1_GPIO_Port GPIOB
#define LCD1_CS_Pin GPIO_PIN_1
#define LCD1_CS_GPIO_Port GPIOB
#define I2C_SCL_HMC5883L_Pin GPIO_PIN_10
#define I2C_SCL_HMC5883L_GPIO_Port GPIOB
#define I2C_SDA_HMC5883L_Pin GPIO_PIN_11
#define I2C_SDA_HMC5883L_GPIO_Port GPIOB
#define MICROWAVE_MOVEMENT_SENSOR_Pin GPIO_PIN_12
#define MICROWAVE_MOVEMENT_SENSOR_GPIO_Port GPIOB
#define MICROWAVE_MOVEMENT_SENSOR_EXTI_IRQn EXTI15_10_IRQn
#define HCSR04_TRIGGER_Pin GPIO_PIN_9
#define HCSR04_TRIGGER_GPIO_Port GPIOA
#define HCSR04_ECHO_Pin GPIO_PIN_10
#define HCSR04_ECHO_GPIO_Port GPIOA
#define HCSR04_ECHO_EXTI_IRQn EXTI15_10_IRQn
#define I2C_SCL_BMP280_CJMCU530_Pin GPIO_PIN_6
#define I2C_SCL_BMP280_CJMCU530_GPIO_Port GPIOB
#define I2C_SDA_BMP280_CJMCU530_Pin GPIO_PIN_7
#define I2C_SDA_BMP280_CJMCU530_GPIO_Port GPIOB

/* USER CODE BEGIN Private defines */

/* USER CODE END Private defines */

void _Error_Handler(char *, int);

#define Error_Handler() _Error_Handler(__FILE__, __LINE__)

/**
  * @}
  */

/**
  * @}
*/

#endif /* __MAIN_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
using System;

namespace SharpKit.Html.indexeddb
{

    using SharpKit.JavaScript;

    [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "IDBRequest")]
    public partial class IDBRequest<Result>
    {
        public  Result result { get; set; }

        public  DOMError error { get; set; }

        public  IDBAny source { get; set; }

        public  IDBTransaction transaction { get; set; }

        public  JsString readyState { get; set; }

        public  EventListener onsuccess { get; set; }

        public  EventListener<ErrorEvent> onerror { get; set; }

        public  void addEventListener(string type, EventListener listener)
        {
        }

        public  void addEventListener(string type, EventListener listener, bool useCapture)
        {
        }

        public  void removeEventListener(string type, EventListener listener)
        {
        }

        public  void removeEventListener(string type, EventListener listener, bool useCapture)
        {
        }

        public  bool dispatchEvent(DOMEvent evt)
        {
            return default(bool);
        }
    }

}


text:
package compressor

import (
	"archive/tar"
	"compress/gzip"
	"fmt"
	"io"
	"os"

	"github.com/lehmrob/backer/scanner"
)

// A Compressor implements the compression of a directory tree into a archive.
type Compressor struct {
	tFile *os.File
	tw    *tar.Writer
	gw    *gzip.Writer
	quiet bool
}

// NewCompressor creates a new instance of the Compressor structure and returns
// it. This is the main way to create a Compressor
func NewCompressor(tarfile string, quiet bool) (*Compressor, error) {
	c := new(Compressor)
	tFile, err := os.Create(tarfile)
	if err != nil {
		return nil, NewError(err)
	}
	gw := gzip.NewWriter(tFile)
	tw := tar.NewWriter(gw)
	c.tFile = tFile
	c.gw = gw
	c.tw = tw

	c.quiet = quiet

	return c, nil
}

// Print the the element which will compressed. The path will print if
// dryRun und quiet are both false
func (c *Compressor) printCompress(path string, elemcnt int, length int) {
	if !c.quiet {
		fmt.Printf("[%d/%d] %s\n", elemcnt, length, path)
	}
}

// Compress the directory of file which is given by the argument basepath
// to an archive file.
func (c *Compressor) Compress(scan scanner.Scan) error {
	defer c.tFile.Close()
	defer c.gw.Close()
	defer c.tw.Close()

	e := scan.Walk(func(path string, info os.FileInfo, index int) error {
		c.printCompress(path, index, len(scan))
		header, err := tar.FileInfoHeader(info, info.Name())
		if err != nil {
			return err
		}

		header.Name = path

		if !info.IsDir() && !isLink(info) {
			header.Size = info.Size()
		}

		if err = c.tw.WriteHeader(header); err != nil {
			return err
		}

		if isLink(info) {
			return nil
		}

		if info.IsDir() {
			return nil
		}

		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()

		_, err = io.Copy(c.tw, file)
		return err
	})

	if e != nil {
		return NewError(e)
	}

	return nil
}

func isLink(info os.FileInfo) bool {
	return info.Mode()&os.ModeSymlink == os.ModeSymlink
}


text:
module Ci
  class Build < CommitStatus
    include TokenAuthenticatable
    include AfterCommitQueue
    include Presentable

    belongs_to :runner
    belongs_to :trigger_request
    belongs_to :erased_by, class_name: 'User'

    has_many :deployments, as: :deployable
    has_one :last_deployment, -> { order('deployments.id DESC') }, as: :deployable, class_name: 'Deployment'

    # The "environment" field for builds is a String, and is the unexpanded name
    def persisted_environment
      @persisted_environment ||= Environment.find_by(
        name: expanded_environment_name,
        project: project
      )
    end

    serialize :options # rubocop:disable Cop/ActiveRecordSerialize
    serialize :yaml_variables, Gitlab::Serializer::Ci::Variables # rubocop:disable Cop/ActiveRecordSerialize

    delegate :name, to: :project, prefix: true

    validates :coverage, numericality: true, allow_blank: true
    validates :ref, presence: true

    scope :unstarted, ->() { where(runner_id: nil) }
    scope :ignore_failures, ->() { where(allow_failure: false) }
    scope :with_artifacts, ->() { where.not(artifacts_file: [nil, '']) }
    scope :with_artifacts_not_expired, ->() { with_artifacts.where('artifacts_expire_at IS NULL OR artifacts_expire_at > ?', Time.now) }
    scope :with_expired_artifacts, ->() { with_artifacts.where('artifacts_expire_at < ?', Time.now) }
    scope :last_month, ->() { where('created_at > ?', Date.today - 1.month) }
    scope :manual_actions, ->() { where(when: :manual, status: COMPLETED_STATUSES + [:manual]) }

    mount_uploader :artifacts_file, ArtifactUploader
    mount_uploader :artifacts_metadata, ArtifactUploader

    acts_as_taggable

    add_authentication_token_field :token

    before_save :update_artifacts_size, if: :artifacts_file_changed?
    before_save :ensure_token
    before_destroy { unscoped_project }

    after_create :execute_hooks
    after_commit :update_project_statistics_after_save, on: [:create, :update]
    after_commit :update_project_statistics, on: :destroy

    class << self
      # This is needed for url_for to work,
      # as the controller is JobsController
      def model_name
        ActiveModel::Name.new(self, nil, 'job')
      end

      def first_pending
        pending.unstarted.order('created_at ASC').first
      end

      def retry(build, current_user)
        Ci::RetryBuildService
          .new(build.project, current_user)
          .execute(build)
      end
    end

    state_machine :status do
      event :actionize do
        transition created: :manual
      end

      after_transition any => [:pending] do |build|
        build.run_after_commit do
          BuildQueueWorker.perform_async(id)
        end
      end

      after_transition pending: :running do |build|
        build.run_after_commit do
          BuildHooksWorker.perform_async(id)
        end
      end

      after_transition any => [:success, :failed, :canceled] do |build|
        build.run_after_commit do
          BuildFinishedWorker.perform_async(id)
        end
      end

      after_transition any => [:success] do |build|
        build.run_after_commit do
          BuildSuccessWorker.perform_async(id)
        end
      end

      before_transition any => [:failed] do |build|
        next if build.retries_max.zero?

        if build.retries_count < build.retries_max
          Ci::Build.retry(build, build.user)
        end
      end
    end

    def detailed_status(current_user)
      Gitlab::Ci::Status::Build::Factory
        .new(self, current_user)
        .fabricate!
    end

    def other_actions
      pipeline.manual_actions.where.not(name: name)
    end

    def playable?
      action? && (manual? || complete?)
    end

    def action?
      self.when == 'manual'
    end

    def play(current_user)
      Ci::PlayBuildService
        .new(project, current_user)
        .execute(self)
    end

    def cancelable?
      active?
    end

    def retryable?
      success? || failed? || canceled?
    end

    def retries_count
      pipeline.builds.retried.where(name: self.name).count
    end

    def retries_max
      self.options.fetch(:retry, 0).to_i
    end

    def latest?
      !retried?
    end

    def expanded_environment_name
      ExpandVariables.expand(environment, simple_variables) if environment
    end

    def has_environment?
      environment.present?
    end

    def starts_environment?
      has_environment? && self.environment_action == 'start'
    end

    def stops_environment?
      has_environment? && self.environment_action == 'stop'
    end

    def environment_action
      self.options.fetch(:environment, {}).fetch(:action, 'start') if self.options
    end

    def outdated_deployment?
      success? && !last_deployment.try(:last?)
    end

    def depends_on_builds
      # Get builds of the same type
      latest_builds = self.pipeline.builds.latest

      # Return builds from previous stages
      latest_builds.where('stage_idx < ?', stage_idx)
    end

    def timeout
      project.build_timeout
    end

    # A slugified version of the build ref, suitable for inclusion in URLs and
    # domain names. Rules:
    #
    #   * Lowercased
    #   * Anything not matching [a-z0-9-] is replaced with a -
    #   * Maximum length is 63 bytes
    #   * First/Last Character is not a hyphen
    def ref_slug
      ref.to_s
          .downcase
          .gsub(/[^a-z0-9]/, '-')[0..62]
          .gsub(/(\A-+|-+\z)/, '')
    end

    # Variables whose value does not depend on environment
    def simple_variables
      variables(environment: nil)
    end

    # All variables, including those dependent on environment, which could
    # contain unexpanded variables.
    def variables(environment: persisted_environment)
      variables = predefined_variables
      variables += project.predefined_variables
      variables += pipeline.predefined_variables
      variables += runner.predefined_variables if runner
      variables += project.container_registry_variables
      variables += project.deployment_variables if has_environment?
      variables += yaml_variables
      variables += user_variables
      variables += project.group.secret_variables_for(ref, project).map(&:to_runner_variable) if project.group
      variables += secret_variables(environment: environment)
      variables += trigger_request.user_variables if trigger_request
      variables += pipeline.pipeline_schedule.job_variables if pipeline.pipeline_schedule
      variables += persisted_environment_variables if environment

      variables
    end

    def merge_request
      return @merge_request if defined?(@merge_request)

      @merge_request ||=
        begin
          merge_requests = MergeRequest.includes(:merge_request_diff)
            .where(source_branch: ref,
                   source_project: pipeline.project)
            .reorder(iid: :desc)

          merge_requests.find do |merge_request|
            merge_request.commit_shas.include?(pipeline.sha)
          end
        end
    end

    def repo_url
      auth = "gitlab-ci-token:#{ensure_token!}@"
      project.http_url_to_repo.sub(/^https?:\/\//) do |prefix|
        prefix + auth
      end
    end

    def allow_git_fetch
      project.build_allow_git_fetch
    end

    def update_coverage
      coverage = trace.extract_coverage(coverage_regex)
      update_attributes(coverage: coverage) if coverage.present?
    end

    def trace
      Gitlab::Ci::Trace.new(self)
    end

    def has_trace?
      trace.exist?
    end

    def trace=(data)
      raise NotImplementedError
    end

    def old_trace
      read_attribute(:trace)
    end

    def erase_old_trace!
      write_attribute(:trace, nil)
      save
    end

    def needs_touch?
      Time.now - updated_at > 15.minutes.to_i
    end

    def valid_token?(token)
      self.token && ActiveSupport::SecurityUtils.variable_size_secure_compare(token, self.token)
    end

    def has_tags?
      tag_list.any?
    end

    def any_runners_online?
      project.any_runners? { |runner| runner.active? && runner.online? && runner.can_pick?(self) }
    end

    def stuck?
      pending? && !any_runners_online?
    end

    def execute_hooks
      return unless project
      build_data = Gitlab::DataBuilder::Build.build(self)
      project.execute_hooks(build_data.dup, :job_hooks)
      project.execute_services(build_data.dup, :job_hooks)
      PagesService.new(build_data).execute
      project.running_or_pending_build_count(force: true)
    end

    def artifacts?
      !artifacts_expired? && artifacts_file.exists?
    end

    def artifacts_metadata?
      artifacts? && artifacts_metadata.exists?
    end

    def artifacts_metadata_entry(path, **options)
      metadata = Gitlab::Ci::Build::Artifacts::Metadata.new(
        artifacts_metadata.path,
        path,
        **options)

      metadata.to_entry
    end

    def erase_artifacts!
      remove_artifacts_file!
      remove_artifacts_metadata!
      save
    end

    def erase(opts = {})
      return false unless erasable?

      erase_artifacts!
      erase_trace!
      update_erased!(opts[:erased_by])
    end

    def erasable?
      complete? && (artifacts? || has_trace?)
    end

    def erased?
      !self.erased_at.nil?
    end

    def artifacts_expired?
      artifacts_expire_at && artifacts_expire_at < Time.now
    end

    def artifacts_expire_in
      artifacts_expire_at - Time.now if artifacts_expire_at
    end

    def artifacts_expire_in=(value)
      self.artifacts_expire_at =
        if value
          ChronicDuration.parse(value)&.seconds&.from_now
        end
    end

    def has_expiring_artifacts?
      artifacts_expire_at.present? && artifacts_expire_at > Time.now
    end

    def keep_artifacts!
      self.update(artifacts_expire_at: nil)
    end

    def coverage_regex
      super || project.try(:build_coverage_regex)
    end

    def when
      read_attribute(:when) || build_attributes_from_config[:when] || 'on_success'
    end

    def yaml_variables
      read_attribute(:yaml_variables) || build_attributes_from_config[:yaml_variables] || []
    end

    def user_variables
      return [] if user.blank?

      [
        { key: 'GITLAB_USER_ID', value: user.id.to_s, public: true },
        { key: 'GITLAB_USER_EMAIL', value: user.email, public: true }
      ]
    end

    def secret_variables(environment: persisted_environment)
      project.secret_variables_for(ref: ref, environment: environment)
        .map(&:to_runner_variable)
    end

    def steps
      [Gitlab::Ci::Build::Step.from_commands(self),
       Gitlab::Ci::Build::Step.from_after_script(self)].compact
    end

    def image
      Gitlab::Ci::Build::Image.from_image(self)
    end

    def services
      Gitlab::Ci::Build::Image.from_services(self)
    end

    def artifacts
      [options[:artifacts]]
    end

    def cache
      [options[:cache]]
    end

    def credentials
      Gitlab::Ci::Build::Credentials::Factory.new(self).create!
    end

    def dependencies
      return [] if empty_dependencies?

      depended_jobs = depends_on_builds

      return depended_jobs unless options[:dependencies].present?

      depended_jobs.select do |job|
        options[:dependencies].include?(job.name)
      end
    end

    def empty_dependencies?
      options[:dependencies]&.empty?
    end

    def hide_secrets(trace)
      return unless trace

      trace = trace.dup
      Ci::MaskSecret.mask!(trace, project.runners_token) if project
      Ci::MaskSecret.mask!(trace, token)
      trace
    end

    private

    def update_artifacts_size
      self.artifacts_size = if artifacts_file.exists?
                              artifacts_file.size
                            else
                              nil
                            end
    end

    def erase_trace!
      trace.erase!
    end

    def update_erased!(user = nil)
      self.update(erased_by: user, erased_at: Time.now, artifacts_expire_at: nil)
    end

    def unscoped_project
      @unscoped_project ||= Project.unscoped.find_by(id: project_id)
    end

    CI_REGISTRY_USER = 'gitlab-ci-token'.freeze

    def predefined_variables
      variables = [
        { key: 'CI', value: 'true', public: true },
        { key: 'GITLAB_CI', value: 'true', public: true },
        { key: 'CI_SERVER_NAME', value: 'GitLab', public: true },
        { key: 'CI_SERVER_VERSION', value: Gitlab::VERSION, public: true },
        { key: 'CI_SERVER_REVISION', value: Gitlab::REVISION, public: true },
        { key: 'CI_JOB_ID', value: id.to_s, public: true },
        { key: 'CI_JOB_NAME', value: name, public: true },
        { key: 'CI_JOB_STAGE', value: stage, public: true },
        { key: 'CI_JOB_TOKEN', value: token, public: false },
        { key: 'CI_COMMIT_SHA', value: sha, public: true },
        { key: 'CI_COMMIT_REF_NAME', value: ref, public: true },
        { key: 'CI_COMMIT_REF_SLUG', value: ref_slug, public: true },
        { key: 'CI_REGISTRY_USER', value: CI_REGISTRY_USER, public: true },
        { key: 'CI_REGISTRY_PASSWORD', value: token, public: false },
        { key: 'CI_REPOSITORY_URL', value: repo_url, public: false }
      ]

      variables << { key: "CI_COMMIT_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_PIPELINE_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_JOB_MANUAL", value: 'true', public: true } if action?
      variables.concat(legacy_variables)
    end

    def persisted_environment_variables
      return [] unless persisted_environment

      variables = persisted_environment.predefined_variables

      # Here we're passing unexpanded environment_url for runner to expand,
      # and we need to make sure that CI_ENVIRONMENT_NAME and
      # CI_ENVIRONMENT_SLUG so on are available for the URL be expanded.
      variables << { key: 'CI_ENVIRONMENT_URL', value: environment_url, public: true } if environment_url

      variables
    end

    def legacy_variables
      variables = [
        { key: 'CI_BUILD_ID', value: id.to_s, public: true },
        { key: 'CI_BUILD_TOKEN', value: token, public: false },
        { key: 'CI_BUILD_REF', value: sha, public: true },
        { key: 'CI_BUILD_BEFORE_SHA', value: before_sha, public: true },
        { key: 'CI_BUILD_REF_NAME', value: ref, public: true },
        { key: 'CI_BUILD_REF_SLUG', value: ref_slug, public: true },
        { key: 'CI_BUILD_NAME', value: name, public: true },
        { key: 'CI_BUILD_STAGE', value: stage, public: true }
      ]

      variables << { key: "CI_BUILD_TAG", value: ref, public: true } if tag?
      variables << { key: "CI_BUILD_TRIGGERED", value: 'true', public: true } if trigger_request
      variables << { key: "CI_BUILD_MANUAL", value: 'true', public: true } if action?
      variables
    end

    def environment_url
      options&.dig(:environment, :url) || persisted_environment&.external_url
    end

    def build_attributes_from_config
      return {} unless pipeline.config_processor

      pipeline.config_processor.build_attributes(name)
    end

    def update_project_statistics
      return unless project

      ProjectCacheWorker.perform_async(project_id, [], [:build_artifacts_size])
    end

    def update_project_statistics_after_save
      if previous_changes.include?('artifacts_size')
        update_project_statistics
      end
    end
  end
end


text:
/* eslint-env mocha, jest */

import RepeatIcon from 'material-ui/svg-icons/av/repeat';

import getActualComponentFactory from '../../lib/testUtils';
import Repeat from '../Repeat';

const defaultProps = {
  repeat: 0,
};
const getActualRepeat = getActualComponentFactory(Repeat, defaultProps);

it('should render', () => {
  getActualRepeat();
});
it('should be a small', () => {
  const wrapper = getActualRepeat();
  expect(wrapper.is('small.Repeat')).toEqual(true);
});
it('should have 0 RepeatIcon if repeat is 0', () => {
  const wrapper = getActualRepeat({ repeat: '0' });
  expect(wrapper.find(RepeatIcon).length).toEqual(0);
});
it('should have some RepeatIcon if repeat is not 0', () => {
  const wrapper = getActualRepeat({ repeat: '3' });
  expect(wrapper.find(RepeatIcon).length).toBeGreaterThan(0);
});


text:
Organizer

                     Add

                    Alert! No Organizers Found

                        Name

                        {{ organizer.name }}


text:
import os
import unittest

from click.testing import CliRunner

from EasyEuler import data, paths
from EasyEuler.cli import cli

class CommandTestCase(unittest.TestCase):
    def setUp(self):
        self.runner = CliRunner()

class TestCreateCommand(CommandTestCase):
    def test_file_creation(self):
        with self.runner.isolated_filesystem():
            self.runner.invoke(cli, ['create', '1'])
            self.runner.invoke(cli, ['create', '1', 'c'])

            self.assertTrue(os.path.exists('euler_001.py'))
            self.assertTrue(os.path.exists('euler_001.c'))

    def test_file_already_exists(self):
        with self.runner.isolated_filesystem():
            open('euler_001.py', 'a').close()
            result = self.runner.invoke(cli, ['create', '1', 'python'],
                                        input='n\n')

            self.assertTrue(os.path.getsize('euler_001.py') == 0)

    def test_overwrite(self):
        with self.runner.isolated_filesystem():
            open('euler_001.py', 'a').close()
            result = self.runner.invoke(cli, ['create', '1', 'python'],
                                        input='y\n')

            self.assertTrue(os.path.getsize('euler_001.py') > 0)

    def test_path(self):
        with self.runner.isolated_filesystem():
            self.runner.invoke(cli, ['create', '--path', 'test.py',
                                     '1', 'python'])

            self.assertTrue(os.path.exists('test.py'))

    def test_invalid_problem_id(self):
        result = self.runner.invoke(cli, ['create', '0'])
        self.assertEqual(result.exit_code, 2)

class TestGenerateResourcesCommand(CommandTestCase):
    def test_generate_problem_resources(self):
        with self.runner.isolated_filesystem():
            self.runner.invoke(cli, ['generate-resources', '22'])
            self.assertTrue(os.path.exists('names.txt'))

    def test_generate_all_resources(self):
        with self.runner.isolated_filesystem():
            self.runner.invoke(cli, ['generate-resources'])

            for filename in os.listdir(paths.RESOURCES):
                self.assertTrue(os.path.exists(filename))

    def test_problem_with_no_resources(self):
        result = self.runner.invoke(cli, ['generate-resources', '1'])
        self.assertEqual(result.exit_code, 1)

class TestVerifyCommand(CommandTestCase):
    def test_problem_verification_with_execution_only(self):
        with self.runner.isolated_filesystem():
            problem1 = data.problems[1]
            problem2 = data.problems[2]

            with open('euler_001.py', 'w') as f:
                f.write('print(%s)' % problem1['answer'])

            with open('euler_002.py', 'w') as f:
                f.write('print(%s)' % problem2['answer'])

            result = self.runner.invoke(cli, ['verify',
                                              'euler_001.py', 'euler_002.py'])
            output = str(result.output_bytes, encoding='UTF-8')

            self.assertIn(problem1['answer'], output)
            self.assertIn(problem2['answer'], output)

    def test_problem_verification_with_build_and_cleanup(self):
        problem = data.problems[1]
        with self.runner.isolated_filesystem():
            with open('euler_001.c', 'w') as f:
                f.writelines(['#include <stdio.h>\n',
                              'int main(void) {\n',
                              'printf("%s");\n' % problem['answer'],
                              'return 0;\n',
                              '}\n'])

            result = self.runner.invoke(cli, ['verify', '-e', 'euler_001.c'])
            output = str(result.output_bytes, encoding='UTF-8')

            self.assertIn(problem['answer'], output)
            self.assertFalse(os.path.exists('euler_001.c.out'))

    def test_recursive_verification(self):
        with self.runner.isolated_filesystem():
            os.mkdir('test')
            problem = data.problems[1]

            with open('test/euler_001.py', 'w') as f:
                f.write('print(%s)' % problem['answer'])

            result = self.runner.invoke(cli, ['verify', '--recursive',
                                              'test'])
            output = str(result.output_bytes, encoding='UTF-8')

            self.assertIn(problem['answer'], output)

    def test_show_execute_errors(self):
        with self.runner.isolated_filesystem():
            with open('euler_001.py', 'w') as f:
                f.write('print(')

            result = self.runner.invoke(cli, ['verify', 'euler_001.py'])
            output = str(result.output_bytes, encoding='UTF-8')
            result_with_errors = self.runner.invoke(cli, ['verify', '--errors',
                                                          'euler_001.py'])
            output_with_errors = str(result_with_errors.output_bytes,
                                     encoding='UTF-8')

            self.assertIn('[error during execute]', output)
            self.assertIn('SyntaxError', output_with_errors)

    def test_show_build_errors(self):
        with self.runner.isolated_filesystem():
            with open('euler_001.c', 'w') as f:
                f.write('#include <invalid_header.h>')

            result = self.runner.invoke(cli, ['verify', 'euler_001.c'])
            output = str(result.output_bytes, encoding='UTF-8')
            result_with_errors = self.runner.invoke(cli, ['verify', '--errors',
                                                          'euler_001.c'])
            output_with_errors = str(result_with_errors.output_bytes,
                                     encoding='UTF-8')

            self.assertIn('[error during build]', output)
            self.assertIn('fatal error: invalid_header.h', output_with_errors)


text:
using Windows.UI.Xaml;

namespace Shagu.Utils.Controls
{
    public sealed partial class ToastView
    {
        public ToastView(string info, bool isNightMode)
        {
            InitializeComponent();
            lightInfo.Text = darkInfo.Text = info;

            VisualStateManager.GoToState(this, isNightMode?"Light": "Dark", true);
        }

    }
}


text:
"""
Solves day 24 of Advent of Code

http://adventofcode.com/day/24

Props to the leaderboard folks on Reddit who made me realize
I was way, way overengineering the problem.
"""

import operator
from functools import reduce
from itertools import combinations

def lowest_quantum_entanglement(packages, num_groups):
    """
    Find the minimum quantum entanglement for the minimum-sized
    group of packages split into num_groups groups of equal weight.
    """
    target_weight = sum(packages) // num_groups
    max_combo_length = len(packages) // num_groups
    best_combo_length = float('inf')
    best_qe = float('inf')

    #print(packages, num_groups, target_weight, max_combo_length)

    # Limit our search space to combinations no larger than the number
    # of packages divided by the number of groups; no "minimum length"
    # combination will ever be more than 1/n of the packages.
    for i in range(1, max_combo_length + 1):

        # Build combinations of increasing size...
        for combo in combinations(packages, i):

            # Throw out anything that won't give us a balanced load
            if sum(combo) != target_weight:
                continue

            # We only want the minimum length combos (to maximize
            # Santa's legroom)
            combo_length = len(combo)
            if combo_length > best_combo_length:
                continue
            best_combo_length = combo_length

            # Calculate the "quantum entanglement" and see how it fares
            qe = reduce(operator.mul, combo)
            #print(combo, sum(combo), qe)
            best_qe = min(best_qe, qe)

    return best_qe

if __name__ == '__main__':
    with open('input.txt') as f:
        packages = [int(x) for x in f.readlines()]

        print("Part 1:", lowest_quantum_entanglement(packages, 3))
        print("Part 2:", lowest_quantum_entanglement(packages, 4))


text:
package com.rgpt.pdflib;

/**
 * A PDFMatrix2D object represents a 3x3 matrix that, in turn, represents an
 * affine transformation. A PDFMatrix2D object stores only six of the nine
 * numbers in a 3x3 matrix because all 3x3 matrices that represent affine
 * transformations have the same third column (0, 0, 1). Affine transformations
 * include rotating, scaling, reflecting, shearing, and translating. In PDF Lib,
 * the PDFMatrix2D class should provide the foundation for performing affine
 * transformations on vector drawings, images, and text. A transformation matrix
 * also specifies the relationship between two coordinate spaces.
 *
 * @author Narayan
 *
 */

public abstract class PDFMatrix2D {

	/**
	 * This method is used to retrieve the actual PDF Libs Matrix2D
	 *
	 * @return the actual PDF Libs Matrix
	 */
	public abstract Object getPDFMatrix2D();

	/**
	 * Multiplies this matrix with another matrix and return the result in a new
	 * matrix.
	 *
	 * @param mtx
	 * @return the result of the multiplication
	 */
	public abstract PDFMatrix2D multiply(PDFMatrix2D mtx)
			throws PDFLibException;

}


text:
/**
 FOAM Bootstrap

 FOAM uses Models to specify class definitions.
 The FOAM Model class is itself specified with a FOAM model, meaning
 that Model is defined in the same language which it defines.
 This self-modeling system requires some care to bootstrap, but results
 in a very compact, uniform, and powerful system.

            Abstract Class
                  ^
                  |
 FObject -> FObject Class                     Prototype
    ^                        +-.prototype---------^
    |                        |                    |
  Model  -> buildClass()  -> Class -> create() -> instance

  FObject is the root model/class of all other classes, including Model.
  Abstract Class is the prototype of FObject's Class, which makes it the root of all Classes.
  From a Model we call buildClass() to create a Class (or the previously created Class) object.
  From the Class we call create() to create new instances of that class.
  New instances extend the classes prototype object, which is stored on the class as .prototype.

  instance ---> .cls_   -> Object's Class
       |
       +------> .model_ -> Object's Model

  All descendents of FObject have references to both their Model and Class.
    - obj.cls_ refers to an Object's Class
    - obj.model_ refers to an Object's Model

  Classes also refer to their Model with .model_.

  Model is its own definition:

    Model.buildClass().create(Model) == Model
    Model.model_ === Model

  Models are defined as a collection of Axioms.
  It is the responsibility of Axioms to install itself onto a Model's Class and/or Prototype.

  Axioms are defined with the following psedo-interface:

    public interface Axiom {
      optional installInClass(cls)
      optional installInProto(proto)
    }

  Ex. of a Model with one Axiom:

  foam.CLASS({
    name: 'Sample',

    axioms: [
      {
        name: 'axiom1',
        installInClass: function(cls) { ... },
        installInProto: function(proto) { ... }
      }
    ]
  });

  Axioms can be added either during the initial creation of a class and prototype,
  or anytime after.  This allows classes to be extended with new functionality,
  and this is very important to the bootstrap process because it allows us to
  start out with very simple definitions of Model and FObject, and then build
  them up until they're fully bootstrapped.

  However, raw axioms are rarely used directly. Instead we model higher-level
  axiom types, including:

Requires   - Require other classes

Imports    - Context imports

Exports    - Context exports

Implements - Declare interfaces implemented / mix-ins mixed-in

Constants  - Add constants to the prototype and class

Properties - High-level instance variable definitions

Methods    - Prototype methods

Topics     - Publish/sub topics

Listeners  - Like methods, but with extra features for use as callbacks

*/

/**
 Bootstrap support.

 Is discarded after use.
*/
foam.LIB({
  name: 'foam.boot',

  constants: {
    startTime: Date.now(),
  },

  methods: [
    /**
      Create or Update a Prototype from a Model definition.

      This will be added as a method on the Model class
      when it is eventually built.

      (Model is 'this').
    */
    function buildClass() {
      var context = this.__context__ || foam.__context__;
      var cls;

      if ( this.refines ) {
        cls = context.lookup(this.refines);
        console.assert(cls, 'Unknown refinement class: ' + this.refines);
      } else {
        console.assert(this.id, 'Missing id name.', this.name);
        console.assert(this.name, 'Missing class name.');

        var parent = this.extends      ?
          context.lookup(this.extends) :
          foam.AbstractClass;

        cls                  = Object.create(parent);
        cls.prototype        = Object.create(parent.prototype);
        cls.prototype.cls_   = cls;
        cls.prototype.model_ = this;
        cls.private_         = { axiomCache: {} };
        cls.axiomMap_        = Object.create(parent.axiomMap_);
        cls.id               = this.id;
        cls.package          = this.package;
        cls.name             = this.name;
        cls.model_           = this;

        // Install an FObject on the class that we can use as a pub/sub hub.
        // We have to do this because classes aren't FObjects.
        // This is used to publish 'installAxiom' events to, so that descendents
        // properties know when they need to be re-installed.
        cls.pubsub_ =
          foam.core.FObject &&
          foam.core.FObject.create &&
          foam.core.FObject.create();

        // Relay 'installAxiom' events from parent class.
        parent.pubsub_ && parent.pubsub_.sub(
            'installAxiom',
            function(_, a1, a2, a3) { cls.pubsub_.pub(a1, a2, a3); });
      }

      cls.installModel(this);

      return cls;
    },

    function start() {
      /* Start the bootstrap process. */

      var buildClass = this.buildClass;

      // Will be replaced in phase2.
      foam.CLASS = function(m) {
        m.id = m.package + '.' + m.name;
        var cls = buildClass.call(m);

        console.assert(
          ! m.refines,
          'Refines is not supported in early bootstrap');

        foam.register(cls);

        // Register the class in the global package path.
        foam.package.registerClass(cls);

        return cls;
      };
    },

    /** Start second phase of bootstrap process. */
    function phase2() {
      // Upgrade to final CLASS() definition.
      /** Creates a Foam class from a plain-old-object definition.
          @method CLASS
          @memberof module:foam */
      foam.CLASS = function(m) {
        var model = foam.core.Model.create(m);
        model.validate();
        var cls = model.buildClass();
        cls.validate();

        if ( ! m.refines ) {
          foam.register(cls);

          // Register the class in the global package path.
          foam.package.registerClass(cls);
        }

        return cls;
      };

      // Upgrade existing classes to real classes.
      for ( var key in foam.core ) {
        var m = foam.lookup(key).model_;
        m.refines = m.id;
        foam.CLASS(m);
      }
    },

    function phase3() {
      // Substitute AbstractClass.installModel() with simpler axiom-only version.
      foam.AbstractClass.installModel = function installModel(m) {
        this.installAxioms(m.axioms_);
      };
    },

    /** Finish the bootstrap process, deleting foam.boot when done. */
    function end() {
      var Model = foam.core.Model;

      // Update psedo-Models to real Models
      for ( var key in foam.core ) {
        var c = foam.core[key];
        c.prototype.model_ = c.model_ = Model.create(c.model_);
      }

      delete foam.boot;

      console.log('core boot time: ', Date.now() - this.startTime);
    }
  ]
});

foam.boot.start();


text:
package org.apache.hadoop.mapred.gridmix;

import java.util.concurrent.CountDownLatch;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.gridmix.Statistics.ClusterStats;
import org.apache.hadoop.mapred.gridmix.Statistics.JobStats;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.tools.rumen.JobStory;
import org.apache.hadoop.tools.rumen.TaskAttemptInfo;
import org.apache.hadoop.tools.rumen.TaskInfo;
import org.apache.hadoop.tools.rumen.Pre21JobHistoryConstants.Values;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Test the Gridmix's {@link Statistics} class.
 */
public class TestGridmixStatistics {
  /**
   * Test {@link Statistics.JobStats}.
   */
  @Test
  @SuppressWarnings("deprecation")
  public void testJobStats() throws Exception {
    Job job = new Job() {};
    JobStats stats = new JobStats(1, 2, job);
    assertEquals("Incorrect num-maps", 1, stats.getNoOfMaps());
    assertEquals("Incorrect num-reds", 2, stats.getNoOfReds());
    assertTrue("Incorrect job", job == stats.getJob());
    assertNull("Unexpected job status", stats.getJobStatus());

    // add a new status
    JobStatus status = new JobStatus();
    stats.updateJobStatus(status);
    assertNotNull("Missing job status", stats.getJobStatus());
    assertTrue("Incorrect job status", status == stats.getJobStatus());
  }

  private static JobStory getCustomJobStory(final int numMaps,
                                            final int numReds) {
    return new JobStory() {
      @Override
      public InputSplit[] getInputSplits() {
        return null;
      }
      @Override
      public JobConf getJobConf() {
        return null;
      }
      @Override
      public JobID getJobID() {
        return null;
      }
      @Override
      public TaskAttemptInfo getMapTaskAttemptInfoAdjusted(int arg0, int arg1,
                                                           int arg2) {
        return null;
      }
      @Override
      public String getName() {
        return null;
      }
      @Override
      public int getNumberMaps() {
        return numMaps;
      }
      @Override
      public int getNumberReduces() {
        return numReds;
      }
      @Override
      public Values getOutcome() {
        return null;
      }
      @Override
      public String getQueueName() {
        return null;
      }
      @Override
      public long getSubmissionTime() {
        return 0;
      }
      @Override
      public TaskAttemptInfo getTaskAttemptInfo(TaskType arg0, int arg1,
                                                int arg2) {
        return null;
      }
      @Override
      public TaskInfo getTaskInfo(TaskType arg0, int arg1) {
        return null;
      }
      @Override
      public String getUser() {
        return null;
      }
    };
  }

  /**
   * Test {@link Statistics}.
   */
  @Test
  @SuppressWarnings("deprecation")
  public void testStatistics() throws Exception {
    // test job stats generation
    Configuration conf = new Configuration();

    // test dummy jobs like data-generation etc
    Job job = new Job(conf) {
    };
    JobStats stats = Statistics.generateJobStats(job, null);
    testJobStats(stats, -1, -1, null, job);

    // add a job desc with 2 map and 1 reduce task
    conf.setInt(GridmixJob.GRIDMIX_JOB_SEQ, 1);

    // test dummy jobs like data-generation etc
    job = new Job(conf) {
    };
    JobStory zjob = getCustomJobStory(2, 1);
    stats = Statistics.generateJobStats(job, zjob);
    testJobStats(stats, 2, 1, null, job);

    // add a job status
    JobStatus jStatus = new JobStatus();
    stats.updateJobStatus(jStatus);
    testJobStats(stats, 2, 1, jStatus, job);

    // start the statistics
    CountDownLatch startFlag = new CountDownLatch(1); // prevents the collector
                                                      // thread from starting
    Statistics statistics = new Statistics(new JobConf(), 0, startFlag);
    statistics.start();

    testClusterStats(0, 0, 0);

    // add to the statistics object
    statistics.addJobStats(stats);
    testClusterStats(2, 1, 1);

    // add another job
    JobStory zjob2 = getCustomJobStory(10, 5);
    conf.setInt(GridmixJob.GRIDMIX_JOB_SEQ, 2);
    job = new Job(conf) {
    };

    JobStats stats2 = Statistics.generateJobStats(job, zjob2);
    statistics.addJobStats(stats2);
    testClusterStats(12, 6, 2);

    // finish off one job
    statistics.add(stats2);
    testClusterStats(2, 1, 1);

    // finish off the other job
    statistics.add(stats);
    testClusterStats(0, 0, 0);

    statistics.shutdown();
  }

  // test the job stats
  private static void testJobStats(JobStats stats, int numMaps, int numReds,
                                   JobStatus jStatus, Job job) {
    assertEquals("Incorrect num map tasks", numMaps, stats.getNoOfMaps());
    assertEquals("Incorrect num reduce tasks", numReds, stats.getNoOfReds());

    if (job != null) {
      assertNotNull("Missing job", job);
    }
    // check running job
    assertTrue("Incorrect job", job == stats.getJob());

    if (jStatus != null) {
      assertNotNull("Missing job status", jStatus);
    }
    // check job stats
    assertTrue("Incorrect job status", jStatus == stats.getJobStatus());
  }

  // test the cluster stats
  private static void testClusterStats(int numSubmittedMapTasks,
                                       int numSubmittedReduceTasks,
                                       int numSubmittedJobs) {
    assertEquals("Incorrect count of total number of submitted map tasks",
                 numSubmittedMapTasks, ClusterStats.getSubmittedMapTasks());
    assertEquals("Incorrect count of total number of submitted reduce tasks",
                 numSubmittedReduceTasks,
                 ClusterStats.getSubmittedReduceTasks());
    assertEquals("Incorrect submitted jobs",
                 numSubmittedJobs, ClusterStats.getRunningJobStats().size());
  }
}