text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>SQLScriptParser</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.connection.jdbc

Class SQLScriptParser

java.lang.Object

org.jetel.connection.jdbc.SQLScriptParser

All Implemented Interfaces:

java.lang.Iterable<java.lang.String>

public class SQLScriptParser
extends java.lang.Object
implements java.lang.Iterable<java.lang.String>

Splits SQL script into series of SQL statements.

Ignores delimiter in comments and strings.

Works on Strings, InputStreams and ReadableByteChannels.

Removes single-line comments.

Keeps multi-line comments

Supports optimization hint comments /*! MySQL code here */
     or /*+ Oracle code here */

Recognizes MySQL double-quote (") strings

Supports MySQL quote escaping (\')

Strips away whitespace at the beginning of the statement.

Throws IOException when input ends unexpectedly or when the underline data source throws IOException.

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
DEFAULT_SQL_DELIMITER

Constructor Summary

Constructors

Constructor and Description

SQLScriptParser()

SQLScriptParser(java.io.InputStream stream,
               java.nio.charset.Charset charset,
               java.lang.String delimiter)

SQLScriptParser(java.nio.channels.ReadableByteChannel channel,
               java.nio.charset.Charset charset,
               java.lang.String delimiter)

SQLScriptParser(java.lang.String string,
               java.lang.String delimiter)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getDelimiter()

java.lang.String
getNextStatement()

Returns next parsed SQL statement or null if end of input was reached.

boolean
isBackslashQuoteEscaping()

boolean
isRequireLastDelimiter()

boolean
istReplaceStrings()

java.util.Iterator<java.lang.String>
iterator()

void
setBackslashQuoteEscaping(boolean backslashQuoteEscaping)

When enabled, \' is treated as escaped quote in string and does not terminate string parsing.

void
setChannelInput(java.nio.channels.ReadableByteChannel channel,
               java.nio.charset.Charset charset)

void
setDelimiter(java.lang.String delimiter)

void
setInput(java.lang.Object input,
        java.nio.charset.Charset charset)

void
setReader(java.io.Reader reader)

void
setReplaceStrings(boolean replaceStrings)

When enabled, replaces all strings by space char: ' '.

void
setRequireLastDelimiter(boolean requireLastDelimiter)

When enabled will not fail when last statement is not terminated with semicolon.

void
setStreamInput(java.io.InputStream stream,
              java.nio.charset.Charset charset)

void
setStringInput(java.lang.String string)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DEFAULT_SQL_DELIMITER

public static final java.lang.String DEFAULT_SQL_DELIMITER

See Also:

Constant Field Values

Constructor Detail

SQLScriptParser

public SQLScriptParser()

SQLScriptParser

public SQLScriptParser(java.lang.String string,
               java.lang.String delimiter)

SQLScriptParser

public SQLScriptParser(java.io.InputStream stream,
               java.nio.charset.Charset charset,
               java.lang.String delimiter)

SQLScriptParser

public SQLScriptParser(java.nio.channels.ReadableByteChannel channel,
               java.nio.charset.Charset charset,
               java.lang.String delimiter)

Method Detail

setInput

public void setInput(java.lang.Object input,
            java.nio.charset.Charset charset)

setDelimiter

public void setDelimiter(java.lang.String delimiter)

getDelimiter

public java.lang.String getDelimiter()

setReplaceStrings

public void setReplaceStrings(boolean replaceStrings)

When enabled, replaces all strings by space char: ' '. Keeps the same length.

Parameters:

replaceStrings -

istReplaceStrings

public boolean istReplaceStrings()

setRequireLastDelimiter

public void setRequireLastDelimiter(boolean requireLastDelimiter)

When enabled will not fail when last statement is not terminated with semicolon.

isRequireLastDelimiter

public boolean isRequireLastDelimiter()

setBackslashQuoteEscaping

public void setBackslashQuoteEscaping(boolean backslashQuoteEscaping)

When enabled, \' is treated as escaped quote in string and does not terminate string parsing.

isBackslashQuoteEscaping

public boolean isBackslashQuoteEscaping()

setReader

public void setReader(java.io.Reader reader)

setStringInput

public void setStringInput(java.lang.String string)

setStreamInput

public void setStreamInput(java.io.InputStream stream,
                  java.nio.charset.Charset charset)

setChannelInput

public void setChannelInput(java.nio.channels.ReadableByteChannel channel,
                   java.nio.charset.Charset charset)

iterator

public java.util.Iterator<java.lang.String> iterator()

Specified by:

iterator in interface java.lang.Iterable<java.lang.String>

getNextStatement

public java.lang.String getNextStatement()
                                  throws java.io.IOException

Returns next parsed SQL statement or null if end of input was reached.

Throws:

java.io.IOException - When underlining stream or channel throws IOException or when input unexpectedly
 end in the middle of comment or string.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
// This file was automatically generated from ParseInfoExample.soy.
// Please don't edit this file by hand.

package com.google.template.soy.test_data;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.template.soy.parseinfo.SoyFileInfo;
import com.google.template.soy.parseinfo.SoyTemplateInfo;
import com.google.template.soy.parseinfo.SoyTemplateInfo.ParamRequisiteness;

/**
 * Soy parse info for ParseInfoExample.soy.
 */
public class ParseInfoExampleSoyInfo extends SoyFileInfo {

  public static class Param {
    private Param() {}

    /** Listed by .aaa, .bbbCcc, .ddd (private). */
    public static final String PPP_1 = "ppp1";
    /** Listed by .bbbCcc, .ddd (private). */
    public static final String QQQ_22 = "qqq22";
    /** Listed by .ddd (private). */
    public static final String RRR_3 = "rrr_3";
    /** Listed by .aaa. */
    public static final String XXX = "xxx";
    /** Listed by .bbbCcc. */
    public static final String YYY_ZZZ = "yyyZzz";
  }

  /**
   * This template has no params.
   */
  public static final SoyTemplateInfo HELLO = new SoyTemplateInfo(
      "examples.abc.hello",
      ImmutableMap.<String, ParamRequisiteness>of(),
      ImmutableSortedSet.<String>of());

  /**
   * Aaa template.
   */
  public static final AaaSoyTemplateInfo AAA =
      new AaaSoyTemplateInfo();

  public static class AaaSoyTemplateInfo extends SoyTemplateInfo {
    private AaaSoyTemplateInfo() {
      super("examples.abc.aaa",
            ImmutableMap.<String, ParamRequisiteness>builder()
                .put("xxx", ParamRequisiteness.OPTIONAL)
                .put("ppp1", ParamRequisiteness.REQUIRED)
                .put("qqq22", ParamRequisiteness.REQUIRED)
                .put("rrr_3", ParamRequisiteness.REQUIRED)
                .put("yyyZzz", ParamRequisiteness.REQUIRED)
                .build(),
            ImmutableSortedSet.<String>of());
    }

    /** One line description. */
    public final String XXX = "xxx";

    /** Desc of ppp from aaa. */
    public final String PPP_1 = "ppp1";

    // Indirect params.
    /** Listed by .bbbCcc, .ddd (private). */
    public final String QQQ_22 = "qqq22";
    /** Listed by .ddd (private). */
    public final String RRR_3 = "rrr_3";
    /** Listed by .bbbCcc. */
    public final String YYY_ZZZ = "yyyZzz";
  }

  /**
   * Bbb Ccc
   * template.
   */
  public static final BbbCccSoyTemplateInfo BBB_CCC =
      new BbbCccSoyTemplateInfo();

  public static class BbbCccSoyTemplateInfo extends SoyTemplateInfo {
    private BbbCccSoyTemplateInfo() {
      super("examples.abc.bbbCcc",
            ImmutableMap.<String, ParamRequisiteness>builder()
                .put("yyyZzz", ParamRequisiteness.REQUIRED)
                .put("ppp1", ParamRequisiteness.REQUIRED)
                .put("qqq22", ParamRequisiteness.REQUIRED)
                .put("rrr_3", ParamRequisiteness.REQUIRED)
                .build(),
            ImmutableSortedSet.<String>of());
    }

    /**
     * Multiline
     * description.
     */
    public final String YYY_ZZZ = "yyyZzz";

    /** Desc of ppp from bbbCcc. */
    public final String PPP_1 = "ppp1";

    /** Desc of qqq from bbbCcc. */
    public final String QQQ_22 = "qqq22";

    // Indirect params.
    /** Listed by .ddd (private). */
    public final String RRR_3 = "rrr_3";
  }

  private ParseInfoExampleSoyInfo() {
    super("ParseInfoExample.soy",
          "examples.abc",
          ImmutableSortedSet.<String>of(
              Param.PPP_1,
              Param.QQQ_22,
              Param.RRR_3,
              Param.XXX,
              Param.YYY_ZZZ),
          ImmutableList.<SoyTemplateInfo>of(
              HELLO,
              AAA,
              BBB_CCC),
          ImmutableMap.<String, CssTagsPrefixPresence>builder()
              .put("GGG_HHH", CssTagsPrefixPresence.NEVER)
              .put("_eee_fff", CssTagsPrefixPresence.ALWAYS)
              .put("aaa-bbb", CssTagsPrefixPresence.NEVER)
              .put("cccDdd", CssTagsPrefixPresence.SOMETIMES)
              .build());
  }

  private static final ParseInfoExampleSoyInfo __INSTANCE__ = new ParseInfoExampleSoyInfo();

  public static ParseInfoExampleSoyInfo getInstance() {
    return __INSTANCE__;
  }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "ModuleInterface.h"

/**
* Interface for the JavascriptUMG Module.
*/
class IJavascriptUMGModule : public IModuleInterface
{
public:

	/**
	* Singleton-like access to this module's interface.  This is just for convenience!
	* Beware of calling this during the shutdown phase, though.  Your module might have been unloaded already.
	*
	* @return Returns singleton instance, loading the module on demand if needed
	*/
	static inline IJavascriptUMGModule& Get()
	{
		return FModuleManager::LoadModuleChecked< IJavascriptUMGModule >("JavascriptUMG");
	}

	/**
	* Checks to see if this module is loaded and ready.  It is only valid to call Get() if IsAvailable() returns true.
	*
	* @return True if the module is loaded and ready to use
	*/
	static inline bool IsAvailable()
	{
		return FModuleManager::Get().IsModuleLoaded("JavascriptUMG");
	}
};


text:
@implementation JMUISendMsgManager
+ (JMUISendMsgManager *)ins {
  static JMUISendMsgManager *sendMsgManage = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sendMsgManage = [[JMUISendMsgManager alloc] init];
  });
  return sendMsgManage;
}

- (id)init {
  self = [super init];
  if (self) {
    _sendMsgListDic  = @{}.mutableCopy;
    _textDraftDic = @{}.mutableCopy;
  }
  return self;
}

- (void)addMessage:(JMSGMessage *)imgMsg withConversation:(JMSGConversation *)conversation {
  NSString *key = nil;
  if (conversation.conversationType == kJMSGConversationTypeSingle) {
    key = ((JMSGUser *)conversation.target).username;
  } else {
    key = ((JMSGGroup *)conversation.target).gid;
  }

  if (_sendMsgListDic[key] == nil) {
    JMUISendMsgController *sendMsgCtl = [[JMUISendMsgController alloc] init];
    sendMsgCtl.msgConversation = conversation;
    [sendMsgCtl addDelegateForConversation:conversation];
    [sendMsgCtl prepareImageMessage:imgMsg];
    _sendMsgListDic[key] = sendMsgCtl;
  } else {
    JMUISendMsgController *sendMsgCtl = _sendMsgListDic[key];
    [sendMsgCtl prepareImageMessage:imgMsg];
  }
}

- (void)updateConversation:(JMSGConversation *)conversation withDraft:(NSString *)draftString {
  NSString *key = nil;
  key = [JMUIStringUtils conversationIdWithConversation:conversation];
  _textDraftDic[key] = draftString;
}

- (NSString *)draftStringWithConversation:(JMSGConversation *)conversation {
  NSString *key = nil;
  key = [JMUIStringUtils conversationIdWithConversation:conversation];
  return _textDraftDic[key] ? _textDraftDic[key] : @"";
}
@end


text:
//===----------------------------------------------------------------------===//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

const char *usage =
    "  swift-stdlib-tool --print [options...]\n"
    "    Find and print the Swift libraries required by an app.\n"
    "\n"
    "  swift-stdlib-tool --copy [options...]\n"
    "    Copy the Swift libraries into an app bundle, and optionally sign them.\n"
    "\n"
    "  --verbose\n"
    "      Print progress.\n"
    "  --verbose --verbose\n"
    "      Print debugging details.\n"
    "  --help\n"
    "      Print usage.\n"
    "\n"
    "  Options for lookup:\n"
    "  --scan-executable <path>\n"
    "      Scan the executable at <path> for references to Swift libraries.\n"
    "      This option may be set multiple times.\n"
    "  --scan-folder <path>\n"
    "      Scan any executables inside <path> for references to Swift libraries.\n"
    "      This option may be set multiple times.\n"
    "  --platform <macosx|iphoneos|iphonesimulator>\n"
    "      Use the Swift libraries for <platform>.\n"
    "  --source-libraries <path>\n"
    "      Search <path> for Swift libraries.\n"
    "      The default is /path/to/swift-stdlib-tool/../../lib/swift/<platform>/\n"
    "\n"
    "  Options for copying and signing:\n"
    "  --destination <path>\n"
    "      Copy Swift libraries into <path>.\n"
    "  --unsigned-destination <path>\n"
    "      Copy Swift libraries into <path> without signing them.\n"
    "  --sign <identity>\n"
    "      Sign copied Swift libraries using <identity>.\n"
    "  --keychain <keychain>\n"
    "      Search <keychain> for the code signing identity.\n"
    "  --Xcodesign <option>\n"
    "      Pass <option> to the codesign tool.\n"
    "  --strip-bitcode\n"
    "      Remove embedded bitcode from libraries copied to --destination.\n"
    "      Libraries copied to --unsigned-destination are unmodified.\n"
    "\n"
    "  Options for libraries copied as resources\n"
    "  --resource-library <library>\n"
    "      Copy <library> and its dependencies as resources without signing\n"
    "      them. These copies are in addition to any libraries copied as a result\n"
    "      of the --scan-executable option.\n"
    "      Any library in the Swift library search path can be specified for\n"
    "      <library>.\n"
    "      This option may be set multiple times.\n"
    "  --resource-destination <path>\n"
    "      The <path> to copy Swift resource libraries to.\n"
    "\n";

#include <copyfile.h>
#include <dirent.h>
#include <dispatch/dispatch.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <libkern/OSByteOrder.h>
#include <mach-o/dyld.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
#include <os/overflow.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <uuid/uuid.h>

#include <algorithm>
#include <mutex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#pragma clang diagnostic ignored "-Wgcc-compat"

#ifndef CPU_TYPE_ARM64
#define CPU_TYPE_ARM64 ((cpu_type_t)(CPU_TYPE_ARM | CPU_ARCH_ABI64))
#endif

static int Verbose = 0;

#ifdef __OPTIMIZE__
#define INLINE __attribute__((always_inline))
#else
#define INLINE
#endif

//
// This abstraction layer is for use with file formats that have 64-bit/32-bit and Big-Endian/Little-Endian variants
//
// For example: to make a utility that handles 32-bit little enidan files use:  Pointer32<LittleEndian>
//
//
//		get16()			read a 16-bit number from an E endian struct
//		set16()			write a 16-bit number to an E endian struct
//		get32()			read a 32-bit number from an E endian struct
//		set32()			write a 32-bit number to an E endian struct
//		get64()			read a 64-bit number from an E endian struct
//		set64()			write a 64-bit number to an E endian struct
//
//		getBits()		read a bit field from an E endian struct (bitCount=number of bits in field, firstBit=bit index of field)
//		setBits()		write a bit field to an E endian struct (bitCount=number of bits in field, firstBit=bit index of field)
//
//		getBitsRaw()	read a bit field from a struct with native endianness
//		setBitsRaw()	write a bit field from a struct with native endianness
//

class BigEndian {
public:
  static uint16_t get16(const uint16_t &from) INLINE {
    return OSReadBigInt16(&from, 0);
  }
  static void set16(uint16_t &into, uint16_t value) INLINE {
    OSWriteBigInt16(&into, 0, value);
  }

  static uint32_t get32(const uint32_t &from) INLINE {
    return OSReadBigInt32(&from, 0);
  }
  static void set32(uint32_t &into, uint32_t value) INLINE {
    OSWriteBigInt32(&into, 0, value);
  }

  static uint64_t get64(const uint64_t &from) INLINE {
    return OSReadBigInt64(&from, 0);
  }
  static void set64(uint64_t &into, uint64_t value) INLINE {
    OSWriteBigInt64(&into, 0, value);
  }

  static uint32_t getBits(const uint32_t &from, uint8_t firstBit,
                          uint8_t bitCount) INLINE {
    return getBitsRaw(get32(from), firstBit, bitCount);
  }
  static void setBits(uint32_t &into, uint32_t value, uint8_t firstBit,
                      uint8_t bitCount) INLINE {
    uint32_t temp = get32(into);
    setBitsRaw(temp, value, firstBit, bitCount);
    set32(into, temp);
  }

  static uint32_t getBitsRaw(const uint32_t &from, uint8_t firstBit,
                             uint8_t bitCount) INLINE {
    return ((from >> (32 - firstBit - bitCount)) & ((1 << bitCount) - 1));
  }
  static void setBitsRaw(uint32_t &into, uint32_t value, uint8_t firstBit,
                         uint8_t bitCount) INLINE {
    uint32_t temp = into;
    const uint32_t mask = ((1 << bitCount) - 1);
    temp &= ~(mask << (32 - firstBit - bitCount));
    temp |= ((value & mask) << (32 - firstBit - bitCount));
    into = temp;
  }
  enum { little_endian = 0 };
};

class LittleEndian {
public:
  static uint16_t get16(const uint16_t &from) INLINE {
    return OSReadLittleInt16(&from, 0);
  }
  static void set16(uint16_t &into, uint16_t value) INLINE {
    OSWriteLittleInt16(&into, 0, value);
  }

  static uint32_t get32(const uint32_t &from) INLINE {
    return OSReadLittleInt32(&from, 0);
  }
  static void set32(uint32_t &into, uint32_t value) INLINE {
    OSWriteLittleInt32(&into, 0, value);
  }

  static uint64_t get64(const uint64_t &from) INLINE {
    return OSReadLittleInt64(&from, 0);
  }
  static void set64(uint64_t &into, uint64_t value) INLINE {
    OSWriteLittleInt64(&into, 0, value);
  }

  static uint32_t getBits(const uint32_t &from, uint8_t firstBit,
                          uint8_t bitCount) INLINE {
    return getBitsRaw(get32(from), firstBit, bitCount);
  }
  static void setBits(uint32_t &into, uint32_t value, uint8_t firstBit,
                      uint8_t bitCount) INLINE {
    uint32_t temp = get32(into);
    setBitsRaw(temp, value, firstBit, bitCount);
    set32(into, temp);
  }

  static uint32_t getBitsRaw(const uint32_t &from, uint8_t firstBit,
                             uint8_t bitCount) INLINE {
    return ((from >> firstBit) & ((1 << bitCount) - 1));
  }
  static void setBitsRaw(uint32_t &into, uint32_t value, uint8_t firstBit,
                         uint8_t bitCount) INLINE {
    uint32_t temp = into;
    const uint32_t mask = ((1 << bitCount) - 1);
    temp &= ~(mask << firstBit);
    temp |= ((value & mask) << firstBit);
    into = temp;
  }
  enum { little_endian = 1 };
};

#if __BIG_ENDIAN__
typedef BigEndian CurrentEndian;
typedef LittleEndian OtherEndian;
#elif __LITTLE_ENDIAN__
typedef LittleEndian CurrentEndian;
typedef BigEndian OtherEndian;
#else
#error unknown endianness
#endif

template <typename _E>
class Pointer32 {
public:
  typedef uint32_t uint_t;
  typedef int32_t sint_t;
  typedef _E E;

  static uint64_t getP(const uint_t &from) INLINE { return _E::get32(from); }
  static void setP(uint_t &into, uint64_t value) INLINE {
    _E::set32(into, value);
  }
};

template <typename _E>
class Pointer64 {
public:
  typedef uint64_t uint_t;
  typedef int64_t sint_t;
  typedef _E E;

  static uint64_t getP(const uint_t &from) INLINE { return _E::get64(from); }
  static void setP(uint_t &into, uint64_t value) INLINE {
    _E::set64(into, value);
  }
};

//
// mach-o file header
//
template <typename P>
struct macho_header_content {};
template <>
struct macho_header_content<Pointer32<BigEndian>> {
  mach_header fields;
};
template <>
struct macho_header_content<Pointer64<BigEndian>> {
  mach_header_64 fields;
};
template <>
struct macho_header_content<Pointer32<LittleEndian>> {
  mach_header fields;
};
template <>
struct macho_header_content<Pointer64<LittleEndian>> {
  mach_header_64 fields;
};

template <typename P>
class macho_header {
public:
  uint32_t magic() const INLINE { return E::get32(header.fields.magic); }
  void set_magic(uint32_t value) INLINE {
    E::set32(header.fields.magic, value);
  }

  uint32_t cputype() const INLINE { return E::get32(header.fields.cputype); }
  void set_cputype(uint32_t value) INLINE {
    E::set32((uint32_t &)header.fields.cputype, value);
  }

  uint32_t cpusubtype() const INLINE {
    return E::get32(header.fields.cpusubtype);
  }
  void set_cpusubtype(uint32_t value) INLINE {
    E::set32((uint32_t &)header.fields.cpusubtype, value);
  }

  uint32_t filetype() const INLINE { return E::get32(header.fields.filetype); }
  void set_filetype(uint32_t value) INLINE {
    E::set32(header.fields.filetype, value);
  }

  uint32_t ncmds() const INLINE { return E::get32(header.fields.ncmds); }
  void set_ncmds(uint32_t value) INLINE {
    E::set32(header.fields.ncmds, value);
  }

  uint32_t sizeofcmds() const INLINE {
    return E::get32(header.fields.sizeofcmds);
  }
  void set_sizeofcmds(uint32_t value) INLINE {
    E::set32(header.fields.sizeofcmds, value);
  }

  uint32_t flags() const INLINE { return E::get32(header.fields.flags); }
  void set_flags(uint32_t value) INLINE {
    E::set32(header.fields.flags, value);
  }

  uint32_t reserved() const INLINE { return E::get32(header.fields.reserved); }
  void set_reserved(uint32_t value) INLINE {
    E::set32(header.fields.reserved, value);
  }

  typedef typename P::E E;

private:
  macho_header_content<P> header;
};

//
// mach-o load command
//
template <typename P>
class macho_load_command {
public:
  uint32_t cmd() const INLINE { return E::get32(command.cmd); }
  void set_cmd(uint32_t value) INLINE { E::set32(command.cmd, value); }

  uint32_t cmdsize() const INLINE { return E::get32(command.cmdsize); }
  void set_cmdsize(uint32_t value) INLINE { E::set32(command.cmdsize, value); }

  typedef typename P::E E;

private:
  load_command command;
};

//
// mach-o uuid load command
//
template <typename P>
class macho_uuid_command {
public:
  uint32_t cmd() const INLINE { return E::get32(fields.cmd); }
  void set_cmd(uint32_t value) INLINE { E::set32(fields.cmd, value); }

  uint32_t cmdsize() const INLINE { return E::get32(fields.cmdsize); }
  void set_cmdsize(uint32_t value) INLINE { E::set32(fields.cmdsize, value); }

  const uint8_t *uuid() const INLINE { return fields.uuid; }
  void set_uuid(uint8_t value[16]) INLINE { memcpy(&fields.uuid, value, 16); }

  typedef typename P::E E;

private:
  uuid_command fields;
};

//
// mach-o dylib load command
//
template <typename P>
class macho_dylib_command {
public:
  uint32_t cmd() const INLINE { return E::get32(fields.cmd); }
  void set_cmd(uint32_t value) INLINE { E::set32(fields.cmd, value); }

  uint32_t cmdsize() const INLINE { return E::get32(fields.cmdsize); }
  void set_cmdsize(uint32_t value) INLINE { E::set32(fields.cmdsize, value); }

  uint32_t name_offset() const INLINE {
    return E::get32(fields.dylib.name.offset);
  }
  void set_name_offset(uint32_t value) INLINE {
    E::set32(fields.dylib.name.offset, value);
  }

  uint32_t timestamp() const INLINE { return E::get32(fields.dylib.timestamp); }
  void set_timestamp(uint32_t value) INLINE {
    E::set32(fields.dylib.timestamp, value);
  }

  uint32_t current_version() const INLINE {
    return E::get32(fields.dylib.current_version);
  }
  void set_current_version(uint32_t value) INLINE {
    E::set32(fields.dylib.current_version, value);
  }

  uint32_t compatibility_version() const INLINE {
    return E::get32(fields.dylib.compatibility_version);
  }
  void set_compatibility_version(uint32_t value) INLINE {
    E::set32(fields.dylib.compatibility_version, value);
  }

  const char *name() const INLINE {
    return (const char *)&fields + name_offset();
  }
  void set_name_offset() INLINE { set_name_offset(sizeof(fields)); }

  typedef typename P::E E;

private:
  dylib_command fields;
};

// Print everything to standard output.
// Mixing stdout and stderr looks bad when the output is reprinted by Xcode.

void printUsage() { fprintf(stdout, "%s", usage); }

void fail(const char *msg, ...) __attribute__((format(printf, 1, 2)))
__attribute__((noreturn)) {
  va_list args;
  va_start(args, msg);
  char *msg2;
  asprintf(&msg2, "*** error: %s\n", msg);
  vfprintf(stdout, msg2, args);
  exit(1);
}

void fail_errno(const char *msg, ...) __attribute__((format(printf, 1, 2)))
__attribute__((noreturn)) {
  va_list args;
  va_start(args, msg);
  char *msg2;
  asprintf(&msg2, "*** error: %s: %s\n", msg, strerror(errno));
  vfprintf(stdout, msg2, args);
  exit(1);
}

void fail_usage(const char *msg, ...) __attribute__((format(printf, 1, 2)))
__attribute__((noreturn)) {
  va_list args;
  va_start(args, msg);
  char *msg2;
  asprintf(&msg2, "*** error: %s\n\n", msg);
  vfprintf(stdout, msg2, args);
  printUsage();
  exit(1);
}

void log_vn(int verbosity, const char *msg, va_list args)
    __attribute__((format(printf, 2, 0))) {
  if (verbosity <= Verbose) {
    char *msg2;
    asprintf(&msg2, "%s\n", msg);
    vfprintf(stdout, msg2, args);
    free(msg2);
  }
}

int log_v(const char *msg, ...) __attribute__((format(printf, 1, 2))) {
  va_list args;
  va_start(args, msg);
  log_vn(1, msg, args);
  return -1;
}

int log_vv(const char *msg, ...) __attribute__((format(printf, 1, 2))) {
  va_list args;
  va_start(args, msg);
  log_vn(2, msg, args);
  return -1;
}

ssize_t pread_all(int fd, void *buf, size_t count, off_t offset) {
  size_t total = 0;
  while (total < count) {
    ssize_t readed =
        pread(fd, (void *)((char *)buf + total), count - total, offset + total);
    if (readed > 0)
      total += readed; // got data
    else if (readed == 0)
      return total; // EOF: done
    else if (readed == -1 && errno != EINTR)
      return -1;
    // error but not EINTR: fail
  }

  return total;
}

template <typename T>
int parse_macho(int fd, uint32_t offset, uint32_t size,
                void (^dylibVisitor)(const std::string &path),
                void (^uuidVisitor)(const uuid_t uuid)) {
  ssize_t readed;

  macho_header<T> mh;
  if (size < sizeof(mh))
    return log_vv("file is too small");
  readed = pread_all(fd, &mh, sizeof(mh), offset);
  if (readed != sizeof(mh))
    return log_vv("pread failed");

  uint32_t sizeofcmds = mh.sizeofcmds();
  size -= sizeof(mh);
  offset += sizeof(mh);
  if (size < sizeofcmds)
    return log_vv("file is badly formed");

  uint8_t *cmdp = (uint8_t *)malloc(sizeofcmds);
  if (!cmdp)
    return log_vv("malloc(sizeofcmds) failed");

  readed = pread_all(fd, cmdp, sizeofcmds, offset);
  if (readed == sizeofcmds) {
    uint8_t *cmds = cmdp;
    for (uint32_t c = 0; c < mh.ncmds(); c++) {
      macho_load_command<T> *cmd;
      if (size < sizeof(*cmd))
        return log_vv("file is badly formed");
      cmd = (macho_load_command<T> *)cmds;
      if (size < cmd->cmdsize())
        return log_vv("file is badly formed");
      cmds += cmd->cmdsize();
      size -= cmd->cmdsize();

      if (dylibVisitor &&
          (cmd->cmd() == LC_LOAD_DYLIB || cmd->cmd() == LC_LOAD_WEAK_DYLIB ||
           cmd->cmd() == LC_LAZY_LOAD_DYLIB)) {
        macho_dylib_command<T> *dylib = (macho_dylib_command<T> *)cmd;
        if (dylib->cmdsize() < dylib->name_offset())
          continue;
        char *name = (char *)dylib + dylib->name_offset();
        size_t name_len =
            strnlen(name, dylib->cmdsize() - dylib->name_offset());
        log_vv("  loads %.*s", (int)name_len, name);

#define PREPREFIX "@rpath/"
#define PREFIX PREPREFIX "libswift"
        if (0 == strncmp(name, PREFIX, strlen(PREFIX))) {
          dylibVisitor(name + strlen(PREPREFIX));
        }
      } else if (uuidVisitor && cmd->cmd() == LC_UUID) {
        macho_uuid_command<T> *uuid_cmd = (macho_uuid_command<T> *)cmd;
        if (uuid_cmd->cmdsize() < sizeof(uuid_command))
          continue;
        uuidVisitor(uuid_cmd->uuid());
      }
    }
  }
  free(cmdp);

  return 0;
}

int parse_macho(int fd, uint32_t offset, uint32_t size,
                void (^dylibVisitor)(const std::string &path),
                void (^uuidVisitor)(const uuid_t uuid)) {
  uint32_t magic;
  if (size < sizeof(magic))
    return log_vv("file is too small");
  ssize_t readed = pread_all(fd, &magic, sizeof(magic), offset);
  if (readed != sizeof(magic))
    return log_vv("pread failed");

  switch (magic) {
  case MH_MAGIC_64:
    return parse_macho<Pointer64<CurrentEndian>>(fd, offset, size, dylibVisitor,
                                                 uuidVisitor);
  case MH_MAGIC:
    return parse_macho<Pointer32<CurrentEndian>>(fd, offset, size, dylibVisitor,
                                                 uuidVisitor);
  case MH_CIGAM_64:
    return parse_macho<Pointer64<OtherEndian>>(fd, offset, size, dylibVisitor,
                                               uuidVisitor);
  case MH_CIGAM:
    return parse_macho<Pointer32<OtherEndian>>(fd, offset, size, dylibVisitor,
                                               uuidVisitor);
  default:
    return log_vv("file is not mach-o");
  }
}

int parse_fat(int fd, off_t fsize, char *buffer, size_t size,
              void (^dylibVisitor)(const std::string &path),
              void (^uuidVisitor)(const uuid_t uuid)) {
  uint32_t magic;

  if (size < sizeof(magic)) {
    return log_vv("file is too small");
  }

  magic = *(uint32_t *)buffer;
  if (magic == FAT_MAGIC || magic == FAT_CIGAM) {
    struct fat_header *fh;
    uint32_t fat_magic, fat_nfat_arch;
    struct fat_arch *archs;
    uint32_t i;

    if (size < sizeof(struct fat_header)) {
      return log_vv("file is too small");
    }

    fh = (struct fat_header *)buffer;
    fat_magic = OSSwapBigToHostInt32(fh->magic);
    fat_nfat_arch = OSSwapBigToHostInt32(fh->nfat_arch);

    size_t fat_arch_size;
    // fat_nfat_arch * sizeof(struct fat_arch) + sizeof(struct fat_header)
    if (os_mul_and_add_overflow(fat_nfat_arch, sizeof(struct fat_arch),
                                sizeof(struct fat_header), &fat_arch_size)) {
      return log_vv("too many fat archs\n");
    }
    if (size < fat_arch_size) {
      return log_vv("file is too small");
    }

    archs = (struct fat_arch *)(buffer + sizeof(struct fat_header));

    /* Special case hidden CPU_TYPE_ARM64 */
    size_t fat_arch_plus_one_size;
    if (os_add_overflow(fat_arch_size, sizeof(struct fat_arch),
                        &fat_arch_plus_one_size)) {
      return log_vv("too many fat archs\n");
    }
    if (size >= fat_arch_plus_one_size) {
      if (fat_nfat_arch > 0 &&
          OSSwapBigToHostInt32(archs[fat_nfat_arch].cputype) ==
              CPU_TYPE_ARM64) {
        fat_nfat_arch++;
      }
    }
    /* End special case hidden CPU_TYPE_ARM64 */

    for (i = 0; i < fat_nfat_arch; i++) {
      int ret;
      uint32_t arch_cputype, arch_cpusubtype, arch_offset, arch_size,
          arch_align;

      arch_cputype = OSSwapBigToHostInt32(archs[i].cputype);
      arch_cpusubtype = OSSwapBigToHostInt32(archs[i].cpusubtype);
      arch_offset = OSSwapBigToHostInt32(archs[i].offset);
      arch_size = OSSwapBigToHostInt32(archs[i].size);
      arch_align = OSSwapBigToHostInt32(archs[i].align);

      /* Check that slice data is after all fat headers and archs */
      if (arch_offset < fat_arch_size) {
        return log_vv("file is badly formed");
      }

      /* Check that the slice ends before the file does */
      if (arch_offset > fsize) {
        return log_vv("file is badly formed");
      }

      if (arch_size > fsize) {
        return log_vv("file is badly formed");
      }

      if (arch_offset > (fsize - arch_size)) {
        return log_vv("file is badly formed");
      }

      ret = parse_macho(fd, arch_offset, arch_size, dylibVisitor, uuidVisitor);
      if (ret != 0) {
        return ret;
      }
    }
    return 0;
  } else {
    /* Not a fat file */
    return parse_macho(fd, 0, fsize, dylibVisitor, uuidVisitor);
  }
}

void process(const std::string &path, void (^dylibVisitor)(const std::string &),
             void (^uuidVisitor)(const uuid_t)) {
  log_vv("Scanning %s...", path.c_str());

  int fd = open(path.c_str(), O_RDONLY);
  if (fd < 0)
    log_vv("%s: open failed: %s", path.c_str(), strerror(errno));

  struct stat st;
  if (fstat(fd, &st) < 0) {
    log_vv("%s: stat failed: %s", path.c_str(), strerror(errno));
  } else {
    const int len = 4096;
    char buf[len];
    ssize_t readed = pread_all(fd, buf, len, 0);
    if (readed != len) {
      log_vv("%s: pread failed: %s", path.c_str(), strerror(errno));
    } else {
      parse_fat(fd, st.st_size, buf, len, dylibVisitor, uuidVisitor);
    }
  }
  close(fd);
}

bool operator<=(const struct timespec &lhs, const struct timespec &rhs) {
  if (lhs.tv_sec == rhs.tv_sec)
    return lhs.tv_nsec <= rhs.tv_nsec;
  return lhs.tv_sec <= rhs.tv_sec;
}

std::string parentPath(std::string path) {
  const char *pathCstr = path.c_str();
  char parent[MAXPATHLEN];

  return dirname_r(pathCstr, parent) ? parent : pathCstr;
}

std::string filename(std::string path) {
  const char *pathCstr = path.c_str();
  char filename[MAXPATHLEN];

  return basename_r(pathCstr, filename) ? filename : pathCstr;
}

// This executable's own path.
std::string self_executable = []() -> std::string {
  char path[MAXPATHLEN] = {0};
  uint32_t len = sizeof(path);
  _NSGetExecutablePath(path, &len);
  return std::string(path);
}();

// This executable's own xctoolchain path.
std::string self_toolchain = []() -> std::string {
  auto result = self_executable;

  // Remove the executable name.
  result = parentPath(result);

  // Remove trailing /usr/bin, if any
  if (filename(result) == "bin") {
    result = parentPath(result);
  }
  if (filename(result) == "usr") {
    result = parentPath(result);
  }
  return result;
}();

std::vector<uint8_t> readToEOF(int fd) {
  std::vector<uint8_t> retData;
#define BUFFER_SIZE 1024
  uint8_t readBuffer[BUFFER_SIZE];
  ssize_t readSize = 0;
  while ((readSize = read(fd, readBuffer, BUFFER_SIZE)) > 0) {
    retData.reserve(retData.size() + readSize);
    std::copy(readBuffer, readBuffer + readSize, std::back_inserter(retData));
  }
  return retData;
}

// Runs a tool with `xcrun`.
// Returns the tool's termination status.
// Prints the tool's command line if we are verbose.
// Prints the tool's stdout and stderr if terminationStatus is non-zero
//   or if we are very verbose.
typedef void (^XcrunToolBlock)(std::vector<uint8_t> stdOutData,
                               std::vector<uint8_t> stdErrorData, int err);

int xcrunToolCommand(std::vector<std::string> commandAndArguments,
                     XcrunToolBlock block = 0) {
  const char *launchPath = "/usr/bin/xcrun";

  // Tell xcrun to search our toolchain first.
  std::vector<const char *> arguments;
  arguments.push_back(launchPath);
  arguments.push_back("--toolchain");
  arguments.push_back(self_toolchain.c_str());

  // Tell xcrun to print its command if we are very verbose.
  if (Verbose > 1) {
    arguments.push_back("--log");
  }

  for (const auto &string : commandAndArguments) {
    arguments.push_back(string.c_str());
  }
  arguments.push_back(NULL);

  int outPipe[2];
  int errPipe[2];

  pipe(outPipe);
  pipe(errPipe);

  log_v("  %s", launchPath);

  int childPid = fork();

  if (childPid == 0) {
    dup2(outPipe[1], STDOUT_FILENO);
    dup2(errPipe[1], STDERR_FILENO);

    close(outPipe[0]);
    close(errPipe[0]);

    execv(launchPath, const_cast<char **>(arguments.data()));
  }
  close(outPipe[1]);
  close(errPipe[1]);

  // Read stdout and stderr in parallel, then wait for the task
  // to exit. Anything else risks deadlock if the task fills
  // one of the output buffers.

  int errPipeReadFd = errPipe[1];
  __block std::vector<uint8_t> stdErrData;
  dispatch_semaphore_t gotStdErr = dispatch_semaphore_create(0);
  dispatch_queue_t concurrentQueue =
      dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_async(concurrentQueue, ^{
    stdErrData = readToEOF(errPipeReadFd);
    dispatch_semaphore_signal(gotStdErr);
  });

  const auto stdOutData = readToEOF(outPipe[0]);
  close(outPipe[0]);

  dispatch_semaphore_wait(gotStdErr, DISPATCH_TIME_FOREVER);
  dispatch_release(gotStdErr);
  close(errPipe[0]);

  int status = 0;
  waitpid(childPid, &status, 0);
  status = WIFSIGNALED(status) ? WTERMSIG(status)
                               : (WIFEXITED(status) ? WEXITSTATUS(status) : 0);

  // Task is finished and we have its stdout and stderr output.

  // Print its stdout and stderr if it failed or we are verbose.
  // (Print nothing by default because codesign is noisy.)

  if (status || Verbose > 1) {
    fwrite(stdErrData.data(), stdErrData.size(), 1, stdout);
    fwrite(stdOutData.data(), stdOutData.size(), 1, stdout);
  }
  if (block) {
    block(stdOutData, stdErrData, status);
  }
  return status;
}

void copyAndStripBitcode(std::string src, std::string dst) {
  // -r removes bitcode
  std::vector<std::string> commandAndArgs = {"bitcode_strip", src, "-r", "-o",
                                             dst};
  int err = xcrunToolCommand(commandAndArgs);

  // Fail if bitcode_strip failed.
  if (err) {
    fail("Couldn't copy and strip bitcode %s to %s: bitcode_strip failed "
         "with exit code %d",
         src.c_str(), dst.c_str(), err);
  }
}

void copyFile(std::string src, std::string dst, bool stripBitcode) {
  if (stripBitcode) {
    copyAndStripBitcode(src, dst);
  } else {
    if (copyfile(src.c_str(), dst.c_str(), NULL, COPYFILE_ALL) != 0) {
      fail("Couldn't copy %s to %s: %s", src.c_str(), dst.c_str(),
           strerror(errno));
    }
  }
}

std::string uuidString(const uuid_t uuid) {
  char buffer[37];
  uuid_unparse(uuid, buffer);
  return buffer;
}

void copyLibraries(
    std::string dst_dir,
    const std::unordered_map<std::string, std::unordered_set<std::string>>
        &libs,
    bool stripBitcode) {
  mkpath_np(dst_dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);

  for (const auto &pair : libs) {
    const auto &src = pair.first;
    const auto &srcUUIDs = pair.second;

    std::string dst = dst_dir + "/" + filename(src);

    // Compare UUIDs of src and dst and don't copy if they're the same.
    // Do not use mod times for this task: the dst copy gets code-signed
    // and bitcode-stripped so it can look newer than it really is.
    __block std::unordered_set<std::string> dstUUIDs;
    process(dst, NULL, ^(const uuid_t uuid) {
      dstUUIDs.insert(uuidString(uuid));
    });

    std::string srcUUIDsString;
    srcUUIDsString.reserve(37 * srcUUIDs.size());

    for (const auto &uuidString : srcUUIDs) {
      srcUUIDsString.append(uuidString + std::string(" "));
    }

    std::string dstUUIDsString;
    dstUUIDsString.reserve(37 * dstUUIDs.size());

    for (const auto &uuidString : dstUUIDs) {
      dstUUIDsString.append(uuidString + " ");
    }

    log_vv("Source UUIDs %s: %s", src.c_str(), srcUUIDsString.c_str());
    log_vv("Destination UUIDs %s: %s", dst.c_str(), dstUUIDsString.c_str());

    if (srcUUIDs == dstUUIDs) {
      log_v("%s is up to date at %s", src.c_str(), dst.c_str());
      continue;
    }

    // Perform the copy.

    log_v("Copying %s to %s", src.c_str(), dst_dir.c_str());

    unlink(dst.c_str());
    copyFile(src, dst, stripBitcode);
  }
}

std::vector<uint8_t> query_code_signature(std::string file) {
  __block std::vector<uint8_t> d;
  std::vector<std::string> command = {"codesign", "-r-", "--display", file};
  log_v("Probing signature of %s", file.c_str());
  xcrunToolCommand(command, ^(std::vector<uint8_t> stdOutData,
                              std::vector<uint8_t> stdErrData, int err) {
    if (!err) {
      d = stdOutData;
    }
  });
  return d;
}

template <typename F>
void listDirectoryContents(std::string directory, F &&func) {
  DIR *dir = opendir(directory.c_str());
  if (dir == NULL) {
    return;
  }

  struct dirent *entry;
  while ((entry = readdir(dir))) {
    func(directory + "/" + entry->d_name);
  }
  closedir(dir);
}

template <typename F>
void recursivelyListFiles(std::string directory, F &&func) {
  DIR *dir = opendir(directory.c_str());
  if (dir == NULL) {
    return;
  }

  std::vector<std::string> subpaths;
  struct dirent *entry;
  while ((entry = readdir(dir)) != NULL) {
    std::string path = directory + "/" + entry->d_name;
    if (entry->d_type == DT_REG) {
      func(path);
    } else if (entry->d_type == DT_DIR) {
      // check if . or ..
      if (strncmp(entry->d_name, "..", entry->d_namlen) == 0) {
        continue;
      }
      subpaths.push_back(path);
    }
  }
  closedir(dir);
  for (const auto &path : subpaths) {
    recursivelyListFiles(path, func);
  }
}

int main(int argc, const char *argv[]) {
  // Executables to scan for Swift references.
  // --scan-executable
  std::vector<std::string> executables;

  // Directories to scan for more executables.
  // --scan-folder
  std::vector<std::string> embedDirs;

  // Platform name.
  // --platform
  // or the last path component of --source-libraries
  std::string platform;

  // Copy source.
  // --source-libraries
  // or /path/to/swift-stdlib-tool/../../lib/swift/<--platform>
  std::vector<std::string> src_dirs;

  // Copy destinations, signed and unsigned.
  // --destination and --unsigned-destination
  std::string dst_dir;
  std::string unsigned_dst_dir;

  // Resource copy destination.
  // --resource-destination
  std::string resource_dst_dir;

  // Resource libraries.
  // --resource-library
  std::vector<std::string> resourceLibraries;

  // Code signing options.
  std::string ident;
  std::string keychain;
  std::vector<std::string> otherCodesignFlags;

  // Read arguments
  bool print = false;
  bool copy = false;
  bool stripBitcode = false;
  for (int i = 1; i < argc; i++) {
    if (0 == strcmp(argv[i], "--print"))
      print = true;
    if (0 == strcmp(argv[i], "--copy"))
      copy = true;
    if (0 == strcmp(argv[i], "--verbose"))
      Verbose++;
    if (0 == strcmp(argv[i], "--help")) {
      printUsage();
      exit(0);
    }

    if (0 == strcmp(argv[i], "--scan-executable")) {
      executables.emplace_back(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--scan-folder")) {
      embedDirs.emplace_back(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--source-libraries")) {
      src_dirs.emplace_back(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--platform")) {
      platform = std::string(argv[++i]);
    }

    if (0 == strcmp(argv[i], "--destination")) {
      dst_dir = std::string(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--unsigned-destination")) {
      unsigned_dst_dir = std::string(argv[++i]);
    }

    if (0 == strcmp(argv[i], "--sign")) {
      ident = std::string(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--keychain")) {
      keychain = std::string(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--Xcodesign")) {
      otherCodesignFlags.push_back(std::string(argv[++i]));
    }

    if (0 == strcmp(argv[i], "--strip-bitcode")) {
      stripBitcode = true;
    }

    if (0 == strcmp(argv[i], "--resource-destination")) {
      resource_dst_dir = std::string(argv[++i]);
    }
    if (0 == strcmp(argv[i], "--resource-library")) {
      resourceLibraries.push_back(std::string(argv[++i]));
    }
  }

  // Fix up src_dirs and platform values.
  if (src_dirs.empty() && platform.empty()) {
    // Neither src_dirs nor platform is set. Die.
    fail_usage("At least one of --source-libraries and --platform "
               "must be set.");
  } else if (src_dirs.empty()) {
    // platform is set but src_dirs is not.
    // Use platform to set src_dirs relative to us.
    std::string root_path =
        parentPath(parentPath(self_executable)) + "/" + "lib";

    listDirectoryContents(root_path, [&](std::string entry) {
      if (filename(entry).compare(0, strlen("swift-"), "swift-") == 0) {
        src_dirs.push_back(entry + "/" + platform);
      }
    });

    if (src_dirs.empty()) {
      fail("Couldn't discover Swift library directories in: %s",
           root_path.c_str());
    }
  } else if (platform.empty()) {
    // src_dirs is set but platform is not.
    // Pick platform from any src_dirs's name.
    platform = filename(src_dirs.front());
  }

  // Add the platform to unsigned_dst_dir if it is not already present.
  if (!unsigned_dst_dir.empty()) {
    const auto unsigned_platform = unsigned_dst_dir;
    if (platform != unsigned_platform) {
      unsigned_dst_dir = unsigned_dst_dir + "/" + platform;
    }
  }

  // If the user specifies --strip-bitcode but not --sign, this
  // will cause the dylibs to get copied, stripped, but not resigned.
  // This will cause apps to fail to launch because the code signature
  // is invalid.  In this case, ignore --strip-bitcode.
  if (stripBitcode && ident.empty()) {
    stripBitcode = false;
  }

  // Collect executables from the --scan-folder locations.
  for (const auto &embedDir : embedDirs) {
    recursivelyListFiles(embedDir, [&](std::string entry) {
      if (0 == access(entry.c_str(), X_OK)) {
        executables.push_back(entry);
      } else {
        log_vv("%s is not an executable file", entry.c_str());
      }
    });
  }

  // Collect Swift library names from the input files.
  // If the library does not exist in src_dirs then assume the user wrote
  // their own library named libswift* and is handling it elsewhere.
  __block std::unordered_map<std::string, std::unordered_set<std::string>>
      swiftLibs;
  for (const auto &path : executables) {
    process(
        path,
        ^(const std::string &linkedLib) {
          for (const auto &src_dir : src_dirs) {
            const auto linkedSrc = src_dir + "/" + linkedLib;
            if (access(linkedSrc.c_str(), F_OK) == 0) {
              swiftLibs[linkedSrc] = std::unordered_set<std::string>();
              break;
            }
          }
        },
        NULL);
  }

  // Collect more Swift library names from the Swift libraries themselves.
  // Also collect the Swift libraries' UUIDs.
  __block std::vector<std::string> worklist;
  worklist.reserve(swiftLibs.size());
  for (const auto &pair : swiftLibs) {
    worklist.push_back(pair.first);
  }
  while (worklist.size()) {
    const auto path = worklist.back();
    worklist.pop_back();
    process(
        path,
        ^(const std::string &linkedLib) {
          for (const auto &src_dir : src_dirs) {
            const auto linkedSrc = src_dir + "/" + linkedLib;
            if (swiftLibs.count(linkedSrc) == 0 &&
                access(linkedSrc.c_str(), F_OK) == 0) {
              swiftLibs[linkedSrc] = std::unordered_set<std::string>();
              worklist.push_back(linkedSrc);
              break;
            }
          }
        },
        ^(const uuid_t uuid) {
          swiftLibs[path].insert(uuidString(uuid));
        });
  }

  // Collect all the Swift libraries that the user requested
  // with --resource-library.
  __block std::unordered_map<std::string, std::unordered_set<std::string>>
      swiftLibsForResources;
  for (const auto &lib : resourceLibraries) {
    for (const auto &src_dir : src_dirs) {
      const auto libSrc = src_dir + "/" + lib;
      if (access(libSrc.c_str(), F_OK) == 0) {
        swiftLibsForResources[libSrc] = std::unordered_set<std::string>();
      }
    }
  }

  // Collect dependencies of --resource-library libs.
  worklist.clear();
  for (const auto &pair : swiftLibsForResources) {
    worklist.push_back(pair.first);
  }
  while (worklist.size()) {
    const auto path = worklist.back();
    worklist.pop_back();
    process(
        path,
        ^(const std::string &linkedLib) {
          for (const auto &src_dir : src_dirs) {
            const auto linkedSrc = src_dir + "/" + linkedLib;
            if (swiftLibsForResources.count(linkedSrc) == 0 &&
                access(linkedSrc.c_str(), F_OK) == 0) {
              swiftLibsForResources[linkedSrc] =
                  std::unordered_set<std::string>();
              worklist.push_back(linkedSrc);
            }
          }
        },
        ^(const uuid_t uuid) {
          swiftLibsForResources[path].insert(uuidString(uuid));
        });
  }

  // Print the Swift libraries (full path to toolchain's copy)
  if (print) {
    for (const auto &lib : swiftLibs) {
      printf("%s\n", lib.first.c_str());
    }
  }

  // Copy the Swift libraries to $build_dir/$frameworks
  // and $build_dir/$unsigned_frameworks
  if (copy) {
    copyLibraries(dst_dir, swiftLibs, stripBitcode);
    if (!unsigned_dst_dir.empty()) {
      // Never strip bitcode from the unsigned libraries.
      // Their existing signatures must be preserved.
      copyLibraries(unsigned_dst_dir, swiftLibs, false);
    }

    if (!resource_dst_dir.empty()) {
      // Never strip bitcode from resources libraries, for
      // the same reason as the libraries copied to
      // unsigned_dst_dir.
      copyLibraries(resource_dst_dir, swiftLibsForResources, false);
    }
  }

  // Codesign the Swift libraries in $build_dir/$frameworks
  // but not the libraries in $build_dir/$unsigned_frameworks.
  if (!ident.empty()) {
    // Swift libraries that are up-to-date get codesigned anyway
    // (in case options changed or a previous build was incomplete).
    // We do employ an optimization, however, if resigning the dylib
    // results in getting the same signing identity and credentials
    // then we keep the original file to optimize for delta updates
    // to the device.

    __block bool signedOne = false;
    std::mutex signingLock;

    for (const auto &pair : swiftLibs) {
      const auto &lib = pair.first;
      // Work around authentication UI problems
      // by signing one synchronously and then signing the rest.
      signingLock.lock();
      if (signedOne) {
        // First signer is complete. Proceed concurrently.
        signingLock.unlock();
      } else {
        // We are the first signer. Hold the lock until we finish.
      }

      // Get the code signature, and copy the dylib to the side
      // to preserve it in case it does not change.  We can use
      // this to avoid unnecessary copies during delta installs
      // to devices.
      const auto dst = dst_dir + "/" + filename(lib);
      const auto oldSignatureData = query_code_signature(dst);
      const char *tmpFilePath = 0;
      if (!oldSignatureData.empty()) {
        // Make a copy of the existing file, with permissions and
        // mtime preserved.
        auto tmpFile = dst + ".original";
        tmpFilePath = tmpFile.c_str();
        xcrunToolCommand({"cp", "-p", dst, tmpFile});
      }

      // Proceed with (re-)codesigning.
      log_v("Codesigning %s at %s", lib.c_str(), dst_dir.c_str());

      // Build the codesign invocation.
      std::vector<std::string> commandAndArguments{
          "codesign", "--force", "--sign", ident, "--verbose"};

      if (!keychain.empty()) {
        commandAndArguments.push_back("--keychain");
        commandAndArguments.push_back(keychain);
      }

      // Other codesign flags come later
      // so they can override the default flags.
      std::copy(otherCodesignFlags.begin(), otherCodesignFlags.end(),
                std::back_inserter(commandAndArguments));

      commandAndArguments.push_back(dst);

      int err = xcrunToolCommand(commandAndArguments);

      // Fail if codesign failed.
      if (err) {
        // Clean up any temporary files.
        if (tmpFilePath)
          unlink(tmpFilePath);
        fail("Couldn't codesign %s: codesign failed with "
             "exit code %d",
             dst.c_str(), err);
      }

      // If we have an existing code signature data, query the new one and
      // compare it with the code signature of the file before we re-signed it.
      // If they are the same, use the original file instead.  This preserves
      // the contents of the file and mtime for use with delta installs.
      if (!oldSignatureData.empty()) {
        const auto newSignatureData = query_code_signature(dst);

#if 0
        // For Debugging.
        fprintf(stdout, "oldSignature (%lu bytes)\n",
                (unsigned long)oldSignatureData.size());
        fwrite(oldSignatureData.data(), oldSignatureData.size(), 1, stdout);
        fprintf(stdout, "\nnewSignature (%lu bytes)\n",
                (unsigned long)newSignatureData.size());
        fwrite(newSignatureData.data(), newSignatureData.size(), 1, stdout);
        fprintf(stdout, "\n");
        fflush(stdout);
#endif

        const auto newLength = newSignatureData.size();
        if (newLength == oldSignatureData.size() &&
            memcmp(newSignatureData.data(), oldSignatureData.data(),
                   newLength) == 0) {
          log_v("Code signature of %s is unchanged; keeping original",
                lib.c_str());
          // The two signatures match.  Unlink the new file, and re-link the old
          // file.
          const char *filePath = dst.c_str();
          unlink(filePath);
          link(tmpFilePath, filePath);
        }
      }
      // Clean up any temporary files.
      if (tmpFilePath) {
        unlink(tmpFilePath);
      }

      if (!signedOne) {
        // We are the first signer. Allow the others to proceed now.
        signedOne = true;
        signingLock.unlock();
      }
    };
  }
  exit(0);
}


text:
<?php
/*
* app/validators.php
*/

Validator::extend('alpha_spaces', function($attribute, $value)
{
    return preg_match('/^[\pL\s]+$/u', $value);
});


text:
define([
  '../core',
  '../method',
  '../find'
], function( Han, $ ) {

var HANGABLE_CLASS = 'bd-hangable'
var HANGABLE_AVOID = 'h-char.bd-hangable'
var HANGABLE_CS_HTML = '<h-cs hidden class="jinze-outer hangable-outer"> </h-cs>'

var matches = Han.find.matches

function detectSpaceFont() {
  var div = $.create( 'div' )
  var ret

  div.innerHTML = 'a ba b'
  body.appendChild( div )
  ret = div.firstChild.offsetWidth !== div.lastChild.offsetWidth
  $.remove( div )
  return ret
}

function insertHangableCS( $jinze ) {
  var $cs = $jinze.nextSibling

  if ( $cs && matches( $cs, 'h-cs.jinze-outer' )) {
    $cs.classList.add( 'hangable-outer' )
  } else {
    $jinze.insertAdjacentHTML(
      'afterend',
      HANGABLE_CS_HTML
    )
  }
}

Han.support['han-space'] = detectSpaceFont()

$.extend( Han, {
  detectSpaceFont:   detectSpaceFont,
  isSpaceFontLoaded: detectSpaceFont(),

  renderHanging: function( context ) {
    var context = context || document
    var finder  = Han.find( context )

    finder
    .avoid( 'textarea, code, kbd, samp, pre' )
    .avoid( HANGABLE_AVOID )
    .replace(
      TYPESET.jinze.hanging,
      function( portion ) {
        if ( /^[\x20\t\r\n\f]+$/.test( portion.text )) {
          return ''
        }

        var $elmt = portion.node.parentNode
        var $jinze, $new, $bd, biaodian

        if ( $jinze = $.parent( $elmt, 'h-jinze' )) {
          insertHangableCS( $jinze )
        }

        biaodian = portion.text.trim()

        $new = Han.createBDChar( biaodian )
        $new.innerHTML = '<h-inner>' + biaodian + '</h-inner>'
        $new.classList.add( HANGABLE_CLASS )

        $bd = $.parent( $elmt, 'h-char.biaodian' )

        return !$bd
          ? $new
          : (function() {
            $bd.classList.add( HANGABLE_CLASS )

            return matches( $elmt, 'h-inner, h-inner *' )
              ? biaodian
              : $new.firstChild
          })()
      }
    )
    return finder
  }
})

$.extend( Han.fn, {
  renderHanging: function() {
    var classList = this.condition.classList
    Han.isSpaceFontLoaded = detectSpaceFont()

    if (
      Han.isSpaceFontLoaded &&
      classList.contains( 'no-han-space' )
    ) {
      classList.remove( 'no-han-space' )
      classList.add( 'han-space' )
    }

    Han.renderHanging( this.context )
    return this
  },

  revertHanging: function() {
    $.qsa(
      'h-char.bd-hangable, h-cs.hangable-outer',
      this.context
    ).forEach(function( $elmt ) {
      var classList = $elmt.classList
      classList.remove( 'bd-hangable' )
      classList.remove( 'hangable-outer' )
    })
    return this
  }
})

return Han
})


text:
require 'smartystreets/base_json_object'

module SmartyStreets

  # Represents a response for a zipcode.
  #
  # @author Peter Edge (peter.edge@gmail.com)
  class ZipcodeResponse < BaseJsonObject

    module ErrorStatus
      BLANK = 'blank'
      INVALID_STATE = 'invalid_state'
      INVALID_CITY = 'invalid_city'
      INVALID_ZIPCODE = 'invalid_zipcode'
      CONFLICT = 'conflict'
    end

    def initialize(hash)
      super(hash)

      error_status = get_optional_string(hash, :status)
      if error_status
        @error_status = case error_status
        when ErrorStatus::BLANK then error_status
        when ErrorStatus::INVALID_STATE then error_status
        when ErrorStatus::INVALID_CITY then error_status
        when ErrorStatus::INVALID_ZIPCODE then error_status
        when ErrorStatus::CONFLICT then error_status
        else raise ArgumentError.new("Unrecognized error status: #{error_status}")
        end
      else
        city_states = get_optional_array(hash, :city_states)
        zipcodes = get_optional_array(hash, :zipcodes)
        @city_states = city_states.map { |city_state| CityState.new(city_state) } if city_states
        @zipcodes = zipcodes.map { |zipcode| ZipCode.new(zipcode) } if zipcodes
      end
    end

    def error?
      error_status != nil
    end

    def error_status
      @error_status
    end

    def city_states
      raise StandardError.new("Error status was #{error_status}") if error?
      @city_states
    end

    def zipcodes
      raise StandardError.new("Error status was #{error_status}") if error?
      @zipcodes
    end

    class CityState < BaseJsonObject

      attr_reader :city
      attr_reader :state_abbreviation
      attr_reader :state

      def initialize(hash)
        super(hash)
        @city = get_optional_string(hash, :city)
        @state_abbreviation = get_optional_string(hash, :state_abbreviation)
        @state = get_optional_string(hash, :state)
      end
    end

    class ZipCode < BaseJsonObject

      attr_reader :zipcode
      attr_reader :zipcode_type
      attr_reader :county_fips
      attr_reader :county_name
      attr_reader :latitude
      attr_reader :longitude

      def initialize(hash)
        super(hash)
        @zipcode = get_optional_string(hash, :zipcode)
        @zipcode_type = get_optional_string(hash, :zipcode_type)
        @county_fips = get_optional_string(hash, :county_fips)
        @county_name = get_optional_string(hash, :county_name)
        @latitude = get_optional_float(hash, :latitude)
        @longitude = get_optional_float(hash, :longitude)
      end
    end
  end
end


text:
package org.objectweb.jtests.jms.conform.connection;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.junit.Assert;
import org.junit.Test;
import org.objectweb.jtests.jms.framework.PTPTestCase;
import org.objectweb.jtests.jms.framework.TestConfig;

/**
 * Test connections.
 *
 * See JMS specifications, sec. 4.3.5 Closing a Connection
 */
public class ConnectionTest extends PTPTestCase {

   /**
    * Test that invoking the acknowledge() method of a received message
    * from a closed connection's session must throw an IllegalStateException.
    */
   @Test
   public void testAcknowledge() {
      try {
         receiverConnection.stop();
         receiverSession = receiverConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
         receiver.close(); // Before assigning a new receiver, we need to close the old one...
         // Not closing it could cause load balancing between receivers.
         // Not having this close might be valid for JORAM or JBossMQ, but it's not valid for ActiveMQ Artemis (and still legal)

         receiver = receiverSession.createReceiver(receiverQueue);
         receiverConnection.start();

         Message message = senderSession.createMessage();
         sender.send(message);

         Message m = receiver.receive(TestConfig.TIMEOUT);
         receiverConnection.close();
         m.acknowledge();
         Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException.\n");
      }
      catch (javax.jms.IllegalStateException e) {
      }
      catch (JMSException e) {
         Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException, not a " +
                        e);
      }
      catch (java.lang.IllegalStateException e) {
         Assert.fail("sec. 4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw an [javax.jms.]IllegalStateException " + "[not a java.lang.IllegalStateException]");
      }
   }

   /**
    * Test that an attempt to use a Connection which has been closed
    * throws a javax.jms.IllegalStateException.
    */
   @Test
   public void testUseClosedConnection() {
      try {
         senderConnection.close();
         senderConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         Assert.fail("Should raise a javax.jms.IllegalStateException");
      }
      catch (javax.jms.IllegalStateException e) {
      }
      catch (JMSException e) {
         Assert.fail("Should raise a javax.jms.IllegalStateException, not a " + e);
      }
      catch (java.lang.IllegalStateException e) {
         Assert.fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException");
      }
   }

   /**
    * Test that a MessageProducer can send messages while a
    * Connection is stopped.
    */
   @Test
   public void testMessageSentWhenConnectionClosed() {
      try {
         senderConnection.stop();
         Message message = senderSession.createTextMessage();
         sender.send(message);

         receiver.receive(TestConfig.TIMEOUT);
      }
      catch (JMSException e) {
         fail(e);
      }
   }

   /**
    * Test that closing a closed connectiondoes not throw an exception.
    */
   @Test
   public void testCloseClosedConnection() {
      try {
         // senderConnection is already started
         // we close it once
         senderConnection.close();
         // we close it a second time
         senderConnection.close();
      }
      catch (Exception e) {
         Assert.fail("sec. 4.3.5 Closing a closed connection must not throw an exception.\n");
      }
   }

   /**
    * Test that starting a started connection is ignored
    */
   @Test
   public void testStartStartedConnection() {
      try {
         // senderConnection is already started
         // start it again should be ignored
         senderConnection.start();
      }
      catch (JMSException e) {
         fail(e);
      }
   }

   /**
    * Test that stopping a stopped connection is ignored
    */
   @Test
   public void testStopStoppedConnection() {
      try {
         // senderConnection is started
         // we stop it once
         senderConnection.stop();
         // stopping it a second time is ignored
         senderConnection.stop();
      }
      catch (JMSException e) {
         fail(e);
      }
   }

   /**
    * Test that delivery of message is stopped if the message consumer connection is stopped
    */
   @Test
   public void testStopConsumerConnection() {
      try {
         receiverConnection.stop();

         receiver.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(final Message m) {
               try {
                  Assert.fail("The message must not be received, the consumer connection is stopped");
                  Assert.assertEquals("test", ((TextMessage) m).getText());
               }
               catch (JMSException e) {
                  fail(e);
               }
            }
         });

         TextMessage message = senderSession.createTextMessage();
         message.setText("test");
         sender.send(message);
         synchronized (this) {
            try {
               Thread.sleep(1000);
            }
            catch (Exception e) {
               fail(e);
            }
         }
      }
      catch (JMSException e) {
         fail(e);
      }
   }
}


text:
VacuumPercept::VacuumPercept(TileLocation *loc, bool isDirty) {
    setIsDirty(isDirty);
    if(loc->getX()==0) {
        setTileName('A');
    } else {
        setTileName('B');
    }
}

std::string VacuumPercept::toString() {
    std::string result;
    if(tileName=='A') {
       result = "[A, ";
    } else {
        result = "[B, ";
    }

    if(isDirty()) {
        result = result + "Dirty]";
    } else {
        result = result + "Clean]";
    }

    return result;
}

char VacuumPercept::getTileName() {
    return tileName;
}

void VacuumPercept::setTileName(char tileName) {
    if(tileName=='A' || tileName=='B') {
        this->tileName = tileName;
    } else {
        this->tileName = 'A';
    }
}

bool VacuumPercept::isDirty()  {
    return dirty;
}

void VacuumPercept::setIsDirty(bool isDirty) {
   dirty = isDirty;
}


text:
package org.arsenal.framework.core;

public class NotExistStateException extends IllegalStateException {

	public NotExistStateException() {
		super();

	}

	public NotExistStateException(String message, Throwable cause) {
		super(message, cause);

	}

	public NotExistStateException(String message) {
		super(message);

	}

	public NotExistStateException(Throwable cause) {
		super(cause);

	}

}


text:
<?php

namespace Scene7\Commands\Layer;

trait Sharpen
{
    public function setSharpen($sharpen)
    {
        $this->addCommand(['op_sharpen' => (int) (bool) $sharpen]);
        return $this;
    }
}


text:
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.haxe.lang.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*;
import com.intellij.plugins.haxe.lang.psi.*;

public class HaxeWhileStatementImpl extends HaxePsiCompositeElementImpl implements HaxeWhileStatement {

  public HaxeWhileStatementImpl(ASTNode node) {
    super(node);
  }

  @Override
  @Nullable
  public HaxeBlockStatement getBlockStatement() {
    return findChildByClass(HaxeBlockStatement.class);
  }

  @Override
  @Nullable
  public HaxeBreakStatement getBreakStatement() {
    return findChildByClass(HaxeBreakStatement.class);
  }

  @Override
  @Nullable
  public HaxeContinueStatement getContinueStatement() {
    return findChildByClass(HaxeContinueStatement.class);
  }

  @Override
  @Nullable
  public HaxeDoWhileStatement getDoWhileStatement() {
    return findChildByClass(HaxeDoWhileStatement.class);
  }

  @Override
  @NotNull
  public List<HaxeExpression> getExpressionList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, HaxeExpression.class);
  }

  @Override
  @Nullable
  public HaxeForStatement getForStatement() {
    return findChildByClass(HaxeForStatement.class);
  }

  @Override
  @Nullable
  public HaxeIfStatement getIfStatement() {
    return findChildByClass(HaxeIfStatement.class);
  }

  @Override
  @Nullable
  public HaxeLocalFunctionDeclaration getLocalFunctionDeclaration() {
    return findChildByClass(HaxeLocalFunctionDeclaration.class);
  }

  @Override
  @Nullable
  public HaxeLocalVarDeclaration getLocalVarDeclaration() {
    return findChildByClass(HaxeLocalVarDeclaration.class);
  }

  @Override
  @Nullable
  public HaxeReturnStatement getReturnStatement() {
    return findChildByClass(HaxeReturnStatement.class);
  }

  @Override
  @Nullable
  public HaxeSwitchStatement getSwitchStatement() {
    return findChildByClass(HaxeSwitchStatement.class);
  }

  @Override
  @Nullable
  public HaxeThrowStatement getThrowStatement() {
    return findChildByClass(HaxeThrowStatement.class);
  }

  @Override
  @Nullable
  public HaxeTryStatement getTryStatement() {
    return findChildByClass(HaxeTryStatement.class);
  }

  @Override
  @Nullable
  public HaxeWhileStatement getWhileStatement() {
    return findChildByClass(HaxeWhileStatement.class);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof HaxeVisitor) ((HaxeVisitor)visitor).visitWhileStatement(this);
    else super.accept(visitor);
  }

}


text:
'use strict';

// FUNCTIONS //

var ceil = Math.ceil,
	max = Math.max,
	ln = Math.log;

// QUANTILE //

/**
* FUNCTION: quantile( p, prob )
*	Evaluates the quantile function for a Geometric distribution with success probability `prob` at a probability `p`.
*
* @param {Number} p - input value
* @param {Number} prob - success probability
* @returns {Number} evaluated quantile function
*/
function quantile( p, prob ) {
	if ( p !== p || p < 0 || p > 1 ) {
		return NaN;
	}
	if ( p === 1 ) {
		return 0;
	}
	return max( 0, ceil( ln( 1 - p ) / ln( 1 - prob ) - ( 1 + 1e-12 ) ) );
} // end FUNCTION quantile()

// EXPORTS //

module.exports = quantile;


text:
package prometheus

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net"
	"sync"

	"google.golang.org/grpc"

	adptModel "istio.io/api/mixer/adapter/model/v1beta1"
	"istio.io/api/policy/v1beta1"
	"istio.io/istio/mixer/adapter/prometheus"
	"istio.io/istio/mixer/adapter/prometheus/config"
	"istio.io/istio/mixer/pkg/adapter"
	"istio.io/istio/mixer/pkg/runtime/handler"
	"istio.io/istio/mixer/template/metric"
	"istio.io/pkg/pool"
)

type (
	// Server is basic server interface
	Server interface {
		Addr() string
		Close() error
		PromPort() int
		Run()
	}
	promServer interface {
		io.Closer
		Port() int
	}

	// NoSessionServer models no session adapter backend.
	NoSessionServer struct {
		listener net.Listener
		shutdown chan error
		server   *grpc.Server

		rawcfg      []byte
		builder     adapter.HandlerBuilder
		env         adapter.Env
		builderLock sync.RWMutex

		h metric.Handler

		promServer promServer
	}
)

var _ metric.HandleMetricServiceServer = &NoSessionServer{}

func (s *NoSessionServer) getHandler(rawcfg []byte) (metric.Handler, error) {
	s.builderLock.RLock()
	if bytes.Equal(rawcfg, s.rawcfg) {
		h := s.h
		s.builderLock.RUnlock()
		return h, nil
	}
	s.builderLock.RUnlock()

	// establish session

	cfg := &config.Params{}

	if err := cfg.Unmarshal(rawcfg); err != nil {
		return nil, err
	}

	s.builderLock.Lock()
	defer s.builderLock.Unlock()

	// check again if someone else beat you to this.
	if bytes.Equal(rawcfg, s.rawcfg) {
		return s.h, nil
	}

	s.env.Logger().Infof("Loaded handler with: %v", cfg)

	s.builder.SetAdapterConfig(cfg)
	if ce := s.builder.Validate(); ce != nil {
		return nil, ce
	}

	h, err := s.builder.Build(context.Background(), s.env)
	if err != nil {
		return nil, s.env.Logger().Errorf("could not build: %v", err)
	}
	s.rawcfg = rawcfg
	s.h = h.(metric.Handler)
	return s.h, err
}

func instances(in []*metric.InstanceMsg) []*metric.Instance {
	out := make([]*metric.Instance, 0, len(in))
	for _, inst := range in {
		out = append(out, &metric.Instance{
			Name:       inst.Name,
			Value:      decodeValue(inst.Value.GetValue()),
			Dimensions: decodeDimensions(inst.Dimensions),
		})
	}
	return out
}

func decodeDimensions(in map[string]*v1beta1.Value) map[string]interface{} {
	out := make(map[string]interface{}, len(in))
	for k, v := range in {
		out[k] = decodeValue(v.GetValue())
	}
	return out
}

func decodeValue(in interface{}) interface{} {
	switch t := in.(type) {
	case *v1beta1.Value_StringValue:
		return t.StringValue
	case *v1beta1.Value_Int64Value:
		return t.Int64Value
	case *v1beta1.Value_DoubleValue:
		return t.DoubleValue
	default:
		return fmt.Sprintf("%v", in)
	}
}

// HandleMetric records metric entries and responds with the programmed response
func (s *NoSessionServer) HandleMetric(ctx context.Context, r *metric.HandleMetricRequest) (*adptModel.ReportResult, error) {
	h, err := s.getHandler(r.AdapterConfig.Value)
	if err != nil {
		return nil, err
	}

	if err = h.HandleMetric(ctx, instances(r.Instances)); err != nil {
		return nil, s.env.Logger().Errorf("Could not process: %v", err)
	}

	return &adptModel.ReportResult{}, nil
}

// Addr returns the listening address of the server
func (s *NoSessionServer) Addr() string {
	return s.listener.Addr().String()
}

// PromPort returns the listening address of the prometheus server
func (s *NoSessionServer) PromPort() int {
	return s.promServer.Port()
}

// Run starts the server run
func (s *NoSessionServer) Run() {
	s.shutdown = make(chan error, 1)
	go func() {
		err := s.server.Serve(s.listener)

		// notify closer we're done
		s.shutdown <- err
	}()
}

// Wait waits for server to stop
func (s *NoSessionServer) Wait() error {
	if s.shutdown == nil {
		return fmt.Errorf("server not running")
	}

	err := <-s.shutdown
	s.shutdown = nil
	return err
}

// Close gracefully shuts down the server
func (s *NoSessionServer) Close() error {
	if s.shutdown != nil {
		s.server.GracefulStop()
		_ = s.Wait()
	}

	if s.listener != nil {
		_ = s.listener.Close()
	}

	if s.promServer != nil {
		return s.promServer.Close()
	}

	return nil
}

// NewNoSessionServer creates a new no session server from given args.
func NewNoSessionServer(addr uint16, promAddr uint16) (*NoSessionServer, error) {
	saddr := fmt.Sprintf(":%d", addr)
	pddr := fmt.Sprintf(":%d", promAddr)

	gp := pool.NewGoroutinePool(5, false)
	inf, srv := prometheus.GetInfoWithAddr(pddr)
	s := &NoSessionServer{builder: inf.NewBuilder(),
		env:    handler.NewEnv(0, "prometheus-nosession", gp),
		rawcfg: []byte{0xff, 0xff},
	}
	var err error
	if s.listener, err = net.Listen("tcp", saddr); err != nil {
		_ = s.Close()
		return nil, fmt.Errorf("unable to listen on socket: %v", err)
	}

	fmt.Printf("listening on :%v\n", s.listener.Addr())
	s.server = grpc.NewServer()
	metric.RegisterHandleMetricServiceServer(s.server, s)
	if _, err = s.getHandler(nil); err != nil {
		return nil, err
	}
	s.promServer = srv
	return s, nil
}


text:
#ifdef HAVE_CONFIG_H
  #include "../../config.h"
#endif

#include "device_setup.h"
#ifdef DARWIN
#include "macwebcam_prefs.h"
#include "macwebcamft_prefs.h"
#else
#include "webcam_prefs.h"
#include "webcam_ft_prefs.h"
#endif
#include "tir_prefs.h"
#include "wiimote_prefs.h"
#include "help_view.h"
#include "ltr_gui_prefs.h"
#include "guardian.h"
#include "tracking.h"
#include <iostream>

/* Coding:
            bit0 (lsb) - invert camera X values
            bit1       - invert camera Y values
            bit2       - switch X and Y values (applied first!)
            bit4       - invert pitch, roll, X and Z translations (for tracking from behind)
*/

QString DeviceSetup::descs[8] = {
    QString::fromUtf8("Normal"),                        //0
    QString::fromUtf8("Top to the right"),              //6
    QString::fromUtf8("Upside-down"),                   //3
    QString::fromUtf8("Top to the left"),               //5
    QString::fromUtf8("Normal, from behind"),           //8
    QString::fromUtf8("Top to the right, from behind"), //14
    QString::fromUtf8("Upside-down, from behind"),      //11
    QString::fromUtf8("Top to the left, from behind")   //12
  };

//int DeviceSetup::orientValues[] = {0, 6, 3, 5, 8, 14, 11, 13};
int DeviceSetup::orientValues[] = {ORIENT_NOP, // 0
                                   ORIENT_FLIP_Y | ORIENT_XCHG_XY, // 6
                                   ORIENT_FLIP_X | ORIENT_FLIP_Y, // 3
                                   ORIENT_FLIP_X | ORIENT_XCHG_XY, //5
                                   ORIENT_FROM_BEHIND, // 8
                                   ORIENT_FLIP_Y | ORIENT_XCHG_XY | ORIENT_FROM_BEHIND, // 14
                                   ORIENT_FLIP_X | ORIENT_FLIP_Y  | ORIENT_FROM_BEHIND, // 11
                                   ORIENT_FLIP_X | ORIENT_XCHG_XY | ORIENT_FROM_BEHIND}; // 13

DeviceSetup::DeviceSetup(Guardian *grd, QBoxLayout *tgt, QWidget *parent)
  : QWidget(parent), devPrefs(NULL), target(tgt)
{
  grd->regTgt(this);
  ui.setupUi(this);
  on_RefreshDevices_pressed();
  initOrientations();
}

DeviceSetup::~DeviceSetup()
{
  if(devPrefs != NULL){
    target->removeWidget(devPrefs);
    delete devPrefs;
    devPrefs = NULL;
  }
}

void DeviceSetup::initOrientations()
{
  int i;
  int orientVal = 0;
  int orientIndex = 0;

  QString orient;
  if(PREF.getKeyVal(QString::fromUtf8("Global"), QString::fromUtf8("Camera-orientation"), orient)){
    orientVal=orient.toInt();
  }

  //Initialize Orientations combobox and lookup saved val
  ui.CameraOrientation->clear();
  for(i = 0; i < 8; ++i){
    ui.CameraOrientation->addItem(descs[i]);
    if(orientValues[i] == orientVal){
      orientIndex = i;
    }
  }

  ui.CameraOrientation->setCurrentIndex(orientIndex);
}

void DeviceSetup::on_DeviceSelector_activated(int index)
{
  if(index < 0){
    return;
  }
  if(devPrefs != NULL){
    target->removeWidget(devPrefs);
    delete devPrefs;
    devPrefs = NULL;
  }
  QVariant v = ui.DeviceSelector->itemData(index);
  PrefsLink pl = v.value<PrefsLink>();
#ifndef DARWIN
  if(pl.deviceType == WEBCAM){
    devPrefs = new WebcamPrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("Webcam"));
  }else
  if(pl.deviceType == WEBCAM_FT){
    devPrefs = new WebcamFtPrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("Webcam Face Tracker"));
  }else
#else
  if(pl.deviceType == MACWEBCAM){
    devPrefs = new MacWebcamPrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("Webcam"));
  }else
  if(pl.deviceType == MACWEBCAM_FT){
    devPrefs = new MacWebcamFtPrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("Webcam Face Tracker"));
  }else
#endif
  if(pl.deviceType == WIIMOTE){
    devPrefs = new WiimotePrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("Wiimote"));
  }else
  if(pl.deviceType == TIR){
    devPrefs = new TirPrefs(pl.ID, this);
    emit deviceTypeChanged(pl.deviceType, QString::fromUtf8("TrackIR"));
  }
  if(devPrefs != NULL){
    target->insertWidget(-1, devPrefs);
  }
}

void DeviceSetup::on_CameraOrientation_activated(int index)
{
  if(index < 0){
    return;
  }
  PREF.setKeyVal(QString::fromUtf8("Global"), QString::fromUtf8("Camera-orientation"), orientValues[index]);
}

void DeviceSetup::on_RefreshDevices_pressed()
{
  refresh();
}

void DeviceSetup::refresh()
{
  ui.DeviceSelector->clear();
  bool res = false;
  res |= WiimotePrefs::AddAvailableDevices(*(ui.DeviceSelector));
  res |= TirPrefs::AddAvailableDevices(*(ui.DeviceSelector));
#ifdef DARWIN
  res |= MacWebcamFtPrefs::AddAvailableDevices(*(ui.DeviceSelector));
  res |= MacWebcamPrefs::AddAvailableDevices(*(ui.DeviceSelector));
#else
  res |= WebcamFtPrefs::AddAvailableDevices(*(ui.DeviceSelector));
  res |= WebcamPrefs::AddAvailableDevices(*(ui.DeviceSelector));
#endif
  if(!res){
    initialized = true;
  }
  on_DeviceSelector_activated(ui.DeviceSelector->currentIndex());
  initialized = true;
}


text:
class UniqueUserFacingVersionForContentIdAndLocale < ActiveRecord::Migration[5.0]
  disable_ddl_transaction!

  def change
    # No 2 content items with the same content_id and locale can share a
    # user_facing_version
    add_index :content_items,
              %i[content_id locale user_facing_version],
              unique: true,
              algorithm: :concurrently,
              name: "index_unique_ufv_content_id_locale"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace EPocalipse.Json.Viewer
{
    class JsonObjectTypeDescriptionProvider : TypeDescriptionProvider
    {
        public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
        {
            return new JsonTreeObjectTypeDescriptor((JsonObject)instance);
        }
    }

    class JsonTreeObjectTypeDescriptor : CustomTypeDescriptor, ICustomTypeDescriptor
    {
        JsonObject _jsonObject;
        PropertyDescriptorCollection _propertyCollection;

        public JsonTreeObjectTypeDescriptor(JsonObject jsonObject)
        {
            _jsonObject = jsonObject;
            InitPropertyCollection();
        }

        private void InitPropertyCollection()
        {
            List<PropertyDescriptor> propertyDescriptors = new List<PropertyDescriptor>();

            if (_jsonObject != null)
            {
                foreach (JsonObject field in _jsonObject.Fields)
                {
                    PropertyDescriptor pd = new JsonTreeObjectPropertyDescriptor(field);
                    propertyDescriptors.Add(pd);
                }
            }
            _propertyCollection = new PropertyDescriptorCollection(propertyDescriptors.ToArray());
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
        {
            return _propertyCollection;
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
        {
            return ((ICustomTypeDescriptor)this).GetProperties(null);
        }

        object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
        {
            return _jsonObject;
        }
    }

    class JsonTreeObjectPropertyDescriptor : PropertyDescriptor
    {
        JsonObject _jsonObject;
        JsonObject[] _jsonObjects;

        public JsonTreeObjectPropertyDescriptor(JsonObject jsonObject)
            : base(jsonObject.Id, null)
        {
            _jsonObject = jsonObject;
            if (_jsonObject.JsonType == JsonType.Array)
                InitJsonObject();
        }

        private void InitJsonObject()
        {
            List<JsonObject> jsonObjectList = new List<JsonObject>();
            foreach (JsonObject field in _jsonObject.Fields)
            {
                jsonObjectList.Add(field);
            }
            _jsonObjects = jsonObjectList.ToArray();
        }

        public override bool CanResetValue(object component)
        {
            return false;
        }

        public override Type ComponentType
        {
            get
            {
                return null;
            }
        }

        public override object GetValue(object component)
        {
            switch (_jsonObject.JsonType)
            {
                case JsonType.Array:
                    return "Array";
                case JsonType.Object:
                    return "Object";
                default:
                    return _jsonObject.Value;
            }
        }

        public override bool IsReadOnly
        {
            get
            {
                if (_jsonObject.JsonType == JsonType.Value)
                    return false;
                return true;
            }
        }

        public override Type PropertyType
        {
            get
            {
                switch (_jsonObject.JsonType)
                {
                    case JsonType.Array:
                        return typeof(string);
                    case JsonType.Object:
                        return typeof(string);
                    default:
                        return _jsonObject.Value == null ? typeof(string) : _jsonObject.Value.GetType();
                }
            }
        }

        public override void ResetValue(object component)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void SetValue(object component, object value)
        {
            //TODO: Implement?
        }

        public override bool ShouldSerializeValue(object component)
        {
            return false;
        }

        public override object GetEditor(Type editorBaseType)
        {
            return base.GetEditor(editorBaseType);
        }
    }
}


text:
/*
 *  Reference counting implementation.
 */

#include "duk_internal.h"

#ifdef DUK_USE_REFERENCE_COUNTING

#ifndef DUK_USE_DOUBLE_LINKED_HEAP
#error internal error, reference counting requires a double linked heap
#endif

/*
 *  Misc
 */

static void queue_refzero(duk_heap *heap, duk_heaphdr *hdr) {
	/* tail insert: don't disturb head in case refzero is running */

	if (heap->refzero_list != NULL) {
		duk_heaphdr *hdr_prev;

		hdr_prev = heap->refzero_list_tail;
		DUK_ASSERT(hdr_prev != NULL);
		DUK_ASSERT(DUK_HEAPHDR_GET_NEXT(hdr_prev) == NULL);

		DUK_HEAPHDR_SET_NEXT(hdr, NULL);
		DUK_HEAPHDR_SET_PREV(hdr, hdr_prev);
		DUK_HEAPHDR_SET_NEXT(hdr_prev, hdr);
		heap->refzero_list_tail = hdr;
	} else {
		DUK_ASSERT(heap->refzero_list_tail == NULL);
		DUK_HEAPHDR_SET_NEXT(hdr, NULL);
		DUK_HEAPHDR_SET_PREV(hdr, NULL);
		heap->refzero_list = hdr;
		heap->refzero_list_tail = hdr;
	}
}

/*
 *  Heap object refcount finalization.
 *
 *  When an object is about to be freed, all other objects it refers to must
 *  be decref'd.  Refcount finalization does NOT free the object or its inner
 *  allocations (mark-and-sweep shares these helpers), it just manipulates
 *  the refcounts.
 *
 *  Note that any of the decref's may cause a refcount to drop to zero, BUT
 *  it will not be processed inline; instead, because refzero is already
 *  running, the objects will just be queued to refzero list and processed
 *  later.  This eliminates C recursion.
 */

static void refcount_finalize_hobject(duk_hthread *thr, duk_hobject *h) {
	int i;

	DUK_ASSERT(h);
	DUK_ASSERT(DUK_HEAPHDR_GET_TYPE((duk_heaphdr *) h) == DUK_HTYPE_OBJECT);

	/* XXX: better to get base and walk forwards? */

	for (i = 0; i < h->e_used; i++) {
		duk_hstring *key = DUK_HOBJECT_E_GET_KEY(h, i);
		if (!key) {
			continue;
		}
		duk_heap_heaphdr_decref(thr, (duk_heaphdr *) key);
		if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(h, i)) {
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_GETTER(h, i));
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_SETTER(h, i));
		} else {
			duk_heap_tval_decref(thr, DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(h, i));
		}
	}

	for (i = 0; i < h->a_size; i++) {
		duk_heap_tval_decref(thr, DUK_HOBJECT_A_GET_VALUE_PTR(h, i));
	}

	/* hash part is a 'weak reference' and does not contribute */

	duk_heap_heaphdr_decref(thr, (duk_heaphdr *) h->prototype);

	if (DUK_HOBJECT_IS_COMPILEDFUNCTION(h)) {
		duk_hcompiledfunction *f = (duk_hcompiledfunction *) h;
		duk_tval *tv, *tv_end;
		duk_hobject **funcs, **funcs_end;

		DUK_ASSERT(f->data != NULL);  /* compiled functions must be created 'atomically' */

		tv = DUK_HCOMPILEDFUNCTION_GET_CONSTS_BASE(f);
		tv_end = DUK_HCOMPILEDFUNCTION_GET_CONSTS_END(f);
		while (tv < tv_end) {
			duk_heap_tval_decref(thr, tv);
			tv++;
		}

		funcs = DUK_HCOMPILEDFUNCTION_GET_FUNCS_BASE(f);
		funcs_end = DUK_HCOMPILEDFUNCTION_GET_FUNCS_END(f);
		while (funcs < funcs_end) {
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) *funcs);
			funcs++;
		}

		duk_heap_heaphdr_decref(thr, (duk_heaphdr *) f->data);
	} else if (DUK_HOBJECT_IS_NATIVEFUNCTION(h)) {
		duk_hnativefunction *f = (duk_hnativefunction *) h;
		DUK_UNREF(f);
		/* nothing to finalize */
	} else if (DUK_HOBJECT_IS_THREAD(h)) {
		duk_hthread *t = (duk_hthread *) h;
		duk_tval *tv;

		tv = t->valstack;
		while (tv < t->valstack_end) {
			duk_heap_tval_decref(thr, tv);
			tv++;
		}

		for (i = 0; i < t->callstack_top; i++) {
			duk_activation *act = &t->callstack[i];
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) act->func);
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) act->var_env);
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) act->lex_env);
		}

#if 0  /* nothing now */
		for (i = 0; i < t->catchstack_top; i++) {
			duk_catcher *cat = &t->catchstack[i];
		}
#endif

		for (i = 0; i < DUK_NUM_BUILTINS; i++) {
			duk_heap_heaphdr_decref(thr, (duk_heaphdr *) t->builtins[i]);
		}

		duk_heap_heaphdr_decref(thr, (duk_heaphdr *) t->resumer);
	}
}

void duk_heap_refcount_finalize_heaphdr(duk_hthread *thr, duk_heaphdr *hdr) {
	DUK_ASSERT(hdr);

	switch (DUK_HEAPHDR_GET_TYPE(hdr)) {
	case DUK_HTYPE_OBJECT:
		refcount_finalize_hobject(thr, (duk_hobject *) hdr);
		break;
	case DUK_HTYPE_BUFFER:
		/* nothing to finalize */
		break;
	case DUK_HTYPE_STRING:
		/* cannot happen: strings are not put into refzero list (they don't even have the next/prev pointers) */
	default:
		DUK_UNREACHABLE();
	}
}

/*
 *  Refcount memory freeing loop.
 *
 *  Frees objects in the refzero_pending list until the list becomes
 *  empty.  When an object is freed, its references get decref'd and
 *  may cause further objects to be queued for freeing.
 *
 *  This could be expanded to allow incremental freeing: just bail out
 *  early and resume at a future alloc/decref/refzero.
 */

static void refzero_free_pending(duk_hthread *thr) {
	duk_heaphdr *h1, *h2;
	duk_heap *heap;
	int count = 0;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	/*
	 *  Detect recursive invocation
	 */

	if (DUK_HEAP_HAS_REFZERO_FREE_RUNNING(heap)) {
		DUK_DDDPRINT("refzero free running, skip run");
		return;
	}

	/*
	 *  Churn refzero_list until empty
	 */

	DUK_HEAP_SET_REFZERO_FREE_RUNNING(heap);
	while (heap->refzero_list) {
		duk_hobject *obj;
		int rescued = 0;

		/*
		 *  Pick an object from the head (don't remove yet).
		 */

		h1 = heap->refzero_list;
		obj = (duk_hobject *) h1;
		DUK_DDPRINT("refzero processing %p: %!O", h1, h1);
		DUK_ASSERT(DUK_HEAPHDR_GET_PREV(h1) == NULL);
		DUK_ASSERT(DUK_HEAPHDR_GET_TYPE(h1) == DUK_HTYPE_OBJECT);  /* currently, always the case */

		/*
		 *  Finalizer check.
		 *
		 *  Note: running a finalizer may have arbitrary side effects, e.g.
		 *  queue more objects on refzero_list (tail), or even trigger a
		 *  mark-and-sweep.
		 *
		 *  Note: quick reject check should match vast majority of
		 *  objects and must be safe (not throw any errors, ever).
		 */

		/* FIXME: If object has FINALIZED, it was finalized by mark-and-sweep on
		 * its previous run.  Any point in running finalizer again here?  If
		 * finalization semantics is changed so that finalizer is only run once,
		 * checking for FINALIZED would happen here.
		 */

		if (duk_hobject_hasprop_raw(thr, obj, DUK_HTHREAD_STRING_INT_FINALIZER(thr))) {
			DUK_DDDPRINT("object has a finalizer, run it");

			DUK_ASSERT(h1->h_refcount == 0);
			h1->h_refcount++;  /* bump refcount to prevent refzero during finalizer processing */

			duk_hobject_run_finalizer(thr, obj);  /* must never longjmp */

			h1->h_refcount--;  /* remove artificial bump */
			DUK_ASSERT(h1->h_refcount >= 0);

			if (h1->h_refcount != 0) {
				DUK_DDDPRINT("-> object refcount after finalization non-zero, object will be rescued");
				rescued = 1;
			} else {
				DUK_DDDPRINT("-> object refcount still zero after finalization, object will be freed");
			}
		}

  		/* Refzero head is still the same.  This is the case even if finalizer
		 * inserted more refzero objects; they are inserted to the tail.
		 */
		DUK_ASSERT(h1 == heap->refzero_list);

		/*
		 *  Remove the object from the refzero list.  This cannot be done
		 *  before a possible finalizer has been executed; the finalizer
		 *  may trigger a mark-and-sweep, and mark-and-sweep must be able
		 *  to traverse a complete refzero_list.
		 */

		h2 = DUK_HEAPHDR_GET_NEXT(h1);
		if (h2) {
			DUK_HEAPHDR_SET_PREV(h2, NULL);  /* not strictly necessary */
			heap->refzero_list = h2;
		} else {
			heap->refzero_list = NULL;
			heap->refzero_list_tail = NULL;
		}

		/*
		 *  Rescue or free.
		 */

		if (rescued) {
			/* yes -> move back to heap allocated */
			DUK_DDPRINT("object rescued during refcount finalization: %p", (void *) h1);
			DUK_HEAPHDR_SET_PREV(h1, NULL);
			DUK_HEAPHDR_SET_NEXT(h1, heap->heap_allocated);
			heap->heap_allocated = h1;
		} else {
			/* no -> decref members, then free */
			refcount_finalize_hobject(thr, obj);
			duk_heap_free_heaphdr_raw(heap, h1);
		}

		count++;
	}
	DUK_HEAP_CLEAR_REFZERO_FREE_RUNNING(heap);

	DUK_DDDPRINT("refzero processed %d objects", count);

	/*
	 *  Once the whole refzero cascade has been freed, check for
	 *  a voluntary mark-and-sweep.
	 */

#ifdef DUK_USE_MARK_AND_SWEEP
	heap->mark_and_sweep_trigger_counter -= count;
	if (heap->mark_and_sweep_trigger_counter <= 0) {
		int rc;
		int emergency = 0;
		DUK_DPRINT("refcount triggering mark-and-sweep");
		rc = duk_heap_mark_and_sweep(heap, emergency);
		DUK_UNREF(rc);
		DUK_DPRINT("refcount triggered mark-and-sweep => rc %d", rc);
	}
#endif
}

/*
 *  Incref and decref functions.
 *
 *  Decref may trigger immediate refzero handling, which may free and finalize
 *  an arbitrary number of objects.
 *
 */

void duk_heap_tval_incref(duk_tval *tv) {
#if 0
	DUK_DDDPRINT("tval incref %p (%d->%d): %!T",
	             (void *) tv,
	             (tv != NULL && DUK_TVAL_IS_HEAP_ALLOCATED(tv) ? DUK_TVAL_GET_HEAPHDR(tv)->h_refcount : 0),
	             (tv != NULL && DUK_TVAL_IS_HEAP_ALLOCATED(tv) ? DUK_TVAL_GET_HEAPHDR(tv)->h_refcount + 1 : 0),
	             tv);
#endif

	if (!tv) {
		return;
	}

	if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		if (h) {
			DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
			DUK_ASSERT(h->h_refcount >= 0);
			h->h_refcount++;
		}
	}
}

void duk_heap_tval_decref(duk_hthread *thr, duk_tval *tv) {
#if 0
	DUK_DDDPRINT("tval decref %p (%d->%d): %!T",
	             (void *) tv,
	             (tv != NULL && DUK_TVAL_IS_HEAP_ALLOCATED(tv) ? DUK_TVAL_GET_HEAPHDR(tv)->h_refcount : 0),
	             (tv != NULL && DUK_TVAL_IS_HEAP_ALLOCATED(tv) ? DUK_TVAL_GET_HEAPHDR(tv)->h_refcount - 1 : 0),
	             tv);
#endif

	if (!tv) {
		return;
	}

	if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
		duk_heap_heaphdr_decref(thr, DUK_TVAL_GET_HEAPHDR(tv));
	}
}

void duk_heap_heaphdr_incref(duk_heaphdr *h) {
#if 0
	DUK_DDDPRINT("heaphdr incref %p (%d->%d): %!O",
	             (void *) h,
	             (h != NULL ? h->h_refcount : 0),
	             (h != NULL ? h->h_refcount + 1 : 0),
	             h);
#endif

	if (!h) {
		return;
	}
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
	DUK_ASSERT(h->h_refcount >= 0);

	h->h_refcount++;
}

void duk_heap_heaphdr_decref(duk_hthread *thr, duk_heaphdr *h) {
	duk_heap *heap;

#if 0
	DUK_DDDPRINT("heaphdr decref %p (%d->%d): %!O",
	             (void *) h,
	             (h != NULL ? h->h_refcount : 0),
	             (h != NULL ? h->h_refcount - 1 : 0),
	             h);
#endif

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);

	if (!h) {
		return;
	}
	DUK_ASSERT(DUK_HEAPHDR_HTYPE_VALID(h));
	DUK_ASSERT(h->h_refcount >= 1);

	if (--h->h_refcount != 0) {
		return;
	}

	heap = thr->heap;
	DUK_DDDPRINT("refzero %p: %!O", (void *) h, h);

#ifdef DUK_USE_MARK_AND_SWEEP
	/*
	 *  If mark-and-sweep is running, don't process 'refzero' situations at all.
	 *  They may happen because mark-and-sweep needs to finalize refcounts for
	 *  each object it sweeps.  Otherwise the target objects of swept objects
	 *  would have incorrect refcounts.
	 *
	 *  Note: mark-and-sweep could use a separate decref handler to avoid coming
	 *  here at all.  However, mark-and-sweep may also call finalizers, which
	 *  can do arbitrary operations and would use this decref variant anyway.
	 */
	if (DUK_HEAP_HAS_MARKANDSWEEP_RUNNING(heap)) {
		DUK_DDDPRINT("refzero handling suppressed when mark-and-sweep running, object: %p", (void *) h);
		return;
	}
#endif

	switch (DUK_HEAPHDR_GET_TYPE(h)) {
	case DUK_HTYPE_STRING:
		/*
		 *  Strings have no internal references but do have "weak"
		 *  references in the string cache.  Also note that strings
		 *  are not on the heap_allocated list like other heap
		 *  elements.
		 */

		duk_heap_strcache_string_remove(heap, (duk_hstring *) h);
		duk_heap_string_remove(heap, (duk_hstring *) h);
		duk_heap_free_heaphdr_raw(heap, h);
		break;

	case DUK_HTYPE_OBJECT:
		/*
		 *  Objects have internal references.  Must finalize through
		 *  the "refzero" work list.
		 */

		duk_heap_remove_any_from_heap_allocated(heap, h);
		queue_refzero(heap, h);
		refzero_free_pending(thr);
		break;

	case DUK_HTYPE_BUFFER:
		/*
		 *  Buffers have no internal references.  However, a dynamic
		 *  buffer has a separate allocation for the buffer.  This is
		 *  freed by duk_heap_free_heaphdr_raw().
		 */

		duk_heap_remove_any_from_heap_allocated(heap, h);
		duk_heap_free_heaphdr_raw(heap, h);
		break;

	default:
		DUK_DPRINT("invalid heap type in decref: %d", (int) DUK_HEAPHDR_GET_TYPE(h));
		DUK_UNREACHABLE();
	}
}

#else

/* no refcounting */

#endif  /* DUK_USE_REFERENCE_COUNTING */