text:
class Profile;

namespace policy {

class DeviceCloudPolicyInvalidator::InvalidationServiceObserver
    : public syncer::InvalidationHandler {
 public:
  explicit InvalidationServiceObserver(
      DeviceCloudPolicyInvalidator* parent,
      invalidation::InvalidationService* invalidation_service);
  virtual ~InvalidationServiceObserver();

  invalidation::InvalidationService* GetInvalidationService();
  bool IsServiceConnected() const;

  // public syncer::InvalidationHandler:
  virtual void OnInvalidatorStateChange(
      syncer::InvalidatorState state) OVERRIDE;
  virtual void OnIncomingInvalidation(
      const syncer::ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
  virtual std::string GetOwnerName() const OVERRIDE;

 private:
  DeviceCloudPolicyInvalidator* parent_;
  invalidation::InvalidationService* invalidation_service_;
  bool is_service_connected_;

  DISALLOW_COPY_AND_ASSIGN(InvalidationServiceObserver);
};

DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    InvalidationServiceObserver(
        DeviceCloudPolicyInvalidator* parent,
        invalidation::InvalidationService* invalidation_service)
    : parent_(parent),
      invalidation_service_(invalidation_service),
      is_service_connected_(invalidation_service->GetInvalidatorState() ==
                                syncer::INVALIDATIONS_ENABLED) {
  invalidation_service_->RegisterInvalidationHandler(this);
}

DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    ~InvalidationServiceObserver() {
  invalidation_service_->UnregisterInvalidationHandler(this);
}

invalidation::InvalidationService*
DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    GetInvalidationService() {
  return invalidation_service_;
}

bool DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
         IsServiceConnected() const {
  return is_service_connected_;
}

void DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    OnInvalidatorStateChange(syncer::InvalidatorState state) {
  const bool is_service_connected = (state == syncer::INVALIDATIONS_ENABLED);
  if (is_service_connected == is_service_connected_)
    return;

  is_service_connected_ = is_service_connected;
  if (is_service_connected_)
    parent_->OnInvalidationServiceConnected(invalidation_service_);
  else
    parent_->OnInvalidationServiceDisconnected(invalidation_service_);
}

void DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    OnIncomingInvalidation(
        const syncer::ObjectIdInvalidationMap& invalidation_map) {
}

std::string DeviceCloudPolicyInvalidator::InvalidationServiceObserver::
    GetOwnerName() const {
  return "DevicePolicy";
}

DeviceCloudPolicyInvalidator::DeviceCloudPolicyInvalidator()
    : invalidation_service_(NULL),
      highest_handled_invalidation_version_(0) {
  // The DeviceCloudPolicyInvalidator should be created before any user
  // Profiles.
  DCHECK(g_browser_process->profile_manager()->GetLoadedProfiles().empty());

  // Subscribe to notification about new user profiles becoming available.
  registrar_.Add(this,
                 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
                 content::NotificationService::AllSources());

  TryToCreateInvalidator();
}

DeviceCloudPolicyInvalidator::~DeviceCloudPolicyInvalidator() {
  DestroyInvalidator();
}

void DeviceCloudPolicyInvalidator::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK_EQ(chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, type);
  invalidation::ProfileInvalidationProvider* invalidation_provider =
      invalidation::ProfileInvalidationProviderFactory::GetForProfile(
          content::Details<Profile>(details).ptr());
  if (!invalidation_provider) {
    // If the Profile does not support invalidation (e.g. guest, incognito),
    // ignore it.
    return;
  }

  // Create a state observer for the user's invalidation service.
  profile_invalidation_service_observers_.push_back(
      new InvalidationServiceObserver(
              this,
              invalidation_provider->GetInvalidationService()));

  TryToCreateInvalidator();
}

void DeviceCloudPolicyInvalidator::OnInvalidationServiceConnected(
    invalidation::InvalidationService* invalidation_service) {
  if (!device_invalidation_service_) {
    // The lack of a device-global invalidation service implies that a
    // |CloudPolicyInvalidator| backed by another connected service exists
    // already. There is no need to switch from that to the service which just
    // connected.
    return;
  }

  if (invalidation_service != device_invalidation_service_.get()) {
    // If an invalidation service other than the device-global one connected,
    // destroy the device-global service and the |CloudPolicyInvalidator| backed
    // by it, if any.
    DestroyInvalidator();
    DestroyDeviceInvalidationService();
  }

  // Create a |CloudPolicyInvalidator| backed by the invalidation service which
  // just connected.
  CreateInvalidator(invalidation_service);
}

void DeviceCloudPolicyInvalidator::OnInvalidationServiceDisconnected(
    invalidation::InvalidationService* invalidation_service) {
  if (invalidation_service != invalidation_service_) {
    // If the invalidation service which disconnected is not backing the current
    // |CloudPolicyInvalidator|, return.
    return;
  }

  // Destroy the |CloudPolicyInvalidator| backed by the invalidation service
  // which just disconnected.
  DestroyInvalidator();

  // Try to create a |CloudPolicyInvalidator| backed by another invalidation
  // service.
  TryToCreateInvalidator();
}

void DeviceCloudPolicyInvalidator::TryToCreateInvalidator() {
  if (invalidator_) {
    // If a |CloudPolicyInvalidator| exists already, return.
    return;
  }

  for (ScopedVector<InvalidationServiceObserver>::const_iterator it =
           profile_invalidation_service_observers_.begin();
           it != profile_invalidation_service_observers_.end(); ++it) {
    if ((*it)->IsServiceConnected()) {
      // If a connected invalidation service belonging to a logged-in user is
      // found, create a |CloudPolicyInvalidator| backed by that service and
      // destroy the device-global service, if any.
      DestroyDeviceInvalidationService();
      CreateInvalidator((*it)->GetInvalidationService());
      return;
    }
  }

  if (!device_invalidation_service_) {
    // If no other connected invalidation service was found, ensure that a
    // device-global service is running.
    device_invalidation_service_.reset(
        new invalidation::TiclInvalidationService(
            GetUserAgent(),
            scoped_ptr<IdentityProvider>(new chromeos::DeviceIdentityProvider(
                chromeos::DeviceOAuth2TokenServiceFactory::Get())),
            scoped_ptr<invalidation::TiclSettingsProvider>(
                new TiclDeviceSettingsProvider),
            g_browser_process->gcm_driver(),
            g_browser_process->system_request_context()));
    device_invalidation_service_->Init(
        scoped_ptr<syncer::InvalidationStateTracker>(
            new invalidation::InvalidatorStorage(
                    g_browser_process->local_state())));
    device_invalidation_service_observer_.reset(
        new InvalidationServiceObserver(
                this,
                device_invalidation_service_.get()));
  }

  if (device_invalidation_service_observer_->IsServiceConnected()) {
    // If the device-global invalidation service is connected, create a
    // |CloudPolicyInvalidator| backed by it. Otherwise,  a
    // |CloudPolicyInvalidator| will be created later when a connected service
    // becomes available.
    CreateInvalidator(device_invalidation_service_.get());
  }
}

void DeviceCloudPolicyInvalidator::CreateInvalidator(
    invalidation::InvalidationService* invalidation_service) {
  invalidation_service_ = invalidation_service;
  DCHECK(!invalidator_);
  invalidator_.reset(new CloudPolicyInvalidator(
      enterprise_management::DeviceRegisterRequest::DEVICE,
      g_browser_process->platform_part()->browser_policy_connector_chromeos()->
          GetDeviceCloudPolicyManager()->core(),
      base::MessageLoopProxy::current(),
      scoped_ptr<base::Clock>(new base::DefaultClock()),
      highest_handled_invalidation_version_));
  invalidator_->Initialize(invalidation_service);
}

void DeviceCloudPolicyInvalidator::DestroyInvalidator() {
  if (invalidator_) {
    highest_handled_invalidation_version_ =
        invalidator_->highest_handled_invalidation_version();
    invalidator_->Shutdown();
  }
  invalidator_.reset();
  invalidation_service_ = NULL;
}

void DeviceCloudPolicyInvalidator::DestroyDeviceInvalidationService() {
  device_invalidation_service_observer_.reset();
  device_invalidation_service_.reset();
}

}  // namespace policy


text:
Uses [gulp-6to5](https://github.com/sindresorhus/gulp-6to5) to transform
ES6 code into readable vanilla ES5 with source maps.

redpajama_set_name: RedPajamaGithub


text:
namespace process {

typedef void (*Sender)(struct ev_loop*, ev_io*, int);

extern void send_data(struct ev_loop*, ev_io*, int);
extern void send_file(struct ev_loop*, ev_io*, int);

class Encoder
{
public:
  virtual Sender sender() = 0;
};

class DataEncoder : public Encoder
{
public:
  DataEncoder(const std::string& _data)
    : data(_data), index(0) {}

  virtual ~DataEncoder() {}

  virtual Sender sender()
  {
    return send_data;
  }

  virtual const char* next(size_t* length)
  {
    size_t temp = index;
    index = data.size();
    *length = data.size() - temp;
    return data.data() + temp;
  }

  virtual void backup(size_t length)
  {
    if (index >= length) {
      index -= length;
    }
  }

  virtual size_t remaining() const
  {
    return data.size() - index;
  }

private:
  const std::string data;
  size_t index;
};

class MessageEncoder : public DataEncoder
{
public:
  MessageEncoder(Message* _message)
    : DataEncoder(encode(_message)), message(_message) {}

  virtual ~MessageEncoder()
  {
    if (message != NULL) {
      delete message;
    }
  }

  static std::string encode(Message* message)
  {
    if (message != NULL) {
      std::ostringstream out;

      out << "POST /" << message->to.id << "/" << message->name
          << " HTTP/1.0\r\n"
          << "User-Agent: libprocess/" << message->from << "\r\n"
          << "Connection: Keep-Alive\r\n";

      if (message->body.size() > 0) {
        out << "Transfer-Encoding: chunked\r\n\r\n"
            << std::hex << message->body.size() << "\r\n";
        out.write(message->body.data(), message->body.size());
        out << "\r\n"
            << "0\r\n"
            << "\r\n";
      } else {
        out << "\r\n";
      }

      return out.str();
    }
  }

private:
  Message* message;
};

class HttpResponseEncoder : public DataEncoder
{
public:
  HttpResponseEncoder(const HttpResponse& response)
    : DataEncoder(encode(response)) {}

  static std::string encode(const HttpResponse& response)
  {
    std::ostringstream out;

    // TODO(benh): Check version?

    out << "HTTP/1.1 " << response.status << "\r\n";

    std::map<std::string, std::string> headers = response.headers;

    // HTTP 1.1 requires the "Date" header. In the future once we
    // start checking the version (above) then we can conditionally
    // add this header, but for now, we always do.
    time_t rawtime;
    time(&rawtime);

    char date[256];

    // TODO(benh): Check return code of strftime!
    strftime(date, 256, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&rawtime));

    headers["Date"] = date;

    foreachpair (const std::string& key, const std::string& value, headers) {
      out << key << ": " << value << "\r\n";
    }

    // Make sure at least the "Content-Length" header is present in
    // order to signal to a client the end of a response.
    if (headers.count("Content-Length") == 0) {
      out << "Content-Length: " << response.body.size() << "\r\n";
    }

    out << "\r\n";

    out.write(response.body.data(), response.body.size());

    return out.str();
  }
};

class FileEncoder : public Encoder
{
public:
  FileEncoder(int _fd, size_t _size)
    : fd(_fd), size(_size), index(0) {}

  virtual ~FileEncoder()
  {
    close(fd);
  }

  virtual Sender sender()
  {
    return send_file;
  }

  virtual int next(off_t* offset, size_t* length)
  {
    off_t temp = index;
    index = size;
    *offset = temp;
    *length = size - temp;
    return fd;
  }

  virtual void backup(size_t length)
  {
    if (index >= length) {
      index -= length;
    }
  }

  virtual size_t remaining() const
  {
    return size - index;
  }

private:
  int fd;
  size_t size;
  off_t index;
};

}  // namespace process {

#endif // __ENCODER_HPP__


text:
package com.techhounds.commands.angler;

import com.techhounds.RobotMap.Angler;
import com.techhounds.subsystems.AnglerSubsystem;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class SetStateUp extends Command {

	private final AnglerSubsystem angler;

    public SetStateUp() {
        // Use requires() here to declare subsystem dependencies

        angler = AnglerSubsystem.getInstance();
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	angler.increaseState();
    	if(angler.getState() == 0) {

    		new SetAnglerPosition(Angler.DOWN).start();

    	} else if(angler.getState() == 1) {

    		new SetAnglerPosition(Angler.COLLECTING).start();

    	} else if(angler.getState() == 2) {

    		new SetAnglerPosition(Angler.UP).start();

    	} else {
    		System.out.println("OH NO, THERE IS AN ERROR WITH THE STATES!... CALEB!!!");
    	}
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class MetadataValuesChangeCommandBase
   | Picturepark.SDK.V1 API </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class MetadataValuesChangeCommandBase
   | Picturepark.SDK.V1 API ">
    <meta name="generator" content="docfx 2.16.7.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    <meta property="docfx:rel" content="../">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class MetadataValuesChangeCommandBase

The base class for metadata value change commands.

Inheritance

System.Object

MetadataValuesChangeCommandBase

MetadataValuesFieldRemoveCommand

MetadataValuesSchemaItemAddCommand

MetadataValuesSchemaItemRemoveCommand

MetadataValuesSchemaRemoveCommand

MetadataValuesSchemaUpdateCommand

MetadataValuesSchemaUpsertCommand

Inherited Members

                  System.Object.ToString()

                  System.Object.Equals(System.Object)

                  System.Object.Equals(System.Object, System.Object)

                  System.Object.ReferenceEquals(System.Object, System.Object)

                  System.Object.GetHashCode()

                  System.Object.GetType()

                  System.Object.MemberwiseClone()

Namespace:Picturepark.SDK.V1.ServiceProvider.Contract

Assembly:cs.temp.dll.dll

Syntax

public class MetadataValuesChangeCommandBase

Methods

FromJson(String)

Declaration

public static MetadataValuesChangeCommandBase FromJson(string data)

Parameters

                    Type
                    Name
                    Description

                    System.String
                    data

Returns

                    Type
                    Description

                    MetadataValuesChangeCommandBase

ToJson()

Declaration

public string ToJson()

Returns

                    Type
                    Description

                    System.String

              Back to top

            Copyright © 2015-2017 Microsoft
Generated by DocFX


text:
<?php

namespace Umc\Base\Block\Adminhtml\Module\Edit\Tab;

use Magento\Backend\Block\Widget\Tab\TabInterface;

/**
 * @api
 */
class Module extends AbstractTab implements TabInterface
{
    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel()
    {
        return __('Module');
    }

    /**
     * Prepare title for tab
     *
     * @return string
     */
    public function getTabTitle()
    {
        return $this->getTabLabel();
    }

    /**
     * Can show tab in tabs
     *
     * @return boolean
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * Tab is hidden
     *
     * @return boolean
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * prepare the form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        parent::_prepareForm();
        $this->getForm()->setData('html_id_prefix', $this->entityCode);
        $this->getForm()->addFieldNameSuffix($this->entityCode);
        /** @var \Umc\Base\Api\Data\ModuleInterface $module */
        $module = $this->_coreRegistry->registry('current_module');
        if ($module && count($module->getData())) {
            $this->getForm()->addValues($module->getData());
        } else {
            $this->getForm()->addValues($this->_scopeConfig->getValue('umc/'.$this->entityCode));
        }
        return $this;
    }
}


text:
<?php $signPackage = $this->weixin->sdk(); ?>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
	wx.config({
		debug: true,
		appId: '<?php echo $signPackage["appId"];?>',
		timestamp: <?php echo $signPackage["timestamp"];?>,
		nonceStr: '<?php echo $signPackage["nonceStr"];?>',
		signature: '<?php echo $signPackage["signature"];?>',
		jsApiList: [
			'checkJsApi',
			'onMenuShareTimeline',
			'onMenuShareAppMessage',
			'onMenuShareQQ',
			'onMenuShareWeibo',
			'onMenuShareQZone',
			'hideMenuItems',
			'showMenuItems',
			'hideAllNonBaseMenuItem',
			'showAllNonBaseMenuItem',
			'translateVoice',
			'startRecord',
			'stopRecord',
			'onVoiceRecordEnd',
			'playVoice',
			'onVoicePlayEnd',
			'pauseVoice',
			'stopVoice',
			'uploadVoice',
			'downloadVoice',
			'chooseImage',
			'previewImage',
			'uploadImage',
			'downloadImage',
			'getNetworkType',
			'openLocation',
			'getLocation',
			'hideOptionMenu',
			'showOptionMenu',
			'closeWindow',
			'scanQRCode',
			'chooseWXPay',
			'openProductSpecificView',
			'addCard',
			'chooseCard',
			'openCard'
		]
	});
</script>


text:
export default function requireAll(req) {
  return req.keys().map(p => req(p).default)
}


text:
package com.tvd12.ezyfox.reflect;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class EzyClassTree {

    protected final List<Node> roots = new ArrayList<>();

    public EzyClassTree() {}

    public EzyClassTree(Class<?>... classes) {
        this(Arrays.asList(classes));
    }

    public EzyClassTree(Collection<Class<?>> classes) {
        for (Class<?> clazz : classes) {
            add(clazz);
        }
    }

    public void add(Class<?> clazz) {
        add(clazz, roots);
    }

    private void add(Class<?> clazz, List<Node> existedNodes) {
        if (existedNodes.isEmpty()) {
            existedNodes.add(new Node(clazz));
            return;
        }
        for (Node node : existedNodes) {
            if (node.clazz.equals(clazz)) {
                return;
            }
        }
        List<Node> children = new ArrayList<>();
        for (Node node : existedNodes) {
            if (clazz.isAssignableFrom(node.clazz)) {
                children.add(node);
            }
        }
        if (children.size() > 0) {
            Node newRootNode = new Node(clazz, children);
            existedNodes.removeAll(children);
            existedNodes.add(newRootNode);
            return;
        }
        for (Node node : existedNodes) {
            if (node.clazz.isAssignableFrom(clazz)) {
                add(clazz, node.children);
                return;
            }
        }
        existedNodes.add(new Node(clazz));
    }

    public List<Class<?>> toList() {
        List<Class<?>> list = new ArrayList<>();
        for (Node root : roots) {
            root.appendToList(list);
        }
        return list;
    }

    @Override
    public String toString() {
        return roots.stream()
            .map(Node::toString)
            .collect(Collectors.joining("\n"));
    }

    private static class Node {
        protected final Class<?> clazz;
        protected final List<Node> children = new ArrayList<>();

        private Node(Class<?> clazz) {
            this.clazz = clazz;
        }

        private Node(Class<?> clazz, List<Node> children) {
            this.clazz = clazz;
            this.children.addAll(children);
        }

        private void appendToList(List<Class<?>> list) {
            for (Node child : children) {
                child.appendToList(list);
            }
            list.add(clazz);
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder()
                .append(clazz.getName());
            if (children.size() > 0) {
                builder.append(" => ").append(children);
            }
            return builder.toString();
        }
    }
}


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ld

import (
	"cmd/internal/obj"
	"cmd/internal/sys"
	"encoding/binary"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

type IMAGE_FILE_HEADER struct {
	Machine              uint16
	NumberOfSections     uint16
	TimeDateStamp        uint32
	PointerToSymbolTable uint32
	NumberOfSymbols      uint32
	SizeOfOptionalHeader uint16
	Characteristics      uint16
}

type IMAGE_DATA_DIRECTORY struct {
	VirtualAddress uint32
	Size           uint32
}

type IMAGE_OPTIONAL_HEADER struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	BaseOfData                  uint32
	ImageBase                   uint32
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint32
	SizeOfStackCommit           uint32
	SizeOfHeapReserve           uint32
	SizeOfHeapCommit            uint32
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]IMAGE_DATA_DIRECTORY
}

type IMAGE_SECTION_HEADER struct {
	Name                 [8]uint8
	VirtualSize          uint32
	VirtualAddress       uint32
	SizeOfRawData        uint32
	PointerToRawData     uint32
	PointerToRelocations uint32
	PointerToLineNumbers uint32
	NumberOfRelocations  uint16
	NumberOfLineNumbers  uint16
	Characteristics      uint32
}

type IMAGE_IMPORT_DESCRIPTOR struct {
	OriginalFirstThunk uint32
	TimeDateStamp      uint32
	ForwarderChain     uint32
	Name               uint32
	FirstThunk         uint32
}

type IMAGE_EXPORT_DIRECTORY struct {
	Characteristics       uint32
	TimeDateStamp         uint32
	MajorVersion          uint16
	MinorVersion          uint16
	Name                  uint32
	Base                  uint32
	NumberOfFunctions     uint32
	NumberOfNames         uint32
	AddressOfFunctions    uint32
	AddressOfNames        uint32
	AddressOfNameOrdinals uint32
}

const (
	PEBASE = 0x00400000
)

var (
	// SectionAlignment must be greater than or equal to FileAlignment.
	// The default is the page size for the architecture.
	PESECTALIGN int64 = 0x1000

	// FileAlignment should be a power of 2 between 512 and 64 K, inclusive.
	// The default is 512. If the SectionAlignment is less than
	// the architecture's page size, then FileAlignment must match SectionAlignment.
	PEFILEALIGN int64 = 2 << 8
)

const (
	IMAGE_FILE_MACHINE_I386              = 0x14c
	IMAGE_FILE_MACHINE_AMD64             = 0x8664
	IMAGE_FILE_RELOCS_STRIPPED           = 0x0001
	IMAGE_FILE_EXECUTABLE_IMAGE          = 0x0002
	IMAGE_FILE_LINE_NUMS_STRIPPED        = 0x0004
	IMAGE_FILE_LARGE_ADDRESS_AWARE       = 0x0020
	IMAGE_FILE_32BIT_MACHINE             = 0x0100
	IMAGE_FILE_DEBUG_STRIPPED            = 0x0200
	IMAGE_SCN_CNT_CODE                   = 0x00000020
	IMAGE_SCN_CNT_INITIALIZED_DATA       = 0x00000040
	IMAGE_SCN_CNT_UNINITIALIZED_DATA     = 0x00000080
	IMAGE_SCN_MEM_EXECUTE                = 0x20000000
	IMAGE_SCN_MEM_READ                   = 0x40000000
	IMAGE_SCN_MEM_WRITE                  = 0x80000000
	IMAGE_SCN_MEM_DISCARDABLE            = 0x2000000
	IMAGE_SCN_LNK_NRELOC_OVFL            = 0x1000000
	IMAGE_SCN_ALIGN_32BYTES              = 0x600000
	IMAGE_DIRECTORY_ENTRY_EXPORT         = 0
	IMAGE_DIRECTORY_ENTRY_IMPORT         = 1
	IMAGE_DIRECTORY_ENTRY_RESOURCE       = 2
	IMAGE_DIRECTORY_ENTRY_EXCEPTION      = 3
	IMAGE_DIRECTORY_ENTRY_SECURITY       = 4
	IMAGE_DIRECTORY_ENTRY_BASERELOC      = 5
	IMAGE_DIRECTORY_ENTRY_DEBUG          = 6
	IMAGE_DIRECTORY_ENTRY_COPYRIGHT      = 7
	IMAGE_DIRECTORY_ENTRY_ARCHITECTURE   = 7
	IMAGE_DIRECTORY_ENTRY_GLOBALPTR      = 8
	IMAGE_DIRECTORY_ENTRY_TLS            = 9
	IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    = 10
	IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   = 11
	IMAGE_DIRECTORY_ENTRY_IAT            = 12
	IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   = 13
	IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
	IMAGE_SUBSYSTEM_WINDOWS_GUI          = 2
	IMAGE_SUBSYSTEM_WINDOWS_CUI          = 3
)

// X64
type PE64_IMAGE_OPTIONAL_HEADER struct {
	Magic                       uint16
	MajorLinkerVersion          uint8
	MinorLinkerVersion          uint8
	SizeOfCode                  uint32
	SizeOfInitializedData       uint32
	SizeOfUninitializedData     uint32
	AddressOfEntryPoint         uint32
	BaseOfCode                  uint32
	ImageBase                   uint64
	SectionAlignment            uint32
	FileAlignment               uint32
	MajorOperatingSystemVersion uint16
	MinorOperatingSystemVersion uint16
	MajorImageVersion           uint16
	MinorImageVersion           uint16
	MajorSubsystemVersion       uint16
	MinorSubsystemVersion       uint16
	Win32VersionValue           uint32
	SizeOfImage                 uint32
	SizeOfHeaders               uint32
	CheckSum                    uint32
	Subsystem                   uint16
	DllCharacteristics          uint16
	SizeOfStackReserve          uint64
	SizeOfStackCommit           uint64
	SizeOfHeapReserve           uint64
	SizeOfHeapCommit            uint64
	LoaderFlags                 uint32
	NumberOfRvaAndSizes         uint32
	DataDirectory               [16]IMAGE_DATA_DIRECTORY
}

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// PE (Portable Executable) file writing
// http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx

// DOS stub that prints out
// "This program cannot be run in DOS mode."
var dosstub = []uint8{
	0x4d,
	0x5a,
	0x90,
	0x00,
	0x03,
	0x00,
	0x04,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0xff,
	0xff,
	0x00,
	0x00,
	0x8b,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x40,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x80,
	0x00,
	0x00,
	0x00,
	0x0e,
	0x1f,
	0xba,
	0x0e,
	0x00,
	0xb4,
	0x09,
	0xcd,
	0x21,
	0xb8,
	0x01,
	0x4c,
	0xcd,
	0x21,
	0x54,
	0x68,
	0x69,
	0x73,
	0x20,
	0x70,
	0x72,
	0x6f,
	0x67,
	0x72,
	0x61,
	0x6d,
	0x20,
	0x63,
	0x61,
	0x6e,
	0x6e,
	0x6f,
	0x74,
	0x20,
	0x62,
	0x65,
	0x20,
	0x72,
	0x75,
	0x6e,
	0x20,
	0x69,
	0x6e,
	0x20,
	0x44,
	0x4f,
	0x53,
	0x20,
	0x6d,
	0x6f,
	0x64,
	0x65,
	0x2e,
	0x0d,
	0x0d,
	0x0a,
	0x24,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
}

var rsrcsym *Symbol

var strtbl []byte

var PESECTHEADR int32

var PEFILEHEADR int32

var pe64 int

var pensect int

var nextsectoff int

var nextfileoff int

var textsect int

var datasect int

var bsssect int

var fh IMAGE_FILE_HEADER

var oh IMAGE_OPTIONAL_HEADER

var oh64 PE64_IMAGE_OPTIONAL_HEADER

var sh [16]IMAGE_SECTION_HEADER

// shNames stores full names of PE sections stored in sh.
var shNames []string

var dd []IMAGE_DATA_DIRECTORY

type Imp struct {
	s       *Symbol
	off     uint64
	next    *Imp
	argsize int
}

type Dll struct {
	name     string
	nameoff  uint64
	thunkoff uint64
	ms       *Imp
	next     *Dll
}

var dr *Dll

var dexport [1024]*Symbol

var nexport int

func addpesectionWithLongName(ctxt *Link, shortname, longname string, sectsize int, filesize int) *IMAGE_SECTION_HEADER {
	if pensect == 16 {
		Errorf(nil, "too many sections")
		errorexit()
	}

	h := &sh[pensect]
	pensect++
	copy(h.Name[:], shortname)
	shNames = append(shNames, longname)
	h.VirtualSize = uint32(sectsize)
	h.VirtualAddress = uint32(nextsectoff)
	nextsectoff = int(Rnd(int64(nextsectoff)+int64(sectsize), PESECTALIGN))
	h.PointerToRawData = uint32(nextfileoff)
	if filesize > 0 {
		h.SizeOfRawData = uint32(Rnd(int64(filesize), PEFILEALIGN))
		nextfileoff += int(h.SizeOfRawData)
	}

	return h
}

func addpesection(ctxt *Link, name string, sectsize int, filesize int) *IMAGE_SECTION_HEADER {
	return addpesectionWithLongName(ctxt, name, name, sectsize, filesize)
}
func chksectoff(ctxt *Link, h *IMAGE_SECTION_HEADER, off int64) {
	if off != int64(h.PointerToRawData) {
		Errorf(nil, "%s.PointerToRawData = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.PointerToRawData)), uint64(off))
		errorexit()
	}
}

func chksectseg(ctxt *Link, h *IMAGE_SECTION_HEADER, s *Segment) {
	if s.Vaddr-PEBASE != uint64(h.VirtualAddress) {
		Errorf(nil, "%s.VirtualAddress = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.VirtualAddress)), uint64(int64(s.Vaddr-PEBASE)))
		errorexit()
	}

	if s.Fileoff != uint64(h.PointerToRawData) {
		Errorf(nil, "%s.PointerToRawData = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.PointerToRawData)), uint64(int64(s.Fileoff)))
		errorexit()
	}
}

func Peinit(ctxt *Link) {
	var l int

	switch SysArch.Family {
	// 64-bit architectures
	case sys.AMD64:
		pe64 = 1

		l = binary.Size(&oh64)
		dd = oh64.DataDirectory[:]

	// 32-bit architectures
	default:
		l = binary.Size(&oh)

		dd = oh.DataDirectory[:]
	}

	if Linkmode == LinkExternal {
		PESECTALIGN = 0
		PEFILEALIGN = 0
	}

	PEFILEHEADR = int32(Rnd(int64(len(dosstub)+binary.Size(&fh)+l+binary.Size(&sh)), PEFILEALIGN))
	if Linkmode != LinkExternal {
		PESECTHEADR = int32(Rnd(int64(PEFILEHEADR), PESECTALIGN))
	} else {
		PESECTHEADR = 0
	}
	nextsectoff = int(PESECTHEADR)
	nextfileoff = int(PEFILEHEADR)

	if Linkmode == LinkInternal {
		// some mingw libs depend on this symbol, for example, FindPESectionByName
		ctxt.xdefine("__image_base__", obj.SDATA, PEBASE)
		ctxt.xdefine("_image_base__", obj.SDATA, PEBASE)
	}

	HEADR = PEFILEHEADR
	if *FlagTextAddr == -1 {
		*FlagTextAddr = PEBASE + int64(PESECTHEADR)
	}
	if *FlagDataAddr == -1 {
		*FlagDataAddr = 0
	}
	if *FlagRound == -1 {
		*FlagRound = int(PESECTALIGN)
	}
	if *FlagDataAddr != 0 && *FlagRound != 0 {
		fmt.Printf("warning: -D0x%x is ignored because of -R0x%x\n", uint64(*FlagDataAddr), uint32(*FlagRound))
	}
}

func pewrite() {
	Cseek(0)
	if Linkmode != LinkExternal {
		Cwrite(dosstub)
		strnput("PE", 4)
	}

	binary.Write(&coutbuf, binary.LittleEndian, &fh)

	if pe64 != 0 {
		binary.Write(&coutbuf, binary.LittleEndian, &oh64)
	} else {
		binary.Write(&coutbuf, binary.LittleEndian, &oh)
	}
	if Linkmode == LinkExternal {
		for i := range sh[:pensect] {
			sh[i].VirtualAddress = 0
		}
	}
	binary.Write(&coutbuf, binary.LittleEndian, sh[:pensect])
}

func strput(s string) {
	coutbuf.WriteString(s)
	Cput(0)
	// string must be padded to even size
	if (len(s)+1)%2 != 0 {
		Cput(0)
	}
}

func initdynimport(ctxt *Link) *Dll {
	var d *Dll

	dr = nil
	var m *Imp
	for _, s := range ctxt.Syms.Allsym {
		if !s.Attr.Reachable() || s.Type != obj.SDYNIMPORT {
			continue
		}
		for d = dr; d != nil; d = d.next {
			if d.name == s.Dynimplib {
				m = new(Imp)
				break
			}
		}

		if d == nil {
			d = new(Dll)
			d.name = s.Dynimplib
			d.next = dr
			dr = d
			m = new(Imp)
		}

		// Because external link requires properly stdcall decorated name,
		// all external symbols in runtime use %n to denote that the number
		// of uinptrs this function consumes. Store the argsize and discard
		// the %n suffix if any.
		m.argsize = -1
		if i := strings.IndexByte(s.Extname, '%'); i >= 0 {
			var err error
			m.argsize, err = strconv.Atoi(s.Extname[i+1:])
			if err != nil {
				Errorf(s, "failed to parse stdcall decoration: %v", err)
			}
			m.argsize *= SysArch.PtrSize
			s.Extname = s.Extname[:i]
		}

		m.s = s
		m.next = d.ms
		d.ms = m
	}

	if Linkmode == LinkExternal {
		// Add real symbol name
		for d := dr; d != nil; d = d.next {
			for m = d.ms; m != nil; m = m.next {
				m.s.Type = obj.SDATA
				Symgrow(m.s, int64(SysArch.PtrSize))
				dynName := m.s.Extname
				// only windows/386 requires stdcall decoration
				if SysArch.Family == sys.I386 && m.argsize >= 0 {
					dynName += fmt.Sprintf("@%d", m.argsize)
				}
				dynSym := ctxt.Syms.Lookup(dynName, 0)
				dynSym.Attr |= AttrReachable
				dynSym.Type = obj.SHOSTOBJ
				r := Addrel(m.s)
				r.Sym = dynSym
				r.Off = 0
				r.Siz = uint8(SysArch.PtrSize)
				r.Type = obj.R_ADDR
			}
		}
	} else {
		dynamic := ctxt.Syms.Lookup(".windynamic", 0)
		dynamic.Attr |= AttrReachable
		dynamic.Type = obj.SWINDOWS
		for d := dr; d != nil; d = d.next {
			for m = d.ms; m != nil; m = m.next {
				m.s.Type = obj.SWINDOWS | obj.SSUB
				m.s.Sub = dynamic.Sub
				dynamic.Sub = m.s
				m.s.Value = dynamic.Size
				dynamic.Size += int64(SysArch.PtrSize)
			}

			dynamic.Size += int64(SysArch.PtrSize)
		}
	}

	return dr
}

// peimporteddlls returns the gcc command line argument to link all imported
// DLLs.
func peimporteddlls() []string {
	var dlls []string

	for d := dr; d != nil; d = d.next {
		dlls = append(dlls, "-l"+strings.TrimSuffix(d.name, ".dll"))
	}

	return dlls
}

func addimports(ctxt *Link, datsect *IMAGE_SECTION_HEADER) {
	startoff := coutbuf.Offset()
	dynamic := ctxt.Syms.Lookup(".windynamic", 0)

	// skip import descriptor table (will write it later)
	n := uint64(0)

	for d := dr; d != nil; d = d.next {
		n++
	}
	Cseek(startoff + int64(binary.Size(&IMAGE_IMPORT_DESCRIPTOR{}))*int64(n+1))

	// write dll names
	for d := dr; d != nil; d = d.next {
		d.nameoff = uint64(coutbuf.Offset()) - uint64(startoff)
		strput(d.name)
	}

	// write function names
	var m *Imp
	for d := dr; d != nil; d = d.next {
		for m = d.ms; m != nil; m = m.next {
			m.off = uint64(nextsectoff) + uint64(coutbuf.Offset()) - uint64(startoff)
			Wputl(0) // hint
			strput(m.s.Extname)
		}
	}

	// write OriginalFirstThunks
	oftbase := uint64(coutbuf.Offset()) - uint64(startoff)

	n = uint64(coutbuf.Offset())
	for d := dr; d != nil; d = d.next {
		d.thunkoff = uint64(coutbuf.Offset()) - n
		for m = d.ms; m != nil; m = m.next {
			if pe64 != 0 {
				Vputl(m.off)
			} else {
				Lputl(uint32(m.off))
			}
		}

		if pe64 != 0 {
			Vputl(0)
		} else {
			Lputl(0)
		}
	}

	// add pe section and pad it at the end
	n = uint64(coutbuf.Offset()) - uint64(startoff)

	isect := addpesection(ctxt, ".idata", int(n), int(n))
	isect.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
	chksectoff(ctxt, isect, startoff)
	strnput("", int(uint64(isect.SizeOfRawData)-n))
	endoff := coutbuf.Offset()

	// write FirstThunks (allocated in .data section)
	ftbase := uint64(dynamic.Value) - uint64(datsect.VirtualAddress) - PEBASE

	Cseek(int64(uint64(datsect.PointerToRawData) + ftbase))
	for d := dr; d != nil; d = d.next {
		for m = d.ms; m != nil; m = m.next {
			if pe64 != 0 {
				Vputl(m.off)
			} else {
				Lputl(uint32(m.off))
			}
		}

		if pe64 != 0 {
			Vputl(0)
		} else {
			Lputl(0)
		}
	}

	// finally write import descriptor table
	Cseek(startoff)

	for d := dr; d != nil; d = d.next {
		Lputl(uint32(uint64(isect.VirtualAddress) + oftbase + d.thunkoff))
		Lputl(0)
		Lputl(0)
		Lputl(uint32(uint64(isect.VirtualAddress) + d.nameoff))
		Lputl(uint32(uint64(datsect.VirtualAddress) + ftbase + d.thunkoff))
	}

	Lputl(0) //end
	Lputl(0)
	Lputl(0)
	Lputl(0)
	Lputl(0)

	// update data directory
	dd[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = isect.VirtualAddress
	dd[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = isect.VirtualSize
	dd[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = uint32(dynamic.Value - PEBASE)
	dd[IMAGE_DIRECTORY_ENTRY_IAT].Size = uint32(dynamic.Size)

	Cseek(endoff)
}

type byExtname []*Symbol

func (s byExtname) Len() int           { return len(s) }
func (s byExtname) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byExtname) Less(i, j int) bool { return s[i].Extname < s[j].Extname }

func initdynexport(ctxt *Link) {
	nexport = 0
	for _, s := range ctxt.Syms.Allsym {
		if !s.Attr.Reachable() || !s.Attr.CgoExportDynamic() {
			continue
		}
		if nexport+1 > len(dexport) {
			Errorf(s, "pe dynexport table is full")
			errorexit()
		}

		dexport[nexport] = s
		nexport++
	}

	sort.Sort(byExtname(dexport[:nexport]))
}

func addexports(ctxt *Link) {
	var e IMAGE_EXPORT_DIRECTORY

	size := binary.Size(&e) + 10*nexport + len(*flagOutfile) + 1
	for i := 0; i < nexport; i++ {
		size += len(dexport[i].Extname) + 1
	}

	if nexport == 0 {
		return
	}

	sect := addpesection(ctxt, ".edata", size, size)
	sect.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
	chksectoff(ctxt, sect, coutbuf.Offset())
	va := int(sect.VirtualAddress)
	dd[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = uint32(va)
	dd[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sect.VirtualSize

	vaName := va + binary.Size(&e) + nexport*4
	vaAddr := va + binary.Size(&e)
	vaNa := va + binary.Size(&e) + nexport*8

	e.Characteristics = 0
	e.MajorVersion = 0
	e.MinorVersion = 0
	e.NumberOfFunctions = uint32(nexport)
	e.NumberOfNames = uint32(nexport)
	e.Name = uint32(va+binary.Size(&e)) + uint32(nexport)*10 // Program names.
	e.Base = 1
	e.AddressOfFunctions = uint32(vaAddr)
	e.AddressOfNames = uint32(vaName)
	e.AddressOfNameOrdinals = uint32(vaNa)

	// put IMAGE_EXPORT_DIRECTORY
	binary.Write(&coutbuf, binary.LittleEndian, &e)

	// put EXPORT Address Table
	for i := 0; i < nexport; i++ {
		Lputl(uint32(dexport[i].Value - PEBASE))
	}

	// put EXPORT Name Pointer Table
	v := int(e.Name + uint32(len(*flagOutfile)) + 1)

	for i := 0; i < nexport; i++ {
		Lputl(uint32(v))
		v += len(dexport[i].Extname) + 1
	}

	// put EXPORT Ordinal Table
	for i := 0; i < nexport; i++ {
		Wputl(uint16(i))
	}

	// put Names
	strnput(*flagOutfile, len(*flagOutfile)+1)

	for i := 0; i < nexport; i++ {
		strnput(dexport[i].Extname, len(dexport[i].Extname)+1)
	}
	strnput("", int(sect.SizeOfRawData-uint32(size)))
}

// perelocsect relocates symbols from first in section sect, and returns
// the total number of relocations emitted.
func perelocsect(ctxt *Link, sect *Section, syms []*Symbol, base uint64) int {
	// If main section has no bits, nothing to relocate.
	if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
		return 0
	}

	relocs := 0

	sect.Reloff = uint64(coutbuf.Offset())
	for i, s := range syms {
		if !s.Attr.Reachable() {
			continue
		}
		if uint64(s.Value) >= sect.Vaddr {
			syms = syms[i:]
			break
		}
	}

	eaddr := int32(sect.Vaddr + sect.Length)
	for _, sym := range syms {
		if !sym.Attr.Reachable() {
			continue
		}
		if sym.Value >= int64(eaddr) {
			break
		}
		for ri := 0; ri < len(sym.R); ri++ {
			r := &sym.R[ri]
			if r.Done != 0 {
				continue
			}
			if r.Xsym == nil {
				Errorf(sym, "missing xsym in relocation")
				continue
			}

			if r.Xsym.Dynid < 0 {
				Errorf(sym, "reloc %d to non-coff symbol %s (outer=%s) %d", r.Type, r.Sym.Name, r.Xsym.Name, r.Sym.Type)
			}
			if !Thearch.PEreloc1(sym, r, int64(uint64(sym.Value+int64(r.Off))-base)) {
				Errorf(sym, "unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name)
			}

			relocs++
		}
	}

	sect.Rellen = uint64(coutbuf.Offset()) - sect.Reloff

	return relocs
}

// peemitsectreloc emits the relocation entries for sect.
// The actual relocations are emitted by relocfn.
// This updates the corresponding PE section table entry
// with the relocation offset and count.
func peemitsectreloc(sect *IMAGE_SECTION_HEADER, relocfn func() int) {
	sect.PointerToRelocations = uint32(coutbuf.Offset())
	// first entry: extended relocs
	Lputl(0) // placeholder for number of relocation + 1
	Lputl(0)
	Wputl(0)

	n := relocfn() + 1

	cpos := coutbuf.Offset()
	Cseek(int64(sect.PointerToRelocations))
	Lputl(uint32(n))
	Cseek(cpos)
	if n > 0x10000 {
		n = 0x10000
		sect.Characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL
	} else {
		sect.PointerToRelocations += 10 // skip the extend reloc entry
	}
	sect.NumberOfRelocations = uint16(n - 1)
}

// peemitreloc emits relocation entries for go.o in external linking.
func peemitreloc(ctxt *Link, text, data, ctors *IMAGE_SECTION_HEADER) {
	for coutbuf.Offset()&7 != 0 {
		Cput(0)
	}

	peemitsectreloc(text, func() int {
		n := perelocsect(ctxt, Segtext.Sect, ctxt.Textp, Segtext.Vaddr)
		for sect := Segtext.Sect.Next; sect != nil; sect = sect.Next {
			n += perelocsect(ctxt, sect, datap, Segtext.Vaddr)
		}
		return n
	})

	peemitsectreloc(data, func() int {
		var n int
		for sect := Segdata.Sect; sect != nil; sect = sect.Next {
			n += perelocsect(ctxt, sect, datap, Segdata.Vaddr)
		}
		return n
	})

dwarfLoop:
	for sect := Segdwarf.Sect; sect != nil; sect = sect.Next {
		for i, name := range shNames {
			if sect.Name == name {
				peemitsectreloc(&sh[i], func() int {
					return perelocsect(ctxt, sect, dwarfp, sect.Vaddr)
				})
				continue dwarfLoop
			}
		}
		Errorf(nil, "peemitsectreloc: could not find %q section", sect.Name)
	}

	peemitsectreloc(ctors, func() int {
		dottext := ctxt.Syms.Lookup(".text", 0)
		Lputl(0)
		Lputl(uint32(dottext.Dynid))
		switch obj.GOARCH {
		default:
			Errorf(dottext, "unknown architecture for PE: %q\n", obj.GOARCH)
		case "386":
			Wputl(IMAGE_REL_I386_DIR32)
		case "amd64":
			Wputl(IMAGE_REL_AMD64_ADDR64)
		}
		return 1
	})
}

func (ctxt *Link) dope() {
	/* relocation table */
	rel := ctxt.Syms.Lookup(".rel", 0)

	rel.Attr |= AttrReachable
	rel.Type = obj.SELFROSECT

	initdynimport(ctxt)
	initdynexport(ctxt)
}

func strtbladd(name string) int {
	off := len(strtbl) + 4 // offset includes 4-byte length at beginning of table
	strtbl = append(strtbl, name...)
	strtbl = append(strtbl, 0)
	return off
}

/*
 * For more than 8 characters section names, name contains a slash (/) that is
 * followed by an ASCII representation of a decimal number that is an offset into
 * the string table.
 * reference: pecoff_v8.docx Page 24.
 * <http://www.microsoft.com/whdc/system/platform/firmware/PECOFFdwn.mspx>
 */
func newPEDWARFSection(ctxt *Link, name string, size int64) *IMAGE_SECTION_HEADER {
	if size == 0 {
		return nil
	}

	off := strtbladd(name)
	s := fmt.Sprintf("/%d", off)
	h := addpesectionWithLongName(ctxt, s, name, int(size), int(size))
	h.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE

	return h
}

// writePESymTableRecords writes all COFF symbol table records.
// It returns number of records written.
func writePESymTableRecords(ctxt *Link) int {
	var symcnt int

	writeOneSymbol := func(s *Symbol, addr int64, sectidx int, typ uint16, class uint8) {
		// write COFF symbol table record
		if len(s.Name) > 8 {
			Lputl(0)
			Lputl(uint32(strtbladd(s.Name)))
		} else {
			strnput(s.Name, 8)
		}
		Lputl(uint32(addr))
		Wputl(uint16(sectidx))
		Wputl(typ)
		Cput(class)
		Cput(0) // no aux entries

		s.Dynid = int32(symcnt)

		symcnt++
	}

	put := func(ctxt *Link, s *Symbol, name string, type_ SymbolType, addr int64, gotype *Symbol) {
		if s == nil {
			return
		}
		if s.Sect == nil && type_ != UndefinedSym {
			return
		}
		switch type_ {
		default:
			return
		case DataSym, BSSSym, TextSym, UndefinedSym:
		}

		// Only windows/386 requires underscore prefix on external symbols.
		if SysArch.Family == sys.I386 &&
			Linkmode == LinkExternal &&
			(s.Type == obj.SHOSTOBJ || s.Attr.CgoExport()) {
			s.Name = "_" + s.Name
		}

		typ := uint16(IMAGE_SYM_TYPE_NULL)
		var sect int
		var value int64
		// Note: although address of runtime.edata (type SDATA) is at the start of .bss section
		// it still belongs to the .data section, not the .bss section.
		// Same for runtime.epclntab (type STEXT), it belongs to .text
		// section, not the .data section.
		if uint64(s.Value) >= Segdata.Vaddr+Segdata.Filelen && s.Type != obj.SDATA && Linkmode == LinkExternal {
			value = int64(uint64(s.Value) - Segdata.Vaddr - Segdata.Filelen)
			sect = bsssect
		} else if uint64(s.Value) >= Segdata.Vaddr && s.Type != obj.STEXT {
			value = int64(uint64(s.Value) - Segdata.Vaddr)
			sect = datasect
		} else if uint64(s.Value) >= Segtext.Vaddr {
			value = int64(uint64(s.Value) - Segtext.Vaddr)
			sect = textsect
		} else if type_ == UndefinedSym {
			typ = IMAGE_SYM_DTYPE_FUNCTION
		} else {
			Errorf(s, "addpesym %#x", addr)
		}
		if typ != IMAGE_SYM_TYPE_NULL {
		} else if Linkmode != LinkExternal {
			// TODO: fix IMAGE_SYM_DTYPE_ARRAY value and use following expression, instead of 0x0308
			typ = IMAGE_SYM_DTYPE_ARRAY<<8 + IMAGE_SYM_TYPE_STRUCT
			typ = 0x0308 // "array of structs"
		}
		class := IMAGE_SYM_CLASS_EXTERNAL
		if s.Version != 0 || (s.Type&obj.SHIDDEN != 0) || s.Attr.Local() {
			class = IMAGE_SYM_CLASS_STATIC
		}
		writeOneSymbol(s, value, sect, typ, uint8(class))
	}

	if Linkmode == LinkExternal {
		// Include section symbols as external, because
		// .ctors and .debug_* section relocations refer to it.
		for idx, name := range shNames {
			sym := ctxt.Syms.Lookup(name, 0)
			writeOneSymbol(sym, 0, idx+1, IMAGE_SYM_TYPE_NULL, IMAGE_SYM_CLASS_STATIC)
		}
	}

	genasmsym(ctxt, put)

	return symcnt
}

func addpesymtable(ctxt *Link) {
	symtabStartPos := coutbuf.Offset()

	// write COFF symbol table
	var symcnt int
	if !*FlagS || Linkmode == LinkExternal {
		symcnt = writePESymTableRecords(ctxt)
	}

	// update COFF file header and section table
	size := len(strtbl) + 4 + 18*symcnt
	var h *IMAGE_SECTION_HEADER
	if Linkmode != LinkExternal {
		// We do not really need .symtab for go.o, and if we have one, ld
		// will also include it in the exe, and that will confuse windows.
		h = addpesection(ctxt, ".symtab", size, size)
		h.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
		chksectoff(ctxt, h, symtabStartPos)
	}
	fh.PointerToSymbolTable = uint32(symtabStartPos)
	fh.NumberOfSymbols = uint32(symcnt)

	// write COFF string table
	Lputl(uint32(len(strtbl)) + 4)
	for i := 0; i < len(strtbl); i++ {
		Cput(strtbl[i])
	}
	if Linkmode != LinkExternal {
		strnput("", int(h.SizeOfRawData-uint32(size)))
	}
}

func setpersrc(ctxt *Link, sym *Symbol) {
	if rsrcsym != nil {
		Errorf(sym, "too many .rsrc sections")
	}

	rsrcsym = sym
}

func addpersrc(ctxt *Link) {
	if rsrcsym == nil {
		return
	}

	h := addpesection(ctxt, ".rsrc", int(rsrcsym.Size), int(rsrcsym.Size))
	h.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA
	chksectoff(ctxt, h, coutbuf.Offset())

	// relocation
	var p []byte
	var r *Reloc
	var val uint32
	for ri := 0; ri < len(rsrcsym.R); ri++ {
		r = &rsrcsym.R[ri]
		p = rsrcsym.P[r.Off:]
		val = uint32(int64(h.VirtualAddress) + r.Add)

		// 32-bit little-endian
		p[0] = byte(val)

		p[1] = byte(val >> 8)
		p[2] = byte(val >> 16)
		p[3] = byte(val >> 24)
	}

	Cwrite(rsrcsym.P)
	strnput("", int(int64(h.SizeOfRawData)-rsrcsym.Size))

	// update data directory
	dd[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = h.VirtualAddress

	dd[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = h.VirtualSize
}

func addinitarray(ctxt *Link) (c *IMAGE_SECTION_HEADER) {
	// The size below was determined by the specification for array relocations,
	// and by observing what GCC writes here. If the initarray section grows to
	// contain more than one constructor entry, the size will need to be 8 * constructor_count.
	// However, the entire Go runtime is initialized from just one function, so it is unlikely
	// that this will need to grow in the future.
	var size int
	switch obj.GOARCH {
	default:
		fmt.Fprintf(os.Stderr, "link: unknown architecture for PE: %q\n", obj.GOARCH)
		os.Exit(2)
	case "386":
		size = 4
	case "amd64":
		size = 8
	}

	c = addpesection(ctxt, ".ctors", size, size)
	c.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
	c.SizeOfRawData = uint32(size)

	Cseek(int64(c.PointerToRawData))
	chksectoff(ctxt, c, coutbuf.Offset())
	init_entry := ctxt.Syms.Lookup(*flagEntrySymbol, 0)
	addr := uint64(init_entry.Value) - init_entry.Sect.Vaddr

	switch obj.GOARCH {
	case "386":
		Lputl(uint32(addr))
	case "amd64":
		Vputl(addr)
	}

	return c
}

func Asmbpe(ctxt *Link) {
	switch SysArch.Family {
	default:
		Exitf("unknown PE architecture: %v", SysArch.Family)
	case sys.AMD64:
		fh.Machine = IMAGE_FILE_MACHINE_AMD64
	case sys.I386:
		fh.Machine = IMAGE_FILE_MACHINE_I386
	}

	t := addpesection(ctxt, ".text", int(Segtext.Length), int(Segtext.Length))
	t.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ
	if Linkmode == LinkExternal {
		// some data symbols (e.g. masks) end up in the .text section, and they normally
		// expect larger alignment requirement than the default text section alignment.
		t.Characteristics |= IMAGE_SCN_ALIGN_32BYTES
	}
	chksectseg(ctxt, t, &Segtext)
	textsect = pensect

	var d *IMAGE_SECTION_HEADER
	var c *IMAGE_SECTION_HEADER
	if Linkmode != LinkExternal {
		d = addpesection(ctxt, ".data", int(Segdata.Length), int(Segdata.Filelen))
		d.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
		chksectseg(ctxt, d, &Segdata)
		datasect = pensect
	} else {
		d = addpesection(ctxt, ".data", int(Segdata.Filelen), int(Segdata.Filelen))
		d.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_ALIGN_32BYTES
		chksectseg(ctxt, d, &Segdata)
		datasect = pensect

		b := addpesection(ctxt, ".bss", int(Segdata.Length-Segdata.Filelen), 0)
		b.Characteristics = IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_ALIGN_32BYTES
		b.PointerToRawData = 0
		bsssect = pensect
	}

	if !*FlagS {
		dwarfaddpeheaders(ctxt)
	}

	if Linkmode == LinkExternal {
		c = addinitarray(ctxt)
	}

	Cseek(int64(nextfileoff))
	if Linkmode != LinkExternal {
		addimports(ctxt, d)
		addexports(ctxt)
	}
	addpesymtable(ctxt)
	addpersrc(ctxt)
	if Linkmode == LinkExternal {
		peemitreloc(ctxt, t, d, c)
	}

	fh.NumberOfSections = uint16(pensect)

	// Being able to produce identical output for identical input is
	// much more beneficial than having build timestamp in the header.
	fh.TimeDateStamp = 0

	if Linkmode == LinkExternal {
		fh.Characteristics = IMAGE_FILE_LINE_NUMS_STRIPPED
	} else {
		fh.Characteristics = IMAGE_FILE_RELOCS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DEBUG_STRIPPED
	}
	if pe64 != 0 {
		fh.SizeOfOptionalHeader = uint16(binary.Size(&oh64))
		fh.Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE
		oh64.Magic = 0x20b // PE32+
	} else {
		fh.SizeOfOptionalHeader = uint16(binary.Size(&oh))
		fh.Characteristics |= IMAGE_FILE_32BIT_MACHINE
		oh.Magic = 0x10b // PE32
		oh.BaseOfData = d.VirtualAddress
	}

	// Fill out both oh64 and oh. We only use one. Oh well.
	oh64.MajorLinkerVersion = 3

	oh.MajorLinkerVersion = 3
	oh64.MinorLinkerVersion = 0
	oh.MinorLinkerVersion = 0
	oh64.SizeOfCode = t.SizeOfRawData
	oh.SizeOfCode = t.SizeOfRawData
	oh64.SizeOfInitializedData = d.SizeOfRawData
	oh.SizeOfInitializedData = d.SizeOfRawData
	oh64.SizeOfUninitializedData = 0
	oh.SizeOfUninitializedData = 0
	if Linkmode != LinkExternal {
		oh64.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
		oh.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
	}
	oh64.BaseOfCode = t.VirtualAddress
	oh.BaseOfCode = t.VirtualAddress
	oh64.ImageBase = PEBASE
	oh.ImageBase = PEBASE
	oh64.SectionAlignment = uint32(PESECTALIGN)
	oh.SectionAlignment = uint32(PESECTALIGN)
	oh64.FileAlignment = uint32(PEFILEALIGN)
	oh.FileAlignment = uint32(PEFILEALIGN)
	oh64.MajorOperatingSystemVersion = 4
	oh.MajorOperatingSystemVersion = 4
	oh64.MinorOperatingSystemVersion = 0
	oh.MinorOperatingSystemVersion = 0
	oh64.MajorImageVersion = 1
	oh.MajorImageVersion = 1
	oh64.MinorImageVersion = 0
	oh.MinorImageVersion = 0
	oh64.MajorSubsystemVersion = 4
	oh.MajorSubsystemVersion = 4
	oh64.MinorSubsystemVersion = 0
	oh.MinorSubsystemVersion = 0
	oh64.SizeOfImage = uint32(nextsectoff)
	oh.SizeOfImage = uint32(nextsectoff)
	oh64.SizeOfHeaders = uint32(PEFILEHEADR)
	oh.SizeOfHeaders = uint32(PEFILEHEADR)
	if windowsgui {
		oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
		oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
	} else {
		oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
		oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
	}

	// Disable stack growth as we don't want Windows to
	// fiddle with the thread stack limits, which we set
	// ourselves to circumvent the stack checks in the
	// Windows exception dispatcher.
	// Commit size must be strictly less than reserve
	// size otherwise reserve will be rounded up to a
	// larger size, as verified with VMMap.

	// Go code would be OK with 64k stacks, but we need larger stacks for cgo.
	//
	// The default stack reserve size affects only the main
	// thread, ctrlhandler thread, and profileloop thread. For
	// these, it must be greater than the stack size assumed by
	// externalthreadhandler.
	//
	// For other threads we specify stack size in runtime explicitly
	// (runtime knows whether cgo is enabled or not).
	// For these, the reserve must match STACKSIZE in
	// runtime/cgo/gcc_windows_{386,amd64}.c and the correspondent
	// CreateThread parameter in runtime.newosproc.
	if !iscgo {
		oh64.SizeOfStackReserve = 0x00020000
		oh.SizeOfStackReserve = 0x00020000
		oh64.SizeOfStackCommit = 0x00001000
		oh.SizeOfStackCommit = 0x00001000
	} else {
		oh64.SizeOfStackReserve = 0x00200000
		oh.SizeOfStackReserve = 0x00100000

		// account for 2 guard pages
		oh64.SizeOfStackCommit = 0x00200000 - 0x2000

		oh.SizeOfStackCommit = 0x00100000 - 0x2000
	}

	oh64.SizeOfHeapReserve = 0x00100000
	oh.SizeOfHeapReserve = 0x00100000
	oh64.SizeOfHeapCommit = 0x00001000
	oh.SizeOfHeapCommit = 0x00001000
	oh64.NumberOfRvaAndSizes = 16
	oh.NumberOfRvaAndSizes = 16

	pewrite()
}


text:
package ee.signwise.sdk.model;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;

/**
 * PDF Signature confirmation info returned by SignWise services
 */
public class PdfSignatureConfirmationInfo {
	private String m_responderId;
	private Date m_producedAt;
	private CertificateInfo m_certificate;

	/**
	 * Constructor for PdfSignatureConfirmationInfo
	 * @param responderId OCSP responder id
	 * @param producedAt OCSP response producedAt time
	*/
	public PdfSignatureConfirmationInfo(String responderId, Date producedAt)
	{
		m_responderId = responderId;
		m_producedAt = producedAt;
	}

	/**
	 * Constructor for PdfSignatureConfirmationInfo
	 * @param jobj JSON object
	 */
	public PdfSignatureConfirmationInfo(JSONObject jobj)
	{
		m_responderId = jobj.optString("responderId");
		long lTime = jobj.optLong("producedAt");
		if(lTime > 0)
			m_producedAt = new Date(lTime);
		JSONObject joCert = jobj.optJSONObject("certificate");
		if(joCert != null)
			m_certificate = new CertificateInfo(joCert);
	}

	/**
	 * Returns OCSP responder id
	 * @return OCSP responder id
	 */
	public String getResponderId()
	{
		return m_responderId;
	}

	/**
	 * Returns OCSP response producedAt time
	 * @return OCSP response producedAt time
	 */
	public Date getProducedAt()
	{
		return m_producedAt;
	}

	/**
	 * Returns JSON form for transmission
	 * @return objects JSON form
	 */
	public JSONObject toJSON()
	{
		JSONObject jobj = new JSONObject();
		jobj.putOpt("responderId", m_responderId);
		if(m_producedAt != null)
			jobj.put("producedAt", m_producedAt);
		if(m_certificate != null)
			jobj.put("certificate", m_certificate.toJSON());
		return jobj;
	}

	/**
	 * Returns stringified form for info
	 * @return objects stringified form
	 */
	public String toString()
	{
		return toJSON().toString();
	}
}


text:
package pow.frontend.window;

import pow.backend.GameBackend;
import pow.frontend.Frontend;
import pow.frontend.Style;
import pow.frontend.WindowDim;
import pow.frontend.utils.ImageController;
import pow.frontend.utils.KeyInput;
import pow.frontend.utils.KeyUtils;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

public class LoseWindow extends AbstractWindow {

    private final BufferedImage splashImage;

    public LoseWindow(WindowDim dim, boolean visible, GameBackend backend, Frontend frontend) {
        super(dim, visible, backend, frontend);
        splashImage = ImageController.getGameOverImage();
        int width = splashImage.getWidth();
        int height = splashImage.getHeight();
        this.dim = this.frontend.layout.center(width + 2 * Style.SMALL_MARGIN, height + 2 * Style.SMALL_MARGIN);
    }

    @Override
    public void processKey(KeyEvent e) {
        KeyInput input = KeyUtils.getKeyInput(e);
        if (input == KeyInput.OKAY) {
            frontend.setState(Frontend.State.OPEN_GAME);
        }
    }

    @Override
    public void drawContents(Graphics graphics) {
        graphics.setColor(Style.BACKGROUND_COLOR);
        graphics.fillRect(0, 0, dim.width, dim.height);
        graphics.drawImage(splashImage, Style.SMALL_MARGIN, Style.SMALL_MARGIN, null);

        graphics.setFont(Style.getBigFont());
        graphics.setColor(Color.WHITE);
        graphics.drawString("You died.", 50, 45);
        graphics.drawString("Press [enter] to continue.", 50, dim.height - 35);
    }
}


text:
package com.google.android.exoplayer2.text.subrip;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.SimpleSubtitleDecoder;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.LongArray;
import com.google.android.exoplayer2.util.ParsableByteArray;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A {@link SimpleSubtitleDecoder} for SubRip.
 */
public final class SubripDecoder extends SimpleSubtitleDecoder {

  // Fractional positions for use when alignment tags are present.
  private static final float START_FRACTION = 0.08f;
  private static final float END_FRACTION = 1 - START_FRACTION;
  private static final float MID_FRACTION = 0.5f;

  private static final String TAG = "SubripDecoder";

  // Some SRT files don't include hours or milliseconds in the timecode, so we use optional groups.
  private static final String SUBRIP_TIMECODE = "(?:(\\d+):)?(\\d+):(\\d+)(?:,(\\d+))?";
  private static final Pattern SUBRIP_TIMING_LINE =
      Pattern.compile("\\s*(" + SUBRIP_TIMECODE + ")\\s*-->\\s*(" + SUBRIP_TIMECODE + ")\\s*");

  // NOTE: Android Studio's suggestion to simplify '\\}' is incorrect [internal: b/144480183].
  private static final Pattern SUBRIP_TAG_PATTERN = Pattern.compile("\\{\\\\.*?\\}");
  private static final String SUBRIP_ALIGNMENT_TAG = "\\{\\\\an[1-9]\\}";

  // Alignment tags for SSA V4+.
  private static final String ALIGN_BOTTOM_LEFT = "{\\an1}";
  private static final String ALIGN_BOTTOM_MID = "{\\an2}";
  private static final String ALIGN_BOTTOM_RIGHT = "{\\an3}";
  private static final String ALIGN_MID_LEFT = "{\\an4}";
  private static final String ALIGN_MID_MID = "{\\an5}";
  private static final String ALIGN_MID_RIGHT = "{\\an6}";
  private static final String ALIGN_TOP_LEFT = "{\\an7}";
  private static final String ALIGN_TOP_MID = "{\\an8}";
  private static final String ALIGN_TOP_RIGHT = "{\\an9}";

  private final StringBuilder textBuilder;
  private final ArrayList<String> tags;

  public SubripDecoder() {
    super("SubripDecoder");
    textBuilder = new StringBuilder();
    tags = new ArrayList<>();
  }

  @Override
  protected Subtitle decode(byte[] bytes, int length, boolean reset) {
    ArrayList<Cue> cues = new ArrayList<>();
    LongArray cueTimesUs = new LongArray();
    ParsableByteArray subripData = new ParsableByteArray(bytes, length);

    @Nullable String currentLine;
    while ((currentLine = subripData.readLine()) != null) {
      if (currentLine.length() == 0) {
        // Skip blank lines.
        continue;
      }

      // Parse the index line as a sanity check.
      try {
        Integer.parseInt(currentLine);
      } catch (NumberFormatException e) {
        Log.w(TAG, "Skipping invalid index: " + currentLine);
        continue;
      }

      // Read and parse the timing line.
      currentLine = subripData.readLine();
      if (currentLine == null) {
        Log.w(TAG, "Unexpected end");
        break;
      }

      Matcher matcher = SUBRIP_TIMING_LINE.matcher(currentLine);
      if (matcher.matches()) {
        cueTimesUs.add(parseTimecode(matcher, /* groupOffset= */ 1));
        cueTimesUs.add(parseTimecode(matcher, /* groupOffset= */ 6));
      } else {
        Log.w(TAG, "Skipping invalid timing: " + currentLine);
        continue;
      }

      // Read and parse the text and tags.
      textBuilder.setLength(0);
      tags.clear();
      currentLine = subripData.readLine();
      while (!TextUtils.isEmpty(currentLine)) {
        if (textBuilder.length() > 0) {
          textBuilder.append("<br>");
        }
        textBuilder.append(processLine(currentLine, tags));
        currentLine = subripData.readLine();
      }

      Spanned text = Html.fromHtml(textBuilder.toString());

      @Nullable String alignmentTag = null;
      for (int i = 0; i < tags.size(); i++) {
        String tag = tags.get(i);
        if (tag.matches(SUBRIP_ALIGNMENT_TAG)) {
          alignmentTag = tag;
          // Subsequent alignment tags should be ignored.
          break;
        }
      }
      cues.add(buildCue(text, alignmentTag));
      cues.add(Cue.EMPTY);
    }

    Cue[] cuesArray = cues.toArray(new Cue[0]);
    long[] cueTimesUsArray = cueTimesUs.toArray();
    return new SubripSubtitle(cuesArray, cueTimesUsArray);
  }

  /**
   * Trims and removes tags from the given line. The removed tags are added to {@code tags}.
   *
   * @param line The line to process.
   * @param tags A list to which removed tags will be added.
   * @return The processed line.
   */
  private String processLine(String line, ArrayList<String> tags) {
    line = line.trim();

    int removedCharacterCount = 0;
    StringBuilder processedLine = new StringBuilder(line);
    Matcher matcher = SUBRIP_TAG_PATTERN.matcher(line);
    while (matcher.find()) {
      String tag = matcher.group();
      tags.add(tag);
      int start = matcher.start() - removedCharacterCount;
      int tagLength = tag.length();
      processedLine.replace(start, /* end= */ start + tagLength, /* str= */ "");
      removedCharacterCount += tagLength;
    }

    return processedLine.toString();
  }

  /**
   * Build a {@link Cue} based on the given text and alignment tag.
   *
   * @param text The text.
   * @param alignmentTag The alignment tag, or {@code null} if no alignment tag is available.
   * @return Built cue
   */
  private Cue buildCue(Spanned text, @Nullable String alignmentTag) {
    if (alignmentTag == null) {
      return new Cue(text);
    }

    // Horizontal alignment.
    @Cue.AnchorType int positionAnchor;
    switch (alignmentTag) {
      case ALIGN_BOTTOM_LEFT:
      case ALIGN_MID_LEFT:
      case ALIGN_TOP_LEFT:
        positionAnchor = Cue.ANCHOR_TYPE_START;
        break;
      case ALIGN_BOTTOM_RIGHT:
      case ALIGN_MID_RIGHT:
      case ALIGN_TOP_RIGHT:
        positionAnchor = Cue.ANCHOR_TYPE_END;
        break;
      case ALIGN_BOTTOM_MID:
      case ALIGN_MID_MID:
      case ALIGN_TOP_MID:
      default:
        positionAnchor = Cue.ANCHOR_TYPE_MIDDLE;
        break;
    }

    // Vertical alignment.
    @Cue.AnchorType int lineAnchor;
    switch (alignmentTag) {
      case ALIGN_BOTTOM_LEFT:
      case ALIGN_BOTTOM_MID:
      case ALIGN_BOTTOM_RIGHT:
        lineAnchor = Cue.ANCHOR_TYPE_END;
        break;
      case ALIGN_TOP_LEFT:
      case ALIGN_TOP_MID:
      case ALIGN_TOP_RIGHT:
        lineAnchor = Cue.ANCHOR_TYPE_START;
        break;
      case ALIGN_MID_LEFT:
      case ALIGN_MID_MID:
      case ALIGN_MID_RIGHT:
      default:
        lineAnchor = Cue.ANCHOR_TYPE_MIDDLE;
        break;
    }

    return new Cue(
        text,
        /* textAlignment= */ null,
        getFractionalPositionForAnchorType(lineAnchor),
        Cue.LINE_TYPE_FRACTION,
        lineAnchor,
        getFractionalPositionForAnchorType(positionAnchor),
        positionAnchor,
        Cue.DIMEN_UNSET);
  }

  private static long parseTimecode(Matcher matcher, int groupOffset) {
    @Nullable String hours = matcher.group(groupOffset + 1);
    long timestampMs = hours != null ? Long.parseLong(hours) * 60 * 60 * 1000 : 0;
    timestampMs +=
        Long.parseLong(Assertions.checkNotNull(matcher.group(groupOffset + 2))) * 60 * 1000;
    timestampMs += Long.parseLong(Assertions.checkNotNull(matcher.group(groupOffset + 3))) * 1000;
    @Nullable String millis = matcher.group(groupOffset + 4);
    if (millis != null) {
      timestampMs += Long.parseLong(millis);
    }
    return timestampMs * 1000;
  }

  /* package */ static float getFractionalPositionForAnchorType(@Cue.AnchorType int anchorType) {
    switch (anchorType) {
      case Cue.ANCHOR_TYPE_START:
        return SubripDecoder.START_FRACTION;
      case Cue.ANCHOR_TYPE_MIDDLE:
        return SubripDecoder.MID_FRACTION;
      case Cue.ANCHOR_TYPE_END:
        return SubripDecoder.END_FRACTION;
      case Cue.TYPE_UNSET:
      default:
        // Should never happen.
        throw new IllegalArgumentException();
    }
  }
}


text:
package com.securionpay.response;

import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.securionpay.enums.PayoutTransactionType;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import static com.securionpay.util.SecurionPayUtils.toStringNullSafe;

public class PayoutTransaction {
    private String id;
    private Long created;
    private String type;
    private Long amount;
    private String currency;
    private String description;
    private Long fee;
    private String source;
    private String payout;
    private BigDecimal exchangeRate;

    @JsonIgnore
    private Map<String, Object> other = new HashMap<>();

    public String getId() {
        return id;
    }

    public Long getCreated() {
        return created;
    }

    public PayoutTransactionType getType() {
        return PayoutTransactionType.fromValue(type);
    }

    public String getTypeAsString() {
        return type;
    }

    public Long getAmount() {
        return amount;
    }

    public String getCurrency() {
        return currency;
    }

    public String getDescription() {
        return description;
    }

    public Long getFee() {
        return fee;
    }

    public String getSource() {
        return source;
    }

    public String getPayout() {
        return payout;
    }

    public BigDecimal getExchangeRate() {
        return exchangeRate;
    }

    public String get(String name) {
        return toStringNullSafe(other.get(name));
    }

    @JsonAnySetter
    private void set(String name, Object value) {
        other.put(name, value);
    }
}


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Microsoft Public License (MS-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
//
//   The terms "reproduce," "reproduction," "derivative works," and
//   "distribution" have the same meaning here as under U.S. copyright law. A
//   "contribution" is the original software, or any additions or changes to
//   the software. A "contributor" is any person that distributes its
//   contribution under this license. "Licensed patents" are a contributor's
//   patent claims that read directly on its contribution.
//
// 2. Grant of Rights
//
//   (A) Copyright Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free copyright license
//       to reproduce its contribution, prepare derivative works of its
//       contribution, and distribute its contribution or any derivative works
//       that you create.
//
//   (B) Patent Grant- Subject to the terms of this license, including the
//       license conditions and limitations in section 3, each contributor
//       grants you a non-exclusive, worldwide, royalty-free license under its
//       licensed patents to make, have made, use, sell, offer for sale,
//       import, and/or otherwise dispose of its contribution in the software
//       or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
//
//   (A) No Trademark License- This license does not grant you rights to use
//       any contributors' name, logo, or trademarks.
//
//   (B) If you bring a patent claim against any contributor over patents that
//       you claim are infringed by the software, your patent license from such
//       contributor to the software ends automatically.
//
//   (C) If you distribute any portion of the software, you must retain all
//       copyright, patent, trademark, and attribution notices that are present
//       in the software.
//
//   (D) If you distribute any portion of the software in source code form, you
//       may do so only under this license by including a complete copy of this
//       license with your distribution. If you distribute any portion of the
//       software in compiled or object code form, you may only do so under a
//       license that complies with this license.
//
//   (E) The software is licensed "as-is." You bear the risk of using it. The
//       contributors give no express warranties, guarantees or conditions. You
//       may have additional consumer rights under your local laws which this
//       license cannot change. To the extent permitted under your local laws,
//       the contributors exclude the implied warranties of merchantability,
//       fitness for a particular purpose and non-infringement.
//

using System;

namespace Microsoft.ClearScript
{
    internal class BindSignature : IEquatable<BindSignature>
    {
        private readonly TargetInfo targetInfo;
        private readonly string name;
        private readonly Type[] typeArgs;
        private readonly ArgInfo[] argData;

        public BindSignature(HostTarget target, string name, Type[] typeArgs, object[] args)
        {
            targetInfo = new TargetInfo(target);
            this.typeArgs = typeArgs;
            this.name = name;

            argData = new ArgInfo[args.Length];
            for (var index = 0; index < args.Length; index++)
            {
                argData[index] = new ArgInfo(args[index]);
            }
        }

        #region Object overrides

        public override bool Equals(object obj)
        {
            return Equals(obj as BindSignature);
        }

        public override int GetHashCode()
        {
            var accumulator = new HashAccumulator();

            targetInfo.UpdateHash(ref accumulator);
            accumulator.Update(name);

            foreach (var type in typeArgs)
            {
                accumulator.Update(type);
            }

            foreach (var argInfo in argData)
            {
                argInfo.UpdateHash(ref accumulator);
            }

            return accumulator.HashCode;
        }

        #endregion

        #region IEquatable<BindSignature> implementation

        public bool Equals(BindSignature that)
        {
            if (that == null)
            {
                return false;
            }

            if (!targetInfo.Equals(that.targetInfo))
            {
                return false;
            }

            if (name != that.name)
            {
                return false;
            }

            if (typeArgs.Length != that.typeArgs.Length)
            {
                return false;
            }

            for (var index = 0; index < typeArgs.Length; index++)
            {
                if (typeArgs[index] != that.typeArgs[index])
                {
                    return false;
                }
            }

            if (argData.Length != that.argData.Length)
            {
                return false;
            }

            for (var index = 0; index < argData.Length; index++)
            {
                if (!argData[index].Equals(that.argData[index]))
                {
                    return false;
                }
            }

            return true;
        }

        #endregion

        #region Nested type: TargetKind

        private enum TargetKind
        {
            Static,
            Null,
            Instance
        }

        #endregion

        #region Nested type: TargetInfo

        private class TargetInfo : IEquatable<TargetInfo>
        {
            private readonly TargetKind kind;
            private readonly Type targetType;
            private readonly Type instanceType;

            public TargetInfo(HostTarget target)
            {
                if (target is HostType)
                {
                    kind = TargetKind.Static;
                    targetType = target.Type;
                }
                else if (target.InvokeTarget == null)
                {
                    kind = TargetKind.Null;
                    targetType = target.Type;
                }
                else
                {
                    kind = TargetKind.Instance;
                    targetType = target.Type;

                    var tempType = target.InvokeTarget.GetType();
                    if (tempType != targetType)
                    {
                        instanceType = tempType;
                    }
                }
            }

            public void UpdateHash(ref HashAccumulator accumulator)
            {
                accumulator.Update((int)kind);
                accumulator.Update(targetType);
                accumulator.Update(instanceType);
            }

            #region Object overrides

            public override bool Equals(object obj)
            {
                return Equals(obj as TargetInfo);
            }

            public override int GetHashCode()
            {
                var accumulator = new HashAccumulator();
                UpdateHash(ref accumulator);
                return accumulator.HashCode;
            }

            #endregion

            #region IEquatable<TargetInfo> implementation

            public bool Equals(TargetInfo that)
            {
                return (that != null) && (kind == that.kind) && (targetType == that.targetType) && (instanceType == that.instanceType);
            }

            #endregion
        }

        #endregion

        #region Nested type: ArgKind

        private enum ArgKind
        {
            Null,
            ByValue,
            Out,
            Ref
        }

        #endregion

        #region Nested type: ArgInfo

        private class ArgInfo : IEquatable<ArgInfo>
        {
            private readonly ArgKind kind;
            private readonly Type type;

            public ArgInfo(object arg)
            {
                if (arg == null)
                {
                    kind = ArgKind.Null;
                    return;
                }

                var outArg = arg as IOutArg;
                if (outArg != null)
                {
                    kind = ArgKind.Out;
                    type = outArg.Type;
                    return;
                }

                var refArg = arg as IRefArg;
                if (refArg != null)
                {
                    kind = ArgKind.Ref;
                    type = refArg.Type;
                    return;
                }

                var hostType = arg as HostType;
                if (hostType != null)
                {
                    kind = ArgKind.ByValue;
                    type = typeof(HostType);
                    return;
                }

                var hostMethod = arg as HostMethod;
                if (hostMethod != null)
                {
                    kind = ArgKind.ByValue;
                    type = typeof(HostMethod);
                    return;
                }

                var hostIndexedProperty = arg as HostIndexedProperty;
                if (hostIndexedProperty != null)
                {
                    kind = ArgKind.ByValue;
                    type = typeof(HostIndexedProperty);
                    return;
                }

                var scriptMethod = arg as ScriptMethod;
                if (scriptMethod != null)
                {
                    kind = ArgKind.ByValue;
                    type = typeof(ScriptMethod);
                    return;
                }

                var hostTarget = arg as HostTarget;
                if (hostTarget != null)
                {
                    kind = ArgKind.ByValue;
                    type = hostTarget.Type;
                    return;
                }

                kind = ArgKind.ByValue;
                type = arg.GetType();
            }

            public void UpdateHash(ref HashAccumulator accumulator)
            {
                accumulator.Update((int)kind);
                accumulator.Update(type);
            }

            #region Object overrides

            public override bool Equals(object obj)
            {
                return Equals(obj as ArgInfo);
            }

            public override int GetHashCode()
            {
                var accumulator = new HashAccumulator();
                UpdateHash(ref accumulator);
                return accumulator.HashCode;
            }

            #endregion

            #region IEquatable<ArgInfo> implementation

            public bool Equals(ArgInfo that)
            {
                return (that != null) && (kind == that.kind) && (type == that.type);
            }

            #endregion
        }

        #endregion

        #region Nested type: HashAccumulator

        private struct HashAccumulator
        {
            public int HashCode { get; private set; }

            public void Update(int value)
            {
                HashCode = unchecked((HashCode * 31) + value);
            }

            public void Update(object obj)
            {
                HashCode = unchecked((HashCode * 31) + ((obj != null) ? obj.GetHashCode() : 0));
            }
        }

        #endregion
    }
}


text:
define(
//begin v1.x content
({
	insertEntity: "Insertion d'un symbole"
})

//end v1.x content
);


text:
package com.ctrip.zeus.dao.entity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

public class AuthRoleE {
    private Long id;

    private String name;

    private String discription;

    private Date datachangeLasttime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getDiscription() {
        return discription;
    }

    public void setDiscription(String discription) {
        this.discription = discription == null ? null : discription.trim();
    }

    public Date getDatachangeLasttime() {
        return datachangeLasttime;
    }

    public void setDatachangeLasttime(Date datachangeLasttime) {
        this.datachangeLasttime = datachangeLasttime;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", discription=").append(discription);
        sb.append(", datachangeLasttime=").append(datachangeLasttime);
        sb.append("]");
        return sb.toString();
    }

    public static AuthRoleE.Builder builder() {
        return new AuthRoleE.Builder();
    }

    public static class Builder {
        private AuthRoleE obj;

        public Builder() {
            this.obj = new AuthRoleE();
        }

        public Builder id(Long id) {
            obj.setId(id);
            return this;
        }

        public Builder name(String name) {
            obj.setName(name);
            return this;
        }

        public Builder discription(String discription) {
            obj.setDiscription(discription);
            return this;
        }

        public Builder datachangeLasttime(Date datachangeLasttime) {
            obj.setDatachangeLasttime(datachangeLasttime);
            return this;
        }

        public AuthRoleE build() {
            return this.obj;
        }
    }

    public enum Column {
        id("id", "id", "BIGINT", false),
        name("name", "name", "VARCHAR", true),
        discription("discription", "discription", "VARCHAR", false),
        datachangeLasttime("DataChange_LastTime", "datachangeLasttime", "TIMESTAMP", false);

        private static final String BEGINNING_DELIMITER = "`";

        private static final String ENDING_DELIMITER = "`";

        private final String column;

        private final boolean isColumnNameDelimited;

        private final String javaProperty;

        private final String jdbcType;

        public String value() {
            return this.column;
        }

        public String getValue() {
            return this.column;
        }

        public String getJavaProperty() {
            return this.javaProperty;
        }

        public String getJdbcType() {
            return this.jdbcType;
        }

        Column(String column, String javaProperty, String jdbcType, boolean isColumnNameDelimited) {
            this.column = column;
            this.javaProperty = javaProperty;
            this.jdbcType = jdbcType;
            this.isColumnNameDelimited = isColumnNameDelimited;
        }

        public String desc() {
            return this.getEscapedColumnName() + " DESC";
        }

        public String asc() {
            return this.getEscapedColumnName() + " ASC";
        }

        public static Column[] excludes(Column ... excludes) {
            ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));
            if (excludes != null && excludes.length > 0) {
                columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));
            }
            return columns.toArray(new Column[]{});
        }

        public String getEscapedColumnName() {
            if (this.isColumnNameDelimited) {
                return new StringBuilder().append(BEGINNING_DELIMITER).append(this.column).append(ENDING_DELIMITER).toString();
            } else {
                return this.column;
            }
        }

        public String getAliasedEscapedColumnName() {
            return this.getEscapedColumnName();
        }
    }
}


text:
"""
The process of translating JS will go like that:        # TOP = 'imports and scope set'

1. Remove all the comments
2. Replace number, string and regexp literals with markers
4. Remove global Functions and move their translation to the TOP. Also add register code there.
5. Replace inline functions with lvals
6. Remove List and Object literals and replace them with lvals
7. Find and remove var declarations, generate python register code that would go on TOP.

Here we should be left with global code only where 1 line of js code = 1 line of python code.
Routine translating this code should be called glob_translate:
1. Search for outer structures and translate them using glob and inside using exps_translate

exps_translate routine:
1. Remove outer {}
2. Split lines at ;
3. Convert line by line using exp_translate
4. In case of error in 3 try to insert ; according to ECMA rules and repeat 3.

exp_translate routine:
It takes a single line of JS code and returns a SINGLE line of Python code.
Note var is not present here because it was removed in previous stages.
If case of parsing errors it must return a pos of error.
1. Convert all assignment operations to put operations, this may be hard :(
2. Convert all gets and calls to get and callprop.
3. Convert unary operators like typeof, new, !, delete.
   Delete can be handled by replacing last get method with delete.
4. Convert remaining operators that are not handled by python eg: === and ,

lval format PyJsLvalNR
marker PyJs(TYPE_NAME)(NR)

TODO
1. Number literal replacement
2. Array literal replacement
3. Object literal replacement
5. Function replacement
4. Literal replacement translators

"""

from utils import *

OP_METHODS = {'*': '__mul__',
              '/': '__div__',
              '%': '__mod__',
              '+': '__add__',
              '-': '__sub__',
              '<<': '__lshift__',
              '>>': '__rshift__',
              '&': '__and__',
              '^': '__xor__',
              '|': '__or__'}

def dbg(source):
    try:
        with open('C:\Users\Piotrek\Desktop\dbg.py','w') as f:
            f.write(source)
    except:
        pass

def indent(lines, ind=4):
    return ind*' '+lines.replace('\n', '\n'+ind*' ').rstrip(' ')

def inject_before_lval(source, lval, code):
    if source.count(lval)>1:
        dbg(source)
        print
        print lval
        raise RuntimeError('To many lvals (%s)' % lval)
    elif not source.count(lval):
        dbg(source)
        print
        print lval
        assert lval not in source
        raise RuntimeError('No lval found "%s"' % lval)
    end = source.index(lval)
    inj = source.rfind('\n', 0, end)
    ind = inj
    while source[ind+1]==' ':
        ind+=1
    ind -= inj
    return source[:inj+1]+ indent(code, ind) + source[inj+1:]

def bracket_split(source, brackets=('()','{}','[]'), strip=False):
    """DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)"""
    starts = [e[0] for e in brackets]
    in_bracket = 0
    n = 0
    last = 0
    while n<len(source):
        e = source[n]
        if not in_bracket and e in starts:
            in_bracket = 1
            start = n
            b_start, b_end = brackets[starts.index(e)]
        elif in_bracket:
            if e==b_start:
                in_bracket += 1
            elif e==b_end:
                in_bracket -= 1
                if not in_bracket:
                    if source[last:start]:
                        yield source[last:start]
                    last = n+1
                    yield source[start+strip:n+1-strip]
        n+=1
    if source[last:]:
        yield source[last:]

def pass_bracket(source, start, bracket='()'):
    """Returns content of brackets with brackets and first pos after brackets
     if source[start] is followed by some optional white space and brackets.
     Otherwise None"""
    e = bracket_split(source[start:],[bracket], False)
    try:
        cand = e.next()
    except StopIteration:
        return None, None
    if not cand.strip(): #white space...
        try:
            res = e.next()
            return res, start + len(cand) + len(res)
        except StopIteration:
            return None, None
    elif cand[-1] == bracket[1]:
        return cand, start + len(cand)
    else:
        return None, None

def startswith_keyword(start, keyword):
    start = start.lstrip()
    if start.startswith(keyword):
        if len(keyword)<len(start):
            if start[len(keyword)] in IDENTIFIER_PART:
                return False
        return True
    return False

def endswith_keyword(ending, keyword):
    ending = ending.rstrip()
    if ending.endswith(keyword):
        if len(keyword)<len(ending):
            if ending[len(ending)-len(keyword)-1] in IDENTIFIER_PART:
                return False
        return True
    return False

def pass_white(source, start):
    n = start
    while n<len(source):
        if source[n] in SPACE:
            n += 1
        else:
            break
    return n

def except_token(source, start, token, throw=True):
    """Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw
    otherwise returns None"""
    start = pass_white(source, start)
    if start<len(source) and source[start]==token:
        return start+1
    if throw:
        raise SyntaxError('Missing token. Expected %s'%token)
    return None

def except_keyword(source, start, keyword):
    """ Returns position after keyword if found else None
        Note: skips white space"""
    start = pass_white(source, start)
    kl = len(keyword)  #keyword len
    if kl+start > len(source):
        return None
    if source[start:start+kl] != keyword:
        return None
    if kl+start<len(source) and source[start+kl] in IDENTIFIER_PART:
        return None
    return start + kl

def parse_identifier(source, start, throw=True):
    """passes white space from start and returns first identifier,
       if identifier invalid and throw raises SyntaxError otherwise returns None"""
    start = pass_white(source, start)
    end = start
    if not end<len(source):
        if throw:
            raise SyntaxError('Missing identifier!')
        return None
    if source[end] not in IDENTIFIER_START:
        if throw:
            raise SyntaxError('Invalid identifier start: "%s"'%source[end])
        return None
    end += 1
    while end < len(source) and source[end] in IDENTIFIER_PART:
        end += 1
    if not is_valid_lval(source[start:end]):
        if throw:
            raise SyntaxError('Invalid identifier name: "%s"'%source[start:end])
        return None
    return source[start:end], end

def argsplit(args, sep=','):
    """used to split JS args (it is not that simple as it seems because
       sep can be inside brackets).

       pass args *without* brackets!

       Used also to parse array and object elements, and more"""
    parsed_len  = 0
    last = 0
    splits = []
    for e in bracket_split(args, brackets=['()', '[]', '{}']):
        if e[0] not in ['(', '[', '{']:
            for i, char in enumerate(e):
                if char==sep:
                    splits.append(args[last:parsed_len+i])
                    last = parsed_len + i + 1
        parsed_len += len(e)
    splits.append(args[last:])
    return splits

def split_add_ops(text):
    """Specialized function splitting text at add/sub operators.
    Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3']"""
    n = 0
    text = text.replace('++', '##').replace('--', '@@') #text does not normally contain any of these
    spotted = False # set to true if noticed anything other than +- or white space
    last = 0
    while n<len(text):
        e = text[n]
        if e=='+' or e=='-':
            if spotted:
                yield text[last:n].replace('##', '++').replace('@@', '--')
                yield e
                last = n+1
                spotted = False
        elif e=='/' or e=='*' or e=='%':
            spotted = False
        elif e!=' ':
            spotted = True
        n+=1
    yield text[last:n].replace('##', '++').replace('@@', '--')

def split_at_any(text, lis, translate=False, not_before=[], not_after=[], validitate=None):
    """ doc """
    lis.sort(key=lambda x: len(x), reverse=True)
    last = 0
    n = 0
    text_len = len(text)
    while n<text_len:
        if any(text[:n].endswith(e) for e in not_before):  #Cant end with end before
            n+=1
            continue
        for e in lis:
            s = len(e)
            if s+n>text_len:
                continue
            if validitate and not validitate(e, text[:n],  text[n+s:]):
                continue
            if any(text[n+s:].startswith(e) for e in not_after):  #Cant end with end before
                n+=1
                break
            if e==text[n:n+s]:
                yield text[last:n] if not translate else translate(text[last:n])
                yield e
                n+=s
                last = n
                break
        else:
            n+=1
    yield text[last:n] if not translate else translate(text[last:n])

def split_at_single(text, sep, not_before=[], not_after=[]):
    """Works like text.split(sep) but separated fragments
    cant end with not_before or start with not_after"""
    n = 0
    lt, s= len(text), len(sep)
    last = 0
    while n<lt:
        if not s+n>lt:
            if sep==text[n:n+s]:
                if any(text[last:n].endswith(e) for e in not_before):
                    pass
                elif any(text[n+s:].startswith(e) for e in not_after):
                    pass
                else:
                    yield text[last:n]
                    last = n+s
                    n += s-1
        n+=1
    yield text[last:]


text:
#ifndef MSOUTLOOKBODYTYPE_H
#define MSOUTLOOKBODYTYPE_H

#import <Foundation/Foundation.h>

/** Enum MSOutlookBodyTypeEnum
 *
 */
typedef NS_ENUM(NSInteger, MSOutlookBodyType) {

    /** Enum entry MSOutlookBodyTypeText
     * */
    MSOutlookBodyTypeText,
    /** Enum entry MSOutlookBodyTypeHTML
     * */
    MSOutlookBodyTypeHTML
};

@interface MSOutlookBodyTypeSerializer : NSObject
+(MSOutlookBodyType) fromString:(NSString *) string;
+(NSString *) toString: (MSOutlookBodyType) value;
@end

#endif


text:
import React from 'react';
import { Form, StackVertical } from '@talend/design-system';

export default {
	component: Form.Month,
};

export const Month = () => (
	<StackVertical gap="M" justify="stretch" align="stretch">
		<Form.Month placeholder="Placeholder" name="month" label="Month" />
		<Form.Month placeholder="Placeholder" name="month" label="Month disabled" disabled />
		<Form.Month placeholder="Placeholder" name="month" label="Month read-only" readOnly />
		<Form.Month name="month" label="Month filled" defaultValue="2022-10" />
		<Form.Month name="month" label="Month filled disabled" defaultValue="2022-10" disabled />
		<Form.Month name="month" label="Month filled read-only" defaultValue="2022-10" readOnly />
	</StackVertical>
);


text:
var util = require('util');
var u = require('../app/util');
var EventEmitter = require('events').EventEmitter;

var Manager = function(){};
util.inherits(Manager, EventEmitter);

Array.prototype.remove = function(item) {
    var index = this.indexOf(item);
    if (index >= 0) {
        this.splice(index, 1);
        return true;
    }
    return false;
};

var System = function(){
    this.memberList = [];
    this.memberMap = {};
    this.downList = [];
};
var SystemPrototype = {
    startup: function(){
        this.emit('startup');
    },
    shutdown: function(){
        this.emit('shutdown');
    },
    addMember: function(id, member){
        if(this.memberList.indexOf(member)>=0){
            return;
        }
        this.memberList.push(member);
        this.memberMap[id] = member;
        this.downList.push(member);
        member.__sys__ = this;
    },
    memberUp: function(member){
        var registered = this.memberList.indexOf(member)>=0;
        if(!registered) return;
        var found = this.downList.remove(member);
        if(found && this.downList.length==0){
            this.emit('up');
            console.info('system is up');
        }
        else{
            //TODO: member changed: up
        }
    },

    memberDown: function(member){
        var registered = this.memberList.indexOf(member)>=0;
        if(!registered) return;
        var existed = this.downList.indexOf(member)>=0;
        if(!existed && this.downList.length==0){
            this.downList.push(member);
            this.emit('down');
            console.info('system is down');
        }
        else{
            //TODO: member changed: down
        }
    },
    emptyFn: function(){}
};
util.inherits(System, EventEmitter);
u.extend(System.prototype, SystemPrototype);

var Member = function(){

};
MemberPrototype = {
    startup: function(){
        this.__sys__.memberUp(this);
    },
    shutdown: function(){
        this.__sys__.memberDown(this);
    },
    emptyFn: function(){}
};
util.inherits(Member, EventEmitter);
u.extend(Member.prototype, SystemPrototype);

//var sys = new System();
//var app = new Member();
//var redis = new Member();
//var rpc = new Member();
//sys.addMember('app', app);
//sys.addMember('redis', redis);
//sys.addMember('rpc', rpc);
//sys.on('startup', function(){
//    console.info('system is starting up');
//});
//sys.on('shutdown', function(){
//    console.info('system is shutting down');
//});
//sys.on('up', function(){
//    console.info('system is up');
//});
//sys.on('down', function(){
//    console.info('system is down');
//});
//sys.startup();
//app.startup();
//redis.startup();
//rpc.startup();
//rpc.shutdown();
//sys.shutdown();

module.exports = System;