text:
<?php

namespace AE\DataBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * DetalleMiembro
 *
 * @ORM\Table(name="detalle_miembro", indexes={@ORM\Index(name="fki_persona", columns={"persona_id"}), @ORM\Index(name="fki_bautizo", columns={"bautizo_id"}), @ORM\Index(name="fk_lider", columns={"lider_id"}), @ORM\Index(name="fki_celula_miembro", columns={"celula_id"}), @ORM\Index(name="fki_encuentro_miembro", columns={"encuentro_id"}), @ORM\Index(name="fki_celula_discipulado", columns={"celula_dis_id"}), @ORM\Index(name="IDX_3E1ED718BBE8922", columns={"red_id"})})
 * @ORM\Entity
 */
class DetalleMiembro
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="detalle_miembro_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="activo", type="boolean", nullable=true)
     */
    private $activo = 'true';

    /**
     * @var integer
     *
     * @ORM\Column(name="consolidador_id", type="bigint", nullable=true)
     */
    private $consolidadorId;

    /**
     * @var integer
     *
     * @ORM\Column(name="lider_id", type="bigint", nullable=true)
     */
    private $liderId;

    /**
     * @var integer
     *
     * @ORM\Column(name="ganado_por", type="bigint", nullable=true)
     */
    private $ganadoPor;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="convertido", type="date", nullable=true)
     */
    private $convertido;

    /**
     * @var \Red
     *
     * @ORM\ManyToOne(targetEntity="Red")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="red_id", referencedColumnName="int_red_id")
     * })
     */
    private $red;

    /**
     * @var \Celula
     *
     * @ORM\ManyToOne(targetEntity="Celula")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="celula_id", referencedColumnName="id")
     * })
     */
    private $celula;

    /**
     * @var \Celula
     *
     * @ORM\ManyToOne(targetEntity="Celula")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="celula_dis_id", referencedColumnName="id")
     * })
     */
    private $celulaDis;

    /**
     * @var \Persona
     *
     * @ORM\ManyToOne(targetEntity="Persona")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="persona_id", referencedColumnName="id")
     * })
     */
    private $persona;

    /**
     * @var \Bautizo
     *
     * @ORM\ManyToOne(targetEntity="Bautizo")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="bautizo_id", referencedColumnName="id")
     * })
     */
    private $bautizo;

    /**
     * @var \DetalleMiembro
     *
     * @ORM\ManyToOne(targetEntity="DetalleMiembro")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="encuentro_id", referencedColumnName="id")
     * })
     */
    private $encuentro;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set activo
     *
     * @param boolean $activo
     * @return DetalleMiembro
     */
    public function setActivo($activo)
    {
        $this->activo = $activo;

        return $this;
    }

    /**
     * Get activo
     *
     * @return boolean
     */
    public function getActivo()
    {
        return $this->activo;
    }

    /**
     * Set consolidadorId
     *
     * @param integer $consolidadorId
     * @return DetalleMiembro
     */
    public function setConsolidadorId($consolidadorId)
    {
        $this->consolidadorId = $consolidadorId;

        return $this;
    }

    /**
     * Get consolidadorId
     *
     * @return integer
     */
    public function getConsolidadorId()
    {
        return $this->consolidadorId;
    }

    /**
     * Set liderId
     *
     * @param integer $liderId
     * @return DetalleMiembro
     */
    public function setLiderId($liderId)
    {
        $this->liderId = $liderId;

        return $this;
    }

    /**
     * Get liderId
     *
     * @return integer
     */
    public function getLiderId()
    {
        return $this->liderId;
    }

    /**
     * Set ganadoPor
     *
     * @param integer $ganadoPor
     * @return DetalleMiembro
     */
    public function setGanadoPor($ganadoPor)
    {
        $this->ganadoPor = $ganadoPor;

        return $this;
    }

    /**
     * Get ganadoPor
     *
     * @return integer
     */
    public function getGanadoPor()
    {
        return $this->ganadoPor;
    }

    /**
     * Set convertido
     *
     * @param \DateTime $convertido
     * @return DetalleMiembro
     */
    public function setConvertido($convertido)
    {
        $this->convertido = $convertido;

        return $this;
    }

    /**
     * Get convertido
     *
     * @return \DateTime
     */
    public function getConvertido()
    {
        return $this->convertido;
    }

    /**
     * Set red
     *
     * @param \AE\DataBundle\Entity\Red $red
     * @return DetalleMiembro
     */
    public function setRed(\AE\DataBundle\Entity\Red $red = null)
    {
        $this->red = $red;

        return $this;
    }

    /**
     * Get red
     *
     * @return \AE\DataBundle\Entity\Red
     */
    public function getRed()
    {
        return $this->red;
    }

    /**
     * Set celula
     *
     * @param \AE\DataBundle\Entity\Celula $celula
     * @return DetalleMiembro
     */
    public function setCelula(\AE\DataBundle\Entity\Celula $celula = null)
    {
        $this->celula = $celula;

        return $this;
    }

    /**
     * Get celula
     *
     * @return \AE\DataBundle\Entity\Celula
     */
    public function getCelula()
    {
        return $this->celula;
    }

    /**
     * Set celulaDis
     *
     * @param \AE\DataBundle\Entity\Celula $celulaDis
     * @return DetalleMiembro
     */
    public function setCelulaDis(\AE\DataBundle\Entity\Celula $celulaDis = null)
    {
        $this->celulaDis = $celulaDis;

        return $this;
    }

    /**
     * Get celulaDis
     *
     * @return \AE\DataBundle\Entity\Celula
     */
    public function getCelulaDis()
    {
        return $this->celulaDis;
    }

    /**
     * Set persona
     *
     * @param \AE\DataBundle\Entity\Persona $persona
     * @return DetalleMiembro
     */
    public function setPersona(\AE\DataBundle\Entity\Persona $persona = null)
    {
        $this->persona = $persona;

        return $this;
    }

    /**
     * Get persona
     *
     * @return \AE\DataBundle\Entity\Persona
     */
    public function getPersona()
    {
        return $this->persona;
    }

    /**
     * Set bautizo
     *
     * @param \AE\DataBundle\Entity\Bautizo $bautizo
     * @return DetalleMiembro
     */
    public function setBautizo(\AE\DataBundle\Entity\Bautizo $bautizo = null)
    {
        $this->bautizo = $bautizo;

        return $this;
    }

    /**
     * Get bautizo
     *
     * @return \AE\DataBundle\Entity\Bautizo
     */
    public function getBautizo()
    {
        return $this->bautizo;
    }

    /**
     * Set encuentro
     *
     * @param \AE\DataBundle\Entity\DetalleMiembro $encuentro
     * @return DetalleMiembro
     */
    public function setEncuentro(\AE\DataBundle\Entity\DetalleMiembro $encuentro = null)
    {
        $this->encuentro = $encuentro;

        return $this;
    }

    /**
     * Get encuentro
     *
     * @return \AE\DataBundle\Entity\DetalleMiembro
     */
    public function getEncuentro()
    {
        return $this->encuentro;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.be_hase.honoumi.controller;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.be_hase.honoumi.domain.ChannelAttachment;
import com.be_hase.honoumi.netty.server.MonitoringServer;
import com.be_hase.honoumi.util.Utils;
import com.espertech.esper.client.EPRuntime;
import com.google.common.collect.Maps;

public class Response {
	private static Logger logger = LoggerFactory.getLogger(Response.class);

	private Response(){};

	public static void execute(MessageEvent evt, HttpResponseStatus status, Map<String, String> headers, String content) {
		HttpRequest request = (HttpRequest)evt.getMessage();

		if (HttpHeaders.is100ContinueExpected(request)) {
			send100Continue(evt);
		}

		ChannelAttachment channelAttachment = ChannelAttachment.getByChannel(evt.getChannel());

		boolean isKeepAlive = channelAttachment.isKeepAliveSupported() && HttpHeaders.isKeepAlive(request);

		DefaultHttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
		res.setContent(ChannelBuffers.copiedBuffer(content, CharsetUtil.UTF_8));
		res.headers().add(CONTENT_TYPE, "application/json");
		if (isKeepAlive) {
			res.headers().add(HttpHeaders.Names.CONTENT_LENGTH, res.getContent().readableBytes());
			res.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		}
		if (headers != null) {
			for (Map.Entry<String, String> e: headers.entrySet()) {
				// can override
				res.headers().set(e.getKey(), e.getValue());
			}
		}

		ChannelFuture future = evt.getChannel().write(res);
		if (!isKeepAlive) {
			future.addListener(ChannelFutureListener.CLOSE);
		}

		// if now monitoring, sendEvent to Esper
		if (channelAttachment.isNowMonitoring()) {
			logger.debug("server is now monitoring.");

			try {
				EPRuntime epRuntime = channelAttachment.getServer().getEpService().getEPRuntime();

				Map<String, Object> accessEvent = Maps.newHashMap();
				accessEvent.put("urlPath", channelAttachment.getUrlPath());
				accessEvent.put("httpMethod", channelAttachment.getHttpMethod());
				accessEvent.put("requestHeaders", channelAttachment.getRequestHeaders());
				accessEvent.put("httpStatusCode", status.getCode());
				accessEvent.put("time", channelAttachment.getStartTime());
				accessEvent.put("responseTime", System.currentTimeMillis() - channelAttachment.getStartTime());
				epRuntime.sendEvent(accessEvent, MonitoringServer.ACCESS_EVENT_TYPE_NAME);
				logger.debug("sendEvent. eventTypeName : {}, event : {}", MonitoringServer.ACCESS_EVENT_TYPE_NAME, accessEvent);

				String eventTypeName = channelAttachment.getEventTypeName();
				if (StringUtils.isNotBlank(eventTypeName)) {
					Map<String, Object> event = channelAttachment.getEvent();
					event.putAll(accessEvent);
					epRuntime.sendEvent(event, eventTypeName);
					logger.debug("sendEvent. eventTypeName : {}, event : {}", eventTypeName, event);
				}
			} catch (Exception e) {
				logger.debug(Utils.stackTraceToStr(e));
			}
		} else {
			logger.debug("server is NOT now monitoring.");
		}
	}

	private static void send100Continue(MessageEvent e) {
		HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
		e.getChannel().write(response);
	}
}


text:
# Median

> [Rayleigh][rayleigh-distribution] distribution [median][median].

The [median][median] for a [Rayleigh][rayleigh-distribution] random variable is

where `σ > 0` is the scale parameter.

## Usage

```javascript
var median = require( '@stdlib/stats/base/dists/rayleigh/median' );
```

#### median( sigma )

Returns the [median][median] of a [Rayleigh][rayleigh-distribution] distribution with scale
parameter `sigma`.

```javascript
var y = median( 9.0 );
// returns ~10.597

y = median( 1.5 );
// returns ~1.766
```

If provided `sigma < 0`, the function returns `NaN`.

```javascript
var y = median( -1.0 );
// returns NaN
```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var round = require( '@stdlib/math/base/special/round' );
var median = require( '@stdlib/stats/base/dists/rayleigh/median' );

var sigma;
var y;
var i;

for ( i = 0; i < 10; i++ ) {
    sigma = randu() * 20.0;
    y = median( sigma );
    console.log( 'σ: %d, Median(X,σ): %d', sigma.toFixed( 4 ), y.toFixed( 4 ) );
}
```

[rayleigh-distribution]: https://en.wikipedia.org/wiki/Rayleigh_distribution

[median]: https://en.wikipedia.org/wiki/Median


text:
import * as React from 'react';
import {SvgIconProps} from '../../SvgIcon';

export default function PortableWifiOff(props: SvgIconProps): React.ReactElement<SvgIconProps>;


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

// For linux_syscall_support.h. This makes it safe to call embedded system
// calls when in seccomp mode.
#define SYS_SYSCALL_ENTRYPOINT "playground$syscallEntryPoint"

#include "chrome/app/breakpad_linux.h"

#include <fcntl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>

#include <algorithm>
#include <string>

#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/global_descriptors_posix.h"
#include "base/linux_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "breakpad/src/client/linux/handler/exception_handler.h"
#include "breakpad/src/client/linux/minidump_writer/directory_reader.h"
#include "breakpad/src/common/linux/linux_libc_support.h"
#include "breakpad/src/common/memory.h"
#include "chrome/common/child_process_logging.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info_posix.h"
#include "chrome/common/env_vars.h"
#include "content/common/chrome_descriptors.h"
#include "seccompsandbox/linux_syscall_support.h"

// Some versions of gcc are prone to warn about unused return values. In cases
// where we either a) know the call cannot fail, or b) there is nothing we
// can do when a call fails, we mark the return code as ignored. This avoids
// spurious compiler warnings.
#define IGNORE_RET(x) do { if (x); } while (0)

static const char kUploadURL[] =
    "https://clients2.google.com/cr/report";

static bool is_crash_reporter_enabled = false;
static uint64_t process_start_time = 0;
static char* crash_log_path = NULL;

// Writes the value |v| as 16 hex characters to the memory pointed at by
// |output|.
static void write_uint64_hex(char* output, uint64_t v) {
  static const char hextable[] = "0123456789abcdef";

  for (int i = 15; i >= 0; --i) {
    output[i] = hextable[v & 15];
    v >>= 4;
  }
}

// The following helper functions are for calculating uptime.

// Converts a struct timeval to milliseconds.
static uint64_t timeval_to_ms(struct timeval *tv) {
  uint64_t ret = tv->tv_sec;  // Avoid overflow by explicitly using a uint64_t.
  ret *= 1000;
  ret += tv->tv_usec / 1000;
  return ret;
}

// Converts a struct timeval to milliseconds.
static uint64_t kernel_timeval_to_ms(struct kernel_timeval *tv) {
  uint64_t ret = tv->tv_sec;  // Avoid overflow by explicitly using a uint64_t.
  ret *= 1000;
  ret += tv->tv_usec / 1000;
  return ret;
}

// uint64_t version of my_int_len() from
// breakpad/src/common/linux/linux_libc_support.h. Return the length of the
// given, non-negative integer when expressed in base 10.
static unsigned my_uint64_len(uint64_t i) {
  if (!i)
    return 1;

  unsigned len = 0;
  while (i) {
    len++;
    i /= 10;
  }

  return len;
}

// uint64_t version of my_itos() from
// breakpad/src/common/linux/linux_libc_support.h. Convert a non-negative
// integer to a string (not null-terminated).
static void my_uint64tos(char* output, uint64_t i, unsigned i_len) {
  for (unsigned index = i_len; index; --index, i /= 10)
    output[index - 1] = '0' + (i % 10);
}

namespace {

// MIME substrings.
static const char g_rn[] = "\r\n";
static const char g_form_data_msg[] = "Content-Disposition: form-data; name=\"";
static const char g_quote_msg[] = "\"";
static const char g_dashdash_msg[] = "--";
static const char g_dump_msg[] = "upload_file_minidump\"; filename=\"dump\"";
static const char g_content_type_msg[] =
    "Content-Type: application/octet-stream";

// MimeWriter manages an iovec for writing MIMEs to a file.
class MimeWriter {
 public:
  static const int kIovCapacity = 30;
  static const size_t kMaxCrashChunkSize = 64;

  MimeWriter(int fd, const char* const mime_boundary);
  ~MimeWriter();

  // Append boundary.
  void AddBoundary();

  // Append end of file boundary.
  void AddEnd();

  // Append key/value pair with specified sizes.
  void AddPairData(const char* msg_type,
                   size_t msg_type_size,
                   const char* msg_data,
                   size_t msg_data_size);

  // Append key/value pair.
  void AddPairString(const char* msg_type,
                     const char* msg_data) {
    AddPairData(msg_type, my_strlen(msg_type), msg_data, my_strlen(msg_data));
  }

  // Append key/value pair, splitting value into chunks no larger than
  // kMaxCrashChunkSize. The msg_type string will have a counter suffix to
  // distinguish each chunk.
  void AddPairDataInChunks(const char* msg_type,
                           size_t msg_type_size,
                           const char* msg_data,
                           size_t msg_data_size);

  // Add binary file dump. Currently this is only done once, so the name is
  // fixed.
  void AddFileDump(uint8_t* file_data,
                   size_t file_size);

  // Flush any pending iovecs to the output file.
  void Flush() {
    IGNORE_RET(sys_writev(fd_, iov_, iov_index_));
    iov_index_ = 0;
  }

 private:
  void AddItem(const void* base, size_t size);
  // Minor performance trade-off for easier-to-maintain code.
  void AddString(const char* str) {
    AddItem(str, my_strlen(str));
  }

  struct kernel_iovec iov_[kIovCapacity];
  int iov_index_;

  // Output file descriptor.
  int fd_;

  const char* const mime_boundary_;

  DISALLOW_COPY_AND_ASSIGN(MimeWriter);
};

MimeWriter::MimeWriter(int fd, const char* const mime_boundary)
    : iov_index_(0),
      fd_(fd),
      mime_boundary_(mime_boundary) {
}

MimeWriter::~MimeWriter() {
}

void MimeWriter::AddBoundary() {
  AddString(mime_boundary_);
  AddString(g_rn);
}

void MimeWriter::AddEnd() {
  AddString(mime_boundary_);
  AddString(g_dashdash_msg);
  AddString(g_rn);
}

void MimeWriter::AddPairData(const char* msg_type,
                             size_t msg_type_size,
                             const char* msg_data,
                             size_t msg_data_size) {
  AddString(g_form_data_msg);
  AddItem(msg_type, msg_type_size);
  AddString(g_quote_msg);
  AddString(g_rn);
  AddString(g_rn);
  AddItem(msg_data, msg_data_size);
  AddString(g_rn);
}

void MimeWriter::AddPairDataInChunks(const char* msg_type,
                                     size_t msg_type_size,
                                     const char* msg_data,
                                     size_t msg_data_size) {
  unsigned i = 0;
  size_t done = 0, msg_length = msg_data_size;

  while (msg_length) {
    char num[16];
    const unsigned num_len = my_int_len(++i);
    my_itos(num, i, num_len);

    size_t chunk_len = std::min((size_t)kMaxCrashChunkSize, msg_length);

    AddString(g_form_data_msg);
    AddItem(msg_type, msg_type_size);
    AddItem(num, num_len);
    AddString(g_quote_msg);
    AddString(g_rn);
    AddString(g_rn);
    AddItem(msg_data + done, chunk_len);
    AddString(g_rn);
    AddBoundary();
    Flush();

    done += chunk_len;
    msg_length -= chunk_len;
  }
}

void MimeWriter::AddFileDump(uint8_t* file_data,
                             size_t file_size) {
  AddString(g_form_data_msg);
  AddString(g_dump_msg);
  AddString(g_rn);
  AddString(g_content_type_msg);
  AddString(g_rn);
  AddString(g_rn);
  AddItem(file_data, file_size);
  AddString(g_rn);
}

void MimeWriter::AddItem(const void* base, size_t size) {
  // Check if the iovec is full and needs to be flushed to output file.
  if (iov_index_ == kIovCapacity) {
    Flush();
  }
  iov_[iov_index_].iov_base = const_cast<void*>(base);
  iov_[iov_index_].iov_len = size;
  ++iov_index_;
}

}  // namespace

pid_t HandleCrashDump(const BreakpadInfo& info) {
  // WARNING: this code runs in a compromised context. It may not call into
  // libc nor allocate memory normally.

  const int dumpfd = sys_open(info.filename, O_RDONLY, 0);
  if (dumpfd < 0) {
    static const char msg[] = "Cannot upload crash dump: failed to open\n";
    sys_write(2, msg, sizeof(msg));
    return -1;
  }
  struct kernel_stat st;
  if (sys_fstat(dumpfd, &st) != 0) {
    static const char msg[] = "Cannot upload crash dump: stat failed\n";
    sys_write(2, msg, sizeof(msg));
    IGNORE_RET(sys_close(dumpfd));
    return -1;
  }

  google_breakpad::PageAllocator allocator;

  uint8_t* dump_data = reinterpret_cast<uint8_t*>(allocator.Alloc(st.st_size));
  if (!dump_data) {
    static const char msg[] = "Cannot upload crash dump: cannot alloc\n";
    sys_write(2, msg, sizeof(msg));
    IGNORE_RET(sys_close(dumpfd));
    return -1;
  }

  sys_read(dumpfd, dump_data, st.st_size);
  IGNORE_RET(sys_close(dumpfd));

  // We need to build a MIME block for uploading to the server. Since we are
  // going to fork and run wget, it needs to be written to a temp file.

  const int ufd = sys_open("/dev/urandom", O_RDONLY, 0);
  if (ufd < 0) {
    static const char msg[] = "Cannot upload crash dump because /dev/urandom"
                              " is missing\n";
    sys_write(2, msg, sizeof(msg) - 1);
    return -1;
  }

  static const char temp_file_template[] =
      "/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
  char temp_file[sizeof(temp_file_template)];
  int fd = -1;
  if (info.upload) {
    memcpy(temp_file, temp_file_template, sizeof(temp_file_template));

    for (unsigned i = 0; i < 10; ++i) {
      uint64_t t;
      sys_read(ufd, &t, sizeof(t));
      write_uint64_hex(temp_file + sizeof(temp_file) - (16 + 1), t);

      fd = sys_open(temp_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
      if (fd >= 0)
        break;
    }

    if (fd < 0) {
      static const char msg[] = "Failed to create temporary file in /tmp: "
          "cannot upload crash dump\n";
      sys_write(2, msg, sizeof(msg) - 1);
      IGNORE_RET(sys_close(ufd));
      return -1;
    }
  } else {
    fd = sys_open(info.filename, O_WRONLY, 0600);
    if (fd < 0) {
      static const char msg[] = "Failed to save crash dump: failed to open\n";
      sys_write(2, msg, sizeof(msg) - 1);
      IGNORE_RET(sys_close(ufd));
      return -1;
    }
  }

  // The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
  char mime_boundary[28 + 16 + 1];
  my_memset(mime_boundary, '-', 28);
  uint64_t boundary_rand;
  sys_read(ufd, &boundary_rand, sizeof(boundary_rand));
  write_uint64_hex(mime_boundary + 28, boundary_rand);
  mime_boundary[28 + 16] = 0;
  IGNORE_RET(sys_close(ufd));

  // The MIME block looks like this:
  //   BOUNDARY \r\n (0, 1)
  //   Content-Disposition: form-data; name="prod" \r\n \r\n (2..6)
  //   Chrome_Linux \r\n (7, 8)
  //   BOUNDARY \r\n (9, 10)
  //   Content-Disposition: form-data; name="ver" \r\n \r\n (11..15)
  //   1.2.3.4 \r\n (16, 17)
  //   BOUNDARY \r\n (18, 19)
  //   Content-Disposition: form-data; name="guid" \r\n \r\n (20..24)
  //   1.2.3.4 \r\n (25, 26)
  //   BOUNDARY \r\n (27, 28)
  //
  //   zero or one:
  //   Content-Disposition: form-data; name="ptime" \r\n \r\n (0..4)
  //   abcdef \r\n (5, 6)
  //   BOUNDARY \r\n (7, 8)
  //
  //   zero or one:
  //   Content-Disposition: form-data; name="ptype" \r\n \r\n (0..4)
  //   abcdef \r\n (5, 6)
  //   BOUNDARY \r\n (7, 8)
  //
  //   zero or one:
  //   Content-Disposition: form-data; name="lsb-release" \r\n \r\n (0..4)
  //   abcdef \r\n (5, 6)
  //   BOUNDARY \r\n (7, 8)
  //
  //   zero or more gpu entries:
  //   Content-Disposition: form-data; name="gpu-xxxxx" \r\n \r\n (0..4)
  //   <gpu-xxxxx> \r\n (5, 6)
  //   BOUNDARY \r\n (7, 8)
  //
  //   zero or more:
  //   Content-Disposition: form-data; name="url-chunk-1" \r\n \r\n (0..5)
  //   abcdef \r\n (6, 7)
  //   BOUNDARY \r\n (8, 9)
  //
  //   Content-Disposition: form-data; name="dump"; filename="dump" \r\n (0,1,2)
  //   Content-Type: application/octet-stream \r\n \r\n (3,4,5)
  //   <dump contents> (6)
  //   \r\n BOUNDARY -- \r\n (7,8,9,10)

  #if defined(OS_CHROMEOS)
  static const char chrome_product_msg[] = "Chrome_ChromeOS";
  #else  // OS_LINUX
  static const char chrome_product_msg[] = "Chrome_Linux";
  #endif
  static const char version_msg[] = PRODUCT_VERSION;
  static const char prod_msg[] = "prod";
  static const char ver_msg[] = "ver";
  static const char guid_msg[] = "guid";
  static const char url_chunk_msg[] = "url-chunk-";
  static const char process_time_msg[] = "ptime";
  static const char process_type_msg[] = "ptype";
  static const char distro_msg[] = "lsb-release";

  MimeWriter writer(fd, mime_boundary);

  writer.AddBoundary();
  writer.AddPairString(prod_msg, chrome_product_msg);
  writer.AddBoundary();
  writer.AddPairString(ver_msg, version_msg);
  writer.AddBoundary();
  writer.AddPairString(guid_msg, info.guid);
  writer.AddBoundary();
  writer.Flush();

  if (info.process_start_time > 0) {
    struct kernel_timeval tv;
    if (!sys_gettimeofday(&tv, NULL)) {
      uint64_t time = kernel_timeval_to_ms(&tv);
      if (time > info.process_start_time) {
        time -= info.process_start_time;
        char time_str[21];
        const unsigned time_len = my_uint64_len(time);
        my_uint64tos(time_str, time, time_len);

        writer.AddPairData(process_time_msg, sizeof(process_time_msg) - 1,
                           time_str, time_len);
        writer.AddBoundary();
        writer.Flush();
      }
    }
  }

  if (info.process_type_length) {
    writer.AddPairString(process_type_msg, info.process_type);
    writer.AddBoundary();
    writer.Flush();
  }

  // If GPU info is known, send it.
  unsigned gpu_vendor_len = my_strlen(child_process_logging::g_gpu_vendor_id);
  if (gpu_vendor_len) {
    static const char vendor_msg[] = "gpu-venid";
    static const char device_msg[] = "gpu-devid";
    static const char driver_msg[] = "gpu-driver";
    static const char psver_msg[] = "gpu-psver";
    static const char vsver_msg[] = "gpu-vsver";

    writer.AddPairString(vendor_msg, child_process_logging::g_gpu_vendor_id);
    writer.AddBoundary();
    writer.AddPairString(device_msg, child_process_logging::g_gpu_device_id);
    writer.AddBoundary();
    writer.AddPairString(driver_msg, child_process_logging::g_gpu_driver_ver);
    writer.AddBoundary();
    writer.AddPairString(psver_msg, child_process_logging::g_gpu_ps_ver);
    writer.AddBoundary();
    writer.AddPairString(vsver_msg, child_process_logging::g_gpu_vs_ver);
    writer.AddBoundary();
    writer.Flush();
  }

  if (info.distro_length) {
    writer.AddPairString(distro_msg, info.distro);
    writer.AddBoundary();
    writer.Flush();
  }

  // For rendererers and plugins.
  if (info.crash_url_length) {
    static const unsigned kMaxUrlLength = 8 * MimeWriter::kMaxCrashChunkSize;
    writer.AddPairDataInChunks(url_chunk_msg, sizeof(url_chunk_msg) - 1,
        info.crash_url, std::min(info.crash_url_length, kMaxUrlLength));
  }

  writer.AddFileDump(dump_data, st.st_size);
  writer.AddEnd();
  writer.Flush();

  IGNORE_RET(sys_close(fd));

  if (!info.upload)
    return 0;

  // The --header argument to wget looks like:
  //   --header=Content-Type: multipart/form-data; boundary=XYZ
  // where the boundary has two fewer leading '-' chars
  static const char header_msg[] =
      "--header=Content-Type: multipart/form-data; boundary=";
  char* const header = reinterpret_cast<char*>(allocator.Alloc(
      sizeof(header_msg) - 1 + sizeof(mime_boundary) - 2));
  memcpy(header, header_msg, sizeof(header_msg) - 1);
  memcpy(header + sizeof(header_msg) - 1, mime_boundary + 2,
         sizeof(mime_boundary) - 2);
  // We grab the NUL byte from the end of |mime_boundary|.

  // The --post-file argument to wget looks like:
  //   --post-file=/tmp/...
  static const char post_file_msg[] = "--post-file=";
  char* const post_file = reinterpret_cast<char*>(allocator.Alloc(
       sizeof(post_file_msg) - 1 + sizeof(temp_file)));
  memcpy(post_file, post_file_msg, sizeof(post_file_msg) - 1);
  memcpy(post_file + sizeof(post_file_msg) - 1, temp_file, sizeof(temp_file));

  const pid_t child = sys_fork();
  if (!child) {
    // This code is called both when a browser is crashing (in which case,
    // nothing really matters any more) and when a renderer/plugin crashes, in
    // which case we need to continue.
    //
    // Since we are a multithreaded app, if we were just to fork(), we might
    // grab file descriptors which have just been created in another thread and
    // hold them open for too long.
    //
    // Thus, we have to loop and try and close everything.
    const int fd = sys_open("/proc/self/fd", O_DIRECTORY | O_RDONLY, 0);
    if (fd < 0) {
      for (unsigned i = 3; i < 8192; ++i)
        IGNORE_RET(sys_close(i));
    } else {
      google_breakpad::DirectoryReader reader(fd);
      const char* name;
      while (reader.GetNextEntry(&name)) {
        int i;
        if (my_strtoui(&i, name) && i > 2 && i != fd)
          IGNORE_RET(sys_close(i));
        reader.PopEntry();
      }

      IGNORE_RET(sys_close(fd));
    }

    IGNORE_RET(sys_setsid());

    // Leave one end of a pipe in the wget process and watch for it getting
    // closed by the wget process exiting.
    int fds[2];
    IGNORE_RET(sys_pipe(fds));

    const pid_t child = sys_fork();
    if (child) {
      IGNORE_RET(sys_close(fds[1]));
      char id_buf[17];
      const int len = HANDLE_EINTR(sys_read(fds[0], id_buf,
                                   sizeof(id_buf) - 1));
      if (len > 0) {
        // Write crash dump id to stderr.
        id_buf[len] = 0;
        static const char msg[] = "\nCrash dump id: ";
        sys_write(2, msg, sizeof(msg) - 1);
        sys_write(2, id_buf, my_strlen(id_buf));
        sys_write(2, "\n", 1);

        // Write crash dump id to crash log as: seconds_since_epoch,crash_id
        struct kernel_timeval tv;
        if (crash_log_path && !sys_gettimeofday(&tv, NULL)) {
          uint64_t time = kernel_timeval_to_ms(&tv) / 1000;
          char time_str[21];
          const unsigned time_len = my_uint64_len(time);
          my_uint64tos(time_str, time, time_len);

          int log_fd = sys_open(crash_log_path, O_CREAT | O_WRONLY | O_APPEND,
                                0600);
          if (log_fd > 0) {
            sys_write(log_fd, time_str, time_len);
            sys_write(log_fd, ",", 1);
            sys_write(log_fd, id_buf, my_strlen(id_buf));
            sys_write(log_fd, "\n", 1);
            IGNORE_RET(sys_close(log_fd));
          }
        }
      }
      IGNORE_RET(sys_unlink(info.filename));
      IGNORE_RET(sys_unlink(temp_file));
      sys__exit(0);
    }

    IGNORE_RET(sys_close(fds[0]));
    IGNORE_RET(sys_dup2(fds[1], 3));
    static const char* const kWgetBinary = "/usr/bin/wget";
    const char* args[] = {
      kWgetBinary,
      header,
      post_file,
      kUploadURL,
      "--timeout=10",  // Set a timeout so we don't hang forever.
      "--tries=1",     // Don't retry if the upload fails.
      "-O",  // output reply to fd 3
      "/dev/fd/3",
      NULL,
    };

    execve(kWgetBinary, const_cast<char**>(args), environ);
    static const char msg[] = "Cannot upload crash dump: cannot exec "
                              "/usr/bin/wget\n";
    sys_write(2, msg, sizeof(msg) - 1);
    sys__exit(1);
  }

  HANDLE_EINTR(sys_waitpid(child, NULL, 0));
  return child;
}

static bool CrashDone(const char* dump_path,
                      const char* minidump_id,
                      const bool upload,
                      const bool succeeded) {
  // WARNING: this code runs in a compromised context. It may not call into
  // libc nor allocate memory normally.
  if (!succeeded)
    return false;

  google_breakpad::PageAllocator allocator;
  const unsigned dump_path_len = my_strlen(dump_path);
  const unsigned minidump_id_len = my_strlen(minidump_id);
  char *const path = reinterpret_cast<char*>(allocator.Alloc(
      dump_path_len + 1 /* '/' */ + minidump_id_len +
      4 /* ".dmp" */ + 1 /* NUL */));
  memcpy(path, dump_path, dump_path_len);
  path[dump_path_len] = '/';
  memcpy(path + dump_path_len + 1, minidump_id, minidump_id_len);
  memcpy(path + dump_path_len + 1 + minidump_id_len, ".dmp", 4);
  path[dump_path_len + 1 + minidump_id_len + 4] = 0;

  BreakpadInfo info;
  info.filename = path;
  info.process_type = "browser";
  info.process_type_length = 7;
  info.crash_url = NULL;
  info.crash_url_length = 0;
  info.guid = child_process_logging::g_client_id;
  info.guid_length = my_strlen(child_process_logging::g_client_id);
  info.distro = base::g_linux_distro;
  info.distro_length = my_strlen(base::g_linux_distro);
  info.upload = upload;
  info.process_start_time = process_start_time;
  HandleCrashDump(info);

  return true;
}

// Wrapper script, do not add more code here.
static bool CrashDoneNoUpload(const char* dump_path,
                      const char* minidump_id,
                      void* context,
                      bool succeeded) {
  return CrashDone(dump_path, minidump_id, false, succeeded);
}

// Wrapper script, do not add more code here.
static bool CrashDoneUpload(const char* dump_path,
                      const char* minidump_id,
                      void* context,
                      bool succeeded) {
  return CrashDone(dump_path, minidump_id, true, succeeded);
}

void EnableCrashDumping(const bool unattended) {
  is_crash_reporter_enabled = true;

  FilePath tmp_path("/tmp");
  PathService::Get(base::DIR_TEMP, &tmp_path);

  FilePath dumps_path(tmp_path);
  if (PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path)) {
    FilePath logfile = dumps_path.AppendASCII("uploads.log");
    std::string logfile_str = logfile.value();
    const size_t crash_log_path_len = logfile_str.size() + 1;
    crash_log_path = new char[crash_log_path_len];
    strncpy(crash_log_path, logfile_str.c_str(), crash_log_path_len);
  }

  if (unattended) {
    new google_breakpad::ExceptionHandler(dumps_path.value().c_str(), NULL,
                                          CrashDoneNoUpload, NULL,
                                          true /* install handlers */);
  } else {
    new google_breakpad::ExceptionHandler(tmp_path.value().c_str(), NULL,
                                          CrashDoneUpload, NULL,
                                          true /* install handlers */);
  }
}

// Currently Non-Browser = Renderer, Plugins and Gpu
static bool
NonBrowserCrashHandler(const void* crash_context, size_t crash_context_size,
                       void* context) {
  const int fd = reinterpret_cast<intptr_t>(context);
  int fds[2] = { -1, -1 };
  if (sys_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
    static const char msg[] = "Failed to create socket for crash dumping.\n";
    sys_write(2, msg, sizeof(msg)-1);
    return false;
  }
  char guid[kGuidSize + 1] = {0};
  char crash_url[kMaxActiveURLSize + 1] = {0};
  char distro[kDistroSize + 1] = {0};
  const size_t guid_len =
      std::min(my_strlen(child_process_logging::g_client_id), kGuidSize);
  const size_t crash_url_len =
      std::min(my_strlen(child_process_logging::g_active_url),
               kMaxActiveURLSize);
  const size_t distro_len =
      std::min(my_strlen(base::g_linux_distro), kDistroSize);
  memcpy(guid, child_process_logging::g_client_id, guid_len);
  memcpy(crash_url, child_process_logging::g_active_url, crash_url_len);
  memcpy(distro, base::g_linux_distro, distro_len);

  char b;  // Dummy variable for sys_read below.
  const char* b_addr = &b;  // Get the address of |b| so we can create the
                            // expected /proc/[pid]/syscall content in the
                            // browser to convert namespace tids.

  // The length of the control message:
  static const unsigned kControlMsgSize = CMSG_SPACE(2*sizeof(int));

  const size_t kIovSize = 7;
  struct kernel_msghdr msg;
  my_memset(&msg, 0, sizeof(struct kernel_msghdr));
  struct kernel_iovec iov[kIovSize];
  iov[0].iov_base = const_cast<void*>(crash_context);
  iov[0].iov_len = crash_context_size;
  iov[1].iov_base = guid;
  iov[1].iov_len = kGuidSize + 1;
  iov[2].iov_base = crash_url;
  iov[2].iov_len = kMaxActiveURLSize + 1;
  iov[3].iov_base = distro;
  iov[3].iov_len = kDistroSize + 1;
  iov[4].iov_base = &b_addr;
  iov[4].iov_len = sizeof(b_addr);
  iov[5].iov_base = &fds[0];
  iov[5].iov_len = sizeof(fds[0]);
  iov[6].iov_base = &process_start_time;
  iov[6].iov_len = sizeof(process_start_time);

  msg.msg_iov = iov;
  msg.msg_iovlen = kIovSize;
  char cmsg[kControlMsgSize];
  my_memset(cmsg, 0, kControlMsgSize);
  msg.msg_control = cmsg;
  msg.msg_controllen = sizeof(cmsg);

  struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
  hdr->cmsg_level = SOL_SOCKET;
  hdr->cmsg_type = SCM_RIGHTS;
  hdr->cmsg_len = CMSG_LEN(2*sizeof(int));
  ((int*) CMSG_DATA(hdr))[0] = fds[0];
  ((int*) CMSG_DATA(hdr))[1] = fds[1];

  if (HANDLE_EINTR(sys_sendmsg(fd, &msg, 0)) < 0) {
    static const char msg[] = "Failed to tell parent about crash.\n";
    sys_write(2, msg, sizeof(msg)-1);
    IGNORE_RET(sys_close(fds[1]));
    return false;
  }
  IGNORE_RET(sys_close(fds[1]));

  if (HANDLE_EINTR(sys_read(fds[0], &b, 1)) != 1) {
    static const char msg[] = "Parent failed to complete crash dump.\n";
    sys_write(2, msg, sizeof(msg)-1);
  }

  return true;
}

void EnableNonBrowserCrashDumping() {
  const int fd = base::GlobalDescriptors::GetInstance()->Get(kCrashDumpSignal);
  is_crash_reporter_enabled = true;
  // We deliberately leak this object.
  google_breakpad::ExceptionHandler* handler =
      new google_breakpad::ExceptionHandler("" /* unused */, NULL, NULL,
                                            (void*) fd, true);
  handler->set_crash_handler(NonBrowserCrashHandler);
}

void InitCrashReporter() {
  // Determine the process type and take appropriate action.
  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
  const std::string process_type =
      parsed_command_line.GetSwitchValueASCII(switches::kProcessType);
  if (process_type.empty()) {
    EnableCrashDumping(getenv(env_vars::kHeadless) != NULL);
  } else if (process_type == switches::kRendererProcess ||
             process_type == switches::kPluginProcess ||
             process_type == switches::kPpapiPluginProcess ||
             process_type == switches::kZygoteProcess ||
             process_type == switches::kGpuProcess) {
    // We might be chrooted in a zygote or renderer process so we cannot call
    // GetCollectStatsConsent because that needs access the the user's home
    // dir. Instead, we set a command line flag for these processes.
    // Even though plugins are not chrooted, we share the same code path for
    // simplicity.
    if (!parsed_command_line.HasSwitch(switches::kEnableCrashReporter))
      return;
    // Get the guid and linux distro from the command line switch.
    std::string switch_value =
        parsed_command_line.GetSwitchValueASCII(switches::kEnableCrashReporter);
    size_t separator = switch_value.find(",");
    if (separator != std::string::npos) {
      child_process_logging::SetClientId(switch_value.substr(0, separator));
      base::SetLinuxDistro(switch_value.substr(separator + 1));
    } else {
      child_process_logging::SetClientId(switch_value);
    }
    EnableNonBrowserCrashDumping();
  }

  // Set the base process start time value.
  struct timeval tv;
  if (!gettimeofday(&tv, NULL))
    process_start_time = timeval_to_ms(&tv);
  else
    process_start_time = 0;
}

bool IsCrashReporterEnabled() {
  return is_crash_reporter_enabled;
}


text:
<?php
/**
* ActionDate element class
*
* Heirarchy:
* (%pcd-model)*
*
*/
namespace USLM\Legislation\Element\Action;

use USLM\Legislation\Element\LegislationElement;

class ActionDate extends LegislationElement{

  public function __toString(){
    $this->checkRequirements(array('xml'));

    return (string)$this->xml;
  }
}


text:
<!DOCTYPE html>

    <title>CSS Flexible Box Test: align-content_flex-start</title>
    <link rel="author" title="Intel" href="http://www.intel.com" />
    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property" />
    <link rel="match" href="reference/align-content_flex-start-ref.html">
    <link rel="stylesheet" href="support/test-style.css">
    <meta name="flags" content="" />
    <meta name="assert" content="Check if the web engine can identify the align-content value flex-start." />

Test passes if:

    1. the rectangle 1, 2, 3 show up in a vertical column in a red rectangle and no gap between them.

    2. the rectangle 1, 2, 3 appear in upper left of red rectangle.

1

2

3


text:
class DummyController < ActionController::Base

  impressionist

end


text:
@interface PodsDummy_Pods_SwiftMock_Example : NSObject
@end
@implementation PodsDummy_Pods_SwiftMock_Example
@end


text:
import SecondScreenConfig from './secondScreen.config';
import SecondScreenController from './secondScreen.controller';

let secondScreenModule = angular.module('bpui.secondScreen', []);
secondScreenModule.config(SecondScreenConfig);
secondScreenModule.controller('SecondScreenController', SecondScreenController);

export default secondScreenModule = secondScreenModule.name;


text:
title: "Creating SPARQL Queries with the SparqlBuilder"
toc: true
weight: 4
autonumbering: true
---
RDF4J SparqlBuilder is a fluent Java API used to programmatically create SPARQL query strings.
<!--more-->
It is based on the Spanqit query builder developed by Anqit Praqash, and has been slightly modified to allow tighter integration with the rest of the RDF4J framework.

SparqlBuilder allows the following SPARQL query:

    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    SELECT ?name
    WHERE { ?x foaf:name ?name }
    ORDER BY ?name
    LIMIT 5
    OFFSET 10

to be created as simply as:

```java
query
    .prefix(FOAF.NS)
    .select(name)
    .where(x.has(FOAF.NAME, name))
    .orderBy(name)
    .limit(5)
    .offset(10);
```

The RDF4J SparqlBuilder is based on the SPARQL 1.1 Query Recommendation and the
SPARQL 1.1 Update Receommendation. Almost all features of SPARQL 1.1 are
supported, excluding some current known limitations.

This document assumes the reader is already familiar with the SPARQL query language. Please refer to the above specification if not.

## Getting SparqlBuilder

Obtain SparqlBuilder by adding the following dependency to your maven pom file:

```xml
<dependency>
    <groupId>org.eclipse.rdf4j</groupId>
    <artifactId>rdf4j-sparqlbuilder</artifactId>
    <version>${rdf4j.version}</version>
</dependency>
```

## Queries

The Queries class provides static methods to instantiate the various query objects. For example:

```java
SelectQuery selectQuery = Queries.SELECT();
ConstructQuery constructQuery = Queries.CONSTRUCT();
```

Query objects provide methods to set or add the various elements appropriate for the type of query:

```java
Prefix ex;
Variable product;
TriplePattern personWroteBook, personAuthoredBook;

// ...

selectQuery.prefix(ex).select(product).where(product.isA(ex.iri("book"));
constructQuery.prefix(ex).construct(personWroteBook).where(personAuthoredBook);
```

## Elements

SPARQL elements are created using various static factory classes. Most core elements of a query are created by the static SparqlBuilder class:

```java
import org.eclipse.rdf4j.model.vocabulary.FOAF;

Variable price = SparqlBuilder.var("price");
System.out.println(price.getQueryString()); // ==> ?price

Prefix foaf = SparqlBuilder.prefix(FOAF.NS);
System.out.println(foaf.getQueryString()); // ==> PREFIX foaf: <http://xmlns.com/foaf/0.1/>
```

Other factory classes include the Queries class mentioned in the previous section, as well as the Expressions, GraphPatterns, and Rdf classes.
All query elements created by SparqlBuilder implement the QueryElement interface, which provides the getQueryString() method. This can be used to get the String representing the SPARQL syntax of any element.

## Graph Patterns

SparqlBuilder uses three classes to represent the SPARQL graph patterns, all of which implement the GraphPattern interface:
- The TriplePattern class represents triple patterns.
- The GraphPatternNotTriple class represents collections of graph patterns.
- The SubSelect class represents a SPARQL sub query.

Graph patterns are created by the more aptly named GraphPatterns class.

###  Triple Patterns

Use `GraphPatterns#tp()` to create a TriplePattern instance:

```java
Prefix dc = SparqlBuilder.prefix("dc", iri("http://purl.org/dc/elements/1.1/"));
Variable book = SparqlBuilder.var("book");

TriplePattern triple = GraphPatterns.tp(book, dc.iri("author"), Rdf.literalOf("J.R.R. Tolkien"));
System.out.println(triple.getQueryString()); // ==> ?book dc:author "J.R.R. Tolkien"
```

or, using RDF4J Model object and vocabulary constants directly:

```java
Prefix dc = SparqlBuilder.prefix(DC.NS);
Variable book = SparqlBuilder.var("book");

TriplePattern triple = GraphPatterns.tp(book, DC.AUTHOR, Rdf.literalOf("J.R.R. Tolkien"));
System.out.println(triple.getQueryString()); // ==> ?book dc:author "J.R.R. Tolkien"
```

In almost all places, SparqlBuilder allows either RDF4J Model objects or its own interfaces to be used. You can freely mix this.

A TriplePattern instance can also be created from the `has()` and `isA()` shortcut methods of `RdfSubject`, and be expanded to contain multiple triples with the same subject via predicate-object lists and object lists:

```java
Prefix foaf = SparqlBuilder.prefix(FOAF.NS);
Variable x = SparqlBuilder.var("x"), name = SparqlBuilder.var("name");

TriplePattern triple = x.has(FOAF.NICK, Rdf.literalOf("Alice"), Rdf.literalOf("Alice_"))
    .andHas(FOAF.NAME, name);
System.out.println(triple.getQueryString());
// ===> ?x foaf:nick "Alice_", "Alice" ;
//	   foaf:name ?name .
```

### Property Paths

Property paths can be generated with a lambda expression that uses a builder pattern
wherever a predicate (IRI) can be passed:
```
SelectQuery query = Queries
    .SELECT(name)
    .prefix(FOAF.NS)
    .where(x.has(p -> p.pred(FOAF.ACCOUNT)
                .then(FOAF.MBOX),
            name))
```
yields
```
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { ?x foaf:account / foaf:mbox ?name . }
```
Here are a few examples and the path they yield

| property path builder code          |  property path |
|--------------------------|---------------- |
|`p -> p.pred(FOAF.ACCOUNT).then(FOAF.MBOX)` | `foaf:account / foaf:mbox` |
|`p -> p.pred(RDF.TYPE).then(RDFS.SUBCLASSOF).zeroOrMore()` | `rdf:type / rdfs:subClassOf *` |
|`p -> p.pred(EX.MOTHER_OF).or(EX.FATHER_OF).oneOrMore()` | `( ex:motherOf \| ex:fatherOf ) +` |
|`p -> p.pred(EX.MOTHER_OF).or(p1 -> p1.pred(EX.FATHER_OF).zeroOrOne())` | `ex:motherOf \| ( ex:fatherOf ? )` |
|`p -> p.negProp().pred(RDF.TYPE).invPred(RDF.TYPE)` | `!( rdf:type \| ^ rdf:type )` |

### Compound graph patterns

Three methods in GraphPatterns exist to create GraphPatternNotTriple instances. `GraphPatterns#and()` creates a group graph pattern, consisting of the GraphPattern instances passed as parameters:

```java
Variable mbox = SparqlBuilder.var("mbox"), x = SparqlBuilder.var("x");
GraphPatternNotTriple groupPattern =
GraphPatterns.and(x.has(FOAF.NAME), name), x.has(FOAF.MBOX, mbox);
System.out.println(groupPattern.getQueryString());
// ==> { ?x foaf:mbox ?mbox . ?x foaf:name ?name }
```

`GraphPatterns#union()` creates an alternative graph pattern, taking the union of the provided GraphPattern instances:

```java
Prefix dc10 = SparqlBuilder.prefix("dc10", iri("http://purl.org/dc/elements/1.0/")),
	dc11 = SparqlBuilder.prefix("dc11", iri("http://purl.org/dc/elements/1.1/"));
Variable book = SparqlBuilder.var("book"), title = SparqlBuilder.var("title");

GraphPatternNotTriple union = GraphPatterns.union(book.has(dc10.iri("title"), title),
	book.has(dc11.iri("title"), title);
System.out.println(union.getQueryString());
// ==> { ?book dc10:title ?title } UNION { ?book dc11:title ?title }
```

`GraphPatterns#optional()` creates an optional group graph pattern, consisting of the passed in `GraphPattern`s:

```java
GraphPatternNotTriple optionalPattern = GraphPatterns.optional(GraphPatterns.tp(x, foaf.iri("mbox"), mbox));
System.out.println(optionalPattern.getQueryString());
// ==> OPTIONAL { ?x foaf:mbox ?mbox }
```

### Sub-select

Finally, GraphPatterns#select() creates an instance of a SubSelect, which represents a SPARQL subquery:

```java
SubSelect subQuery = GraphPatterns.select();
```

## Query Constraints

You can create SPARQL query constraints using the Expressions class which provides static methods to create Expression objects representing SPARQL's built-in expressions:

```java
Variable name = SparqlBuilder.var("name");
Expression<?> regexExpression = Expressions.regex(name, "Smith");
System.out.println(regexExpression.getQueryString());
// ==> REGEX( ?name, "Smith" )
```

`Expression`s take `Operand` instances as arguments. Operand is implemented by the types you would expect (Variable, the RDF model interface RdfValue, and Expression itself). Where possible, Expressions has included wrappers to take appropriate Java primitives as parameters as well:

```java
Variable price = SparqlBuilder.var("price");
Expression<?> priceLimit = Expressions.lt(price, 100);
System.out.println(priceLimit.getQueryString());
// ==> ?price < 100
```

For those places where a wrapper has not (yet) been created, `RdfLiteral`s can be used instead. The `Rdf` class provides factory methods to create StringLiteral, NumericLiteral, and BooleanLiteral instances:

```java
Variable price = SparqlBuilder.var("price");
ExpressionOperand discount = Rdf.literalOf(0.9);
Expression<?> discountedPrice = Expressions.multiply(price, discount);
System.out.println(discountedPrice.getQueryString());
// ==> ( ?price * 0.9 )
```

## The RDF Model

SparqlBuilder provides a collection of interfaces to model RDF objects in the `org.eclipse.rdf4j.sparqlbuilder.rdf` package. Instances of these interfaces can be used when needed and as expected while creating SPARQL queries. The `Rdf` class contains static factory methods to create RDF objects for use with SparqlBuilder, including IRI's, blank nodes, and RDF literals.
Currently SparqlBuilder's set of interfaces for RDF model objects is different from the main RDF4J model interfaces. This will be further integrated in future releases.

## Examples

For more detailed examples of how to use SparqlBuilder, check out the JUnit tests located within the project.

## Known Limitations

Currently, the following SPARQL 1.1 features have not yet been implemented in SparqlBuilder:

- Values Block
- RDF Collection Syntax
- DESCRIBE and ASK Queries


text:
# Improve VirtualDisplayEncoder for stable frame rate

* Proposal: [SDL-0292](0292-improve-VDE-for-stable-frame-rate.md)
* Author: [Shinichi Watanabe](https://github.com/shiniwat)
* Status: **Accepted**
* Impacted Platforms: [Java Suite]

## Introduction

This proposal improves the quality of video projection when using Android `VirtualDisplay` and `MediaEncoder`, as Android `MediaEncoder` does not produce a consistent frame rate for rendering `VirtualDisplay`'s surface.

[SDL-0274](0274-add-preferred-FPS.md) introduced `preferredFPS` parameter specified in `VideoStreamingCapability`. This proposal helps to implement the `preferredFPS` support in the sdl_java_suite platform.

## Motivation

A part of sdl_java_suite library utilizes `VirtualDisplay` and `MediaEncoder` to produce the video projection stream.
Actually, frame rate of video stream depends on how often `MediaCodec.Callback` gets called.
The component structure is illustrated as follows:

![virtualdisplay_unstable_rate](../assets/proposals/0292-improve-VDE-for-stable-frame-rate/vd_mc_unstable.png)

**Fig. 1: VirtualDisplay's surface produces unstable frame rate**

For instance,
- if an app's content in `VirtualDisplay` is updated quite often, the `MediaEncoder` associated with `VirtualDisplay`'s surface produces 60 frames per second.
- if an app's content in `VirtualDisplay` is not updated very frequently, its surface produces rather few frames (e.g. 20 frames) per second.

Most HUs would be designed for consistent video frame rate, so it may cause some negative effect if video frame rate goes up and down.

This proposal addresses this Android specific issue as it's closely related to how Android `VirtualDisplay` works.

## Proposed solution

Because the issue comes from the fact where `VirtualDisplay`'s surface emits output buffer in a variable rate, the idea is:

- Give the intermediate surface to `VirtualDisplay`.
- When `VirtualDisplay` sends frames, the intermediate surface can determine whether or not to forward them into `MediaCodec`'s input surface.

The approach is introduced at http://stackoverflow.com/questions/31527134/controlling-frame-rate-of-virtualdisplay, i.e.

- Create a `SurfaceTexture`, construct a Surface from it, and give it to `VirtualDisplay`.
- When `SurfaceTexture` fires `onFrameAvailable` callback, we can buffer the frame, and render the texture onto `MediaCodec`'s input surface by using GLES.

The idea is illustrated as follows:

![virtualdisplay_w_intermediate_surface](../assets/proposals/0292-improve-VDE-for-stable-frame-rate/vd_w_intermediate_surface.png)

**Fig. 2: VirtualDisplay with intermediate Surface**

### Detailed design

The proposed solution heavily depends on Android OpenGL ES components (classes under android.opengl namespace), which are composed of following classes:
- android.opengl.EGLConfig
- android.opengl.EGLContext
- android.opengl.EGLDisplay
- android.opengl.EGLSurface

Actually an open source graphic library, called [Grafika](https://github.com/google/grafika) already implemented some useful wrapper classes that internally wrap some GLES classes, and the following wrapper classes in Grafika already did exactly what we want:
- `EglCore` (com.android.grafika.gles.EglCore)
- `OffscreenSurface` (com.android.grafika.gles.OffscreenSurface)
- `WindowSurface` (com.android.grafika.gles.WindowSurface)
- `FullFrameRect` (com.android.grafika.gles.FullFrameRect)

Instead of having dependency on above Grafika classes, I tried to use those GLES classes directly.
However, Grafika classes above are just thin wrappers of GLES classes, and because the basic idea is exactly the same as what some part of Grafika does, as a nature of open source policy, we should follow the Grafika's Apache License 2.0.

It is exactly the philosophy of open source, and re-inventing a wheel does not make sense.

Based on the concept above, the detailed design would be:

1. Setup intermediate surface and surface texture.
We need to add the following components into `VirtualDisplayEncoder` class.

- `EglCore` (com.android.grafika.gles.EglCore)
- `OffscreenSurface` (com.android.grafika.gles.OffscreenSurface)
- `TextureId`, which can be created by `FullFrameRect.createTextureObject()`
- `SurfaceTexture` with above `TextureId`
- Surface with above `SurfaceTexture` (let's call this to IntermediateSurface)
- `WindowSurface` (com.android.grafika.gles.WindowSurface)

2. Create `VirtualDisplay` with IntermediateSurface
Instead of inputSurface, we use IntermediateSurface for `VirtualDisplay`, so that we can control update timing of the IntermediateSurface.

3. Create capture thread
In capture thread, we periodically update surface texture, so that we can capture the surface in a constant rate.

The pseudo code of CaptureThread looks as follows:

```java
 import android.os.Looper;private final class CaptureThread extends Thread implements SurfaceTexture.OnFrameAvailableListener {
    long frameInterval; // this is given as the parameter
    static final int MSG_TICK = 1;
    static final int MSG_UPDATE_SURFACE = 2;

    private Handler handler;
    private SurfaceTexture surfaceTexture;
    private int textureId;
    private WindowSurface windowSurface;
    private FullFrameRect fullFrameRect;
    private long frameIntervalInNano = 1000000000 / fps; // fps should be specified by HU.
    private long nextTime;
    private final float[] matrix = new float[16];

    ...
    public void run() {
        Looper.prepare();
        // we use a Handler for this thread
        handler = new Handler() {
                public void handleMessage(Message msg) {
                    switch(msg.what) {
                        case MSG_TICK:
                            // we can draw the image in Surface Texture here, something like
                            long now = System.nanoTime();
                            if (now > nextTime) {
                                try {
                                    windowSurface.makeCurrent();
                                    GLES20.glViewport(0, 0, width, height);
                                    fullFrameRect.drawFrame(textureId, matrix);
                                } catch(RuntimeException e) {
                                    ...
                                }
                                nextTime += frameIntervalInNano;
                            }
                            long delayTime = // adjust delaytime..
                            handler.sendMessageDelayed(handler.obtainMessage(MSG_TICK), delayTime);
                            break;
                        case MSG_UPDATE_SURFACE:
                            // update the surface here.
                            updateSurface();
                    }
                }
         }
    }

    private void updateSurface() {
        try {
            windowSurface.makeCurrent()
        } catch(RuntimeException e) {
            ...
        }
        surfacetexture.updateTexImage();
        surfaceTexture.getTransformMatrix(matrix);
    }

    /**
    * this is where we update the surface
    * @param surfaceTexture
    */
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        // here, we can update surfaceTexture
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            updateSurface();
        } else {
            // note that API level is lower than 21 (LOLLIPOP), setOnFrameAvailableListener(listener) is used,
            // and most likely, OnFrameAvailableListener gets called in main thread.
            // In that case, we have to call updateSurface in CaptureThread instead.
            handler.sendMessage(handler.obtainMessafge(MSG_UPDATE_SURFACE));
        }

        // the first time this gets called, start the loop
        // by mHandler.sendMessage()
        if (nextTime == 0) {
            nextTime = System.nanoTime();
            handler.sendMessage(handler.obtainMessage(MSG_TICK));
        }
    }
 }
```

4. Add `stableFrameRate` to `VideoStreamingParameters`

Consistent frame rate should be beneficial for all head units. However, adding `stableFrameRate` flag to `VideoStreamingParameters` allows developers to turn on or off the capability.

```java
public class VideoStreamingParameters {
    ...
    private boolean stableFrameRate;

    public VideoStreamingParameters(){
        ...
        stableFrameRate = true; // true by default
    }

    public VideoStreamingParameters(int displayDensity, int frameRate, int bitrate, int interval,
                                    ImageResolution resolution, VideoStreamingFormat format, boolean stableFrameRate){
        ...
        this.stableFrameRate = stableFrameRate;
    }

    public void update(VideoStreamingParameters params){
        ...
        this.stableFrameRate = params.stableFrameRate;
    }
}
```

Please note that if head unit specified `preferredFPS` parameter, and if a developer turned off `stableFrameRate` flag, `MediaEncoder` will emit video frames very frequently, which will likely exceed the number of frames specified to `preferredFPS` partameter.

## Potential downsides

In the previous review session, there were some concerns about the quality of the Grafika library. As mentioned in the "Detailed design" section already, what we need are some GLES wrapper classes, which are already implemented as a part of the Grafika library.

We can add some Unit Tests for those wrapper classes to verify the code quality.
The other thing to note is that `Grafika` component is under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).

sdl_java_suite already uses some component under Apache License 2.0 (e.g. `JSON`), so adding another open source component won't cause any issues.

## Impact on existing code

Because this approach does not change an existing API, and changes are inside of `VirtualDisplayEncoder` class, there's no impact to developers who use `VirtualDisplayEncoder`.

Also note that a developer can explicitly turn off this feature by setting `VideoStreamingParameters.stableFrameRate` to false.

This proposal should be combined with "Add preferred FPS to VideoStreamingCapability" proposal, so that we can respect the preferred FPS value, which is specified by head unit.

## Alternatives considered

This is a pure improvement for existing `VistualDisplayEncoder`, so there are no alternatives, but this proposal adds the ability to specify the desired FPS on Proxy end.


text:
#include "config.h"

#include <stdarg.h>
#include <assert.h>

#define COBJMACROS

#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "winreg.h"
#include "ole2.h"
#include "shlguid.h"

#include "mshtml_private.h"
#include "htmlscript.h"
#include "htmlevent.h"
#include "binding.h"

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(mshtml);

#define IE_MAJOR_VERSION 7
#define IE_MINOR_VERSION 0

static const IID NS_ICONTENTUTILS_CID =
    {0x762C4AE7,0xB923,0x422F,{0xB9,0x7E,0xB9,0xBF,0xC1,0xEF,0x7B,0xF0}};

static nsIContentUtils *content_utils;

static PRUnichar *handle_insert_comment(HTMLDocumentNode *doc, const PRUnichar *comment)
{
    int majorv = 0, minorv = 0;
    const PRUnichar *ptr, *end;
    PRUnichar *buf;
    DWORD len;

    enum {
        CMP_EQ,
        CMP_LT,
        CMP_LTE,
        CMP_GT,
        CMP_GTE
    } cmpt = CMP_EQ;

    static const PRUnichar endifW[] = {'<','!','[','e','n','d','i','f',']'};

    if(comment[0] != '[' || comment[1] != 'i' || comment[2] != 'f')
        return NULL;

    ptr = comment+3;
    while(isspaceW(*ptr))
        ptr++;

    if(ptr[0] == 'l' && ptr[1] == 't') {
        ptr += 2;
        if(*ptr == 'e') {
            cmpt = CMP_LTE;
            ptr++;
        }else {
            cmpt = CMP_LT;
        }
    }else if(ptr[0] == 'g' && ptr[1] == 't') {
        ptr += 2;
        if(*ptr == 'e') {
            cmpt = CMP_GTE;
            ptr++;
        }else {
            cmpt = CMP_GT;
        }
    }

    if(!isspaceW(*ptr++))
        return NULL;
    while(isspaceW(*ptr))
        ptr++;

    if(ptr[0] != 'I' || ptr[1] != 'E')
        return NULL;

    ptr +=2;
    if(!isspaceW(*ptr++))
        return NULL;
    while(isspaceW(*ptr))
        ptr++;

    if(!isdigitW(*ptr))
        return NULL;
    while(isdigitW(*ptr))
        majorv = majorv*10 + (*ptr++ - '0');

    if(*ptr == '.') {
        ptr++;
        if(!isdigitW(*ptr))
            return NULL;
        while(isdigitW(*ptr))
            minorv = minorv*10 + (*ptr++ - '0');
    }

    while(isspaceW(*ptr))
        ptr++;
    if(ptr[0] != ']' || ptr[1] != '>')
        return NULL;
    ptr += 2;

    len = strlenW(ptr);
    if(len < sizeof(endifW)/sizeof(WCHAR))
        return NULL;

    end = ptr + len-sizeof(endifW)/sizeof(WCHAR);
    if(memcmp(end, endifW, sizeof(endifW)))
        return NULL;

    switch(cmpt) {
    case CMP_EQ:
        if(majorv == IE_MAJOR_VERSION && minorv == IE_MINOR_VERSION)
            break;
        return NULL;
    case CMP_LT:
        if(majorv > IE_MAJOR_VERSION)
            break;
        if(majorv == IE_MAJOR_VERSION && minorv > IE_MINOR_VERSION)
            break;
        return NULL;
    case CMP_LTE:
        if(majorv > IE_MAJOR_VERSION)
            break;
        if(majorv == IE_MAJOR_VERSION && minorv >= IE_MINOR_VERSION)
            break;
        return NULL;
    case CMP_GT:
        if(majorv < IE_MAJOR_VERSION)
            break;
        if(majorv == IE_MAJOR_VERSION && minorv < IE_MINOR_VERSION)
            break;
        return NULL;
    case CMP_GTE:
        if(majorv < IE_MAJOR_VERSION)
            break;
        if(majorv == IE_MAJOR_VERSION && minorv <= IE_MINOR_VERSION)
            break;
        return NULL;
    }

    buf = heap_alloc((end-ptr+1)*sizeof(WCHAR));
    if(!buf)
        return NULL;

    memcpy(buf, ptr, (end-ptr)*sizeof(WCHAR));
    buf[end-ptr] = 0;

    return buf;
}

static nsresult run_insert_comment(HTMLDocumentNode *doc, nsISupports *comment_iface, nsISupports *arg2)
{
    const PRUnichar *comment;
    nsIDOMComment *nscomment;
    PRUnichar *replace_html;
    nsAString comment_str;
    nsresult nsres;

    nsres = nsISupports_QueryInterface(comment_iface, &IID_nsIDOMComment, (void**)&nscomment);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMComment iface:%08x\n", nsres);
        return nsres;
    }

    nsAString_Init(&comment_str, NULL);
    nsres = nsIDOMComment_GetData(nscomment, &comment_str);
    if(NS_FAILED(nsres))
        return nsres;

    nsAString_GetData(&comment_str, &comment);
    replace_html = handle_insert_comment(doc, comment);
    nsAString_Finish(&comment_str);

    if(replace_html) {
        HRESULT hres;

        hres = replace_node_by_html(doc->nsdoc, (nsIDOMNode*)nscomment, replace_html);
        heap_free(replace_html);
        if(FAILED(hres))
            nsres = NS_ERROR_FAILURE;
    }

    nsIDOMComment_Release(nscomment);
    return nsres;
}

static nsresult run_bind_to_tree(HTMLDocumentNode *doc, nsISupports *nsiface, nsISupports *arg2)
{
    nsIDOMNode *nsnode;
    HTMLDOMNode *node;
    nsresult nsres;
    HRESULT hres;

    TRACE("(%p)->(%p)\n", doc, nsiface);

    nsres = nsISupports_QueryInterface(nsiface, &IID_nsIDOMNode, (void**)&nsnode);
    if(NS_FAILED(nsres))
        return nsres;

    hres = get_node(doc, nsnode, TRUE, &node);
    nsIDOMNode_Release(nsnode);
    if(FAILED(hres)) {
        ERR("Could not get node\n");
        return nsres;
    }

    if(node->vtbl->bind_to_tree)
        node->vtbl->bind_to_tree(node);

    node_release(node);
    return nsres;
}

/* Calls undocumented 69 cmd of CGID_Explorer */
static void call_explorer_69(HTMLDocumentObj *doc)
{
    IOleCommandTarget *olecmd;
    VARIANT var;
    HRESULT hres;

    if(!doc->client)
        return;

    hres = IOleClientSite_QueryInterface(doc->client, &IID_IOleCommandTarget, (void**)&olecmd);
    if(FAILED(hres))
        return;

    VariantInit(&var);
    hres = IOleCommandTarget_Exec(olecmd, &CGID_Explorer, 69, 0, NULL, &var);
    IOleCommandTarget_Release(olecmd);
    if(SUCCEEDED(hres) && V_VT(&var) != VT_NULL)
        FIXME("handle result\n");
}

static void parse_complete(HTMLDocumentObj *doc)
{
    TRACE("(%p)\n", doc);

    if(doc->usermode == EDITMODE)
        init_editor(&doc->basedoc);

    call_explorer_69(doc);
    if(doc->view_sink)
        IAdviseSink_OnViewChange(doc->view_sink, DVASPECT_CONTENT, -1);
    call_property_onchanged(&doc->basedoc.cp_container, 1005);
    call_explorer_69(doc);

    if(doc->webbrowser && doc->usermode != EDITMODE && !(doc->basedoc.window->load_flags & BINDING_REFRESH))
        IDocObjectService_FireNavigateComplete2(doc->doc_object_service, &doc->basedoc.window->base.IHTMLWindow2_iface, 0);

    /* FIXME: IE7 calls EnableModelless(TRUE), EnableModelless(FALSE) and sets interactive state here */
}

static nsresult run_end_load(HTMLDocumentNode *This, nsISupports *arg1, nsISupports *arg2)
{
    TRACE("(%p)\n", This);

    if(!This->basedoc.doc_obj)
        return NS_OK;

    if(This == This->basedoc.doc_obj->basedoc.doc_node) {
        /*
         * This should be done in the worker thread that parses HTML,
         * but we don't have such thread (Gecko parses HTML for us).
         */
        parse_complete(This->basedoc.doc_obj);
    }

    bind_event_scripts(This);
    set_ready_state(This->basedoc.window, READYSTATE_INTERACTIVE);
    return NS_OK;
}

static nsresult run_insert_script(HTMLDocumentNode *doc, nsISupports *script_iface, nsISupports *parser_iface)
{
    nsIDOMHTMLScriptElement *nsscript;
    HTMLScriptElement *script_elem;
    nsIParser *nsparser = NULL;
    script_queue_entry_t *iter;
    HTMLInnerWindow *window;
    nsresult nsres;
    HRESULT hres;

    TRACE("(%p)->(%p)\n", doc, script_iface);

    window = doc->window;
    if(!window)
        return NS_OK;

    nsres = nsISupports_QueryInterface(script_iface, &IID_nsIDOMHTMLScriptElement, (void**)&nsscript);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMHTMLScriptElement: %08x\n", nsres);
        return nsres;
    }

    if(parser_iface) {
        nsres = nsISupports_QueryInterface(parser_iface, &IID_nsIParser, (void**)&nsparser);
        if(NS_FAILED(nsres)) {
            ERR("Could not get nsIParser iface: %08x\n", nsres);
            nsparser = NULL;
        }
    }

    hres = script_elem_from_nsscript(doc, nsscript, &script_elem);
    nsIDOMHTMLScriptElement_Release(nsscript);
    if(FAILED(hres))
        return NS_ERROR_FAILURE;

    if(nsparser) {
        nsIParser_BeginEvaluatingParserInsertedScript(nsparser);
        window->parser_callback_cnt++;
    }

    IHTMLWindow2_AddRef(&window->base.IHTMLWindow2_iface);

    doc_insert_script(window, script_elem);

    while(!list_empty(&window->script_queue)) {
        iter = LIST_ENTRY(list_head(&window->script_queue), script_queue_entry_t, entry);
        list_remove(&iter->entry);
        if(!iter->script->parsed)
            doc_insert_script(window, iter->script);
        IHTMLScriptElement_Release(&iter->script->IHTMLScriptElement_iface);
        heap_free(iter);
    }

    IHTMLWindow2_Release(&window->base.IHTMLWindow2_iface);

    if(nsparser) {
        window->parser_callback_cnt--;
        nsIParser_EndEvaluatingParserInsertedScript(nsparser);
        nsIParser_Release(nsparser);
    }

    IHTMLScriptElement_Release(&script_elem->IHTMLScriptElement_iface);

    return NS_OK;
}

typedef struct nsRunnable nsRunnable;

typedef nsresult (*runnable_proc_t)(HTMLDocumentNode*,nsISupports*,nsISupports*);

struct nsRunnable {
    nsIRunnable  nsIRunnable_iface;

    LONG ref;

    runnable_proc_t proc;

    HTMLDocumentNode *doc;
    nsISupports *arg1;
    nsISupports *arg2;
};

static inline nsRunnable *impl_from_nsIRunnable(nsIRunnable *iface)
{
    return CONTAINING_RECORD(iface, nsRunnable, nsIRunnable_iface);
}

static nsresult NSAPI nsRunnable_QueryInterface(nsIRunnable *iface,
        nsIIDRef riid, void **result)
{
    nsRunnable *This = impl_from_nsIRunnable(iface);

    if(IsEqualGUID(riid, &IID_nsISupports)) {
        TRACE("(%p)->(IID_nsISupports %p)\n", This, result);
        *result = &This->nsIRunnable_iface;
    }else if(IsEqualGUID(riid, &IID_nsIRunnable)) {
        TRACE("(%p)->(IID_nsIRunnable %p)\n", This, result);
        *result = &This->nsIRunnable_iface;
    }else {
        *result = NULL;
        WARN("(%p)->(%s %p)\n", This, debugstr_guid(riid), result);
        return NS_NOINTERFACE;
    }

    nsISupports_AddRef((nsISupports*)*result);
    return NS_OK;
}

static nsrefcnt NSAPI nsRunnable_AddRef(nsIRunnable *iface)
{
    nsRunnable *This = impl_from_nsIRunnable(iface);
    LONG ref = InterlockedIncrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    return ref;
}

static nsrefcnt NSAPI nsRunnable_Release(nsIRunnable *iface)
{
    nsRunnable *This = impl_from_nsIRunnable(iface);
    LONG ref = InterlockedDecrement(&This->ref);

    TRACE("(%p) ref=%d\n", This, ref);

    if(!ref) {
        htmldoc_release(&This->doc->basedoc);
        if(This->arg1)
            nsISupports_Release(This->arg1);
        if(This->arg2)
            nsISupports_Release(This->arg2);
        heap_free(This);
    }

    return ref;
}

static nsresult NSAPI nsRunnable_Run(nsIRunnable *iface)
{
    nsRunnable *This = impl_from_nsIRunnable(iface);

    return This->proc(This->doc, This->arg1, This->arg2);
}

static const nsIRunnableVtbl nsRunnableVtbl = {
    nsRunnable_QueryInterface,
    nsRunnable_AddRef,
    nsRunnable_Release,
    nsRunnable_Run
};

static void add_script_runner(HTMLDocumentNode *This, runnable_proc_t proc, nsISupports *arg1, nsISupports *arg2)
{
    nsRunnable *runnable;

    runnable = heap_alloc_zero(sizeof(*runnable));
    if(!runnable)
        return;

    runnable->nsIRunnable_iface.lpVtbl = &nsRunnableVtbl;
    runnable->ref = 1;

    htmldoc_addref(&This->basedoc);
    runnable->doc = This;
    runnable->proc = proc;

    if(arg1)
        nsISupports_AddRef(arg1);
    runnable->arg1 = arg1;

    if(arg2)
        nsISupports_AddRef(arg2);
    runnable->arg2 = arg2;

    nsIContentUtils_AddScriptRunner(content_utils, &runnable->nsIRunnable_iface);

    nsIRunnable_Release(&runnable->nsIRunnable_iface);
}

static inline HTMLDocumentNode *impl_from_nsIDocumentObserver(nsIDocumentObserver *iface)
{
    return CONTAINING_RECORD(iface, HTMLDocumentNode, nsIDocumentObserver_iface);
}

static nsresult NSAPI nsDocumentObserver_QueryInterface(nsIDocumentObserver *iface,
        nsIIDRef riid, void **result)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);

    if(IsEqualGUID(&IID_nsISupports, riid)) {
        TRACE("(%p)->(IID_nsISupports, %p)\n", This, result);
        *result = &This->nsIDocumentObserver_iface;
    }else if(IsEqualGUID(&IID_nsIMutationObserver, riid)) {
        TRACE("(%p)->(IID_nsIMutationObserver %p)\n", This, result);
        *result = &This->nsIDocumentObserver_iface;
    }else if(IsEqualGUID(&IID_nsIDocumentObserver, riid)) {
        TRACE("(%p)->(IID_nsIDocumentObserver %p)\n", This, result);
        *result = &This->nsIDocumentObserver_iface;
    }else {
        *result = NULL;
        TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), result);
        return NS_NOINTERFACE;
    }

    htmldoc_addref(&This->basedoc);
    return NS_OK;
}

static nsrefcnt NSAPI nsDocumentObserver_AddRef(nsIDocumentObserver *iface)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);
    return htmldoc_addref(&This->basedoc);
}

static nsrefcnt NSAPI nsDocumentObserver_Release(nsIDocumentObserver *iface)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);
    return htmldoc_release(&This->basedoc);
}

static void NSAPI nsDocumentObserver_CharacterDataWillChange(nsIDocumentObserver *iface,
        nsIDocument *aDocument, nsIContent *aContent, void /*CharacterDataChangeInfo*/ *aInfo)
{
}

static void NSAPI nsDocumentObserver_CharacterDataChanged(nsIDocumentObserver *iface,
        nsIDocument *aDocument, nsIContent *aContent, void /*CharacterDataChangeInfo*/ *aInfo)
{
}

static void NSAPI nsDocumentObserver_AttributeWillChange(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContent, LONG aNameSpaceID, nsIAtom *aAttribute, LONG aModType)
{
}

static void NSAPI nsDocumentObserver_AttributeChanged(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContent, LONG aNameSpaceID, nsIAtom *aAttribute, LONG aModType)
{
}

static void NSAPI nsDocumentObserver_AttributeSetToCurrentValue(nsIDocumentObserver *iface, nsIDocument *aDocument,
        void *aElement, LONG aNameSpaceID, nsIAtom *aAttribute)
{
}

static void NSAPI nsDocumentObserver_ContentAppended(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContainer, nsIContent *aFirstNewContent, LONG aNewIndexInContainer)
{
}

static void NSAPI nsDocumentObserver_ContentInserted(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContainer, nsIContent *aChild, LONG aIndexInContainer)
{
}

static void NSAPI nsDocumentObserver_ContentRemoved(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContainer, nsIContent *aChild, LONG aIndexInContainer,
        nsIContent *aProviousSibling)
{
}

static void NSAPI nsDocumentObserver_NodeWillBeDestroyed(nsIDocumentObserver *iface, const nsINode *aNode)
{
}

static void NSAPI nsDocumentObserver_ParentChainChanged(nsIDocumentObserver *iface, nsIContent *aContent)
{
}

static void NSAPI nsDocumentObserver_BeginUpdate(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsUpdateType aUpdateType)
{
}

static void NSAPI nsDocumentObserver_EndUpdate(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsUpdateType aUpdateType)
{
}

static void NSAPI nsDocumentObserver_BeginLoad(nsIDocumentObserver *iface, nsIDocument *aDocument)
{
}

static void NSAPI nsDocumentObserver_EndLoad(nsIDocumentObserver *iface, nsIDocument *aDocument)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);

    TRACE("(%p)\n", This);

    if(This->skip_mutation_notif)
        return;

    This->content_ready = TRUE;
    add_script_runner(This, run_end_load, NULL, NULL);
}

static void NSAPI nsDocumentObserver_ContentStatesChanged(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContent, nsEventStates *aStateMask)
{
}

static void NSAPI nsDocumentObserver_DocumentStatesChanged(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsEventStates *aStateMask)
{
}

static void NSAPI nsDocumentObserver_StyleSheetAdded(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIStyleSheet *aStyleSheet, cpp_bool aDocumentSheet)
{
}

static void NSAPI nsDocumentObserver_StyleSheetRemoved(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIStyleSheet *aStyleSheet, cpp_bool aDocumentSheet)
{
}

static void NSAPI nsDocumentObserver_StyleSheetApplicableStateChanged(nsIDocumentObserver *iface,
        nsIDocument *aDocument, nsIStyleSheet *aStyleSheet, cpp_bool aApplicable)
{
}

static void NSAPI nsDocumentObserver_StyleRuleChanged(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIStyleSheet *aStyleSheet, nsIStyleRule *aOldStyleRule, nsIStyleSheet *aNewStyleRule)
{
}

static void NSAPI nsDocumentObserver_StyleRuleAdded(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIStyleSheet *aStyleSheet, nsIStyleRule *aStyleRule)
{
}

static void NSAPI nsDocumentObserver_StyleRuleRemoved(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIStyleSheet *aStyleSheet, nsIStyleRule *aStyleRule)
{
}

static void NSAPI nsDocumentObserver_BindToDocument(nsIDocumentObserver *iface, nsIDocument *aDocument,
        nsIContent *aContent)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);
    nsIDOMHTMLIFrameElement *nsiframe;
    nsIDOMHTMLFrameElement *nsframe;
    nsIDOMHTMLScriptElement *nsscript;
    nsIDOMComment *nscomment;
    nsIDOMElement *nselem;
    nsresult nsres;

    TRACE("(%p)\n", This);

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMElement, (void**)&nselem);
    if(NS_SUCCEEDED(nsres)) {
        check_event_attr(This, nselem);
        nsIDOMElement_Release(nselem);
    }

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMComment, (void**)&nscomment);
    if(NS_SUCCEEDED(nsres)) {
        TRACE("comment node\n");

        add_script_runner(This, run_insert_comment, (nsISupports*)nscomment, NULL);
        nsIDOMComment_Release(nscomment);
        return;
    }

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMHTMLIFrameElement, (void**)&nsiframe);
    if(NS_SUCCEEDED(nsres)) {
        TRACE("iframe node\n");

        add_script_runner(This, run_bind_to_tree, (nsISupports*)nsiframe, NULL);
        nsIDOMHTMLIFrameElement_Release(nsiframe);
        return;
    }

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMHTMLFrameElement, (void**)&nsframe);
    if(NS_SUCCEEDED(nsres)) {
        TRACE("frame node\n");

        add_script_runner(This, run_bind_to_tree, (nsISupports*)nsframe, NULL);
        nsIDOMHTMLFrameElement_Release(nsframe);
        return;
    }

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMHTMLScriptElement, (void**)&nsscript);
    if(NS_SUCCEEDED(nsres)) {
        HTMLScriptElement *script_elem;
        HRESULT hres;

        TRACE("script element\n");

        hres = script_elem_from_nsscript(This, nsscript, &script_elem);
        nsIDOMHTMLScriptElement_Release(nsscript);
        if(FAILED(hres))
            return;

        if(script_elem->parse_on_bind)
            add_script_runner(This, run_insert_script, (nsISupports*)nsscript, NULL);

        IHTMLScriptElement_Release(&script_elem->IHTMLScriptElement_iface);
    }
}

static void NSAPI nsDocumentObserver_AttemptToExecuteScript(nsIDocumentObserver *iface, nsIContent *aContent,
        nsIParser *aParser, cpp_bool *aBlock)
{
    HTMLDocumentNode *This = impl_from_nsIDocumentObserver(iface);
    nsIDOMHTMLScriptElement *nsscript;
    nsresult nsres;

    TRACE("(%p)->(%p %p %p)\n", This, aContent, aParser, aBlock);

    nsres = nsIContent_QueryInterface(aContent, &IID_nsIDOMHTMLScriptElement, (void**)&nsscript);
    if(NS_SUCCEEDED(nsres)) {
        TRACE("script node\n");

        add_script_runner(This, run_insert_script, (nsISupports*)nsscript, (nsISupports*)aParser);
        nsIDOMHTMLScriptElement_Release(nsscript);
    }
}

static const nsIDocumentObserverVtbl nsDocumentObserverVtbl = {
    nsDocumentObserver_QueryInterface,
    nsDocumentObserver_AddRef,
    nsDocumentObserver_Release,
    nsDocumentObserver_CharacterDataWillChange,
    nsDocumentObserver_CharacterDataChanged,
    nsDocumentObserver_AttributeWillChange,
    nsDocumentObserver_AttributeChanged,
    nsDocumentObserver_AttributeSetToCurrentValue,
    nsDocumentObserver_ContentAppended,
    nsDocumentObserver_ContentInserted,
    nsDocumentObserver_ContentRemoved,
    nsDocumentObserver_NodeWillBeDestroyed,
    nsDocumentObserver_ParentChainChanged,
    nsDocumentObserver_BeginUpdate,
    nsDocumentObserver_EndUpdate,
    nsDocumentObserver_BeginLoad,
    nsDocumentObserver_EndLoad,
    nsDocumentObserver_ContentStatesChanged,
    nsDocumentObserver_DocumentStatesChanged,
    nsDocumentObserver_StyleSheetAdded,
    nsDocumentObserver_StyleSheetRemoved,
    nsDocumentObserver_StyleSheetApplicableStateChanged,
    nsDocumentObserver_StyleRuleChanged,
    nsDocumentObserver_StyleRuleAdded,
    nsDocumentObserver_StyleRuleRemoved,
    nsDocumentObserver_BindToDocument,
    nsDocumentObserver_AttemptToExecuteScript
};

void init_document_mutation(HTMLDocumentNode *doc)
{
    nsIDocument *nsdoc;
    nsresult nsres;

    doc->nsIDocumentObserver_iface.lpVtbl = &nsDocumentObserverVtbl;

    nsres = nsIDOMHTMLDocument_QueryInterface(doc->nsdoc, &IID_nsIDocument, (void**)&nsdoc);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDocument: %08x\n", nsres);
        return;
    }

    nsIContentUtils_AddDocumentObserver(content_utils, nsdoc, &doc->nsIDocumentObserver_iface);
    nsIDocument_Release(nsdoc);
}

void release_document_mutation(HTMLDocumentNode *doc)
{
    nsIDocument *nsdoc;
    nsresult nsres;

    nsres = nsIDOMHTMLDocument_QueryInterface(doc->nsdoc, &IID_nsIDocument, (void**)&nsdoc);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDocument: %08x\n", nsres);
        return;
    }

    nsIContentUtils_RemoveDocumentObserver(content_utils, nsdoc, &doc->nsIDocumentObserver_iface);
    nsIDocument_Release(nsdoc);
}

JSContext *get_context_from_document(nsIDOMHTMLDocument *nsdoc)
{
    nsIDocument *doc;
    JSContext *ctx;
    nsresult nsres;

    nsres = nsIDOMHTMLDocument_QueryInterface(nsdoc, &IID_nsIDocument, (void**)&doc);
    assert(nsres == NS_OK);

    ctx = nsIContentUtils_GetContextFromDocument(content_utils, doc);
    nsIDocument_Release(doc);

    TRACE("ret %p\n", ctx);
    return ctx;
}

void init_mutation(nsIComponentManager *component_manager)
{
    nsIFactory *factory;
    nsresult nsres;

    if(!component_manager) {
        if(content_utils) {
            nsIContentUtils_Release(content_utils);
            content_utils = NULL;
        }
        return;
    }

    nsres = nsIComponentManager_GetClassObject(component_manager, &NS_ICONTENTUTILS_CID,
            &IID_nsIFactory, (void**)&factory);
    if(NS_FAILED(nsres)) {
        ERR("Could not create nsIContentUtils service: %08x\n", nsres);
        return;
    }

    nsres = nsIFactory_CreateInstance(factory, NULL, &IID_nsIContentUtils, (void**)&content_utils);
    nsIFactory_Release(factory);
    if(NS_FAILED(nsres))
        ERR("Could not create nsIContentUtils instance: %08x\n", nsres);
}


text:
# Pushes all deb and rpm files from ./repos to PackageCloud.

packagecloud_user = ENV["PACKAGECLOUD_USER"] || "github"
packagecloud_token = ENV["PACKAGECLOUD_TOKEN"] || begin
  puts "PACKAGECLOUD_TOKEN env required"
  exit 1
end

require "json"

packagecloud_ruby_minimum_version = "1.0.4"
begin
  gem "packagecloud-ruby", ">=#{packagecloud_ruby_minimum_version}"
  require "packagecloud"
  puts "Using packagecloud-ruby:#{Gem.loaded_specs["packagecloud-ruby"].version}"
rescue LoadError
  puts "Requires packagecloud-ruby >=#{packagecloud_ruby_minimum_version}"
  puts %(gem install packagecloud-ruby)
  exit 1
end

credentials = Packagecloud::Credentials.new(packagecloud_user, packagecloud_token)
$client = Packagecloud::Client.new(credentials)

# matches package directories built by docker to one or more packagecloud distros
# https://packagecloud.io/docs#os_distro_version
$distro_name_map = {
  "centos/5" => %w(
    el/5
  ),
  "centos/6" => %w(
    el/6
  ),
  "centos/7" => %w(
    el/7
    fedora/22
    fedora/23
    fedora/24
    fedora/25
  ),
  "debian/7" => %w(
    debian/wheezy
    ubuntu/precise
  ),
  "debian/8" => %w(
    debian/jessie
    linuxmint/rafaela
    linuxmint/rebecca
    linuxmint/rosa
    linuxmint/sarah
    linuxmint/serena
    ubuntu/trusty
    ubuntu/vivid
    ubuntu/wily
    ubuntu/xenial
  ),
  "debian/9" => %W(
    debian/stretch
    ubuntu/yakkety
    ubuntu/zesty
  ),
}

# caches distro id lookups
$distro_id_map = {}

def distro_names_for(filename)
  $distro_name_map.each do |pattern, distros|
    return distros if filename.include?(pattern)
  end

  raise "no distro for #{filename.inspect}"
end

package_files = Dir.glob("repos/**/*.rpm") + Dir.glob("repos/**/*.deb")
package_files.each do |full_path|
  next if full_path =~ /repo-release/
  pkg = Packagecloud::Package.new(:file => full_path)
  distro_names = distro_names_for(full_path)
  distro_names.map do |distro_name|
    distro_id = $distro_id_map[distro_name] ||= $client.find_distribution_id(distro_name)
    if !distro_id
      raise "no distro id for #{distro_name.inspect}"
    end

    puts "pushing #{full_path} to #{$distro_id_map.key(distro_id).inspect}"
    result = $client.put_package("git-lfs", pkg, distro_id)
    result.succeeded || begin
      raise "packagecloud put_package failed, error: #{result.response}"
    end
  end
end

package_files.each do |full_path|
  next if full_path.include?("SRPM") || full_path.include?("i386") || full_path.include?("i686")
  next unless full_path =~ /\/git-lfs[-|_]\d/
  os, distro = case full_path
  when /debian\/7/ then ["Debian 7", "debian/wheezy"]
  when /debian\/8/ then ["Debian 8", "debian/jessie"]
  when /centos\/5/ then ["RPM RHEL 5/CentOS 5", "el/5"]
  when /centos\/6/ then ["RPM RHEL 6/CentOS 6", "el/6"]
  when /centos\/7/ then ["RPM RHEL 7/CentOS 7", "el/7"]
  end

  next unless os

  puts "[#{os}](https://packagecloud.io/#{packagecloud_user}/git-lfs/packages/#{distro}/#{File.basename(full_path)}/download)"
end


text:
class HelperGenerator {
public:
    HelperGenerator(const QString &name);
    bool generate(const QString &dst) const;

private:
    QString name;
};


text:
package net.patrykczarnik.vp.custom_filters;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import net.patrykczarnik.ffmpeg.FFFilter;
import net.patrykczarnik.ffmpeg.FFFilterOption;
import net.patrykczarnik.utils.Positioned;
import net.patrykczarnik.vp.in.VPScriptOption;
import net.patrykczarnik.vp.in.VPScriptValue;
import net.patrykczarnik.vp.out.AFilterMapper;
import net.patrykczarnik.vp.out.AParamOrientedFilterMapper;

public class AutoCurves implements AParamOrientedFilterMapper {
	public static final int POSITION = AFilterMapper.POSITION_VIDEO_EQ+1;

	private int points = 256;
	private double g = 1.0; // should work as gamma, any value >0 is correct, 1.0 is neutral, use >1 to brighten the picture, especially darker parts
	private double a = 0.0; // brightness (stronger for light parts than gamma) without overflow, proper values are between 0 and 1, 0 is neutral
	private double c = 0.0; // non-linear contrast without overflow, proper values are between 0.0 (neutral) and 1.0 (contrast maximally increased)

	@Override
	public void begin() {
	}

	@Override
	public void acceptOption(VPScriptOption vpOption) {
		if("autocurves".equals(vpOption.getName())) {
			List<? extends VPScriptValue> paramValues = vpOption.getValue().asMany();
			if(paramValues.size() >= 1) {
				g = paramValues.get(0).numValue();
			}
			if(paramValues.size() >= 2) {
				a = paramValues.get(1).numValue();
			}
			if(paramValues.size() >= 3) {
				c = paramValues.get(2).numValue();
			}
			System.out.println("g=" + g + ", a="+a + ", c="+c);
		}
	}

	@Override
	public List<Positioned<FFFilter>> getCollectedFFFilters() {

		FFFilter filter = FFFilter.newFilter("curves", FFFilterOption.citedText("master", printPoints()));
		return List.of(Positioned.of(351, filter));
	}

	@Override
	public Set<String> observedParams() {
		return Set.of("autocurves");
	}

	private double curvesFunction(double x) {
		return Math.pow((1.0-c)*(x + a*(Math.pow(0.5, 2) - Math.pow(0.5-x, 2))) + c*(2*(x+(0.5-x)*Math.abs(0.5-x)) - 0.5), 1.0/g);
	}

	private String printPoints() {
		return IntStream.range(0, points)
			.mapToDouble(i -> (double)i / (points-1))
			.mapToObj(x -> x + "/" + curvesFunction(x))
			.collect(Collectors.joining(" "));
	}

}

// examples to check i.e. in kmplot
// g=1.5: f(x) = (x) ^ (1/1.5)
// a=0.7: f(x) = (x + 0.7∙(0.5^2 −(0.5−x)^2))
// c=1.0: f(x) = 1 ∙( 2∙(x + (0.5−x)∙abs(0.5−x)) − 0.5)
// all combined with g = 1.4, a = 0.3, c = 0.6:
// f(x) =  (0.4(x + 0.3∙(0.5^2 −(0.5−x)^2)) + 0.6∙( 2∙(x + (0.5−x)∙abs(0.5−x)) − 0.5)) ^ (1/1.4)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/src/js/bubble_sort.js" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/src/js/main.js" charset="UTF-8" />
  </component>
</project>


text:
@interface HJHomeController : UIViewController

@end


text:
<!DOCTYPE html>

		<title>Transclusion</title>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

Name	Price

				{{item.name}}	{{item.price | currency}}

		<button class="btn btn-default text" ng-click="changeData()">Change</button>


text:
test:
	@NODE_ENV=test ./node_modules/.bin/mocha --reporter list

.PHONY: test


text:
$(document).ready(() => {

    const list = $('#commits');
    const submit = $('#loadCommits');
    const baseURL = 'https://api.github.com/repos';

    submit.on('click', () => {

        loading();

        let username = $('#username').val();
        let repo = $('#repo').val();

        $.get(`${baseURL}\\${username}\\${repo}\\commits`)
            .then(displayCommits)
            .catch(displayErr)
            .always(clearAlways);

    });

    function displayCommits(data) {

        console.log(data);
        for (commit of data) {
            console.log(commit.commit);
            let li = $('
');
            li.html(`${commit.commit.author.name}: ${commit.commit.message}`);
            list.append(li);
        }
    }

    function displayErr(data) {
        list.append((data.status + ' ' + data.responseJSON.message));
    }

    function clearAlways() {
        submit.prop('disabled', false);
        $('#first').detach();
        $('#username').val('');
        $('#repo').val('');
    }

    function loading() {
        list.empty();
        list.append('
Loading...
');
        submit.prop('disabled', true);
    }
});


text:
package org.apache.wicket.markup;

/**
 * A base implementation of {@link IMarkupFragment}.
 */
public abstract class AbstractMarkupFragment implements IMarkupFragment
{

	protected final IMarkupFragment find(final String id, int streamOffset)
	{
		return TagUtils.findTagMarkup(this, id, null, streamOffset);
	}

	@Override
	public String toString()
	{
		return toString(false);
	}
}


text:
import uuid

from flask import Blueprint, request
from flask_restful import abort, Api, marshal_with, Resource
from sqlalchemy import or_

from .extensions import db
from .models import Tag, Category, URL
from .serializers import (
    tag_fields, category_fields, url_fields,
    url_parser_create, url_parser_update
)
from .utils import parse_pagination_args

api_bp = Blueprint('api', __name__)
api = Api(api_bp)

def get_instance_or_404_by_id(cls, id):
    try:
        id = str(id)
        uuid.UUID(id)
    except ValueError:
        abort(404)
    instance = db.session.query(cls).get(id)
    if instance is None:
        abort(404)
    return instance

class TagListView(Resource):
    @marshal_with(tag_fields)
    def get(self):
        return Tag.query.order_by(Tag.url_number.desc()).all()

class CategoryListView(Resource):
    @marshal_with(category_fields)
    def get(self):
        return Category.query.order_by(Category.url_number.desc()).all()

class URLListView(Resource):
    @marshal_with(url_fields)
    def get(self):
        pagination_args = parse_pagination_args(request.args)
        query = []
        search = request.args.get('search', '').strip()
        if search:
            query.append(
                or_(URL.title.contains(search),
                    URL.note.contains(search),
                    URL.url == search)
            )

        tag = request.args.get('tag', '').strip()
        if tag:
            query.append(URL.tags.any(name=tag))
        category = request.args.get('category', '').strip()
        if category:
            query.append(URL.categories.any(name=category))

        items = URL.query.filter(*query).order_by(
            URL.updated_at.desc()
        ).offset(
            pagination_args.offset
        ).limit(
            pagination_args.per_page
        ).all()
        return items

    @marshal_with(url_fields)
    def post(self):
        args = url_parser_create.parse_args()
        instance = URL.new_url(title=args['title'], url=args['url'],
                               starred=args['starred'],
                               tags_str=args['tags'],
                               categories_str=args['categories'])
        db.session.add(instance)
        db.session.commit()
        return instance, 201, {
            'Location': api.url_for(
                URLDetailView, id=instance.id, _external=True
            )
        }

class URLDetailView(Resource):
    @marshal_with(url_fields)
    def get(self, id):
        return get_instance_or_404_by_id(URL, id)

    @marshal_with(url_fields)
    def patch(self, id):
        args = url_parser_update.parse_args()
        instance = get_instance_or_404_by_id(URL, id)
        instance.update_url(url=args.get('url'),
                            title=args.get('title'),
                            starred=args.get('starred'),
                            tags_str=args.get('tags'),
                            categories_str=args.get('categories'))
        db.session.add(instance)
        db.session.commit()
        return instance

    def delete(self, id):
        obj = get_instance_or_404_by_id(URL, id)
        db.session.delete(obj)
        db.session.commit()
        return '', 204, {}

api.add_resource(CategoryListView, '/categories')
api.add_resource(TagListView, '/tags')
api.add_resource(URLDetailView, '/urls/<id>')
api.add_resource(URLListView, '/urls')