text:
"""Utility functions for the main application."""

import os
import subprocess
import re
import sys

def create_directories(directory_names):
    """Create directories from a given list of directory names."""
    for directory in directory_names:
        if not os.path.exists(directory):
            os.makedirs(directory)

def grab_section_text(section_name, filename):
    """Return the text from a section in a file.

    Sections are marked begining with $$section_name$$ and ending with
    $$-$$.  This function returns all text in-between these markers.
    """
    with open(filename, 'r') as f:
        text = f.read()

    return re.match(
        '\$\$' + section_name + '\$\$\\n(.+?)(?=\$\$-\$\$)',
        text,
        re.DOTALL
    ).group(1)

def replace_placeholders(body_text, **kwargs):
    """Replace keywords in text marked like [KEYWORD]."""
    for key, value in kwargs.items():
        body_text = re.sub('\[' + key + ']', value, body_text, 0, re.DOTALL)
    return body_text

def run_pyramid_scaffold(appname, sqlalchemy=True):
    """Create normal pyramid scaffold."""
    p = subprocess.Popen(['pip', 'install', '-U', 'pip', 'setuptools'])
    subprocess.Popen.wait(p)
    p = subprocess.Popen(['pip', 'install', 'pyramid', 'pyramid_ipython'])
    subprocess.Popen.wait(p)

    if sqlalchemy:
        p = subprocess.Popen(['pip', 'install', 'sqlalchemy'])
        subprocess.Popen.wait(p)
        alchemy = 'alchemy'
    else:
        alchemy = ''

    p = subprocess.Popen(['pcreate', '-s', alchemy, appname])
    subprocess.Popen.wait(p)

def create_generic_route_code(route_name, renderer='', permission=''):
    """Return text for a generic route."""
    return replace_placeholders(
        grab_section_text('generic_route', 'generics'),
        ROUTE_NAME=route_name,
        TEMPLATE=renderer,
        PERMISSION=permission)

if __name__ == '__main__':
    if sys.prefix == sys.base_prefix:
        print('Please activate a virtual environment.')
        sys.exit(1)

    # run_pyramid_scaffold('testapp1')
    # print('--Sorry for even more convenience.')

    # # cleanup for testing
    # p = subprocess.Popen(['rm', '-rf', 'testapp1'])
    # subprocess.Popen.wait(p)


text:
package gwt.material.design.client.resources;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;

public interface DarkThemeResources extends ClientBundle {
    DarkThemeResources INSTANCE = GWT.create(DarkThemeResources.class);

    @Source("css/core-dark.min.css")
    TextResource darkCss();
}

redpajama_set_name: RedPajamaGithub


text:
<?php
// check if fields passed are empty
if(empty($_POST['name']) ||
   empty($_POST['phone']) ||
   empty($_POST['email']) ||
   empty($_POST['pickuptime']) ||
   empty($_POST['pickupdate']) ||
   empty($_POST['pickuplocation']) ||
   empty($_POST['passengers']) ||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$pickuptime = $_POST['pickuptime'];
$pickupdate = $_POST['pickupdate'];
$pickuplocation = $_POST['pickuplocation'];
$passengers = $_POST['passengers'];
$message = $_POST['message'];

// create email body and send it
$to = 'taxibase@corkairporttaxi.ie'; // PUT YOUR EMAIL ADDRESS HERE
$email_subject = "Cork Airport Taxi:  $name"; // EDIT THE EMAIL SUBJECT LINE HERE
$email_body = "You have received a new message from your website's contact form.\n\n"."Here are the details:\n\nName: $name\n\nPhone: $phone\n\nEmail: $email_address
                \n\nPickupTime: $pickuptime \n\nPickupDate: $pickupdate \n\nPickupLocation: $pickuplocation \n\Passengers: $passengers \n\nMessage:\n$message";
$headers = "From: noreply@your-domain.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>


text:
using UnityEngine;

public abstract class LogReader  : RAEComponent {
    public abstract StudentAction Current {get;}
    public abstract StudentAction Previous{get;}
    public abstract StudentAction Next { get; }
    public abstract StudentAction LastStartState { get; }

    public abstract bool IsNewAttempt { get; }
    public abstract bool Loaded { get; }
    public abstract bool HasNext { get; }

    public abstract void Load();

    public abstract StudentAction GetNextStudentAction();
}


text:
layout: post
title: "The good, the bad and the ugly with responsive web design"
description: Responsive Web Design has been around for a while and it's worth taking a step back to see what a successful responsive project actually requires.
og_image: /images/blog/talks/the-good-the-bad-and-the-ugly/the-good-the-bad-and-the-ugly.001.jpg
---

# The good, the bad and the ugly with responsive web design

One of the great benefits of attending conferences is that you get to meet interesting people and share ideas.

Last week we traveled to Barcelona and got the opportunity to visit [Elespacio](http://www.elespacio.net/) and give a talk titled "The good, the bad and the ugly with responsive web design" at the [Space is the place 2](https://www.facebook.com/elespacio.net/posts/930710413629827).

{% include post-image.html alt="Awwwards Conference 2015" src="/images/blog/talks/the-good-the-bad-and-the-ugly/the-good-the-bad-and-the-ugly.001.jpg" margin="both" ratio="4_3" %}

Responsive Web Design has been around for a while and it's worth taking a step back to see what a successful responsive project actually requires.

The goal with the talk was to share some opinionated thoughts on what is positive, and what we should pay attention to in our development workflow. An inside look behind some Responsive Web Design case studies were shown, as well as how we addressed some of the good, the bad and the ugly points behind each of those projects.

{% include blog-speakerdeck.html id="c9abb26aa48547998a2bf3bd2d5058d6" ratio="4_3" %}

Big thanks to [Elespacio](http://www.elespacio.net/) for inviting us to the very interesting *Space is the place 2* event. Hope to see you all again soon!

{% include blog-author-marco.html %}


text:
import sys
import dna

a = dna.Genome((sys.argv[1],),'A')
b = dna.Genome((sys.argv[2],),'B')

print a
print b

ckeys = a.chromosomes.keys()
ckeys.sort()
for clabel in ckeys:
  if clabel != 'MT' and clabel != 'Y' and clabel != 'X':
    print clabel
    c = a.chromosomes[clabel]
    positions = c.keys()
    positions.sort()
    matchStart = None
    matchLength = 0
    for p in positions:
      sa = c[p]
      sb = b.chromosomes[clabel][p]
      if sa.hasGenotype() and sb.hasGenotype():
        if sa.matches(sb):
          if matchStart is None:
            matchStart = p
          matchLength += 1
        else:
          if matchLength > 700:
            print 'start:',matchStart,'end:',p,'count:',matchLength
          matchStart = None
          matchLength = 0


text:
"use strict";
var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic');
//import {GOOGLE_MAPS_PROVIDERS} from 'angular2-google-map/core';
var app_module_1 = require('./app.module');
platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule /*, [GOOGLE_MAPS_PROVIDERS]*/);
//# sourceMappingURL=main.js.map


text:
// Define the LiveStreamController on the adminUI module
angular.module('adminUI')
  .controller('LiveStreamController', ['$scope', 'schedulerService', function ($scope, schedulerService) {
    $scope.skipHlsCheck = false;
    $scope.loadVideo = function () {
      var ua = navigator.userAgent.toLowerCase();
      var isAndroid = ua.indexOf("android") > -1;

      if(isAndroid) {
        window.location = 'http://delta-1-yanexx65s8e5.live.elementalclouddev.com/out/p/15/it me.m3u8';
        return;
      }
      if (schedulerService.livestreamURL === '') {
        toastr.error("Please enter an output URL in config.", "Error")
      }
      else {
        if (($scope.skipHlsCheck === false) || (Hls.isSupported() !== undefined)) {
          var video = document.getElementById('video');
          var hls = new Hls();
          hls.loadSource(schedulerService.livestreamURL);
          hls.attachMedia(video);
        }
        else {
          toastr.error("Your browser does not support HLS streaming", "Error");
        }
      }
    }
}]);


text:
#import <Foundation/Foundation.h>

extern NSString * const kPrefKeepMultipleRuns;

extern NSString * const kPrefPublishesBonjourService;
extern NSString * const kPrefHasDirectTCPIPResponder;
extern NSString * const kPrefDirectTCPIPResponderPort;
extern NSString * const kPrefBonjourServiceName;
extern NSString * const kPrefClientApplicationSettings;

extern NSString * const kPref_ApplicationFilterSet;


text:
(function() {
    'use strict';

    angular
    	.module('accounts.transactions')
    	.controller('TransactionsController', TransactionsController);

    function TransactionsController($scope, $resource, $stateParams, Accounts, DTOptionsBuilder, DTColumnDefBuilder) {
        var vm = this;
        var data = '';
        vm.account = {
            id: $stateParams.accountID,
            name: 'Checking',
            transactions: []
        };
        if(vm.account.id == 1){
            vm.account.name = 'Checking'
            data = 'app/data/transactions1.json';
        }
        else if(vm.account.id == 2){
            vm.account.name = 'Savings'
            data = 'app/data/transactions2.json';
        }
        else if(vm.account.id == 3){
            vm.account.name = 'Retirement'
            data = 'app/data/transactions3.json';
        }

        Accounts.getTransactions(1)
            .then(function success(res) {
                    console.log('got transactions');
                }, function error(res) {

                });

        //creates settings for datatable
        $scope.dtOptions = {
            aaSorting     :[0, 'desc']
        }
        $scope.dtColumnDefs = [
            DTColumnDefBuilder.newColumnDef(0).notSortable(),
            DTColumnDefBuilder.newColumnDef(1).notSortable(),
            DTColumnDefBuilder.newColumnDef(2).notSortable(),
            DTColumnDefBuilder.newColumnDef(3).notSortable(),
            DTColumnDefBuilder.newColumnDef(4).notSortable()
        ];

        $resource(data).query().$promise.then(function(transactions) {
	        vm.account.transactions = transactions;
	    });
    }
})();


text:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const uglifySaveLicense = require('uglify-save-license');
const electronVersion = require('./package.json').devDependencies.electron.slice(1);

const isProduction = process.env.NODE_ENV === 'production';

const common = {
  devtool: isProduction ? false : 'inline-source-map',
  node: { __filename: true, __dirname: false },
  resolve: { extensions: ['.ts', '.tsx', '.js'] },
  watchOptions: { ignored: /node_modules|lib/ }
};

function tsModule(targets) {
  return {
    rules: [{
      test: /\.tsx?$/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            env: {
              development: {
                plugins: [['babel-plugin-espower', { 'embedAst': true }]]
              },
              production: {
                presets: ['babili']
              }
            },
            presets: [['env', { targets }]]
          }
        },
        {
          loader: 'ts-loader',
          options: { compilerOptions: { sourceMap: !isProduction } }
        }
      ]
    }]
  };
}

module.exports = [
  Object.assign({},
    common,
    {
      entry: {
        index: ['babel-polyfill', './src/public/js/index.tsx']
      },
      externals: /^electron$/,
      module: tsModule({ uglify: true }),
      output: {
        filename: 'lib/public/js/[name].js',
        libraryTarget: 'commonjs2'
      },
      plugins: [
        ...[
          new CopyWebpackPlugin(
            [
              { from: "src/public/", to: "lib/public/" },
              { from: "src/res/", to: "lib/res/" }
            ],
            {
              ignore: [
                'test/',
                '*.ts',
                '*.tsx'
              ]
            })
        ],
        ...(
          !isProduction ? [] : [
            new webpack.optimize.UglifyJsPlugin({
              output: { comments: uglifySaveLicense }
            })
          ]
        )
      ],
      target: 'electron-renderer'
    }
  ),
  Object.assign({},
    common,
    {
      entry: {
        index: ['babel-polyfill', './src/index.ts'],
        'test/test': ['babel-polyfill', './src/test/test.ts']
      },
      externals: /^(?!\.)/,
      module: tsModule({ electron: electronVersion }),
      output: {
        filename: 'lib/[name].js',
        libraryTarget: 'commonjs2'
      },
      target: 'electron-main'
    }
  )
];


text:
if [[ "$OSTYPE" != (darwin|linux)* ]]; then
  return 1
fi

#
# Variables
#

# Load standard Homebrew shellenv into the shell session.
# Load 'HOMEBREW_' prefixed variables only. Avoid loading 'PATH' related
# variables as they are already handled in standard zsh configuration.
if (( $+commands[brew] )); then
  eval "${(@M)${(f)"$(brew shellenv 2> /dev/null)"}:#export HOMEBREW*}"
fi

#
# Aliases
#

# Homebrew
alias brewc='brew cleanup'
alias brewC='brew cleanup --force'
alias brewi='brew install'
alias brewl='brew list'
alias brewo='brew outdated'
alias brews='brew search'
alias brewu='brew upgrade'
alias brewx='brew uninstall'

# Homebrew Cask
alias cask='brew cask'
alias caskc='hb_deprecated brew cask cleanup'
alias caskC='hb_deprecated brew cask cleanup'
alias caski='brew cask install'
alias caskl='brew cask list'
alias casko='brew cask outdated'
alias casks='hb_deprecated brew cask search'
alias caskx='brew cask uninstall'

function hb_deprecated {
  local cmd="${@[3]}"
  local cmd_args="${@:4}"

  printf "'brew cask %s' has been deprecated, " "${cmd}"
  printf "using 'brew %s' instead\n" "${cmd}"

  command brew "${cmd}" "${=cmd_args}"
}


text:
package fr.univnantes.lina.uima.tkregex.test;

import fr.univnantes.lina.uima.tkregex.model.matchers.RegexCoveredTextMatcher;
import org.apache.uima.jcas.tcas.Annotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class RegexCoveredTextMatcherSpec {
	public Annotation getAnnotation(String coveredText) {
		Annotation anno = Mockito.mock(Annotation.class);
		Mockito.when(anno.getCoveredText()).thenReturn(coveredText);
		return anno;
	}

	@Test
	public void testMatch() {
		doTest("Le baccalauréat", "bac", true);
		// should be case-insensitive
		doTest("Le baccalauréat", "baC", true);
		doTest("Le baccalauréat", "^bac", false);
		doTest("Le baccalauréat", "^Le bac", true);
		doTest("Le baccalauréat", "^Le bac$", false);
		doTest("Le baccalauréat", "^Le b(a|e)?c*", true);
		doTest("Le baccalauréat", "^Le{2} b(a|e)?c*", false);
	}

	public void doTest(String coveredText, String regex, boolean matches) {
		RegexCoveredTextMatcher m = new RegexCoveredTextMatcher(regex);
		assertEquals(matches, m.matches(getAnnotation(coveredText)));
	}
}


text:
#include "sky/engine/config.h"
#include "sky/engine/core/events/CompositionEvent.h"

namespace blink {

CompositionEventInit::CompositionEventInit()
{
}

CompositionEvent::CompositionEvent()
    : m_activeSegmentStart(0)
    , m_activeSegmentEnd(0)
{
    initializeSegments();
}

CompositionEvent::CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data, const Vector<CompositionUnderline>& underlines)
    : UIEvent(type, true, true, view, 0)
    , m_data(data)
    , m_activeSegmentStart(0)
    , m_activeSegmentEnd(0)
{
    initializeSegments(&underlines);
}

CompositionEvent::CompositionEvent(const AtomicString& type, const CompositionEventInit& initializer)
    : UIEvent(type, initializer)
    , m_data(initializer.data)
    , m_activeSegmentStart(0)
    , m_activeSegmentEnd(0)
{
    initializeSegments();
}

CompositionEvent::~CompositionEvent()
{
}

void CompositionEvent::initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
{
    if (dispatched())
        return;

    initUIEvent(type, canBubble, cancelable, view, 0);

    m_data = data;
    initializeSegments();
}

void CompositionEvent::initializeSegments(const Vector<CompositionUnderline>* underlines)
{
    m_activeSegmentStart = 0;
    m_activeSegmentEnd = m_data.length();

    if (!underlines || !underlines->size()) {
        m_segments.append(0);
        return;
    }

    for (size_t i = 0; i < underlines->size(); ++i) {
        if (underlines->at(i).thick) {
            m_activeSegmentStart = underlines->at(i).startOffset;
            m_activeSegmentEnd = underlines->at(i).endOffset;
            break;
        }
    }

    for (size_t i = 0; i < underlines->size(); ++i)
        m_segments.append(underlines->at(i).startOffset);
}

const AtomicString& CompositionEvent::interfaceName() const
{
    return EventNames::CompositionEvent;
}

} // namespace blink


text:
package rocks.bottery.bot.recognizer.luis;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

/**
 * JAX-RS Proxy API definition for LUIS API
 *
 * @author Harald Kuhn
 *
 */
@Path("/")
public interface LuisApi {

	@Path("/apps/{appId}")
	@GET
	@Consumes({ "application/x-www-form-urlencoded" })
	@Produces({ "application/json" })
	public LuisResponse query(@PathParam("appId") String appId, @QueryParam("subscription-key") String subscriptionKey, @QueryParam("q") String query);

}


text:
Rails.application.routes.draw do
  # The priority is based upon order of creation: first created -> highest priority.

  namespace :api, format: true, constraints: { format: 'json' }, except: [:new, :edit] do
    resources :spells do
      resources :ingredients, shallow: true
    end
  end

  match '*unmatched_route', to: 'application#routing_error', via: :all

end


text:
const expect  = require('chai').expect;
const utility = require('../utility');

describe('template', function() {
    it('works as expected', function() {
        expect(utility.template('abc [_1] abc', ['2'])).to.eq('abc 2 abc');
        expect(utility.template('[_1] [_2]', ['1', '2'])).to.eq('1 2');
        expect(utility.template('[_1] [_1]', ['1'])).to.eq('1 1');
    });

    it('does not replace twice', function() {
        expect(utility.template('[_1] [_2]', ['[_2]', 'abc'])).to.eq('[_2] abc');
    });
});

describe('objectNotEmpty', function() {
    it('returns true for empty objects', function() {
        expect(utility.objectNotEmpty({})).to.eq(false);
        expect(utility.objectNotEmpty({ notEmpty: true })).to.eq(true);
    });

    it('returns false for non objects', function() {
        expect(utility.objectNotEmpty(1)).to.eq(false);
        expect(utility.objectNotEmpty(undefined)).to.eq(false);
        expect(utility.objectNotEmpty(null)).to.eq(false);
        expect(utility.objectNotEmpty(false)).to.eq(false);
        expect(utility.objectNotEmpty(true)).to.eq(false);
        expect(utility.objectNotEmpty('')).to.eq(false);
    });
});


text:
var expect = require('chai').expect
  , setup = require('../../../../setup')
  , teardown = require('../../../../teardown')
  , create = require('jsr-client')
  , client;

describe('jsr-server (tcp):', function() {

  before(function(done) {
    setup(function() {
      client = create();
      client.once('connect', done);
    })
  });
  after(teardown);

  it('should reply with zero on non-member (sismember)', function(done) {
    var k = 'set';
    client.sadd(k, 'a', function onReply(err, reply) {
      expect(err).to.eql(null);
      expect(reply).to.eql(1);
      client.sismember(k, 'z', function onReply(err, reply) {
        expect(err).to.eql(null);
        expect(reply).to.eql(0);
        done();
      })
    });
  });

  it('should reply with one on member (sismember)', function(done) {
    var k = 'set';
    client.sadd(k, 'a', function onReply(err, reply) {
      expect(err).to.eql(null);
      expect(reply).to.eql(0);
      client.sismember(k, 'a', function onReply(err, reply) {
        expect(err).to.eql(null);
        expect(reply).to.eql(1);
        done();
      })
    });
  });

});


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Dataflow extends Kohana_Dataflow {}


text:
function(page, match, widgets) {
    $.evently.connect(widgets["topics-list"], widgets["bigLoader"], ["showLoading", "hideLoading"]);
    API.connectVisible(document.body, widgets["topics-list"], ["setFilter", "filter-state-changed"]);
}


text:
 Gets a list of fields from a list by names.

**Namespace:** [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public static IEnumerable<Field> GetFields(this List list, params String[] fieldInternalNames)
```
### Parameters
#### list
  Type: Microsoft.SharePoint.Client.List
  The target list containing the fields.

#### fieldInternalNames
  Type: System.String[]
  List of field names to retreieve.

### Return Value
Type: IEnumerable<Field>
List of fields requested.

## See also
- [FieldAndContentTypeExtensions](Microsoft.SharePoint.Client.FieldAndContentTypeExtensions.md)
- [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md)


text:
==========
desibgsdev
==========

This repository contains development code and documentation for the DESI Bright
Galaxy Survey (BGS) Working Group.

To upload code you need to:

1. Make a fork from the main repository
2. Request a pull
3. Review and merge

These steps are detailed here:
https://help.github.com/articles/creating-a-pull-request-from-a-fork/

Before you make the 'pull request' make sure you are not including temporary files, by adding a .gitignore file (https://git-scm.com/docs/gitignore ).

Also, if you create a new folder, make sure to include a README.md file explaining what is stored there.


text:
import { XmlChildElement, XmlContent, XmlElement } from "xml-core";
import { IConverter } from "xml-core";

import { Any } from "./any";
import { ObjectIdentifier } from "./object_identifier";
import { XmlXades } from "./xml";
import { XadesCollection, XadesObject } from "./xml_base";

/**
 *
 * <xsd:element name="CommitmentTypeIndication" type="CommitmentTypeIndicationType"/>
 * <xsd:complexType name="CommitmentTypeIndicationType">
 *     <xsd:sequence>
 *         <xsd:element name="CommitmentTypeId" type="ObjectIdentifierType"/>
 *         <xsd:choice>
 *             <xsd:element name="ObjectReference" type="xsd:anyURI" maxOccurs="unbounded"/>
 *             <xsd:element name="AllSignedDataObjects"/>
 *         </xsd:choice>
 *         <xsd:element name="CommitmentTypeQualifiers" type="CommitmentTypeQualifiersListType" minOccurs="0"/>
 *     </xsd:sequence>
 * </xsd:complexType>
 * <xsd:complexType name="CommitmentTypeQualifiersListType">
 *     <xsd:sequence>
 *         <xsd:element name="CommitmentTypeQualifier" type="AnyType" minOccurs="0" maxOccurs="unbounded"/>
 *     </xsd:sequence>
 * </xsd:complexType>
 *
 */

@XmlElement({ localName: XmlXades.ElementNames.CommitmentTypeQualifier })
export class CommitmentTypeQualifier extends Any { }

@XmlElement({ localName: XmlXades.ElementNames.CommitmentTypeQualifiers, parser: CommitmentTypeQualifier })
export class CommitmentTypeQualifiers extends XadesCollection<CommitmentTypeQualifier> { }

@XmlElement({ localName: XmlXades.ElementNames.ObjectReference })
export class ObjectReference extends XadesObject {

    @XmlContent({ required: true })
    public Value: string;
}

@XmlElement({ localName: "ObjectReferences", parser: ObjectReference })
export class ObjectReferenceCollection extends XadesCollection<ObjectReference> { }

const XmlAllSignedDataObjectsConverter: IConverter<boolean> = {
    set: (value: string) => {
        // if SignaturePolicyImplied exists then return true
        return true;
    },
    get: (value: boolean) => {
        return void 0;
    },
};

@XmlElement({ localName: XmlXades.ElementNames.CommitmentTypeIndication })
export class CommitmentTypeIndication extends XadesObject {

    @XmlChildElement({
        localName: XmlXades.ElementNames.CommitmentTypeId,
        required: true,
        namespaceURI: XmlXades.NamespaceURI,
        prefix: XmlXades.DefaultPrefix,
        parser: ObjectIdentifier,
    })
    public CommitmentTypeId: ObjectIdentifier;

    @XmlChildElement({ parser: ObjectReferenceCollection, noRoot: true })
    public ObjectReference: ObjectReferenceCollection;

    @XmlChildElement({
        localName: XmlXades.ElementNames.AllSignedDataObjects,
        namespaceURI: XmlXades.NamespaceURI,
        prefix: XmlXades.DefaultPrefix,
        converter: XmlAllSignedDataObjectsConverter,
        defaultValue: false,
    })
    public AllSignedDataObjects: boolean;

    @XmlChildElement({ localName: XmlXades.ElementNames.CommitmentTypeQualifiers, parser: CommitmentTypeQualifier })
    public CommitmentTypeQualifiers: CommitmentTypeQualifiers;

}


text:
package com.cloud.vm.snapshot;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import com.amazonaws.services.ec2.model.HypervisorType;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CreateVMSnapshotAnswer;
import com.cloud.agent.api.CreateVMSnapshotCommand;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;

public class VMSnapshotManagerTest {
    @Spy VMSnapshotManagerImpl _vmSnapshotMgr = new VMSnapshotManagerImpl();
    @Mock Account admin;
    @Mock VMSnapshotDao _vmSnapshotDao;
    @Mock VolumeDao _volumeDao;
    @Mock AccountDao _accountDao;
    @Mock VMInstanceDao _vmInstanceDao;
    @Mock UserVmDao _userVMDao;
    @Mock HostDao _hostDao;
    @Mock UserDao _userDao;
    @Mock AgentManager _agentMgr;
    @Mock HypervisorGuruManager _hvGuruMgr;
    @Mock AccountManager _accountMgr;
    @Mock GuestOSDao _guestOSDao;
    @Mock PrimaryDataStoreDao _storagePoolDao;
    @Mock SnapshotDao _snapshotDao;
    @Mock VirtualMachineManager _itMgr;
    @Mock ConfigurationDao _configDao;
    @Mock HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
    int _vmSnapshotMax = 10;

    private static long TEST_VM_ID = 3L;
    @Mock UserVmVO vmMock;
    @Mock VolumeVO volumeMock;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
        doReturn(admin).when(_vmSnapshotMgr).getCaller();
        _vmSnapshotMgr._accountDao = _accountDao;
        _vmSnapshotMgr._userVMDao = _userVMDao;
        _vmSnapshotMgr._vmSnapshotDao = _vmSnapshotDao;
        _vmSnapshotMgr._volumeDao = _volumeDao;
        _vmSnapshotMgr._accountMgr = _accountMgr;
        _vmSnapshotMgr._snapshotDao = _snapshotDao;
        _vmSnapshotMgr._guestOSDao = _guestOSDao;
        _vmSnapshotMgr._hypervisorCapabilitiesDao = _hypervisorCapabilitiesDao;

        doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class),
                any(Boolean.class), any(ControlledEntity.class));

        _vmSnapshotMgr._vmSnapshotMax = _vmSnapshotMax;

        when(_userVMDao.findById(anyLong())).thenReturn(vmMock);
        when(_vmSnapshotDao.findByName(anyLong(), anyString())).thenReturn(null);
        when(_vmSnapshotDao.findByVm(anyLong())).thenReturn(new ArrayList<VMSnapshotVO>());
        when(_hypervisorCapabilitiesDao.isVmSnapshotEnabled(Hypervisor.HypervisorType.XenServer, "default")).thenReturn(true);

        List<VolumeVO> mockVolumeList = new ArrayList<VolumeVO>();
        mockVolumeList.add(volumeMock);
        when(volumeMock.getInstanceId()).thenReturn(TEST_VM_ID);
        when(_volumeDao.findByInstance(anyLong())).thenReturn(mockVolumeList);

        when(vmMock.getInstanceName()).thenReturn("i-3-VM-TEST");
        when(vmMock.getState()).thenReturn(State.Running);
        when(vmMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer);
        when(_guestOSDao.findById(anyLong())).thenReturn(mock(GuestOSVO.class));
    }

    // vmId null case
    @Test(expected=InvalidParameterValueException.class)
    public void testAllocVMSnapshotF1() throws ResourceAllocationException{
        when(_userVMDao.findById(TEST_VM_ID)).thenReturn(null);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // hypervisorCapabilities not expected case
    @Test(expected=InvalidParameterValueException.class)
    public void testAllocVMSnapshotF6() throws ResourceAllocationException{
        when(vmMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.Ovm);
        when(_hypervisorCapabilitiesDao.isVmSnapshotEnabled(Hypervisor.HypervisorType.Ovm, "default")).thenReturn(false);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // vm state not in [running, stopped] case
    @Test(expected=InvalidParameterValueException.class)
    public void testAllocVMSnapshotF2() throws ResourceAllocationException{
        when(vmMock.getState()).thenReturn(State.Starting);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // VM in stopped state & snapshotmemory case
    @Test(expected=InvalidParameterValueException.class)
    public void testCreateVMSnapshotF3() throws AgentUnavailableException, OperationTimedoutException, ResourceAllocationException{
        when(vmMock.getState()).thenReturn(State.Stopped);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // max snapshot limit case
    @SuppressWarnings("unchecked")
    @Test(expected=CloudRuntimeException.class)
    public void testAllocVMSnapshotF4() throws ResourceAllocationException{
        List<VMSnapshotVO> mockList = mock(List.class);
        when(mockList.size()).thenReturn(10);
        when(_vmSnapshotDao.findByVm(TEST_VM_ID)).thenReturn(mockList);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // active volume snapshots case
    @SuppressWarnings("unchecked")
    @Test(expected=CloudRuntimeException.class)
    public void testAllocVMSnapshotF5() throws ResourceAllocationException{
        List<SnapshotVO> mockList = mock(List.class);
        when(mockList.size()).thenReturn(1);
        when(_snapshotDao.listByInstanceId(TEST_VM_ID,Snapshot.State.Creating,
                Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp)).thenReturn(mockList);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);
    }

    // successful creation case
    @Test
    public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException, ResourceAllocationException, NoTransitionException{
        when(vmMock.getState()).thenReturn(State.Running);
        _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID,"","",true);

        when(_vmSnapshotDao.findCurrentSnapshotByVmId(anyLong())).thenReturn(null);
        doReturn(new ArrayList<VolumeTO>()).when(_vmSnapshotMgr).getVolumeTOList(anyLong());
        doReturn(new CreateVMSnapshotAnswer(null,true,"")).when(_vmSnapshotMgr).sendToPool(anyLong(), any(CreateVMSnapshotCommand.class));
        doNothing().when(_vmSnapshotMgr).processAnswer(any(VMSnapshotVO.class),
                any(UserVmVO.class), any(Answer.class), anyLong());
        doReturn(true).when(_vmSnapshotMgr).vmSnapshotStateTransitTo(any(VMSnapshotVO.class),any(VMSnapshot.Event.class));
        _vmSnapshotMgr.createVmSnapshotInternal(vmMock, mock(VMSnapshotVO.class), 5L);
    }

}


text:
package org.lvu.adapters;

import android.content.Context;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;

import org.lvu.R;
import org.lvu.customize.WrapContentDraweeView;
import org.lvu.models.Data;
import org.lvu.utils.ImmerseUtil;

import java.util.List;

/**
 * Created by wuyr on 6/23/16 3:15 PM.
 */
public abstract class BasePictureListAdapter extends BaseListAdapter {

    protected BasePictureListAdapter(Context context, int layoutId, List<Data> data) {
        super(context, layoutId, data);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_BOTTOM && ImmerseUtil.isAboveKITKAT()
                && ImmerseUtil.isHasNavigationBar(mContext))
            return new FooterHolder(mLayoutInflater.inflate(
                    R.layout.recycler_view_item_footer, parent, false));
        return new ViewHolder(mLayoutInflater.inflate(mLayoutId, parent, false));
    }

    @Override
    public void onBindViewHolder(BaseListAdapter.ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        initItemImage(holder, position);
    }

    protected void initItemImage(final BaseListAdapter.ViewHolder holder, int position) {
        if (mData.isEmpty())
            return;
        try {
            holder.image.setImageURI(Uri.parse(mData.get(position != 0 && position >= mData.size() ? mData.size() - 1 : position).getSrc()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ViewHolder extends BaseListAdapter.ViewHolder {

        public ViewHolder(View itemView) {
            super(itemView);
            image = (WrapContentDraweeView) itemView.findViewById(R.id.image);
        }
    }
}


text:
module Zip
  class Decompressor #:nodoc:all
    CHUNK_SIZE = 32_768

    def self.decompressor_classes
      @decompressor_classes ||= {}
    end

    def self.register(compression_method, decompressor_class)
      decompressor_classes[compression_method] = decompressor_class
    end

    def self.find_by_compression_method(compression_method)
      decompressor_classes[compression_method]
    end

    attr_reader :input_stream
    attr_reader :decompressed_size

    def initialize(input_stream, decompressed_size = nil)
      super()

      @input_stream = input_stream
      @decompressed_size = decompressed_size
    end
  end
end

# Copyright (C) 2002, 2003 Thomas Sondergaard
# rubyzip is free software; you can redistribute it and/or
# modify it under the terms of the ruby license.


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/3rdparty/hermes/hermes.cpp" "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/release/3rdparty/hermes/CMakeFiles/referee.dir/hermes.cpp.o"
  "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/3rdparty/hermes/referee.cpp" "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/release/3rdparty/hermes/CMakeFiles/referee.dir/referee.cpp.o"
  "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/release/3rdparty/hermes/referee_automoc.cpp" "/home/carlo-vd/SVN/LDV_14cpp7/Projekt/release/3rdparty/hermes/CMakeFiles/referee.dir/referee_automoc.cpp.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
SET(CMAKE_TARGET_DEFINITIONS
  "BOOST_SIGNALS_NO_DEPRECATION_WARNING"
  "QT_CORE_LIB"
  "QT_NETWORK_LIB"
  "QT_NO_DEBUG"
  "QT_NO_KEYWORDS"
  )

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  )

# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
  "3rdparty/hermes"
  "../3rdparty/hermes"
  "/usr/include/qt5"
  "/usr/include/qt5/QtNetwork"
  "/usr/include/qt5/QtCore"
  "/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++-64"
  )
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
namespace extensions {

// Tracks the navigation state of all frames in a given tab currently known to
// the webNavigation API. It is mainly used to track in which frames an error
// occurred so no further events for this frame are being sent.
class FrameNavigationState {
 public:
  typedef std::set<int64>::const_iterator const_iterator;

  FrameNavigationState();
  ~FrameNavigationState();

  // Use these to iterate over all frame IDs known by this object.
  const_iterator begin() const { return frame_ids_.begin(); }
  const_iterator end() const { return frame_ids_.end(); }

  // True if navigation events for the given frame can be sent.
  bool CanSendEvents(int64 frame_id) const;

  // True if in general webNavigation events may be sent for the given URL.
  bool IsValidUrl(const GURL& url) const;

  // Starts to track a frame identified by its |frame_id| showing the URL |url|.
  void TrackFrame(int64 frame_id,
                  const GURL& url,
                  bool is_main_frame,
                  bool is_error_page);

  // Update the URL associated with a given frame.
  void UpdateFrame(int64 frame_id, const GURL& url);

  // Returns true if |frame_id| is a known frame.
  bool IsValidFrame(int64 frame_id) const;

  // Returns the URL corresponding to a tracked frame given by its |frame_id|.
  GURL GetUrl(int64 frame_id) const;

  // True if the frame given by its |frame_id| is the main frame of its tab.
  bool IsMainFrame(int64 frame_id) const;

  // Returns the frame ID of the main frame, or -1 if the frame ID is not
  // known.
  int64 GetMainFrameID() const;

  // Marks a frame as in an error state, i.e. the onErrorOccurred event was
  // fired for this frame, and no further events should be sent for it.
  void SetErrorOccurredInFrame(int64 frame_id);

  // True if the frame is marked as being in an error state.
  bool GetErrorOccurredInFrame(int64 frame_id) const;

  // Marks a frame as having finished its last navigation, i.e. the onCompleted
  // event was fired for this frame.
  void SetNavigationCompleted(int64 frame_id);

  // True if the frame is currently not navigating.
  bool GetNavigationCompleted(int64 frame_id) const;

  // Marks a frame as having committed its navigation, i.e. the onCommitted
  // event was fired for this frame.
  void SetNavigationCommitted(int64 frame_id);

  // True if the frame has committed its navigation.
  bool GetNavigationCommitted(int64 frame_id) const;

  // Marks a frame as redirected by the server.
  void SetIsServerRedirected(int64 frame_id);

  // True if the frame was redirected by the server.
  bool GetIsServerRedirected(int64 frame_id) const;

#ifdef UNIT_TEST
  static void set_allow_extension_scheme(bool allow_extension_scheme) {
    allow_extension_scheme_ = allow_extension_scheme;
  }
#endif

 private:
  struct FrameState {
    bool error_occurred;  // True if an error has occurred in this frame.
    bool is_main_frame;  // True if this is a main frame.
    bool is_navigating;  // True if there is a navigation going on.
    bool is_committed;  // True if the navigation is already committed.
    bool is_server_redirected;  // True if a server redirect happened.
    GURL url;  // URL of this frame.
  };
  typedef std::map<int64, FrameState> FrameIdToStateMap;

  // Tracks the state of known frames.
  FrameIdToStateMap frame_state_map_;

  // Set of all known frames.
  std::set<int64> frame_ids_;

  // The current main frame.
  int64 main_frame_id_;

  // If true, also allow events from chrome-extension:// URLs.
  static bool allow_extension_scheme_;

  DISALLOW_COPY_AND_ASSIGN(FrameNavigationState);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_WEB_NAVIGATION_FRAME_NAVIGATION_STATE_H_


text:
import {Destination, DestinationConnectionStatus, DestinationOrigin, DestinationType, DuplexType, GooglePromotedDestinationId, Margins, MarginsType, PrintPreviewModelElement, Size} from 'chrome://print/print_preview.js';
// <if expr="chromeos or lacros">
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
// </if>

import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';

import {getCddTemplate, getCloudDestination, getSaveAsPdfDestination} from './print_preview_test_utils.js';

suite('ModelSettingsAvailabilityTest', function() {
  let model: PrintPreviewModelElement;

  setup(function() {
    document.body.innerHTML = '';
    model = document.createElement('print-preview-model');
    document.body.appendChild(model);

    model.documentSettings = {
      hasCssMediaStyles: false,
      hasSelection: false,
      isFromArc: false,
      isModifiable: true,
      isScalingDisabled: false,
      fitToPageScaling: 100,
      pageCount: 3,
      title: 'title',
    };

    model.pageSize = new Size(612, 792);
    model.margins = new Margins(72, 72, 72, 72);

    // Create a test destination.
    model.destination = new Destination(
        'FooDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'FooName',
        DestinationConnectionStatus.ONLINE);
    model.set(
        'destination.capabilities',
        getCddTemplate(model.destination.id).capabilities);
    model.applyStickySettings();
  });

  // These tests verify that the model correctly updates the settings
  // availability based on the destination and document info.
  test('copies', function() {
    assertTrue(model.settings.copies.available);

    // Set max copies to 1.
    let caps = getCddTemplate(model.destination.id).capabilities!;
    const copiesCap = {max: 1};
    caps.printer!.copies = copiesCap;
    model.set('destination.capabilities', caps);
    assertFalse(model.settings.copies.available);

    // Set max copies to 2 (> 1).
    caps = getCddTemplate(model.destination.id).capabilities!;
    copiesCap.max = 2;
    caps.printer!.copies = copiesCap;
    model.set('destination.capabilities', caps);
    assertTrue(model.settings.copies.available);

    // Remove copies capability.
    caps = getCddTemplate(model.destination.id).capabilities!;
    delete caps.printer!.copies;
    model.set('destination.capabilities', caps);
    assertFalse(model.settings.copies.available);

    // Copies is restored.
    caps = getCddTemplate(model.destination.id).capabilities!;
    model.set('destination.capabilities', caps);
    assertTrue(model.settings.copies.available);
    assertFalse(model.settings.copies.setFromUi);
  });

  test('collate', function() {
    assertTrue(model.settings.collate.available);

    // Remove collate capability.
    let capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.collate;
    model.set('destination.capabilities', capabilities);

    // Copies is no longer available.
    assertFalse(model.settings.collate.available);

    // Copies is restored.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    model.set('destination.capabilities', capabilities);
    assertTrue(model.settings.collate.available);
    assertFalse(model.settings.collate.setFromUi);
  });

  test('layout', function() {
    // Layout is available since the printer has the capability and the
    // document is set to modifiable.
    assertTrue(model.settings.layout.available);

    // Each of these settings should not show the capability.
    [undefined,
     {option: [{type: 'PORTRAIT', is_default: true}]},
     {option: [{type: 'LANDSCAPE', is_default: true}]},
    ].forEach(layoutCap => {
      const capabilities = getCddTemplate(model.destination.id).capabilities!;
      capabilities.printer!.page_orientation = layoutCap;
      // Layout section should now be hidden.
      model.set('destination.capabilities', capabilities);
      assertFalse(model.settings.layout.available);
    });

    // Reset full capabilities
    const capabilities = getCddTemplate(model.destination.id).capabilities!;
    model.set('destination.capabilities', capabilities);
    assertTrue(model.settings.layout.available);

    // Test with PDF - should be hidden.
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.layout.available);

    // Test with ARC - should be available.
    model.set('documentSettings.isFromArc', true);
    assertTrue(model.settings.layout.available);

    model.set('documentSettings.isModifiable', true);
    model.set('documentSettings.isFromArc', false);
    assertTrue(model.settings.layout.available);

    // Unavailable if document has CSS media styles.
    model.set('documentSettings.hasCssMediaStyles', true);
    assertFalse(model.settings.layout.available);
    assertFalse(model.settings.layout.setFromUi);
  });

  test('color', function() {
    // Color is available since the printer has the capability.
    assertTrue(model.settings.color.available);

    // Each of these settings should make the setting unavailable, with
    // |expectedValue| as its unavailableValue.
    [{
      colorCap: undefined,
      expectedValue: false,
    },
     {
       colorCap: {option: [{type: 'STANDARD_COLOR', is_default: true}]},
       expectedValue: true,
     },
     {
       colorCap: {
         option: [
           {type: 'STANDARD_COLOR', is_default: true}, {type: 'CUSTOM_COLOR'}
         ]
       },
       expectedValue: true,
     },
     {
       colorCap: {
         option: [
           {type: 'STANDARD_MONOCHROME', is_default: true},
           {type: 'CUSTOM_MONOCHROME'}
         ]
       },
       expectedValue: false,
     },
     {
       colorCap: {option: [{type: 'STANDARD_MONOCHROME'}]},
       expectedValue: false,
     },
     {
       colorCap: {option: [{type: 'CUSTOM_MONOCHROME', vendor_id: '42'}]},
       expectedValue: false,
     },
     {
       colorCap: {option: [{type: 'CUSTOM_COLOR', vendor_id: '42'}]},
       expectedValue: true,
     }].forEach(capabilityAndValue => {
      const capabilities = getCddTemplate(model.destination.id).capabilities!;
      capabilities.printer!.color = capabilityAndValue.colorCap;
      model.set('destination.capabilities', capabilities);
      assertFalse(model.settings.color.available);
      assertEquals(
          capabilityAndValue.expectedValue,
          model.settings.color.unavailableValue as boolean);
    });

    // Each of these settings should make the setting available, with the
    // default value given by expectedValue.
    [{
      colorCap: {
        option: [
          {type: 'STANDARD_MONOCHROME', is_default: true},
          {type: 'STANDARD_COLOR'}
        ]
      },
      expectedValue: false,
    },
     {
       colorCap: {
         option: [
           {type: 'STANDARD_MONOCHROME'},
           {type: 'STANDARD_COLOR', is_default: true}
         ]
       },
       expectedValue: true,
     },
     {
       colorCap: {
         option: [
           {type: 'CUSTOM_MONOCHROME', vendor_id: '42'},
           {type: 'CUSTOM_COLOR', is_default: true, vendor_id: '43'}
         ]
       },
       expectedValue: true,
     }].forEach(capabilityAndValue => {
      const capabilities = getCddTemplate(model.destination.id).capabilities!;
      capabilities.printer!.color = capabilityAndValue.colorCap;
      model.set('destination.capabilities', capabilities);
      assertEquals(
          capabilityAndValue.expectedValue, model.settings.color.value);
      assertTrue(model.settings.color.available);
    });

    // Google Drive always has an unavailableValue of true when using the cloud
    // destination.
    model.set(
        'destination',
        getCloudDestination(
            GooglePromotedDestinationId.DOCS, GooglePromotedDestinationId.DOCS,
            'foo@chromium.org'));
    const capabilities =
        getCddTemplate(GooglePromotedDestinationId.DOCS).capabilities!;
    delete capabilities.printer!.color;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.color.available);
    assertTrue(model.settings.color.unavailableValue as boolean);
    assertFalse(model.settings.color.setFromUi);
  });

  function setSaveAsPdfDestination() {
    const saveAsPdf = getSaveAsPdfDestination();
    saveAsPdf.capabilities = getCddTemplate(model.destination.id).capabilities;
    model.set('destination', saveAsPdf);
  }

  test('media size', function() {
    // Media size is available since the printer has the capability.
    assertTrue(model.settings.mediaSize.available);

    // Remove capability.
    const capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.media_size;

    // Section should now be hidden.
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.mediaSize.available);

    // Set Save as PDF printer.
    setSaveAsPdfDestination();

    // Save as PDF printer has media size capability.
    assertTrue(model.settings.mediaSize.available);

    // PDF to PDF -> media size is unavailable.
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.mediaSize.available);

    // CSS styles to PDF -> media size is unavailable.
    model.set('documentSettings.isModfiable', true);
    model.set('documentSettings.hasCssMediaStyles', true);
    assertFalse(model.settings.mediaSize.available);
    assertFalse(model.settings.color.setFromUi);
  });

  test('margins', function() {
    // The settings are available since isModifiable is true.
    assertTrue(model.settings.margins.available);
    assertTrue(model.settings.customMargins.available);

    // No margins settings for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.margins.available);
    assertFalse(model.settings.customMargins.available);
    assertFalse(model.settings.margins.setFromUi);
    assertFalse(model.settings.customMargins.setFromUi);

    // No margins settings for PDFs.
    model.set('documentSettings.isFromArc', false);
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.margins.available);
    assertFalse(model.settings.customMargins.available);
    assertFalse(model.settings.margins.setFromUi);
    assertFalse(model.settings.customMargins.setFromUi);
  });

  test('dpi', function() {
    // The settings are available since the printer has multiple DPI options.
    assertTrue(model.settings.dpi.available);

    // No resolution settings for ARC, but uses the default value.
    model.set('documentSettings.isFromArc', true);
    let capabilities = getCddTemplate(model.destination.id).capabilities;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.dpi.available);
    assertEquals(200, model.settings.dpi.unavailableValue.horizontal_dpi);
    assertEquals(200, model.settings.dpi.unavailableValue.vertical_dpi);

    model.set('documentSettings.isFromArc', false);
    assertTrue(model.settings.dpi.available);

    // Remove capability.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.dpi;

    // Section should now be hidden.
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.dpi.available);

    // Does not show up for only 1 option. Unavailable value should be set to
    // the only available option.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    capabilities.printer!.dpi!.option.pop();
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.dpi.available);
    assertEquals(200, model.settings.dpi.unavailableValue.horizontal_dpi);
    assertEquals(200, model.settings.dpi.unavailableValue.vertical_dpi);
    assertFalse(model.settings.dpi.setFromUi);
  });

  test('scaling', function() {
    // HTML -> printer
    assertTrue(model.settings.scaling.available);

    // HTML -> Save as PDF
    const defaultDestination = model.destination;
    setSaveAsPdfDestination();
    assertTrue(model.settings.scaling.available);

    // PDF -> Save as PDF
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.scaling.available);

    // PDF -> printer
    model.set('destination', defaultDestination);
    assertTrue(model.settings.scaling.available);
    assertFalse(model.settings.scaling.setFromUi);

    // ARC -> printer
    model.set('destination', defaultDestination);
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.scaling.available);

    // ARC -> Save as PDF
    setSaveAsPdfDestination();
    assertFalse(model.settings.scaling.available);
  });

  test('scalingType', function() {
    // HTML -> printer
    assertTrue(model.settings.scalingType.available);

    // HTML -> Save as PDF
    const defaultDestination = model.destination;
    setSaveAsPdfDestination();
    assertTrue(model.settings.scalingType.available);

    // PDF -> Save as PDF
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.scalingType.available);

    // PDF -> printer
    model.set('destination', defaultDestination);
    assertFalse(model.settings.scalingType.available);

    // ARC -> printer
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.scalingType.available);

    // ARC -> Save as PDF
    setSaveAsPdfDestination();
    assertFalse(model.settings.scalingType.available);
  });

  test('scalingTypePdf', function() {
    // HTML -> printer
    assertFalse(model.settings.scalingTypePdf.available);

    // HTML -> Save as PDF
    const defaultDestination = model.destination;
    setSaveAsPdfDestination();
    assertFalse(model.settings.scalingTypePdf.available);

    // PDF -> Save as PDF
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.scalingTypePdf.available);

    // PDF -> printer
    model.set('destination', defaultDestination);
    assertTrue(model.settings.scalingTypePdf.available);

    // ARC -> printer
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.scalingTypePdf.available);

    // ARC -> Save as PDF
    setSaveAsPdfDestination();
    assertFalse(model.settings.scalingTypePdf.available);
  });

  test('header footer', function() {
    // Default margins + letter paper + HTML page.
    assertTrue(model.settings.headerFooter.available);

    // Custom margins initializes with customMargins undefined and margins
    // values matching the defaults.
    model.set('settings.margins.value', MarginsType.CUSTOM);
    assertTrue(model.settings.headerFooter.available);

    // Set margins to NONE
    model.set('settings.margins.value', MarginsType.NO_MARGINS);
    assertFalse(model.settings.headerFooter.available);

    // Set margins to MINIMUM
    model.set('settings.margins.value', MarginsType.MINIMUM);
    assertTrue(model.settings.headerFooter.available);

    // Custom margins of 0.
    model.set('settings.margins.value', MarginsType.CUSTOM);
    model.set(
        'settings.customMargins.value',
        {marginTop: 0, marginLeft: 0, marginRight: 0, marginBottom: 0});
    model.set('margins', new Margins(0, 0, 0, 0));
    assertFalse(model.settings.headerFooter.available);

    // Custom margins of 36 -> header/footer available
    model.set(
        'settings.customMargins.value',
        {marginTop: 36, marginLeft: 36, marginRight: 36, marginBottom: 36});
    model.set('margins', new Margins(36, 36, 36, 36));
    assertTrue(model.settings.headerFooter.available);

    // Zero top and bottom -> header/footer unavailable
    model.set(
        'settings.customMargins.value',
        {marginTop: 0, marginLeft: 36, marginRight: 36, marginBottom: 0});
    model.set('margins', new Margins(0, 36, 0, 36));
    assertFalse(model.settings.headerFooter.available);

    // Zero top and nonzero bottom -> header/footer available
    model.set(
        'settings.customMargins.value',
        {marginTop: 0, marginLeft: 36, marginRight: 36, marginBottom: 36});
    model.set('margins', new Margins(0, 36, 36, 36));
    assertTrue(model.settings.headerFooter.available);

    // Small paper sizes
    const capabilities = getCddTemplate(model.destination.id).capabilities!;
    capabilities.printer!.media_size = {
      'option': [
        {
          'name': 'SmallLabel',
          'width_microns': 38100,
          'height_microns': 12700,
          'is_default': false
        },
        {
          'name': 'BigLabel',
          'width_microns': 50800,
          'height_microns': 76200,
          'is_default': true
        }
      ]
    };
    model.set('destination.capabilities', capabilities);
    model.set('settings.margins.value', MarginsType.DEFAULT);

    // Header/footer should be available for default big label with
    // default margins.
    assertTrue(model.settings.headerFooter.available);

    model.set(
        'settings.mediaSize.value', capabilities.printer.media_size.option[0]);

    // Header/footer should not be available for small label
    assertFalse(model.settings.headerFooter.available);

    // Reset to big label.
    model.set(
        'settings.mediaSize.value', capabilities.printer.media_size.option[1]);
    assertTrue(model.settings.headerFooter.available);

    // Header/footer is never available for PDFs.
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.headerFooter.available);
    assertFalse(model.settings.headerFooter.setFromUi);

    // Header/footer is never available for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.headerFooter.available);
    assertFalse(model.settings.headerFooter.setFromUi);
  });

  test('css background', function() {
    // The setting is available since isModifiable is true.
    assertTrue(model.settings.cssBackground.available);

    // No CSS background setting for PDFs.
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.cssBackground.available);
    assertFalse(model.settings.cssBackground.setFromUi);

    // No CSS background setting for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.cssBackground.available);
    assertFalse(model.settings.cssBackground.setFromUi);
  });

  test('duplex', function() {
    assertTrue(model.settings.duplex.available);
    assertTrue(model.settings.duplexShortEdge.available);

    // Remove duplex capability.
    let capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.duplex;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.duplex.available);
    assertFalse(model.settings.duplexShortEdge.available);

    // Set a duplex capability with only 1 type, no duplex.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.duplex;
    capabilities.printer.duplex = {
      option: [{type: DuplexType.NO_DUPLEX, is_default: true}]
    };
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.duplex.available);
    assertFalse(model.settings.duplexShortEdge.available);

    // Set a duplex capability with 2 types, long edge and no duplex.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.duplex;
    capabilities.printer.duplex = {
      option: [
        {type: DuplexType.NO_DUPLEX},
        {type: DuplexType.LONG_EDGE, is_default: true}
      ]
    };
    model.set('destination.capabilities', capabilities);
    assertTrue(model.settings.duplex.available);
    assertFalse(model.settings.duplexShortEdge.available);
    assertFalse(model.settings.duplex.setFromUi);
    assertFalse(model.settings.duplexShortEdge.setFromUi);
  });

  test('rasterize', function() {
    // Availability for PDFs varies depening upon OS.
    // Windows and macOS depend on policy - see policy_test.js for their
    // testing coverage.
    model.set('documentSettings.isModifiable', false);
    // <if expr="chromeos or lacros or is_linux">
    // Always available for PDFs on Linux and ChromeOS
    assertTrue(model.settings.rasterize.available);
    assertFalse(model.settings.rasterize.setFromUi);
    // </if>

    // Unavailable for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.rasterize.available);
  });

  test('selection only', function() {
    // Not available with no selection.
    assertFalse(model.settings.selectionOnly.available);

    model.set('documentSettings.hasSelection', true);
    assertTrue(model.settings.selectionOnly.available);

    // Not available for PDFs.
    model.set('documentSettings.isModifiable', false);
    assertFalse(model.settings.selectionOnly.available);
    assertFalse(model.settings.selectionOnly.setFromUi);

    // Not available for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.selectionOnly.available);
    assertFalse(model.settings.selectionOnly.setFromUi);
  });

  test('pages per sheet', function() {
    // Pages per sheet is available everywhere except for ARC.
    // With the default settings for Blink content, it is available.
    model.set('documentSettings.isModifiable', true);
    assertTrue(model.settings.pagesPerSheet.available);

    // Still available for PDF content.
    model.set('documentSettings.isModifiable', false);
    assertTrue(model.settings.pagesPerSheet.available);

    // Not available for ARC.
    model.set('documentSettings.isFromArc', true);
    assertFalse(model.settings.pagesPerSheet.available);
  });

  // <if expr="chromeos or lacros">
  test('pin', function() {
    // Make device unmanaged.
    loadTimeData.overrideValues({isEnterpriseManaged: false});
    // Check that pin setting is unavailable on unmanaged devices.
    assertFalse(model.settings.pin.available);

    // Make device enterprise managed.
    loadTimeData.overrideValues({isEnterpriseManaged: true});
    // Set capabilities again to update pin availability.
    model.set(
        'destination.capabilities',
        getCddTemplate(model.destination.id).capabilities);
    assertTrue(model.settings.pin.available);

    // Remove pin capability.
    let capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer!.pin;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.pin.available);

    // Set not supported pin capability.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    capabilities.printer!.pin!.supported = false;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.pin.available);
    assertFalse(model.settings.pin.setFromUi);
  });

  test('pinValue', function() {
    assertTrue(model.settings.pinValue.available);

    // Remove pin capability.
    let capabilities = getCddTemplate(model.destination.id).capabilities!;
    delete capabilities.printer.pin;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.pinValue.available);

    // Set not supported pin capability.
    capabilities = getCddTemplate(model.destination.id).capabilities!;
    capabilities.printer.pin!.supported = false;
    model.set('destination.capabilities', capabilities);
    assertFalse(model.settings.pinValue.available);
    assertFalse(model.settings.pinValue.setFromUi);
  });
  // </if>
});