text:
require 'nokogiri'
require 'codemodels'

module CodeModels
module Xml

class Parser < CodeModels::Parser

    def internal_parse_artifact(artifact)
        raw_ast = Nokogiri.XML(artifact.code)
        convert_raw_ast(raw_ast)
    end

    def convert_raw_ast(raw_node)
        if raw_node.is_a?(Nokogiri::XML::Document)
            build_document(raw_node)
        elsif raw_node.is_a?(Nokogiri::XML::Element)
            build_element(raw_node)
        elsif raw_node.is_a?(Nokogiri::XML::Text)
            build_text(raw_node)
        elsif raw_node.is_a?(Nokogiri::XML::Attr)
            build_attribute(raw_node)
        else
            raise "Unknown node type #{raw_node.class}"
        end
    end

    def build_attribute(raw_node)
        node = Attribute.new
        node.name = raw_node.name
        node.value = raw_node.value
        node
    end

    def build_text(raw_node)
        node = Text.new
        node
    end

    def build_element(raw_node)
        node = Element.new
        node.name = raw_node.name
        raw_node.attribute_nodes.each do |c|
            node.addAttributes(convert_raw_ast(c))
        end
        raw_node.children.each do |c|
            if c.is_a?(Nokogiri::XML::Text)
                node.addTexts(convert_raw_ast(c))
            elsif c.is_a?(Nokogiri::XML::Element)
                node.addChildren(convert_raw_ast(c))
            else
                raise "Unexpected child type: #{c.class}"
            end
        end
        node
    end

    def build_document(raw_node)
        node = Document.new
        node.version = raw_node.version
        node.encoding = raw_node.encoding
        for n in raw_node.namespaces
            node.addNamespaces(convert_raw_ast(n))
        end
        node.root = convert_raw_ast(raw_node.root)
        node
    end

end

DefaultParser = Parser.new

end
end


text:
class FileContentDatastream < ActiveFedora::Datastream
  include Hydra::Derivatives::ExtractMetadata
  include Sufia::FileContent::Versions
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

require('./object-keys');
require('./array-map');

var camel = /([a-z])([A-Z])/g;
var hyphens = '$1-$2';
var contexts = {};

function parseStyles (styles) {
  if (typeof styles === 'string') {
    return styles;
  }
  if (Object.prototype.toString.call(styles) !== '[object Object]') {
    return '';
  }
  return Object.keys(styles).map(function (key) {
    var prop = key.replace(camel, hyphens).toLowerCase();
    return prop + ':' + styles[key];
  }).join(';');
}

function context (name) {
  if (contexts[name]) {
    return contexts[name];
  }
  var cache;
  var rules;
  var remove;

  function getStylesheet () {
    if (cache) {
      return cache;
    }
    var style = document.createElement('style');
    document.body.appendChild(style);
    style.setAttribute('data-context', name);
    cache = document.styleSheets[document.styleSheets.length - 1];
    rules = cache.cssRules ? 'cssRules' : 'rules';
    remove = cache.removeRule ? 'removeRule' : 'deleteRule';
    return cache;
  }

  function add (selector, styles) {
    var css = parseStyles(styles);
    var sheet = getStylesheet();
    var len = sheet[rules].length;
    if (sheet.insertRule) {
      sheet.insertRule(selector + '{' + css + '}', len);
    } else if (sheet.addRule) {
      sheet.addRule(selector, css, len);
    }
  }

  function remove (selector) {
    var sheet = getStylesheet();
    var length = sheet[rules].length;
    var i;
    for (i = length - 1; i >= 0; i--) {
      if (sheet[rules][i].selectorText === selector) {
        sheet[remove](i);
      }
    }
  }

  function clear () {
    var sheet = getStylesheet();
    while (sheet[rules].length) {
      sheet[remove](0);
    }
  }

  add.clear = clear;
  add.remove = remove;
  contexts[name] = add;
  return contexts[name];
}

var ctx = context('default');
ctx.context = context;
module.exports = ctx;


text:
/**
 * Trims leading or trailing whitespace from this string
 *
 * @type {String}
 */
String.prototype.trim = function() {
    return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};

/**
 * @namespace
 */
Core.Utils = {

	/**
	 * Returns array of names from map
	 *
	 * @param {Object} map
	 * @type {Array}
	 */
	getNames: function(map) {
		var names = [];
		for (name in map) {
			names.push(name);
		}
		return names;
	},

	/**
	 * Returns array of values from map
	 *
	 * @param {Object} map
	 * @type {Array}
	 */
	getValues: function(map) {
		var values = [];
		for (name in map) {
			values.push(map[name]);
		}
		return values;
	}
};


text:
/*
    Calimero - A library for KNX network access
    Copyright (C) 2006-2008 B. Malinowsky

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or at your option any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    Linking this library statically or dynamically with other modules is
    making a combined work based on this library. Thus, the terms and
    conditions of the GNU General Public License cover the whole
    combination.

    As a special exception, the copyright holders of this library give you
    permission to link this library with independent modules to produce an
    executable, regardless of the license terms of these independent
    modules, and to copy and distribute the resulting executable under terms
    of your choice, provided that you also meet, for each linked independent
    module, the terms and conditions of the license of that module. An
    independent module is a module which is not derived from or based on
    this library. If you modify this library, you may extend this exception
    to your version of the library, but you are not obligated to do so. If
    you do not wish to do so, delete this exception statement from your
    version.
*/

package tuwien.auto.calimero.dptxlator;

import java.util.HashMap;
import java.util.Map;

import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.exception.KNXIllegalArgumentException;
import tuwien.auto.calimero.log.LogLevel;

/**
 * Translator for KNX DPTs with main number 1, type Boolean.
 *

 * The KNX data type width is the lowest bit of 1 byte.

 * The default return value after creation is 0, i.e. false
 * for DPT Boolean for example.
 *
 * @author B. Malinowsky
 */
public class DPTXlatorBoolean extends DPTXlator
{
	/**
	 * DPT ID 1.001, Switch; values off, on.
	 *

	 */
	public static final DPT DPT_SWITCH = new DPT("1.001", "Switch", "off", "on");

	/**
	 * DPT ID 1.002, Boolean; values false, true.
	 *

	 */
	public static final DPT DPT_BOOL = new DPT("1.002", "Boolean", "false", "true");

	/**
	 * DPT ID 1.003, Enable; values enable, disable.
	 *

	 */
	public static final DPT DPT_ENABLE = new DPT("1.003", "Enable", "disable", "enable");

	/**
	 * DPT ID 1.004, Ramp; values no ramp, ramp.
	 *

	 */
	public static final DPT DPT_RAMP = new DPT("1.004", "Ramp", "no ramp", "ramp");

	/**
	 * DPT ID 1.005, Alarm; values no alarm, alarm.
	 *

	 */
	public static final DPT DPT_ALARM = new DPT("1.005", "Alarm", "no alarm", "alarm");

	/**
	 * DPT ID 1.006, Binary value; values low, high.
	 *

	 */
	public static final DPT DPT_BINARYVALUE =
		new DPT("1.006", "Binary value", "low", "high");

	/**
	 * DPT ID 1.007, Step; values decrease, increase.
	 *

	 */
	public static final DPT DPT_STEP = new DPT("1.007", "Step", "decrease", "increase");

	/**
	 * DPT ID 1.008, Up/Down; values up, down.
	 *

	 */
	public static final DPT DPT_UPDOWN = new DPT("1.008", "Up/Down", "up", "down");

	/**
	 * DPT ID 1.009, Open/Close; values open, close.
	 *

	 */
	public static final DPT DPT_OPENCLOSE =
		new DPT("1.009", "Open/Close", "open", "close");

	/**
	 * DPT ID 1.010, Start; values stop, start.
	 *

	 */
	public static final DPT DPT_START = new DPT("1.010", "Start", "stop", "start");

	/**
	 * DPT ID 1.011, State; values inactive, active.
	 *

	 */
	public static final DPT DPT_STATE = new DPT("1.011", "State", "inactive", "active");

	/**
	 * DPT ID 1.012, Invert; values not inverted, inverted.
	 *

	 */
	public static final DPT DPT_INVERT =
		new DPT("1.012", "Invert", "not inverted", "inverted");

	/**
	 * DPT ID 1.013, DimSendStyle; values start/stop, cyclic.
	 *

	 */
	public static final DPT DPT_DIMSENDSTYLE =
		new DPT("1.013", "Dim send-style", "start/stop", "cyclic");

	/**
	 * DPT ID 1.014, Input source; values fixed, calculated.
	 *

	 */
	public static final DPT DPT_INPUTSOURCE =
		new DPT("1.014", "Input source", "fixed", "calculated");

	/**
	 * DPT ID 1.015, Reset; values no action (dummy), reset (trigger).
	 *

	 */
	public static final DPT DPT_RESET = new DPT("1.015", "Reset", "no action", "reset");

	/**
	 * DPT ID 1.016, Acknowledge; values no action (dummy), acknowledge
	 * (trigger).
	 *

	 */
	public static final DPT DPT_ACK =
		new DPT("1.016", "Acknowledge", "no action", "acknowledge");

	/**
	 * DPT ID 1.017, Trigger; values trigger, trigger.
	 *

	 */
	public static final DPT DPT_TRIGGER =
		new DPT("1.017", "Trigger", "trigger", "trigger");

	/**
	 * DPT ID 1.018, Occupancy; values not occupied, occupied.
	 *

	 */
	public static final DPT DPT_OCCUPANCY =
		new DPT("1.018", "Occupancy", "not occupied", "occupied");

	/**
	 * DPT ID 1.019, Window/Door; values closed, open.
	 *

	 */
	public static final DPT DPT_WINDOW_DOOR =
		new DPT("1.019", "Window/Door", "closed", "open");

	/**
	 * DPT ID 1.021, Logical function; values OR, AND.
	 *

	 */
	public static final DPT DPT_LOGICAL_FUNCTION =
		new DPT("1.021", "Logical function", "OR", "AND");

	/**
	 * DPT ID 1.022, Scene A/B; values scene A, scene B.
	 *

	 * Note, when displaying scene numbers, scene A is equal to number 1, scene B to
	 * number 2.
	 */
	public static final DPT DPT_SCENE_AB =
		new DPT("1.022", "Scene A/B", "scene A", "scene B");

	/**
	 * DPT ID 1.023, Shutter/Blinds mode; values only move up/down mode (shutter),
	 * move up/down + step-stop mode (blind).
	 *

	 */
	public static final DPT DPT_SHUTTER_BLINDS_MODE =
		new DPT("1.023", "Shutter/Blinds mode", "only move up/down",
			"move up/down + step-stop");

	private static final Map types;

	/**
	 * Creates a translator for the given datapoint type.
	 *

	 *
	 * @param dpt the requested datapoint type
	 * @throws KNXFormatException on not supported or not available DPT
	 */
	public DPTXlatorBoolean(DPT dpt) throws KNXFormatException
	{
		this(dpt.getID());
	}

	/**
	 * Creates a translator for the given datapoint type ID.
	 *

	 *
	 * @param dptID available implemented datapoint type ID
	 * @throws KNXFormatException on wrong formatted or not expected (available)
	 *         dptID
	 */
	public DPTXlatorBoolean(String dptID) throws KNXFormatException
	{
		super(0);
		setTypeID(types, dptID);
		data = new short[1];
	}

	static {
		types = new HashMap(30);
		types.put(DPT_SWITCH.getID(), DPT_SWITCH);
		types.put(DPT_BOOL.getID(), DPT_BOOL);
		types.put(DPT_ENABLE.getID(), DPT_ENABLE);
		types.put(DPT_RAMP.getID(), DPT_RAMP);
		types.put(DPT_ALARM.getID(), DPT_ALARM);
		types.put(DPT_BINARYVALUE.getID(), DPT_BINARYVALUE);
		types.put(DPT_STEP.getID(), DPT_STEP);
		types.put(DPT_UPDOWN.getID(), DPT_UPDOWN);
		types.put(DPT_OPENCLOSE.getID(), DPT_OPENCLOSE);
		types.put(DPT_START.getID(), DPT_START);
		types.put(DPT_STATE.getID(), DPT_STATE);
		types.put(DPT_INVERT.getID(), DPT_INVERT);
		types.put(DPT_DIMSENDSTYLE.getID(), DPT_DIMSENDSTYLE);
		types.put(DPT_INPUTSOURCE.getID(), DPT_INPUTSOURCE);
		types.put(DPT_RESET.getID(), DPT_RESET);
		types.put(DPT_ACK.getID(), DPT_ACK);
		types.put(DPT_TRIGGER.getID(), DPT_TRIGGER);
		types.put(DPT_OCCUPANCY.getID(), DPT_OCCUPANCY);
		types.put(DPT_WINDOW_DOOR.getID(), DPT_WINDOW_DOOR);
		types.put(DPT_LOGICAL_FUNCTION.getID(), DPT_LOGICAL_FUNCTION);
		types.put(DPT_SCENE_AB.getID(), DPT_SCENE_AB);
		types.put(DPT_SHUTTER_BLINDS_MODE.getID(), DPT_SHUTTER_BLINDS_MODE);
	}

	/**
	 * Sets the translation value from a boolean.
	 *

	 * Any other items in the translator are discarded.
	 *
	 * @param value the boolean value
	 */
	public final void setValue(boolean value)
	{
		data = new short[] { (short) (value ? 1 : 0) };
	}

	/**
	 * Returns the first translation item formatted as boolean.
	 *

	 *
	 * @return boolean representation
	 */
	public final boolean getValueBoolean()
	{
		return (data[0] & 0x01) != 0 ? true : false;
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#getValue()
	 */
	public String getValue()
	{
		return fromDPT(0);
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#getAllValues()
	 */
	public String[] getAllValues()
	{
		final String[] buf = new String[data.length];
		for (int i = 0; i < data.length; ++i)
			buf[i] = fromDPT(i);
		return buf;
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#setData(byte[], int)
	 */
	public void setData(byte[] data, int offset)
	{
		if (offset < 0 || offset > data.length)
			throw new KNXIllegalArgumentException("illegal offset " + offset);
		final int size = data.length - offset;
		if (size == 0)
			throw new KNXIllegalArgumentException("data length " + size
				+ " < KNX data type width " + Math.max(1, getTypeSize()));
		this.data = new short[size];
		for (int i = 0; i < size; ++i)
			this.data[i] = (short) (data[offset + i] & 0x01);
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int)
	 */
	public byte[] getData(byte[] dst, int offset)
	{
		final int end = Math.min(data.length, dst.length - offset);
		for (int i = 0; i < end; ++i)
			if (data[i] != 0)
				dst[offset + i] |= 1;
			else
				dst[offset + i] &= ~1;
		return dst;
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
	 */
	public final Map getSubTypes()
	{
		return types;
	}

	/**
	 * @return the subtypes of the boolean translator type
	 * @see DPTXlator#getSubTypesStatic()
	 */
	protected static Map getSubTypesStatic()
	{
		return types;
	}

	protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
	{
		if (dpt.getLowerValue().equalsIgnoreCase(value))
			dst[index] = 0;
		else if (dpt.getUpperValue().equalsIgnoreCase(value))
			dst[index] = 1;
		else
			throw logThrow(LogLevel.WARN, "translation error for " + value,
				"value not recognized", value);
	}

	private String fromDPT(int index)
	{
		return data[index] != 0 ? dpt.getUpperValue() : dpt.getLowerValue();
	}
}


text:
"""This script is used to download prebuilt clang binaries.

It is also used by package.py to build the prebuilt clang binaries."""

import argparse
import distutils.spawn
import glob
import os
import pipes
import re
import shutil
import subprocess
import stat
import sys
import tarfile
import tempfile
import time
import urllib2
import zipfile

# Do NOT CHANGE this if you don't know what you're doing -- see
# https://chromium.googlesource.com/chromium/src/+/master/docs/updating_clang.md
# Reverting problematic clang rolls is safe, though.
CLANG_REVISION = '277962'

use_head_revision = 'LLVM_FORCE_HEAD_REVISION' in os.environ
if use_head_revision:
  CLANG_REVISION = 'HEAD'

# This is incremented when pushing a new build of Clang at the same revision.
CLANG_SUB_REVISION=1

PACKAGE_VERSION = "%s-%s" % (CLANG_REVISION, CLANG_SUB_REVISION)

# Path constants. (All of these should be absolute paths.)
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
CHROMIUM_DIR = os.path.abspath(os.path.join(THIS_DIR, '..', '..', '..'))
THIRD_PARTY_DIR = os.path.join(CHROMIUM_DIR, 'third_party')
LLVM_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm')
LLVM_BOOTSTRAP_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-bootstrap')
LLVM_BOOTSTRAP_INSTALL_DIR = os.path.join(THIRD_PARTY_DIR,
                                          'llvm-bootstrap-install')
LLVM_LTO_GOLD_PLUGIN_DIR = os.path.join(THIRD_PARTY_DIR, 'llvm-lto-gold-plugin')
CHROME_TOOLS_SHIM_DIR = os.path.join(LLVM_DIR, 'tools', 'chrometools')
LLVM_BUILD_DIR = os.path.join(CHROMIUM_DIR, 'third_party', 'llvm-build',
                              'Release+Asserts')
COMPILER_RT_BUILD_DIR = os.path.join(LLVM_BUILD_DIR, 'compiler-rt')
CLANG_DIR = os.path.join(LLVM_DIR, 'tools', 'clang')
LLD_DIR = os.path.join(LLVM_DIR, 'tools', 'lld')
# compiler-rt is built as part of the regular LLVM build on Windows to get
# the 64-bit runtime, and out-of-tree elsewhere.
# TODO(thakis): Try to unify this.
if sys.platform == 'win32':
  COMPILER_RT_DIR = os.path.join(LLVM_DIR, 'projects', 'compiler-rt')
else:
  COMPILER_RT_DIR = os.path.join(LLVM_DIR, 'compiler-rt')
LIBCXX_DIR = os.path.join(LLVM_DIR, 'projects', 'libcxx')
LIBCXXABI_DIR = os.path.join(LLVM_DIR, 'projects', 'libcxxabi')
LLVM_BUILD_TOOLS_DIR = os.path.abspath(
    os.path.join(LLVM_DIR, '..', 'llvm-build-tools'))
STAMP_FILE = os.path.normpath(
    os.path.join(LLVM_DIR, '..', 'llvm-build', 'cr_build_revision'))
BINUTILS_DIR = os.path.join(THIRD_PARTY_DIR, 'binutils')
BINUTILS_BIN_DIR = os.path.join(BINUTILS_DIR, BINUTILS_DIR,
                                'Linux_x64', 'Release', 'bin')
BFD_PLUGINS_DIR = os.path.join(BINUTILS_DIR, 'Linux_x64', 'Release',
                               'lib', 'bfd-plugins')
VERSION = '4.0.0'
ANDROID_NDK_DIR = os.path.join(
    CHROMIUM_DIR, 'third_party', 'android_tools', 'ndk')

# URL for pre-built binaries.
CDS_URL = os.environ.get('CDS_CLANG_BUCKET_OVERRIDE',
    'https://commondatastorage.googleapis.com/chromium-browser-clang')

LLVM_REPO_URL='https://llvm.org/svn/llvm-project'
if 'LLVM_REPO_URL' in os.environ:
  LLVM_REPO_URL = os.environ['LLVM_REPO_URL']

# Bump after VC updates.
DIA_DLL = {
  '2013': 'msdia120.dll',
  '2015': 'msdia140.dll',
}

def DownloadUrl(url, output_file):
  """Download url into output_file."""
  CHUNK_SIZE = 4096
  TOTAL_DOTS = 10
  num_retries = 3
  retry_wait_s = 5  # Doubled at each retry.

  while True:
    try:
      sys.stdout.write('Downloading %s ' % url)
      sys.stdout.flush()
      response = urllib2.urlopen(url)
      total_size = int(response.info().getheader('Content-Length').strip())
      bytes_done = 0
      dots_printed = 0
      while True:
        chunk = response.read(CHUNK_SIZE)
        if not chunk:
          break
        output_file.write(chunk)
        bytes_done += len(chunk)
        num_dots = TOTAL_DOTS * bytes_done / total_size
        sys.stdout.write('.' * (num_dots - dots_printed))
        sys.stdout.flush()
        dots_printed = num_dots
      if bytes_done != total_size:
        raise urllib2.URLError("only got %d of %d bytes" %
                               (bytes_done, total_size))
      print ' Done.'
      return
    except urllib2.URLError as e:
      sys.stdout.write('\n')
      print e
      if num_retries == 0 or isinstance(e, urllib2.HTTPError) and e.code == 404:
        raise e
      num_retries -= 1
      print 'Retrying in %d s ...' % retry_wait_s
      time.sleep(retry_wait_s)
      retry_wait_s *= 2

def EnsureDirExists(path):
  if not os.path.exists(path):
    print "Creating directory %s" % path
    os.makedirs(path)

def DownloadAndUnpack(url, output_dir):
  with tempfile.TemporaryFile() as f:
    DownloadUrl(url, f)
    f.seek(0)
    EnsureDirExists(output_dir)
    if url.endswith('.zip'):
      zipfile.ZipFile(f).extractall(path=output_dir)
    else:
      tarfile.open(mode='r:gz', fileobj=f).extractall(path=output_dir)

def ReadStampFile(path=STAMP_FILE):
  """Return the contents of the stamp file, or '' if it doesn't exist."""
  try:
    with open(path, 'r') as f:
      return f.read().rstrip()
  except IOError:
    return ''

def WriteStampFile(s, path=STAMP_FILE):
  """Write s to the stamp file."""
  EnsureDirExists(os.path.dirname(path))
  with open(path, 'w') as f:
    f.write(s)
    f.write('\n')

def GetSvnRevision(svn_repo):
  """Returns current revision of the svn repo at svn_repo."""
  if sys.platform == 'darwin':
    # mac_files toolchain must be set for hermetic builds.
    root = os.path.dirname(os.path.dirname(os.path.dirname(
        os.path.dirname(__file__))))
    sys.path.append(os.path.join(root, 'build'))
    import mac_toolchain

    mac_toolchain.SetToolchainEnvironment()
  svn_info = subprocess.check_output('svn info ' + svn_repo, shell=True)
  m = re.search(r'Revision: (\d+)', svn_info)
  return m.group(1)

def RmTree(dir):
  """Delete dir."""
  def ChmodAndRetry(func, path, _):
    # Subversion can leave read-only files around.
    if not os.access(path, os.W_OK):
      os.chmod(path, stat.S_IWUSR)
      return func(path)
    raise

  shutil.rmtree(dir, onerror=ChmodAndRetry)

def RmCmakeCache(dir):
  """Delete CMake cache related files from dir."""
  for dirpath, dirs, files in os.walk(dir):
    if 'CMakeCache.txt' in files:
      os.remove(os.path.join(dirpath, 'CMakeCache.txt'))
    if 'CMakeFiles' in dirs:
      RmTree(os.path.join(dirpath, 'CMakeFiles'))

def RunCommand(command, msvc_arch=None, env=None, fail_hard=True):
  """Run command and return success (True) or failure; or if fail_hard is
     True, exit on failure.  If msvc_arch is set, runs the command in a
     shell with the msvc tools for that architecture."""

  if msvc_arch and sys.platform == 'win32':
    command = GetVSVersion().SetupScript(msvc_arch) + ['&&'] + command

  # https://docs.python.org/2/library/subprocess.html:
  # "On Unix with shell=True [...] if args is a sequence, the first item
  # specifies the command string, and any additional items will be treated as
  # additional arguments to the shell itself.  That is to say, Popen does the
  # equivalent of:
  #   Popen(['/bin/sh', '-c', args[0], args[1], ...])"
  #
  # We want to pass additional arguments to command[0], not to the shell,
  # so manually join everything into a single string.
  # Annoyingly, for "svn co url c:\path", pipes.quote() thinks that it should
  # quote c:\path but svn can't handle quoted paths on Windows.  Since on
  # Windows follow-on args are passed to args[0] instead of the shell, don't
  # do the single-string transformation there.
  if sys.platform != 'win32':
    command = ' '.join([pipes.quote(c) for c in command])
  print 'Running', command
  if subprocess.call(command, env=env, shell=True) == 0:
    return True
  print 'Failed.'
  if fail_hard:
    sys.exit(1)
  return False

def CopyFile(src, dst):
  """Copy a file from src to dst."""
  print "Copying %s to %s" % (src, dst)
  shutil.copy(src, dst)

def CopyDirectoryContents(src, dst, filename_filter=None):
  """Copy the files from directory src to dst
  with an optional filename filter."""
  dst = os.path.realpath(dst)  # realpath() in case dst ends in /..
  EnsureDirExists(dst)
  for root, _, files in os.walk(src):
    for f in files:
      if filename_filter and not re.match(filename_filter, f):
        continue
      CopyFile(os.path.join(root, f), dst)

def Checkout(name, url, dir):
  """Checkout the SVN module at url into dir. Use name for the log message."""
  print "Checking out %s r%s into '%s'" % (name, CLANG_REVISION, dir)

  command = ['svn', 'checkout', '--force', url + '@' + CLANG_REVISION, dir]
  if RunCommand(command, fail_hard=False):
    return

  if os.path.isdir(dir):
    print "Removing %s." % (dir)
    RmTree(dir)

  print "Retrying."
  RunCommand(command)

def DeleteChromeToolsShim():
  OLD_SHIM_DIR = os.path.join(LLVM_DIR, 'tools', 'zzz-chrometools')
  shutil.rmtree(OLD_SHIM_DIR, ignore_errors=True)
  shutil.rmtree(CHROME_TOOLS_SHIM_DIR, ignore_errors=True)

def CreateChromeToolsShim():
  """Hooks the Chrome tools into the LLVM build.

  Several Chrome tools have dependencies on LLVM/Clang libraries. The LLVM build
  detects implicit tools in the tools subdirectory, so this helper install a
  shim CMakeLists.txt that forwards to the real directory for the Chrome tools.

  Note that the shim directory name intentionally has no - or _. The implicit
  tool detection logic munges them in a weird way."""
  assert not any(i in os.path.basename(CHROME_TOOLS_SHIM_DIR) for i in '-_')
  os.mkdir(CHROME_TOOLS_SHIM_DIR)
  with file(os.path.join(CHROME_TOOLS_SHIM_DIR, 'CMakeLists.txt'), 'w') as f:
    f.write('# Automatically generated by tools/clang/scripts/update.py. ' +
            'Do not edit.\n')
    f.write('# Since tools/clang is located in another directory, use the \n')
    f.write('# two arg version to specify where build artifacts go. CMake\n')
    f.write('# disallows reuse of the same binary dir for multiple source\n')
    f.write('# dirs, so the build artifacts need to go into a subdirectory.\n')
    f.write('# dirs, so the build artifacts need to go into a subdirectory.\n')
    f.write('if (CHROMIUM_TOOLS_SRC)\n')
    f.write('  add_subdirectory(${CHROMIUM_TOOLS_SRC} ' +
              '${CMAKE_CURRENT_BINARY_DIR}/a)\n')
    f.write('endif (CHROMIUM_TOOLS_SRC)\n')

def DownloadHostGcc(args):
  """Downloads gcc 4.8.2 and makes sure args.gcc_toolchain is set."""
  if not sys.platform.startswith('linux') or args.gcc_toolchain:
    return
  # Unconditionally download a prebuilt gcc to guarantee the included libstdc++
  # works on Ubuntu Precise.
  gcc_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'gcc482precise')
  if not os.path.exists(gcc_dir):
    print 'Downloading pre-built GCC 4.8.2...'
    DownloadAndUnpack(
        CDS_URL + '/tools/gcc482precise.tgz', LLVM_BUILD_TOOLS_DIR)
  args.gcc_toolchain = gcc_dir

def AddCMakeToPath():
  """Download CMake and add it to PATH."""
  if sys.platform == 'win32':
    zip_name = 'cmake-3.4.3-win32-x86.zip'
    cmake_dir = os.path.join(LLVM_BUILD_TOOLS_DIR,
                             'cmake-3.4.3-win32-x86', 'bin')
  else:
    suffix = 'Darwin' if sys.platform == 'darwin' else 'Linux'
    zip_name = 'cmake343_%s.tgz' % suffix
    cmake_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'cmake343', 'bin')
  if not os.path.exists(cmake_dir):
    DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
  os.environ['PATH'] = cmake_dir + os.pathsep + os.environ.get('PATH', '')

def AddGnuWinToPath():
  """Download some GNU win tools and add them to PATH."""
  if sys.platform != 'win32':
    return

  gnuwin_dir = os.path.join(LLVM_BUILD_TOOLS_DIR, 'gnuwin')
  GNUWIN_VERSION = '4'
  GNUWIN_STAMP = os.path.join(gnuwin_dir, 'stamp')
  if ReadStampFile(GNUWIN_STAMP) == GNUWIN_VERSION:
    print 'GNU Win tools already up to date.'
  else:
    zip_name = 'gnuwin-%s.zip' % GNUWIN_VERSION
    DownloadAndUnpack(CDS_URL + '/tools/' + zip_name, LLVM_BUILD_TOOLS_DIR)
    WriteStampFile(GNUWIN_VERSION, GNUWIN_STAMP)

  os.environ['PATH'] = gnuwin_dir + os.pathsep + os.environ.get('PATH', '')

vs_version = None
def GetVSVersion():
  global vs_version
  if vs_version:
    return vs_version

  # Try using the toolchain in depot_tools.
  # This sets environment variables used by SelectVisualStudioVersion below.
  sys.path.append(os.path.join(CHROMIUM_DIR, 'build'))
  import vs_toolchain
  vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs()

  # Use gyp to find the MSVS installation, either in depot_tools as per above,
  # or a system-wide installation otherwise.
  sys.path.append(os.path.join(CHROMIUM_DIR, 'tools', 'gyp', 'pylib'))
  import gyp.MSVSVersion
  vs_version = gyp.MSVSVersion.SelectVisualStudioVersion(
      vs_toolchain.GetVisualStudioVersion())
  return vs_version

def CopyDiaDllTo(target_dir):
  # This script always wants to use the 64-bit msdia*.dll.
  dia_path = os.path.join(GetVSVersion().Path(), 'DIA SDK', 'bin', 'amd64')
  dia_dll = os.path.join(dia_path, DIA_DLL[GetVSVersion().ShortName()])
  CopyFile(dia_dll, target_dir)

def VeryifyVersionOfBuiltClangMatchesVERSION():
  """Checks that `clang --version` outputs VERSION.  If this fails, VERSION
  in this file is out-of-date and needs to be updated (possibly in an
  `if use_head_revision:` block in main() first)."""
  clang = os.path.join(LLVM_BUILD_DIR, 'bin', 'clang')
  if sys.platform == 'win32':
    # TODO: Parse `clang-cl /?` output for built clang's version and check that
    # to check the binary we're actually shipping? But clang-cl.exe is just
    # a copy of clang.exe, so this does check the same thing.
    clang += '.exe'
  version_out = subprocess.check_output([clang, '--version'])
  version_out = re.match(r'clang version ([0-9.]+)', version_out).group(1)
  if version_out != VERSION:
    print ('unexpected clang version %s (not %s), update VERSION in update.py'
           % (version_out, VERSION))
    sys.exit(1)

def UpdateClang(args):
  print 'Updating Clang to %s...' % PACKAGE_VERSION

  need_gold_plugin = 'LLVM_DOWNLOAD_GOLD_PLUGIN' in os.environ or (
      sys.platform.startswith('linux') and
      'buildtype=Official' in os.environ.get('GYP_DEFINES', '') and
      'branding=Chrome' in os.environ.get('GYP_DEFINES', ''))

  if ReadStampFile() == PACKAGE_VERSION and not args.force_local_build:
    print 'Clang is already up to date.'
    if not need_gold_plugin or os.path.exists(
        os.path.join(LLVM_BUILD_DIR, "lib/LLVMgold.so")):
      return 0

  # Reset the stamp file in case the build is unsuccessful.
  WriteStampFile('')

  if not args.force_local_build:
    cds_file = "clang-%s.tgz" %  PACKAGE_VERSION
    if sys.platform == 'win32' or sys.platform == 'cygwin':
      cds_full_url = CDS_URL + '/Win/' + cds_file
    elif sys.platform == 'darwin':
      cds_full_url = CDS_URL + '/Mac/' + cds_file
    else:
      assert sys.platform.startswith('linux')
      cds_full_url = CDS_URL + '/Linux_x64/' + cds_file

    print 'Downloading prebuilt clang'
    if os.path.exists(LLVM_BUILD_DIR):
      RmTree(LLVM_BUILD_DIR)
    try:
      DownloadAndUnpack(cds_full_url, LLVM_BUILD_DIR)
      print 'clang %s unpacked' % PACKAGE_VERSION
      if sys.platform == 'win32':
        CopyDiaDllTo(os.path.join(LLVM_BUILD_DIR, 'bin'))
      # Download the gold plugin if requested to by an environment variable.
      # This is used by the CFI ClusterFuzz bot, and it's required for official
      # builds on linux.
      if need_gold_plugin:
        RunCommand(['python', CHROMIUM_DIR+'/build/download_gold_plugin.py'])
      WriteStampFile(PACKAGE_VERSION)
      return 0
    except urllib2.URLError:
      print 'Failed to download prebuilt clang %s' % cds_file
      print 'Use --force-local-build if you want to build locally.'
      print 'Exiting.'
      return 1

  if args.with_android and not os.path.exists(ANDROID_NDK_DIR):
    print 'Android NDK not found at ' + ANDROID_NDK_DIR
    print 'The Android NDK is needed to build a Clang whose -fsanitize=address'
    print 'works on Android. See '
    print 'https://www.chromium.org/developers/how-tos/android-build-instructions'
    print 'for how to install the NDK, or pass --without-android.'
    return 1

  DownloadHostGcc(args)
  AddCMakeToPath()
  AddGnuWinToPath()

  DeleteChromeToolsShim()

  Checkout('LLVM', LLVM_REPO_URL + '/llvm/trunk', LLVM_DIR)
  Checkout('Clang', LLVM_REPO_URL + '/cfe/trunk', CLANG_DIR)
  if sys.platform == 'win32' or use_head_revision:
    Checkout('LLD', LLVM_REPO_URL + '/lld/trunk', LLD_DIR)
  Checkout('compiler-rt', LLVM_REPO_URL + '/compiler-rt/trunk', COMPILER_RT_DIR)
  if sys.platform == 'darwin':
    # clang needs a libc++ checkout, else -stdlib=libc++ won't find includes
    # (i.e. this is needed for bootstrap builds).
    Checkout('libcxx', LLVM_REPO_URL + '/libcxx/trunk', LIBCXX_DIR)
    # We used to check out libcxxabi on OS X; we no longer need that.
    if os.path.exists(LIBCXXABI_DIR):
      RmTree(LIBCXXABI_DIR)

  cc, cxx = None, None
  libstdcpp = None
  if args.gcc_toolchain:  # This option is only used on Linux.
    # Use the specified gcc installation for building.
    cc = os.path.join(args.gcc_toolchain, 'bin', 'gcc')
    cxx = os.path.join(args.gcc_toolchain, 'bin', 'g++')

    if not os.access(cc, os.X_OK):
      print 'Invalid --gcc-toolchain: "%s"' % args.gcc_toolchain
      print '"%s" does not appear to be valid.' % cc
      return 1

    # Set LD_LIBRARY_PATH to make auxiliary targets (tablegen, bootstrap
    # compiler, etc.) find the .so.
    libstdcpp = subprocess.check_output(
        [cxx, '-print-file-name=libstdc++.so.6']).rstrip()
    os.environ['LD_LIBRARY_PATH'] = os.path.dirname(libstdcpp)

  cflags = []
  cxxflags = []
  ldflags = []

  base_cmake_args = ['-GNinja',
                     '-DCMAKE_BUILD_TYPE=Release',
                     '-DLLVM_ENABLE_ASSERTIONS=ON',
                     '-DLLVM_ENABLE_THREADS=OFF',
                     '-DLLVM_ENABLE_TIMESTAMPS=OFF',
                     # Statically link MSVCRT to avoid DLL dependencies.
                     '-DLLVM_USE_CRT_RELEASE=MT',
                     ]

  binutils_incdir = ''
  if sys.platform.startswith('linux'):
    binutils_incdir = os.path.join(BINUTILS_DIR, 'Linux_x64/Release/include')

  if args.bootstrap:
    print 'Building bootstrap compiler'
    EnsureDirExists(LLVM_BOOTSTRAP_DIR)
    os.chdir(LLVM_BOOTSTRAP_DIR)
    bootstrap_args = base_cmake_args + [
        '-DLLVM_BINUTILS_INCDIR=' + binutils_incdir,
        '-DLLVM_TARGETS_TO_BUILD=host',
        '-DCMAKE_INSTALL_PREFIX=' + LLVM_BOOTSTRAP_INSTALL_DIR,
        '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
        '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags),
        ]
    if cc is not None:  bootstrap_args.append('-DCMAKE_C_COMPILER=' + cc)
    if cxx is not None: bootstrap_args.append('-DCMAKE_CXX_COMPILER=' + cxx)
    RmCmakeCache('.')
    RunCommand(['cmake'] + bootstrap_args + [LLVM_DIR], msvc_arch='x64')
    RunCommand(['ninja'], msvc_arch='x64')
    if args.run_tests:
      if sys.platform == 'win32':
        CopyDiaDllTo(os.path.join(LLVM_BOOTSTRAP_DIR, 'bin'))
      RunCommand(['ninja', 'check-all'], msvc_arch='x64')
    RunCommand(['ninja', 'install'], msvc_arch='x64')
    if args.gcc_toolchain:
      # Copy that gcc's stdlibc++.so.6 to the build dir, so the bootstrap
      # compiler can start.
      CopyFile(libstdcpp, os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'lib'))

    if sys.platform == 'win32':
      cc = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang-cl.exe')
      cxx = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang-cl.exe')
      # CMake has a hard time with backslashes in compiler paths:
      # https://stackoverflow.com/questions/13050827
      cc = cc.replace('\\', '/')
      cxx = cxx.replace('\\', '/')
    else:
      cc = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang')
      cxx = os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'bin', 'clang++')

    if args.gcc_toolchain:
      # Tell the bootstrap compiler to use a specific gcc prefix to search
      # for standard library headers and shared object files.
      cflags = ['--gcc-toolchain=' + args.gcc_toolchain]
      cxxflags = ['--gcc-toolchain=' + args.gcc_toolchain]
    print 'Building final compiler'

  # Build LLVM gold plugin with LTO. That speeds up the linker by ~10%.
  # We only use LTO for Linux now.
  if args.bootstrap and args.lto_gold_plugin:
    print 'Building LTO LLVM Gold plugin'
    if os.path.exists(LLVM_LTO_GOLD_PLUGIN_DIR):
      RmTree(LLVM_LTO_GOLD_PLUGIN_DIR)
    EnsureDirExists(LLVM_LTO_GOLD_PLUGIN_DIR)
    os.chdir(LLVM_LTO_GOLD_PLUGIN_DIR)

    # Create a symlink to LLVMgold.so build in the previous step so that ar
    # and ranlib could find it while linking LLVMgold.so with LTO.
    EnsureDirExists(BFD_PLUGINS_DIR)
    RunCommand(['ln', '-sf',
                os.path.join(LLVM_BOOTSTRAP_INSTALL_DIR, 'lib', 'LLVMgold.so'),
                os.path.join(BFD_PLUGINS_DIR, 'LLVMgold.so')])

    lto_cflags = ['-flto']
    lto_ldflags = ['-fuse-ld=gold']
    if args.gcc_toolchain:
      # Tell the bootstrap compiler to use a specific gcc prefix to search
      # for standard library headers and shared object files.
      lto_cflags += ['--gcc-toolchain=' + args.gcc_toolchain]
    lto_cmake_args = base_cmake_args + [
        '-DLLVM_BINUTILS_INCDIR=' + binutils_incdir,
        '-DCMAKE_C_COMPILER=' + cc,
        '-DCMAKE_CXX_COMPILER=' + cxx,
        '-DCMAKE_C_FLAGS=' + ' '.join(lto_cflags),
        '-DCMAKE_CXX_FLAGS=' + ' '.join(lto_cflags),
        '-DCMAKE_EXE_LINKER_FLAGS=' + ' '.join(lto_ldflags),
        '-DCMAKE_SHARED_LINKER_FLAGS=' + ' '.join(lto_ldflags),
        '-DCMAKE_MODULE_LINKER_FLAGS=' + ' '.join(lto_ldflags)]

    # We need to use the proper binutils which support LLVM Gold plugin.
    lto_env = os.environ.copy()
    lto_env['PATH'] = BINUTILS_BIN_DIR + os.pathsep + lto_env.get('PATH', '')

    RmCmakeCache('.')
    RunCommand(['cmake'] + lto_cmake_args + [LLVM_DIR], env=lto_env)
    RunCommand(['ninja', 'LLVMgold'], env=lto_env)

  # LLVM uses C++11 starting in llvm 3.5. On Linux, this means libstdc++4.7+ is
  # needed, on OS X it requires libc++. clang only automatically links to libc++
  # when targeting OS X 10.9+, so add stdlib=libc++ explicitly so clang can run
  # on OS X versions as old as 10.7.
  deployment_target = ''

  if sys.platform == 'darwin' and args.bootstrap:
    # When building on 10.9, /usr/include usually doesn't exist, and while
    # Xcode's clang automatically sets a sysroot, self-built clangs don't.
    cflags = ['-isysroot', subprocess.check_output(
        ['xcrun', '--show-sdk-path']).rstrip()]
    cxxflags = ['-stdlib=libc++'] + cflags
    ldflags += ['-stdlib=libc++']
    deployment_target = '10.7'
    # Running libc++ tests takes a long time. Since it was only needed for
    # the install step above, don't build it as part of the main build.
    # This makes running package.py over 10% faster (30 min instead of 34 min)
    RmTree(LIBCXX_DIR)

  # Build clang.

  # If building at head, define a macro that plugins can use for #ifdefing
  # out code that builds at head, but not at CLANG_REVISION or vice versa.
  if use_head_revision:
    cflags += ['-DLLVM_FORCE_HEAD_REVISION']
    cxxflags += ['-DLLVM_FORCE_HEAD_REVISION']

  CreateChromeToolsShim()

  deployment_env = None
  if deployment_target:
    deployment_env = os.environ.copy()
    deployment_env['MACOSX_DEPLOYMENT_TARGET'] = deployment_target

  cmake_args = []
  # TODO(thakis): Unconditionally append this to base_cmake_args instead once
  # compiler-rt can build with clang-cl on Windows (http://llvm.org/PR23698)
  cc_args = base_cmake_args if sys.platform != 'win32' else cmake_args
  if cc is not None:  cc_args.append('-DCMAKE_C_COMPILER=' + cc)
  if cxx is not None: cc_args.append('-DCMAKE_CXX_COMPILER=' + cxx)
  cmake_args += base_cmake_args + [
      '-DLLVM_BINUTILS_INCDIR=' + binutils_incdir,
      '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
      '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags),
      '-DCMAKE_EXE_LINKER_FLAGS=' + ' '.join(ldflags),
      '-DCMAKE_SHARED_LINKER_FLAGS=' + ' '.join(ldflags),
      '-DCMAKE_MODULE_LINKER_FLAGS=' + ' '.join(ldflags),
      '-DCMAKE_INSTALL_PREFIX=' + LLVM_BUILD_DIR,
      # TODO(thakis): Remove this once official builds pass -Wl,--build-id
      # explicitly, https://crbug.com/622775
      '-DENABLE_LINKER_BUILD_ID=ON',
      '-DCHROMIUM_TOOLS_SRC=%s' % os.path.join(CHROMIUM_DIR, 'tools', 'clang'),
      '-DCHROMIUM_TOOLS=%s' % ';'.join(args.tools)]

  EnsureDirExists(LLVM_BUILD_DIR)
  os.chdir(LLVM_BUILD_DIR)
  RmCmakeCache('.')
  RunCommand(['cmake'] + cmake_args + [LLVM_DIR],
             msvc_arch='x64', env=deployment_env)

  if args.gcc_toolchain:
    # Copy in the right stdlibc++.so.6 so clang can start.
    if not os.path.exists(os.path.join(LLVM_BUILD_DIR, 'lib')):
      os.mkdir(os.path.join(LLVM_BUILD_DIR, 'lib'))
    libstdcpp = subprocess.check_output(
        [cxx] + cxxflags + ['-print-file-name=libstdc++.so.6']).rstrip()
    CopyFile(libstdcpp, os.path.join(LLVM_BUILD_DIR, 'lib'))

  RunCommand(['ninja'], msvc_arch='x64')

  if args.tools:
    # If any Chromium tools were built, install those now.
    RunCommand(['ninja', 'cr-install'], msvc_arch='x64')

  if sys.platform == 'darwin':
    # See http://crbug.com/256342
    RunCommand(['strip', '-x', os.path.join(LLVM_BUILD_DIR, 'bin', 'clang')])
  elif sys.platform.startswith('linux'):
    RunCommand(['strip', os.path.join(LLVM_BUILD_DIR, 'bin', 'clang')])

  VeryifyVersionOfBuiltClangMatchesVERSION()

  # Do an out-of-tree build of compiler-rt.
  # On Windows, this is used to get the 32-bit ASan run-time.
  # TODO(hans): Remove once the regular build above produces this.
  # On Mac and Linux, this is used to get the regular 64-bit run-time.
  # Do a clobbered build due to cmake changes.
  if os.path.isdir(COMPILER_RT_BUILD_DIR):
    RmTree(COMPILER_RT_BUILD_DIR)
  os.makedirs(COMPILER_RT_BUILD_DIR)
  os.chdir(COMPILER_RT_BUILD_DIR)
  # TODO(thakis): Add this once compiler-rt can build with clang-cl (see
  # above).
  #if args.bootstrap and sys.platform == 'win32':
    # The bootstrap compiler produces 64-bit binaries by default.
    #cflags += ['-m32']
    #cxxflags += ['-m32']
  compiler_rt_args = base_cmake_args + [
      '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
      '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags)]
  if sys.platform != 'win32':
    compiler_rt_args += ['-DLLVM_CONFIG_PATH=' +
                         os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-config'),
                        '-DSANITIZER_MIN_OSX_VERSION="10.7"']
  # compiler-rt is part of the llvm checkout on Windows but a stand-alone
  # directory elsewhere, see the TODO above COMPILER_RT_DIR.
  RmCmakeCache('.')
  RunCommand(['cmake'] + compiler_rt_args +
             [LLVM_DIR if sys.platform == 'win32' else COMPILER_RT_DIR],
             msvc_arch='x86', env=deployment_env)
  RunCommand(['ninja', 'compiler-rt'], msvc_arch='x86')

  # Copy select output to the main tree.
  # TODO(hans): Make this (and the .gypi and .isolate files) version number
  # independent.
  if sys.platform == 'win32':
    platform = 'windows'
  elif sys.platform == 'darwin':
    platform = 'darwin'
  else:
    assert sys.platform.startswith('linux')
    platform = 'linux'
  asan_rt_lib_src_dir = os.path.join(COMPILER_RT_BUILD_DIR, 'lib', platform)
  if sys.platform == 'win32':
    # TODO(thakis): This too is due to compiler-rt being part of the checkout
    # on Windows, see TODO above COMPILER_RT_DIR.
    asan_rt_lib_src_dir = os.path.join(COMPILER_RT_BUILD_DIR, 'lib', 'clang',
                                       VERSION, 'lib', platform)
  asan_rt_lib_dst_dir = os.path.join(LLVM_BUILD_DIR, 'lib', 'clang',
                                     VERSION, 'lib', platform)
  # Blacklists:
  CopyDirectoryContents(os.path.join(asan_rt_lib_src_dir, '..', '..'),
                        os.path.join(asan_rt_lib_dst_dir, '..', '..'),
                        r'^.*blacklist\.txt$')
  # Headers:
  if sys.platform != 'win32':
    CopyDirectoryContents(
        os.path.join(COMPILER_RT_BUILD_DIR, 'include/sanitizer'),
        os.path.join(LLVM_BUILD_DIR, 'lib/clang', VERSION, 'include/sanitizer'))
  # Static and dynamic libraries:
  CopyDirectoryContents(asan_rt_lib_src_dir, asan_rt_lib_dst_dir)
  if sys.platform == 'darwin':
    for dylib in glob.glob(os.path.join(asan_rt_lib_dst_dir, '*.dylib')):
      # Fix LC_ID_DYLIB for the ASan dynamic libraries to be relative to
      # @executable_path.
      # TODO(glider): this is transitional. We'll need to fix the dylib
      # name either in our build system, or in Clang. See also
      # http://crbug.com/344836.
      subprocess.call(['install_name_tool', '-id',
                       '@executable_path/' + os.path.basename(dylib), dylib])

  if sys.platform == 'win32':
    # Make an extra copy of the sanitizer headers, to be put on the include path
    # of the fallback compiler.
    sanitizer_include_dir = os.path.join(LLVM_BUILD_DIR, 'lib', 'clang',
                                         VERSION, 'include', 'sanitizer')
    aux_sanitizer_include_dir = os.path.join(LLVM_BUILD_DIR, 'lib', 'clang',
                                             VERSION, 'include_sanitizer',
                                             'sanitizer')
    EnsureDirExists(aux_sanitizer_include_dir)
    for _, _, files in os.walk(sanitizer_include_dir):
      for f in files:
        CopyFile(os.path.join(sanitizer_include_dir, f),
                 aux_sanitizer_include_dir)

  if args.with_android:
    make_toolchain = os.path.join(
        ANDROID_NDK_DIR, 'build', 'tools', 'make-standalone-toolchain.sh')
    for target_arch in ['aarch64', 'arm', 'i686']:
      # Make standalone Android toolchain for target_arch.
      toolchain_dir = os.path.join(
          LLVM_BUILD_DIR, 'android-toolchain-' + target_arch)
      RunCommand([
          make_toolchain,
          '--platform=android-' + ('21' if target_arch == 'aarch64' else '19'),
          '--install-dir="%s"' % toolchain_dir,
          '--system=linux-x86_64',
          '--stl=stlport',
          '--toolchain=' + {
              'aarch64': 'aarch64-linux-android-4.9',
              'arm': 'arm-linux-androideabi-4.9',
              'i686': 'x86-4.9',
          }[target_arch]])
      # Android NDK r9d copies a broken unwind.h into the toolchain, see
      # http://crbug.com/357890
      for f in glob.glob(os.path.join(toolchain_dir, 'include/c++/*/unwind.h')):
        os.remove(f)

      # Build ASan runtime for Android in a separate build tree.
      build_dir = os.path.join(LLVM_BUILD_DIR, 'android-' + target_arch)
      if not os.path.exists(build_dir):
        os.mkdir(os.path.join(build_dir))
      os.chdir(build_dir)
      cflags = ['--target=%s-linux-androideabi' % target_arch,
                '--sysroot=%s/sysroot' % toolchain_dir,
                '-B%s' % toolchain_dir]
      android_args = base_cmake_args + [
        '-DCMAKE_C_COMPILER=' + os.path.join(LLVM_BUILD_DIR, 'bin/clang'),
        '-DCMAKE_CXX_COMPILER=' + os.path.join(LLVM_BUILD_DIR, 'bin/clang++'),
        '-DLLVM_CONFIG_PATH=' + os.path.join(LLVM_BUILD_DIR, 'bin/llvm-config'),
        '-DCMAKE_C_FLAGS=' + ' '.join(cflags),
        '-DCMAKE_CXX_FLAGS=' + ' '.join(cflags),
        '-DANDROID=1']
      RmCmakeCache('.')
      RunCommand(['cmake'] + android_args + [COMPILER_RT_DIR])
      RunCommand(['ninja', 'libclang_rt.asan-%s-android.so' % target_arch])

      # And copy it into the main build tree.
      runtime = 'libclang_rt.asan-%s-android.so' % target_arch
      for root, _, files in os.walk(build_dir):
        if runtime in files:
          shutil.copy(os.path.join(root, runtime), asan_rt_lib_dst_dir)

  # Run tests.
  if args.run_tests or use_head_revision:
    os.chdir(LLVM_BUILD_DIR)
    RunCommand(['ninja', 'cr-check-all'], msvc_arch='x64')
  if args.run_tests:
    if sys.platform == 'win32':
      CopyDiaDllTo(os.path.join(LLVM_BUILD_DIR, 'bin'))
    os.chdir(LLVM_BUILD_DIR)
    RunCommand(['ninja', 'check-all'], msvc_arch='x64')

  WriteStampFile(PACKAGE_VERSION)
  print 'Clang update was successful.'
  return 0

def main():
  parser = argparse.ArgumentParser(description='Build Clang.')
  parser.add_argument('--bootstrap', action='store_true',
                      help='first build clang with CC, then with itself.')
  parser.add_argument('--if-needed', action='store_true',
                      help="run only if the script thinks clang is needed")
  parser.add_argument('--force-local-build', action='store_true',
                      help="don't try to download prebuild binaries")
  parser.add_argument('--gcc-toolchain', help='set the version for which gcc '
                      'version be used for building; --gcc-toolchain=/opt/foo '
                      'picks /opt/foo/bin/gcc')
  parser.add_argument('--lto-gold-plugin', action='store_true',
                      help='build LLVM Gold plugin with LTO')
  parser.add_argument('--llvm-force-head-revision', action='store_true',
                      help=('use the revision in the repo when printing '
                            'the revision'))
  parser.add_argument('--print-revision', action='store_true',
                      help='print current clang revision and exit.')
  parser.add_argument('--print-clang-version', action='store_true',
                      help='print current clang version (e.g. x.y.z) and exit.')
  parser.add_argument('--run-tests', action='store_true',
                      help='run tests after building; only for local builds')
  parser.add_argument('--tools', nargs='*',
                      help='select which chrome tools to build',
                      default=['plugins', 'blink_gc_plugin'])
  parser.add_argument('--without-android', action='store_false',
                      help='don\'t build Android ASan runtime (linux only)',
                      dest='with_android',
                      default=sys.platform.startswith('linux'))
  args = parser.parse_args()

  if args.lto_gold_plugin and not args.bootstrap:
    print '--lto-gold-plugin requires --bootstrap'
    return 1
  if args.lto_gold_plugin and not sys.platform.startswith('linux'):
    print '--lto-gold-plugin is only effective on Linux. Ignoring the option.'
    args.lto_gold_plugin = False

  if args.if_needed:
    is_clang_required = False
    # clang is always used on Mac and Linux.
    if sys.platform == 'darwin' or sys.platform.startswith('linux'):
      is_clang_required = True
    # clang requested via $GYP_DEFINES.
    if re.search(r'\b(clang|asan|lsan|msan|tsan)=1',
                 os.environ.get('GYP_DEFINES', '')):
      is_clang_required = True
    # clang previously downloaded, keep it up to date.
    # If you don't want this, delete third_party/llvm-build on your machine.
    if os.path.isdir(LLVM_BUILD_DIR):
      is_clang_required = True
    if not is_clang_required:
      return 0
    if re.search(r'\b(make_clang_dir)=', os.environ.get('GYP_DEFINES', '')):
      print 'Skipping Clang update (make_clang_dir= was set in GYP_DEFINES).'
      return 0

  global CLANG_REVISION, PACKAGE_VERSION
  if args.print_revision:
    if use_head_revision or args.llvm_force_head_revision:
      print GetSvnRevision(LLVM_DIR)
    else:
      print PACKAGE_VERSION
    return 0

  if args.print_clang_version:
    sys.stdout.write(VERSION)
    return 0

  # Don't buffer stdout, so that print statements are immediately flushed.
  # Do this only after --print-revision has been handled, else we'll get
  # an error message when this script is run from gn for some reason.
  sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

  if use_head_revision:
    # Use a real revision number rather than HEAD to make sure that the stamp
    # file logic works.
    CLANG_REVISION = GetSvnRevision(LLVM_REPO_URL)
    PACKAGE_VERSION = CLANG_REVISION + '-0'

    args.force_local_build = True
    if 'OS=android' not in os.environ.get('GYP_DEFINES', ''):
      # Only build the Android ASan rt on ToT bots when targetting Android.
      args.with_android = False

  return UpdateClang(args)

if __name__ == '__main__':
  sys.exit(main())


text:
package com.badlogic.gdx.graphics.glutils;

import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.utils.Disposable;

import java.nio.FloatBuffer;

/** A InstanceData instance holds instance data for rendering with OpenGL. It is implemented as either a
 * {@link InstanceBufferObject} or a {@link InstanceBufferObjectSubData}. Both require Open GL 3.3+.
 *
 * @author mrdlink */
public interface InstanceData extends Disposable {

	/** @return the number of vertices this InstanceData stores */
	public int getNumInstances ();

	/** @return the number of vertices this InstanceData can store */
	public int getNumMaxInstances ();

	/** @return the {@link VertexAttributes} as specified during construction. */
	public VertexAttributes getAttributes ();

	/** Sets the vertices of this InstanceData, discarding the old vertex data. The count must equal the number of floats per
	 * vertex times the number of vertices to be copied to this VertexData. The order of the vertex attributes must be the same as
	 * specified at construction time via {@link VertexAttributes}.
	 *

	 * This can be called in between calls to bind and unbind. The vertex data will be updated instantly.
	 *
	 * @param data the instance data
	 * @param offset the offset to start copying the data from
	 * @param count the number of floats to copy */
	public void setInstanceData (float[] data, int offset, int count);

	/** Update (a portion of) the vertices. Does not resize the backing buffer.
	 *
	 * @param data the instance data
	 * @param sourceOffset the offset to start copying the data from
	 * @param count the number of floats to copy */
	public void updateInstanceData (int targetOffset, float[] data, int sourceOffset, int count);

	/** Sets the vertices of this InstanceData, discarding the old vertex data. The count must equal the number of floats per
	 * vertex times the number of vertices to be copied to this InstanceData. The order of the vertex attributes must be the same
	 * as specified at construction time via {@link VertexAttributes}.
	 *

	 * This can be called in between calls to bind and unbind. The vertex data will be updated instantly.
	 *
	 * @param data the instance data
	 * @param count the number of floats to copy */
	public void setInstanceData (FloatBuffer data, int count);

	/** Update (a portion of) the vertices. Does not resize the backing buffer.
	 *
	 * @param data the vertex data
	 * @param sourceOffset the offset to start copying the data from
	 * @param count the number of floats to copy */
	public void updateInstanceData (int targetOffset, FloatBuffer data, int sourceOffset, int count);

	/** Returns the underlying FloatBuffer and marks it as dirty, causing the buffer contents to be uploaded on the next call to
	 * bind. If you need immediate uploading use {@link #setInstanceData(float[], int, int)}; Any modifications made to the Buffer
	 * *after* the call to bind will not automatically be uploaded.
	 *
	 * @return the underlying FloatBuffer holding the vertex data.
	 * @deprecated use {@link #getBuffer(boolean)} instead */
	@Deprecated
	public FloatBuffer getBuffer ();

	/** Returns the underlying FloatBuffer for reading or writing.
	 * @param forWriting when true, the underlying buffer will be uploaded on the next call to bind. If you need immediate
	 *           uploading use {@link #setInstanceData(float[], int, int)}.
	 * @return the underlying FloatBuffer holding the vertex data. */
	public FloatBuffer getBuffer (boolean forWriting);

	/** Binds this InstanceData for rendering via glDrawArraysInstanced or glDrawElementsInstanced. */
	public void bind (ShaderProgram shader);

	/** Binds this InstanceData for rendering via glDrawArraysInstanced or glDrawElementsInstanced.
	 *
	 * @param locations array containing the attribute locations. */
	public void bind (ShaderProgram shader, int[] locations);

	/** Unbinds this InstanceData. */
	public void unbind (ShaderProgram shader);

	/** Unbinds this InstanceData.
	 *
	 * @param locations array containing the attribute locations. */
	public void unbind (ShaderProgram shader, int[] locations);

	/** Invalidates the InstanceData if applicable. Use this in case of a context loss. */
	public void invalidate ();

	/** Disposes this InstanceData and all its associated OpenGL resources. */
	public void dispose ();
}


text:
{% extends "base.html" %}

{% block hextra %}

{% endblock %}

{% block content %}

    Today's lunch is going to be at fucking

    {{ venue.name }}

    or you can try it out for yourself.

{{ venue.name }}

{{ venue.categories|join(', ') }}

{{ venue.address }}{% if venue.cross_street %} ({{ venue.cross_street }}){% endif %}, {{ venue.city }}, {{ venue.state }}

        {% if venue.rating or venue.price %}

        {% if venue.rating %}
        ♥ {{ venue.rating }}

        {% endif %}
        {% if venue.price %}
        {% for i in range(venue.price) %} $ {% endfor %}{% for i in range(venue.price, 4) %} • {% endfor %}
        {% endif %}

        {% endif %}

{% endblock %}


text:
<?php
/**
 * BankItem
 *
 * PHP version 5
 *
 * @category Class
 * @package  Khipu
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */
/**
 *  Copyright 2015 SmartBear Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Khipu\Model;

use \ArrayAccess;
/**
 * BankItem Class Doc Comment
 *
 * @category    Class
 * @description
 * @package     Khipu
 * @author      http://github.com/swagger-api/swagger-codegen
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class BankItem implements ArrayAccess
{
    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    static $swaggerTypes = array(
        'bank_id' => 'string',
        'name' => 'string',
        'message' => 'string',
        'min_amount' => 'double',
        'type' => 'string',
        'parent' => 'string'
    );

    /**
      * Array of attributes where the key is the local name, and the value is the original name
      * @var string[]
      */
    static $attributeMap = array(
        'bank_id' => 'bank_id',
        'name' => 'name',
        'message' => 'message',
        'min_amount' => 'min_amount',
        'type' => 'type',
        'parent' => 'parent'
    );

    /**
      * Array of attributes to setter functions (for deserialization of responses)
      * @var string[]
      */
    static $setters = array(
        'bank_id' => 'setBankId',
        'name' => 'setName',
        'message' => 'setMessage',
        'min_amount' => 'setMinAmount',
        'type' => 'setType',
        'parent' => 'setParent'
    );

    /**
      * Array of attributes to getter functions (for serialization of requests)
      * @var string[]
      */
    static $getters = array(
        'bank_id' => 'getBankId',
        'name' => 'getName',
        'message' => 'getMessage',
        'min_amount' => 'getMinAmount',
        'type' => 'getType',
        'parent' => 'getParent'
    );

    /**
      * $bank_id
      * @var string
      */
    protected $bank_id;

    /**
      * $name
      * @var string
      */
    protected $name;

    /**
      * $message
      * @var string
      */
    protected $message;

    /**
      * $min_amount
      * @var double
      */
    protected $min_amount;

    /**
      * $type
      * @var string
      */
    protected $type;

    /**
      * $parent
      * @var string
      */
    protected $parent;

    /**
     * Constructor
     * @param mixed[] $data Associated array of property value initalizing the model
     */
    public function __construct(array $data = null)
    {
        if ($data != null) {
            $this->bank_id = $data["bank_id"];
            $this->name = $data["name"];
            $this->message = $data["message"];
            $this->min_amount = $data["min_amount"];
            $this->type = $data["type"];
            $this->parent = $data["parent"];
        }
    }

    /**
     * Gets bank_id
     * @return string
     */
    public function getBankId()
    {
        return $this->bank_id;
    }

    /**
     * Sets bank_id
     * @param string $bank_id
     * @return $this
     */
    public function setBankId($bank_id)
    {

        $this->bank_id = $bank_id;
        return $this;
    }

    /**
     * Gets name
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Sets name
     * @param string $name
     * @return $this
     */
    public function setName($name)
    {

        $this->name = $name;
        return $this;
    }

    /**
     * Gets message
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Sets message
     * @param string $message
     * @return $this
     */
    public function setMessage($message)
    {

        $this->message = $message;
        return $this;
    }

    /**
     * Gets min_amount
     * @return double
     */
    public function getMinAmount()
    {
        return $this->min_amount;
    }

    /**
     * Sets min_amount
     * @param double $min_amount
     * @return $this
     */
    public function setMinAmount($min_amount)
    {

        $this->min_amount = $min_amount;
        return $this;
    }

    /**
     * Gets type
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Sets type
     * @param string $type
     * @return $this
     */
    public function setType($type)
    {

        $this->type = $type;
        return $this;
    }

    /**
     * Gets parent
     * @return string
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Sets parent
     * @param string $parent
     * @return $this
     */
    public function setParent($parent)
    {

        $this->parent = $parent;
        return $this;
    }

    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->$offset;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->$offset);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) {
            return json_encode(get_object_vars($this), JSON_PRETTY_PRINT);
        } else {
            return json_encode(get_object_vars($this));
        }
    }
}


text:
package io.crate.expression.scalar.postgres;

import io.crate.data.Input;
import io.crate.expression.scalar.ScalarFunctionModule;
import io.crate.metadata.FunctionName;
import io.crate.metadata.NodeContext;
import io.crate.metadata.Scalar;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.functions.BoundSignature;
import io.crate.metadata.functions.Signature;
import io.crate.metadata.pgcatalog.PgCatalogSchemaInfo;
import io.crate.metadata.settings.session.SessionSetting;
import io.crate.metadata.settings.session.SessionSettingRegistry;
import io.crate.types.DataTypes;
import org.elasticsearch.common.inject.Provider;

import static io.crate.metadata.functions.Signature.scalar;

public class CurrentSettingFunction extends Scalar<String, Object> {

    private static final String NAME = "current_setting";
    private static final FunctionName FQN = new FunctionName(PgCatalogSchemaInfo.NAME, NAME);

    public static void register(ScalarFunctionModule module, Provider<SessionSettingRegistry> sessionSettingRegistry) {
        module.register(
            scalar(
                FQN,
                DataTypes.STRING.getTypeSignature(),
                DataTypes.STRING.getTypeSignature()
            ),
            (signature, boundSignature) ->
                new CurrentSettingFunction(
                    signature,
                    boundSignature,
                    sessionSettingRegistry
                )
        );

        module.register(
            scalar(
                FQN,
                DataTypes.STRING.getTypeSignature(),
                DataTypes.BOOLEAN.getTypeSignature(),
                DataTypes.STRING.getTypeSignature()
            ),
            (signature, boundSignature) ->
                new CurrentSettingFunction(
                    signature,
                    boundSignature,
                    sessionSettingRegistry
                )
        );
    }

    private final Signature signature;
    private final BoundSignature boundSignature;
    private final Provider<SessionSettingRegistry> sessionSettingRegistry;

    CurrentSettingFunction(Signature signature, BoundSignature boundSignature, Provider<SessionSettingRegistry> sessionSettingRegistry) {
        this.signature = signature;
        this.boundSignature = boundSignature;
        this.sessionSettingRegistry = sessionSettingRegistry;

    }

    @Override
    public Signature signature() {
        return signature;
    }

    @Override
    public BoundSignature boundSignature() {
        return boundSignature;
    }

    @Override
    public String evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<Object>... args) {
        assert args.length == 1 || args.length == 2 : "number of args must be 1 or 2";

        final String settingName = (String) args[0].value();
        if (settingName == null) {
            return null;
        }

        final Boolean missingOk = (args.length == 2)
            ? (Boolean) args[1].value()
            : Boolean.FALSE;
        if (missingOk == null) {
            return null;
        }

        final SessionSetting<?> sessionSetting = sessionSettingRegistry.get().settings().get(settingName);
        if (sessionSetting == null) {
            if (missingOk) {
                return null;
            } else {
                throw new IllegalArgumentException("Unrecognised Setting: " + settingName);
            }
        }
        return sessionSetting.getValue(txnCtx.sessionSettings());
    }
}


text:
#pragma once
#include <aws/lookoutmetrics/LookoutMetrics_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/lookoutmetrics/model/DimensionNameValue.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace LookoutMetrics
{
namespace Model
{

  /**
   *
Details about a metric. A metric is an aggregation of the values of a measure
   * for a dimension value, such as availability in the us-east-1
   * Region.

See Also:
   AWS
   * API Reference

   */
  class AWS_LOOKOUTMETRICS_API TimeSeries
  {
  public:
    TimeSeries();
    TimeSeries(Aws::Utils::Json::JsonView jsonValue);
    TimeSeries& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The ID of the metric.

     */
    inline const Aws::String& GetTimeSeriesId() const{ return m_timeSeriesId; }

    /**
     *
The ID of the metric.

     */
    inline bool TimeSeriesIdHasBeenSet() const { return m_timeSeriesIdHasBeenSet; }

    /**
     *
The ID of the metric.

     */
    inline void SetTimeSeriesId(const Aws::String& value) { m_timeSeriesIdHasBeenSet = true; m_timeSeriesId = value; }

    /**
     *
The ID of the metric.

     */
    inline void SetTimeSeriesId(Aws::String&& value) { m_timeSeriesIdHasBeenSet = true; m_timeSeriesId = std::move(value); }

    /**
     *
The ID of the metric.

     */
    inline void SetTimeSeriesId(const char* value) { m_timeSeriesIdHasBeenSet = true; m_timeSeriesId.assign(value); }

    /**
     *
The ID of the metric.

     */
    inline TimeSeries& WithTimeSeriesId(const Aws::String& value) { SetTimeSeriesId(value); return *this;}

    /**
     *
The ID of the metric.

     */
    inline TimeSeries& WithTimeSeriesId(Aws::String&& value) { SetTimeSeriesId(std::move(value)); return *this;}

    /**
     *
The ID of the metric.

     */
    inline TimeSeries& WithTimeSeriesId(const char* value) { SetTimeSeriesId(value); return *this;}

    /**
     *
The dimensions of the metric.

     */
    inline const Aws::Vector<DimensionNameValue>& GetDimensionList() const{ return m_dimensionList; }

    /**
     *
The dimensions of the metric.

     */
    inline bool DimensionListHasBeenSet() const { return m_dimensionListHasBeenSet; }

    /**
     *
The dimensions of the metric.

     */
    inline void SetDimensionList(const Aws::Vector<DimensionNameValue>& value) { m_dimensionListHasBeenSet = true; m_dimensionList = value; }

    /**
     *
The dimensions of the metric.

     */
    inline void SetDimensionList(Aws::Vector<DimensionNameValue>&& value) { m_dimensionListHasBeenSet = true; m_dimensionList = std::move(value); }

    /**
     *
The dimensions of the metric.

     */
    inline TimeSeries& WithDimensionList(const Aws::Vector<DimensionNameValue>& value) { SetDimensionList(value); return *this;}

    /**
     *
The dimensions of the metric.

     */
    inline TimeSeries& WithDimensionList(Aws::Vector<DimensionNameValue>&& value) { SetDimensionList(std::move(value)); return *this;}

    /**
     *
The dimensions of the metric.

     */
    inline TimeSeries& AddDimensionList(const DimensionNameValue& value) { m_dimensionListHasBeenSet = true; m_dimensionList.push_back(value); return *this; }

    /**
     *
The dimensions of the metric.

     */
    inline TimeSeries& AddDimensionList(DimensionNameValue&& value) { m_dimensionListHasBeenSet = true; m_dimensionList.push_back(std::move(value)); return *this; }

    /**
     *
The values for the metric.

     */
    inline const Aws::Vector<double>& GetMetricValueList() const{ return m_metricValueList; }

    /**
     *
The values for the metric.

     */
    inline bool MetricValueListHasBeenSet() const { return m_metricValueListHasBeenSet; }

    /**
     *
The values for the metric.

     */
    inline void SetMetricValueList(const Aws::Vector<double>& value) { m_metricValueListHasBeenSet = true; m_metricValueList = value; }

    /**
     *
The values for the metric.

     */
    inline void SetMetricValueList(Aws::Vector<double>&& value) { m_metricValueListHasBeenSet = true; m_metricValueList = std::move(value); }

    /**
     *
The values for the metric.

     */
    inline TimeSeries& WithMetricValueList(const Aws::Vector<double>& value) { SetMetricValueList(value); return *this;}

    /**
     *
The values for the metric.

     */
    inline TimeSeries& WithMetricValueList(Aws::Vector<double>&& value) { SetMetricValueList(std::move(value)); return *this;}

    /**
     *
The values for the metric.

     */
    inline TimeSeries& AddMetricValueList(double value) { m_metricValueListHasBeenSet = true; m_metricValueList.push_back(value); return *this; }

  private:

    Aws::String m_timeSeriesId;
    bool m_timeSeriesIdHasBeenSet;

    Aws::Vector<DimensionNameValue> m_dimensionList;
    bool m_dimensionListHasBeenSet;

    Aws::Vector<double> m_metricValueList;
    bool m_metricValueListHasBeenSet;
  };

} // namespace Model
} // namespace LookoutMetrics
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using z.Foundation;
using z.Foundation.LogicInvoke;

namespace InitResource
{
    class Program
    {
        static void Main(string[] args)
        {
            string strYears = Utility.GetConfigValue("Years");
            List<string> years = strYears.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();

            if (years.Count > 0)
            {
                foreach (var item in years)
                {
                    Thread t = new Thread(() => InitThread(item));
                    t.Start();
                }
            }
            else
            {
                InitThread("");
            }
        }

        static void InitThread(string strYear)
        {
            LogicInvoker.Call<string, object>("com.dianyingkankan.Logic.Spider.dll", "com.dianyingkankan.Logic.Spider.GetResource", "Init", strYear);
        }
    }
}


text:
package org.apache.poi.hwpf.sprm;

import org.apache.poi.hwpf.usermodel.BorderCode;
import org.apache.poi.hwpf.usermodel.SectionProperties;
import org.apache.poi.util.HexDump;
import org.apache.poi.util.Internal;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;

@Internal
public final class SectionSprmUncompressor extends SprmUncompressor
{
  private static final POILogger logger = POILogFactory.getLogger(SectionSprmUncompressor.class);

  public SectionSprmUncompressor()
  {
  }
  public static SectionProperties uncompressSEP(byte[] grpprl, int offset)
  {
    SectionProperties newProperties = new SectionProperties();

    SprmIterator sprmIt = new SprmIterator(grpprl, offset);

    while (sprmIt.hasNext())
    {
      SprmOperation sprm = sprmIt.next();
      unCompressSEPOperation(newProperties, sprm);
    }

    return newProperties;
  }

  /**
   * Used in decompression of a sepx. This performs an operation defined by
   * a single sprm.
   *
   * @param newSEP The SectionProperty to perform the operation on.
   * @param operand The operation to perform.
   * @param param The operation's parameter.
   * @param varParam The operation variable length parameter.
   */
  static void unCompressSEPOperation (SectionProperties newSEP, SprmOperation sprm)
  {
    int operation = sprm.getOperation();
    switch (operation)
    {
      case 0:
        newSEP.setCnsPgn ((byte) sprm.getOperand());
        break;
      case 0x1:
        newSEP.setIHeadingPgn ((byte) sprm.getOperand());
        break;
      case 0x2:
        byte[] buf = new byte[sprm.size() - 3];
        System.arraycopy(sprm.getGrpprl(), sprm.getGrpprlOffset(), buf, 0, buf.length);
        newSEP.setOlstAnm (buf);
        break;
      case 0x3:
        //not quite sure
        break;
      case 0x4:
        //not quite sure
        break;
      case 0x5:
        newSEP.setFEvenlySpaced (getFlag (sprm.getOperand()));
        break;
      case 0x6:
        newSEP.setFUnlocked (getFlag (sprm.getOperand()));
        break;
      case 0x7:
        newSEP.setDmBinFirst ((short) sprm.getOperand());
        break;
      case 0x8:
        newSEP.setDmBinOther ((short) sprm.getOperand());
        break;
      case 0x9:
        newSEP.setBkc ((byte) sprm.getOperand());
        break;
      case 0xa:
        newSEP.setFTitlePage (getFlag (sprm.getOperand()));
        break;
      case 0xb:
        newSEP.setCcolM1 ((short) sprm.getOperand());
        break;
      case 0xc:
        newSEP.setDxaColumns (sprm.getOperand());
        break;
      case 0xd:
        newSEP.setFAutoPgn (getFlag (sprm.getOperand()));
        break;
      case 0xe:
        newSEP.setNfcPgn ((byte) sprm.getOperand());
        break;
      case 0xf:
        newSEP.setDyaPgn ((short) sprm.getOperand());
        break;
      case 0x10:
        newSEP.setDxaPgn ((short) sprm.getOperand());
        break;
      case 0x11:
        newSEP.setFPgnRestart (getFlag (sprm.getOperand()));
        break;
      case 0x12:
        newSEP.setFEndNote (getFlag (sprm.getOperand()));
        break;
      case 0x13:
        newSEP.setLnc ((byte) sprm.getOperand());
        break;
      case 0x14:
        newSEP.setGrpfIhdt ((byte) sprm.getOperand());
        break;
      case 0x15:
        newSEP.setNLnnMod ((short) sprm.getOperand());
        break;
      case 0x16:
        newSEP.setDxaLnn (sprm.getOperand());
        break;
      case 0x17:
        newSEP.setDyaHdrTop (sprm.getOperand());
        break;
      case 0x18:
        newSEP.setDyaHdrBottom (sprm.getOperand());
        break;
      case 0x19:
        newSEP.setFLBetween (getFlag (sprm.getOperand()));
        break;
      case 0x1a:
        newSEP.setVjc ((byte) sprm.getOperand());
        break;
      case 0x1b:
        newSEP.setLnnMin ((short) sprm.getOperand());
        break;
      case 0x1c:
        newSEP.setPgnStart ((short) sprm.getOperand());
        break;
      case 0x1d:
        newSEP.setDmOrientPage( sprm.getOperand() != 0 );
        break;
      case 0x1e:

        //nothing
        break;
      case 0x1f:
        newSEP.setXaPage (sprm.getOperand());
        break;
      case 0x20:
        newSEP.setYaPage (sprm.getOperand());
        break;
      case 0x21:
        newSEP.setDxaLeft (sprm.getOperand());
        break;
      case 0x22:
        newSEP.setDxaRight (sprm.getOperand());
        break;
      case 0x23:
        newSEP.setDyaTop (sprm.getOperand());
        break;
      case 0x24:
        newSEP.setDyaBottom (sprm.getOperand());
        break;
      case 0x25:
        newSEP.setDzaGutter (sprm.getOperand());
        break;
      case 0x26:
        newSEP.setDmPaperReq ((short) sprm.getOperand());
        break;
      case 0x27:
        newSEP.setFPropMark (getFlag (sprm.getOperand()));
        break;
      case 0x28:
        break;
      case 0x29:
        break;
      case 0x2a:
        break;
      case 0x2b:
        newSEP.setBrcTop(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset()));
        break;
      case 0x2c:
        newSEP.setBrcLeft(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset()));
        break;
      case 0x2d:
        newSEP.setBrcBottom(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset()));
        break;
      case 0x2e:
        newSEP.setBrcRight(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset()));
        break;
      case 0x2f:
        newSEP.setPgbProp (sprm.getOperand());
        break;
      case 0x30:
        newSEP.setDxtCharSpace (sprm.getOperand());
        break;
      case 0x31:
        newSEP.setDyaLinePitch (sprm.getOperand());
        break;
      case 0x33:
        newSEP.setWTextFlow ((short) sprm.getOperand());
        break;
      case 0x3C:
        // [MS-DOC], v20140721, 2.6.4, sprmSRncFtn
        newSEP.setRncFtn((short) sprm.getOperand());
        break;
      case 0x3E:
        // [MS-DOC], v20140721, 2.6.4, sprmSRncEdn
        newSEP.setRncEdn((short) sprm.getOperand());
        break;
      case 0x3F:
        // [MS-DOC], v20140721, 2.6.4, sprmSNFtn
        newSEP.setNFtn((int) sprm.getOperand());
        break;
      case 0x40:
        // [MS-DOC], v20140721, 2.6.4, sprmSNFtnRef
        newSEP.setNfcFtnRef((int) sprm.getOperand());
        break;
      case 0x41:
        // [MS-DOC], v20140721, 2.6.4, sprmSNEdn
        newSEP.setNEdn((int) sprm.getOperand());
        break;
      case 0x42:
        // [MS-DOC], v20140721, 2.6.4, sprmSNEdnRef
        newSEP.setNfcEdnRef((int) sprm.getOperand());
        break;
      default:
        logger.log(POILogger.INFO, "Unsupported Sprm operation: " + operation + " (" + HexDump.byteToHex(operation) + ")");
        break;
    }

  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="laiks dejot, TIME TO DANCE 2017, laikmetīgā deja, laikmetīgā deja latvijā, time to dance, dance, deja, izrādes, mestarklases">
    <meta name="description" content="Starptautiskais laikmetīgās dejas festivāls LAIKS DEJOT ir aizsācies 1998. gadā kā Latvijas horeogrāfu laikmetīgās dejas izrāžu vakari. Gadiem ritot, tas izaudzis līdz festivāla formātam un kopš 2006. gada ieguvis starptautiska festivāla statusu, desmit gadu laikā ir kļuvis par vērienīgāko laikmetīgās dejas pasākumu Latvijā un pamanāmu notikumu starptautiskajā arēnā. LAIKS DEJOT šobrīd ir stabils, regulārs un atpazīstams laikmetīgās dejas mākslas nozares pasākums, ar kuru rēķinās un kuru gaida gan Latvijas un ārvalstu profesionāļi, gan publika. Festivāla regulāra, ikgadēja norise ir būtiska Latvijas laikmetīgās dejas turpmākai izaugsmei un atpazīstamībai pasaulē, jo īpaši tādēļ, ka Latvijas laikmetīgajai dejai nav savas telpas un skatuves, kur notiktu regulāras izrādes un citi notikumi.">
    <meta name="author" content="tsfrlv">

    <title>Support || TIME TO DANCE 2017</title>

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

    <link href="../../assets/css/landing-page.css" rel="stylesheet">

    <link href="../../assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
      Toggle navigation

    </button>

About

Performances

Workshops

Calendar

Tickets

Support

Archive

LV

© dance.lv

2017

Powered by Bootstrap and GitHub Pages, made by Taisija Frolova


text:
@class Part;

extern NSString * const kSequenceKeyAddPartToOrderedList;

@interface Sequence : NSManagedObject

@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSSet *partSet;

//Transient
@property (nonatomic, readonly) NSInteger duration;
@property (nonatomic, readonly) NSInteger partCount;
@property (nonatomic) BOOL isPlaying;

- (Part *)getPartAtIndex:(NSInteger)index;
- (NSInteger)getPartOrderIndex:(Part *)part;
- (void)addPartToOrderedList:(Part *)part;
- (void)movePartInOrderedListFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex;
- (void)removePartFromOrderedList:(Part *)part;

- (void)invalidate;

@end

#pragma mark - CoreData
@interface Sequence (CoreDataGeneratedAccessors)

- (void)addPartSetObject:(Part *)value;
- (void)removePartSetObject:(Part *)value;
- (void)addPartSet:(NSSet *)values;
- (void)removePartSet:(NSSet *)values;

@end