text:
""" pyModbusTCP utils functions """

import re
import socket
import struct

###############
# bits function
###############
def get_bits_from_int(val_int, val_size=16):
    """Get the list of bits of val_int integer (default size is 16 bits).

    Return bits list, the least significant bit first. Use list.reverse() for msb first.

    :param val_int: integer value
    :type val_int: int
    :param val_size: bit length of integer (word = 16, long = 32) (optional)
    :type val_size: int
    :returns: list of boolean "bits" (the least significant first)
    :rtype: list
    """
    bits = []
    # populate bits list with bool items of val_int
    for i in range(val_size):
        bits.append(bool((val_int >> i) & 0x01))
    # return bits list
    return bits

# short alias
int2bits = get_bits_from_int

def byte_length(bit_length):
    """Return the number of bytes needs to contain a bit_length structure.

    :param bit_length: the number of bits
    :type bit_length: int
    :returns: the number of bytes
    :rtype: int
    """
    return (bit_length + 7) // 8

def test_bit(value, offset):
    """Test a bit at offset position.

    :param value: value of integer to test
    :type value: int
    :param offset: bit offset (0 is lsb)
    :type offset: int
    :returns: value of bit at offset position
    :rtype: bool
    """
    mask = 1 << offset
    return bool(value & mask)

def set_bit(value, offset):
    """Set a bit at offset position.

    :param value: value of integer where set the bit
    :type value: int
    :param offset: bit offset (0 is lsb)
    :type offset: int
    :returns: value of integer with bit set
    :rtype: int
    """
    mask = 1 << offset
    return int(value | mask)

def reset_bit(value, offset):
    """Reset a bit at offset position.

    :param value: value of integer where reset the bit
    :type value: int
    :param offset: bit offset (0 is lsb)
    :type offset: int
    :returns: value of integer with bit reset
    :rtype: int
    """
    mask = ~(1 << offset)
    return int(value & mask)

def toggle_bit(value, offset):
    """Return an integer with the bit at offset position inverted.

    :param value: value of integer where invert the bit
    :type value: int
    :param offset: bit offset (0 is lsb)
    :type offset: int
    :returns: value of integer with bit inverted
    :rtype: int
    """
    mask = 1 << offset
    return int(value ^ mask)

########################
# Word convert functions
########################
def word_list_to_long(val_list, big_endian=True, long_long=False):
    """Word list (16 bits) to long (32 bits) or long long (64 bits) list.

    By default, word_list_to_long() use big endian order. For use little endian, set
    big_endian param to False. Output format could be long long with long_long.
    option set to True.

    :param val_list: list of 16 bits int value
    :type val_list: list
    :param big_endian: True for big endian/False for little (optional)
    :type big_endian: bool
    :param long_long: True for long long 64 bits, default is long 32 bits (optional)
    :type long_long: bool
    :returns: list of 32 bits int value
    :rtype: list
    """
    long_list = []
    block_size = 4 if long_long else 2
    # populate long_list (len is half or quarter of 16 bits val_list) with 32 or 64 bits value
    for index in range(int(len(val_list) / block_size)):
        start = block_size * index
        long = 0
        if big_endian:
            if long_long:
                long += (val_list[start] << 48) + (val_list[start + 1] << 32)
                long += (val_list[start + 2] << 16) + (val_list[start + 3])
            else:
                long += (val_list[start] << 16) + val_list[start + 1]
        else:
            if long_long:
                long += (val_list[start + 3] << 48) + (val_list[start + 2] << 32)
            long += (val_list[start + 1] << 16) + val_list[start]
        long_list.append(long)
    # return long list
    return long_list

# short alias
words2longs = word_list_to_long

def long_list_to_word(val_list, big_endian=True, long_long=False):
    """Long (32 bits) or long long (64 bits) list to word (16 bits) list.

    By default long_list_to_word() use big endian order. For use little endian, set
    big_endian param to False. Input format could be long long with long_long
    param to True.

    :param val_list: list of 32 bits int value
    :type val_list: list
    :param big_endian: True for big endian/False for little (optional)
    :type big_endian: bool
    :param long_long: True for long long 64 bits, default is long 32 bits (optional)
    :type long_long: bool
    :returns: list of 16 bits int value
    :rtype: list
    """
    word_list = []
    # populate 16 bits word_list with 32 or 64 bits value of val_list
    for val in val_list:
        block_l = [val & 0xffff, (val >> 16) & 0xffff]
        if long_long:
            block_l.append((val >> 32) & 0xffff)
            block_l.append((val >> 48) & 0xffff)
        if big_endian:
            block_l.reverse()
        word_list.extend(block_l)
    # return long list
    return word_list

# short alias
longs2words = long_list_to_word

##########################
# 2's complement functions
##########################
def get_2comp(val_int, val_size=16):
    """Get the 2's complement of Python int val_int.

    :param val_int: int value to apply 2's complement
    :type val_int: int
    :param val_size: bit size of int value (word = 16, long = 32) (optional)
    :type val_size: int
    :returns: 2's complement result
    :rtype: int
    :raises ValueError: if mismatch between val_int and val_size
    """
    # avoid overflow
    if not (-1 << val_size - 1) <= val_int < (1 << val_size):
        err_msg = 'could not compute two\'s complement for %i on %i bits'
        err_msg %= (val_int, val_size)
        raise ValueError(err_msg)
    # test negative int
    if val_int < 0:
        val_int += 1 << val_size
    # test MSB (do two's comp if set)
    elif val_int & (1 << (val_size - 1)):
        val_int -= 1 << val_size
    return val_int

# short alias
twos_c = get_2comp

def get_list_2comp(val_list, val_size=16):
    """Get the 2's complement of Python list val_list.

    :param val_list: list of int value to apply 2's complement
    :type val_list: list
    :param val_size: bit size of int value (word = 16, long = 32) (optional)
    :type val_size: int
    :returns: 2's complement result
    :rtype: list
    """
    return [get_2comp(val, val_size) for val in val_list]

# short alias
twos_c_l = get_list_2comp

###############################
# IEEE floating-point functions
###############################
def decode_ieee(val_int, double=False):
    """Decode Python int (32 bits integer) as an IEEE single or double precision format.

    Support NaN.

    :param val_int: a 32 or 64 bits integer as an int Python value
    :type val_int: int
    :param double: set to decode as a 64 bits double precision,
                   default is 32 bits single (optional)
    :type double: bool
    :returns: float result
    :rtype: float
    """
    if double:
        return struct.unpack("d", struct.pack("Q", val_int))[0]
    else:
        return struct.unpack("f", struct.pack("I", val_int))[0]

def encode_ieee(val_float, double=False):
    """Encode Python float to int (32 bits integer) as an IEEE single or double precision format.

    Support NaN.

    :param val_float: float value to convert
    :type val_float: float
    :param double: set to encode as a 64 bits double precision,
                   default is 32 bits single (optional)
    :type double: bool
    :returns: IEEE 32 bits (single precision) as Python int
    :rtype: int
    """
    if double:
        return struct.unpack("Q", struct.pack("d", val_float))[0]
    else:
        return struct.unpack("I", struct.pack("f", val_float))[0]

################
# misc functions
################
def crc16(frame):
    """Compute CRC16.

    :param frame: frame
    :type frame: bytes
    :returns: CRC16
    :rtype: int
    """
    crc = 0xFFFF
    for item in frame:
        next_byte = item
        crc ^= next_byte
        for _ in range(8):
            lsb = crc & 1
            crc >>= 1
            if lsb:
                crc ^= 0xA001
    return crc

def valid_host(host_str):
    """Validate a host string.

    Can be an IPv4/6 address or a valid hostname.

    :param host_str: the host string to test
    :type host_str: str
    :returns: True if host_str is valid
    :rtype: bool
    """
    # IPv4 valid address ?
    try:
        socket.inet_pton(socket.AF_INET, host_str)
        return True
    except socket.error:
        pass
    # IPv6 valid address ?
    try:
        socket.inet_pton(socket.AF_INET6, host_str)
        return True
    except socket.error:
        pass
    # valid hostname ?
    if re.match(r'^[a-zA-Z][a-zA-Z0-9.\-]+$', host_str):
        return True
    # on invalid host
    return False


text:
using AFrame.Core;
using AFrame.Web.Controls;
using AFrame.Web.Tests.PageObjects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;

namespace AFrame.Web.Tests.Features.CreatingControls
{
    [TestClass]
    public class CreatingControlsTests : BaseTest
    {
        [TestMethod]
        public void CreateControlsWithNoConstructors()
        {
            var homePage = this.Context.NavigateTo<HomePage>(this.TestAppUrl);
            Assert.AreEqual(3, homePage.Races.Count());
        }

        [TestMethod]
        public void CreateControlsWithMixedConstructors()
        {
            var homePage = this.Context.NavigateTo<HomePage>(this.TestAppUrl);
            Assert.AreEqual(2, homePage.FindCrazyMultiple.Count());
        }

        [TestMethod]
        public void CreateControlsByDirectConstructor()
        {
            var homePage = this.Context.NavigateTo<HomePage>(this.TestAppUrl);

            var races = new WebControlCollection<WebControl>(homePage.Context, homePage, new SearchProperty[] { new SearchProperty(WebControl.SearchNames.JQuerySelector, ".race") });

            Assert.AreEqual(3, races.Count());
        }

        [TestMethod]
        public void CreateControlByPropertySet()
        {
            var homePage = this.Context.NavigateTo<HomePage>(this.TestAppUrl);

            var race = new WebControl(homePage.Context);
            race.Parent = homePage;
            race.SearchProperties.Add(WebControl.SearchNames.JQuerySelector, ".race .item:eq(0)");

            Assert.AreEqual("Race1 Item1", race.Text);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Directori a exportar

Aquest és el directori que s''exporta als clients llistats a la secció
Exporta a ....

En lloc desmuntar un cert nombre d'exportacions diferents, un client NFSv4 veu
les exportacions del servidor NFSv4 com si estiguessin dins d'un sol sistema
de fitxers, anomenat el pseudo-sistema de fitxers NFSv4.

Així que per a NFSv4, primer es munta aquest directori (amb <tt>mount --bind</tt>)
en el pseudo-sistema de fitxers NFSv4, i el pseudo-sistema s'exporta (si no ho estava), llavors el directori.

És preferible exportar aquest directori sense amagar-lo, de manera que el client
s'hi podrà moure sense muntar-lo.

Contràriament a altres servidors NFS, Linus suporta la reexportació d'un
directori que s'ha muntat a través de NFS des d'un altre host, i l'exportació
d'un directori que conté punts de muntatge per a altres sistemes de fitxers.


text:
package com.pabloam.microservices.converter.history.web;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pabloam.microservices.converter.history.model.CurrencyQuery;
import com.pabloam.microservices.converter.history.services.HistoryServices;

@RestController
@EnableResourceServer
public class HistoryRestController {

	@Autowired
	private HistoryServices historyServices;

	/**
	 * Returns the last number queries for the given user
	 *
	 * @return
	 */
	@RequestMapping(value = "/history/getLast", method = RequestMethod.GET)
	public List<CurrencyQuery> getLastQueriesOf(@RequestParam("n") int number, @RequestParam("u") String userName) {
		return historyServices.getLastQueriesOf(number, userName);
	}

	/**
	 * Returns true if the query has been stored
	 *
	 * @param provider
	 * @param userName
	 * @param currencyQuery
	 * @return
	 */
	@RequestMapping(value = "history/save", method = RequestMethod.POST)
	public Boolean saveQuery(@RequestParam("p") String provider, @RequestParam("u") String userName, @RequestBody Map<String, Object> currencyQuery) {
		return historyServices.save(provider, userName, currencyQuery);
	}

}


text:
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

AberOWL Search

                        Ontology Term
                        Ontology REF
                        IRI
                        Actions


text:
<?php

namespace Application;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;
use Application\TableGateway;
use Application\Service\AuthenticationService;

class Module implements ConfigProviderInterface
{
    const VERSION = '3.0.0';

    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }

    public function getServiceConfig()
    {
        return [
            'factories' => [
                // 'Cache\Adapter\Memcached' => function ($serviceManager) {
                //     $memcached = new \Memcached($serviceManager->get('Cache\Adapter\MemcachedOptions'));
                //     return $memcached;
                // },
                // 'Cache\Adapter\MemcachedOptions' => function ($serviceManager) {
                //     return new \pMemcachedOptions(array(
                //         'ttl'           => 60 * 60 * 24 * 7, // 1 week
                //         'namespace'     => 'cache_listener',
                //         'key_pattern'   => null,
                //         'readable'      => true,
                //         'writable'      => true,
                //         'servers'       => 'localhost',
                //     ));
                // },
            ],
        ];
    }
}


text:
#include "src/envoy/http/jwt_auth/token_extractor.h"
#include "common/common/utility.h"
#include "common/http/utility.h"

using ::istio::envoy::config::filter::http::jwt_auth::v2alpha1::
    JwtAuthentication;

namespace Envoy {
namespace Http {
namespace JwtAuth {
namespace {

// The autorization bearer prefix.
const std::string kBearerPrefix = "Bearer ";

// The query parameter name to get JWT token.
const std::string kParamAccessToken = "access_token";

}  // namespace

JwtTokenExtractor::JwtTokenExtractor(const JwtAuthentication& config) {
  for (const auto& jwt : config.rules()) {
    bool use_default = true;
    if (jwt.from_headers_size() > 0) {
      use_default = false;
      for (const auto& header : jwt.from_headers()) {
        auto& issuers = header_maps_[LowerCaseString(header.name())];
        issuers.insert(jwt.issuer());
      }
    }
    if (jwt.from_params_size() > 0) {
      use_default = false;
      for (const std::string& param : jwt.from_params()) {
        auto& issuers = param_maps_[param];
        issuers.insert(jwt.issuer());
      }
    }

    // If not specified, use default
    if (use_default) {
      authorization_issuers_.insert(jwt.issuer());

      auto& param_issuers = param_maps_[kParamAccessToken];
      param_issuers.insert(jwt.issuer());
    }
  }
}

void JwtTokenExtractor::Extract(
    const HeaderMap& headers,
    std::vector<std::unique_ptr<JwtTokenExtractor::Token>>* tokens) const {
  if (!authorization_issuers_.empty()) {
    const HeaderEntry* entry = headers.Authorization();
    if (entry) {
      // Extract token from header.
      const HeaderString& value = entry->value();
      if (StringUtil::startsWith(value.c_str(), kBearerPrefix, true)) {
        tokens->emplace_back(new Token(value.c_str() + kBearerPrefix.length(),
                                       authorization_issuers_, true, nullptr));
        // Only take the first one.
        return;
      }
    }
  }

  // Check header first
  for (const auto& header_it : header_maps_) {
    const HeaderEntry* entry = headers.get(header_it.first);
    if (entry) {
      tokens->emplace_back(
          new Token(std::string(entry->value().c_str(), entry->value().size()),
                    header_it.second, false, &header_it.first));
      // Only take the first one.
      return;
    }
  }

  if (param_maps_.empty() || headers.Path() == nullptr) {
    return;
  }

  const auto& params = Utility::parseQueryString(std::string(
      headers.Path()->value().c_str(), headers.Path()->value().size()));
  for (const auto& param_it : param_maps_) {
    const auto& it = params.find(param_it.first);
    if (it != params.end()) {
      tokens->emplace_back(
          new Token(it->second, param_it.second, false, nullptr));
      // Only take the first one.
      return;
    }
  }
}

}  // namespace JwtAuth
}  // namespace Http
}  // namespace Envoy


text:
<?php

namespace JHWEB\SeguridadVialBundle\Repository;

/**
 * SvIpatRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SvIpatRepository extends \Doctrine\ORM\EntityRepository
{
    public function getIpatByRango($params) {

        $em = $this->getEntityManager();

        $condicion = null;

        $horaInicio = $params->datos->horaInicio;
        $horaFin = $params->datos->horaFin;
        $fechaInicio = $params->datos->fechaInicio;
        $fechaFin = $params->datos->fechaFin;

        $dql = "SELECT i
            FROM JHWEBSeguridadVialBundle:SvIpat i, JHWEBSeguridadVialBundle:SvIpatVictima iv,
            JHWEBSeguridadVialBundle:SvIpatConductor ic, JHWEBSeguridadVialBundle:SvIpatVehiculo ive
            WHERE i.activo = 1";

        if($params->datos->arrayGravedadAccidente){
            foreach ($params->datos->arrayGravedadAccidente as $keyGravedad => $idGravedad) {
                if($keyGravedad == 0){
                    $condicion .= " AND i.gravedadAccidente = '" . $idGravedad . "'";
                } else {
                    $condicion .= " OR i.gravedadAccidente = '" . $idGravedad . "'";
                }
            }
        }

        if($params->datos->arrayTipoVictima){
            foreach ($params->datos->arrayTipoVictima as $keyTipoVictima => $idTipoVictima) {
                if($keyTipoVictima == 0) {
                    $condicion .= " AND iv.tipoVictima = '" . $idTipoVictima . "'";
                }
                else {
                    $condicion .= " OR iv.tipoVictima = '" . $idTipoVictima . "'";
                }
            }
        }
        /* if($horaInicio && $horaFin){

            $condicion .= " AND i.horaAccidente BETWEEN " . $horaInicio . " AND $horaFin";
        } */

        if($fechaInicio && $fechaFin){
            $condicion .= " AND i.fechaAccidente BETWEEN " . $fechaInicio . " AND $fechaFin";
        }

        if ($params->datos->arrayGrupoEdad) {
            foreach ($params->datos->arrayGrupoEdad as $keyGrupoEdad => $idGrupoEdad) {
                # code...
                $edadInicio = intval($idGrupoEdad);
                $edadFin = $edadInicio + 4;

                if($keyGrupoEdad == 0) {
                    $condicion .= " AND iv.edad BETWEEN " . $edadInicio . " AND $edadFin";
                    $condicion .= " AND ic.edad BETWEEN " . $edadInicio . " AND $edadFin";
                } else {
                    $condicion .= " OR iv.edad BETWEEN " . $edadInicio . " AND $edadFin";
                    $condicion .= " OR ic.edad BETWEEN " . $edadInicio . " AND $edadFin";
                }
            }
        }

        if($params->datos->arrayMunicipio) {
            foreach ($params->datos->arrayMunicipio as $keyMunicipio => $idMunicipio) {
                # code...
                $municipio = $em->getRepository('JHWEBConfigBundle:CfgMunicipio')->find($idMunicipio);

                if($keyMunicipio == 0) {
                    $condicion .= " AND ic.ciudadResidencia = '" . $municipio->getNombre() . "'";
                    $condicion .= " AND iv.ciudadResidencia = '" . $municipio->getNombre() . "'";
                }
                else {
                    $condicion .= " OR ic.ciudadResidencia = '" . $municipio->getNombre() . "'";
                    $condicion .= " OR iv.ciudadResidencia = '" . $municipio->getNombre() . "'";
                }
            }
        }

        if($params->datos->arrayDiaSemana) {
            foreach ($params->datos->arrayDiaSemana as $keyDiaSemana => $diaSemana) {
                # code...
                if($keyDiaSemana == 0) {
                    $condicion .= " AND i.diaAccidente = '" . $diaSemana . "'";
                }
                else {
                    $condicion .= " OR i.diaAccidente = '" . $diaSemana . "'";
                }
            }
        }

        if($params->datos->arrayGenero) {
            foreach ($params->datos->arrayGenero as $keyGenero => $idGenero) {
                # code...
                $genero = $em->getRepository('JHWEBUsuarioBundle:UserCfgGenero')->find($idGenero);

                if($keyGenero == 0) {
                    $condicion .= " AND ic.sexo = '" . $genero->getSigla() . "'";
                    $condicion .= " AND iv.sexo = '" . $genero->getSigla() . "'";
                }
                else {
                    $condicion .= " OR ic.sexo = '" . $genero->getSigla() . "'";
                    $condicion .= " OR iv.sexo = '" . $genero->getSigla() . "'";
                }
            }
        }

        if ($params->datos->arrayClase) {
            foreach ($params->datos->arrayClase as $keyClase => $idClase) {
                # code...
                $clase = $em->getRepository('JHWEBVehiculoBundle:VhloCfgClase')->find($idClase);
                if($keyClase == 0) {
                    $condicion .= " AND ive.clase = '" . $clase->getNombre() . "'";
                }
                else {
                    $condicion .= " OR ive.clase = '" . $clase->getNombre() . "'";
                }
            }
        }

        if($params->datos->arrayClaseAccidente){
            foreach ($params->datos->arrayClaseAccidente as $keyClaseAccidente => $idClaseAccidente) {
                # code...
                if($keyClaseAccidente == 0) {
                    $condicion .= " AND i.claseAccidente = '" . $idClaseAccidente . "'";
                }
                else {
                    $condicion .= " OR i.claseAccidente = '" . $idClaseAccidente . "'";
                }
            }
        }

        if($params->datos->arrayClaseChoque) {
            foreach ($params->datos->arrayClaseChoque as $keyClaseChoque => $idClaseChoque) {
                # code...
                if($keyClaseChoque == 0) {
                    $condicion .= " AND i.claseChoque = '" . $idClaseChoque . "'";
                }
                else {
                    $condicion .= " OR i.claseChoque = '" . $idClaseChoque . "'";
                }
            }
        }

        if($params->datos->arrayObjetoFijo) {
            foreach ($params->datos->arrayObjetoFijo as $keyObjetoFijo => $idObjetoFijo) {
                # code...
                if($keyObjetoFijo == 0) {
                    $condicion .= " AND i.objetoFijo = '" . $idObjetoFijo . "'";
                }
                else {
                    $condicion .= " OR i.objetoFijo = '" . $idObjetoFijo . "'";
                }
            }
        }
        //=====================
        if ($condicion) {
            $dql .= $condicion;
        }

        $consulta = $em->createQuery($dql);

        return $consulta->getResult();
    }
}


text:
package io.advantageous.qbit.events.impl;

import io.advantageous.boon.core.Str;
import io.advantageous.qbit.GlobalConstants;
import io.advantageous.qbit.client.ClientProxy;
import io.advantageous.qbit.client.RemoteTCPClientProxy;
import io.advantageous.qbit.events.spi.EventConnector;
import io.advantageous.qbit.events.spi.EventTransferObject;
import io.advantageous.qbit.service.ServiceProxyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Provides a collection of event connectors and makes them look like a single event connector.
 * It will also work with the RemoteTCPClientProxy to close connectors that are removed.
 * When you remove a remote connector that implements RemoteTCPClientProxy,
 * note it will be closed if removed from the EventConnectorHub.
 */
public class EventConnectorHub implements EventConnector, Iterable<EventConnector> {

    private final List<EventConnector> eventConnectors;
    private final Logger logger = LoggerFactory.getLogger(EventConnectorHub.class);
    private final boolean debug = GlobalConstants.DEBUG || logger.isDebugEnabled();

    public EventConnectorHub(final List<EventConnector> eventConnectors) {

        this.eventConnectors = new CopyOnWriteArrayList<>(eventConnectors);
    }

    public EventConnectorHub() {

        this.eventConnectors = new CopyOnWriteArrayList<>();
    }

    /**
     * Add an event connector
     *
     * @param eventConnector eventConnector
     */
    public void add(final EventConnector eventConnector) {
        this.eventConnectors.add(eventConnector);
    }

    /**
     * Add a bunch of event connectors.
     *
     * @param eventConnectors eventConnectors
     */
    public void addAll(final EventConnector... eventConnectors) {
        Collections.addAll(this.eventConnectors, eventConnectors);
    }

    /**
     * Remove an event connector
     *
     * @param eventConnector eventConnector
     */
    public void remove(final EventConnector eventConnector) {
        if (eventConnector != null) {
            try {

                if (eventConnector instanceof RemoteTCPClientProxy) {
                    final RemoteTCPClientProxy remoteTCPClientProxy = (RemoteTCPClientProxy) eventConnector;

                    logger.info(Str.sputs("Removing event connector host ",
                            remoteTCPClientProxy.host(), " port ", remoteTCPClientProxy.port(),
                            "connected ", remoteTCPClientProxy.connected()));
                    remoteTCPClientProxy.silentClose();
                }
                this.eventConnectors.remove(eventConnector);
            } catch (Exception ex) {
                logger.error("Unable to remove event connector", ex);
            }
        }
    }

    /**
     * Forwards en event to another event system.
     *
     * @param event event
     */
    @Override
    public void forwardEvent(final EventTransferObject<Object> event) {

        if (debug) logger.debug("forwardEvent " + event.channel() + " size " + eventConnectors.size());

        for (int index = 0; index < eventConnectors.size(); index++) {

            EventConnector eventConnector = null;
            try {
                eventConnector = eventConnectors.get(index);
                eventConnector.forwardEvent(event);
            } catch (Exception ex) {
                logger.error("problem sending event to event connector", ex);

                if (eventConnector instanceof RemoteTCPClientProxy) {
                    if (!((RemoteTCPClientProxy) eventConnector).connected()) {
                        eventConnectors.remove(eventConnector);
                    }
                }
            }
        }

        if (debug) logger.debug("forwardEvent done " + event.channel());
    }

    /**
     * Flushes the pool used to optimize flushing of IO operations.
     */
    @Override
    public void flush() {

        for (int index = 0; index < eventConnectors.size(); index++) {

            EventConnector eventConnector = null;
            try {
                eventConnector = eventConnectors.get(index);
                if (eventConnector instanceof ClientProxy) {
                    ServiceProxyUtils.flushServiceProxy(eventConnector);
                } else {
                    eventConnector.flush();
                }
            } catch (Exception ex) {
                logger.debug("problem sending event to event connector", ex);
                if (eventConnector instanceof RemoteTCPClientProxy) {
                    if (!((RemoteTCPClientProxy) eventConnector).connected()) {

                        eventConnectors.remove(eventConnector);
                    }
                }
            }
        }
    }

    @Override
    public Iterator<EventConnector> iterator() {
        return this.eventConnectors.listIterator();
    }

    public ListIterator<EventConnector> listIterator() {
        return this.eventConnectors.listIterator();
    }

    public int size() {
        return eventConnectors.size();
    }
}


text:
CXXFLAGS="${CXXFLAGS} -fno-sanitize=float-divide-by-zero"

# Build Exiv2
mkdir -p build
cd build
cmake -DEXIV2_ENABLE_PNG=ON -DEXIV2_ENABLE_WEBREADY=ON -DEXIV2_ENABLE_CURL=OFF -DEXIV2_ENABLE_BMFF=ON -DEXIV2_TEAM_WARNINGS_AS_ERRORS=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_CXX_COMPILER="${CXX}" -DCMAKE_CXX_FLAGS="${CXXFLAGS}" -DEXIV2_BUILD_FUZZ_TESTS=ON -DEXIV2_TEAM_OSS_FUZZ=ON -DLIB_FUZZING_ENGINE="${LIB_FUZZING_ENGINE}" ..
make -j $(nproc)

# Copy binary and dictionary to $OUT
cp ./bin/fuzz-read-print-write $OUT
cp ../fuzz/exiv2.dict $OUT/fuzz-read-print-write.dict

# Initialize the corpus, using the files in test/data
mkdir corpus
for f in $(find ../test/data -type f -size -20k); do
    s=$(sha1sum "$f" | awk '{print $1}')
    cp $f corpus/$s
done

zip -j $OUT/fuzz-read-print-write.zip corpus/*


text:
layout: default
title: "Mr Charles Walker"
house: commons

---

        {% include members/mr-charles-walker.html %}

What is Mr Charles Walker interested in?

Employment

Taxation

The Economy

Mental Health

Place

Mr Charles Walker is the MP for Broxbourne.

What is a constituency?

Party

Mr Charles Walker is an MP in the Conservative party.

What is a party?


text:
ECS_CLUSTER_S3_BUCKET := example

build: proxy.js
	rm -f proxy.zip && zip -x Makefile -r proxy.zip .

install:
	aws s3 cp proxy.zip s3://$(ECS_CLUSTER_S3_BUCKET)/lambda/proxy.zip


text:
package meta

import (
	"fmt"
	"sort"
	"strconv"
	"strings"
	"time"
)

const (
	antennaMake int = iota
	antennaModel
	antennaSerial
	antennaMark
	antennaHeight
	antennaNorth
	antennaEast
	antennaAzimuth
	antennaStart
	antennaEnd
	antennaLast
)

type InstalledAntenna struct {
	Install
	Offset

	Mark    string
	Azimuth float64

	azimuth string // shadow variable to maintain formatting
}

type InstalledAntennaList []InstalledAntenna

func (a InstalledAntennaList) Len() int           { return len(a) }
func (a InstalledAntennaList) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a InstalledAntennaList) Less(i, j int) bool { return a[i].Install.Less(a[j].Install) }

func (a InstalledAntennaList) encode() [][]string {
	data := [][]string{{
		"Make",
		"Model",
		"Serial",
		"Mark",
		"Height",
		"North",
		"East",
		"Azimuth",
		"Start Date",
		"End Date",
	}}
	for _, v := range a {
		data = append(data, []string{
			strings.TrimSpace(v.Make),
			strings.TrimSpace(v.Model),
			strings.TrimSpace(v.Serial),
			strings.TrimSpace(v.Mark),
			strings.TrimSpace(v.vertical),
			strings.TrimSpace(v.north),
			strings.TrimSpace(v.east),
			strings.TrimSpace(v.azimuth),
			v.Start.Format(DateTimeFormat),
			v.End.Format(DateTimeFormat),
		})
	}
	return data
}

func (a *InstalledAntennaList) decode(data [][]string) error {
	var antennas []InstalledAntenna
	if len(data) > 1 {
		for _, d := range data[1:] {
			if len(d) != antennaLast {
				return fmt.Errorf("incorrect number of installed antenna fields")
			}
			var err error

			var height, north, east float64
			if height, err = strconv.ParseFloat(d[antennaHeight], 64); err != nil {
				return err
			}
			if north, err = strconv.ParseFloat(d[antennaNorth], 64); err != nil {
				return err
			}
			if east, err = strconv.ParseFloat(d[antennaEast], 64); err != nil {
				return err
			}

			var azimuth float64
			if azimuth, err = strconv.ParseFloat(d[antennaAzimuth], 64); err != nil {
				return err
			}

			var start, end time.Time
			if start, err = time.Parse(DateTimeFormat, d[antennaStart]); err != nil {
				return err
			}
			if end, err = time.Parse(DateTimeFormat, d[antennaEnd]); err != nil {
				return err
			}

			antennas = append(antennas, InstalledAntenna{
				Install: Install{
					Equipment: Equipment{
						Make:   strings.TrimSpace(d[antennaMake]),
						Model:  strings.TrimSpace(d[antennaModel]),
						Serial: strings.TrimSpace(d[antennaSerial]),
					},
					Span: Span{
						Start: start,
						End:   end,
					},
				},
				Offset: Offset{
					Vertical: height,
					North:    north,
					East:     east,

					vertical: strings.TrimSpace(d[antennaHeight]),
					north:    strings.TrimSpace(d[antennaNorth]),
					east:     strings.TrimSpace(d[antennaEast]),
				},
				Mark:    strings.TrimSpace(d[antennaMark]),
				Azimuth: azimuth,
				azimuth: strings.TrimSpace(d[antennaAzimuth]),
			})
		}

		*a = InstalledAntennaList(antennas)
	}
	return nil
}

func LoadInstalledAntennas(path string) ([]InstalledAntenna, error) {
	var a []InstalledAntenna

	if err := LoadList(path, (*InstalledAntennaList)(&a)); err != nil {
		return nil, err
	}

	sort.Sort(InstalledAntennaList(a))

	return a, nil
}


text:
/** @jsx React.DOM */

// IMPORTANT: Replace below with your Firebase app URL
var firebaseUrl = "https://my-firebase-app.firebaseio.com/";

var converter = new Showdown.converter();

var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (

{this.props.author}

    );
  }
});

var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment, index) {
      return <Comment key={index} author={comment.author}>{comment.text}</Comment>;
    });
    return
{commentNodes}
;
  }
});

var CommentForm = React.createClass({
  handleSubmit: function() {
    var author = this.refs.author.getDOMNode().value.trim();
    var text = this.refs.text.getDOMNode().value.trim();
    this.props.onCommentSubmit({author: author, text: text});
    this.refs.author.getDOMNode().value = '';
    this.refs.text.getDOMNode().value = '';
    return false;
  },

  render: function() {
    return (
      <form className="commentForm" onSubmit={this.handleSubmit}>
        <input type="text" placeholder="Your name" ref="author" />
        <input type="text" placeholder="Say something..." ref="text" />
        <input type="submit" value="Post" />
      </form>
    );
  }
});

var CommentBox = React.createClass({
  mixins: [ReactFireMixin],

  handleCommentSubmit: function(comment) {
    // Here we push the update out to Firebase and let ReactFire update this.state.data
    this.firebaseRefs["data"].push(comment);
  },

  getInitialState: function() {
    return {
      data: []
    };
  },

  componentWillMount: function() {
    // Here we bind the component to Firebase and it handles all data updates,
    // no need to poll as in the React example.
    this.bindAsArray(new Firebase(firebaseUrl + "commentBox"), "data");
  },

  render: function() {
    return (

Comments

        <CommentList data={this.state.data} />
        <CommentForm onCommentSubmit={this.handleCommentSubmit} />

    );
  }
});

React.render(
  <CommentBox />,
  document.getElementById('content')
);


text:
package com.magnify.utils.ui.living.adapter;

import android.content.Context;
import android.view.View;

import com.magnify.utils.R;
import com.magnify.utils.ui.living.bean.ChatRoomMessage;

import java.util.List;

import adapter.CommonRecylerAdapter;
import adapter.ViewHolders;

/**
 * @author:heinigger 2019/6/6  12:09
 * @function:
 */
public class LivingRoomInfoAdapter extends CommonRecylerAdapter<ChatRoomMessage> {

    public LivingRoomInfoAdapter(Context mContext, List<ChatRoomMessage> datas) {
        super(R.layout.item_chatroom_textview, mContext, datas);
    }

    @Override
    protected void convert(ViewHolders holder, int position, View convertView, ChatRoomMessage mItem) {
        holder.setText(R.id.tv_content, mItem.getSpannedContent());
    }
}


text:
#ifndef SRC_CPP_SVCS_STMGR_SRC_MANAGER_STMGR_H_
#define SRC_CPP_SVCS_STMGR_SRC_MANAGER_STMGR_H_

#include <list>
#include <map>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <chrono>
#include <typeindex>
#include "proto/messages.h"
#include "network/network.h"
#include "basics/basics.h"
#include "config/topology-config-vars.h"

namespace heron {
namespace common {
class HeronStateMgr;
class MetricsMgrSt;
class MultiAssignableMetric;
class CountMetric;
class MultiCountMetric;
class TimeSpentMetric;
}
}

namespace heron {
namespace stmgr {

class StMgrServer;
class InstanceServer;
class StMgrClientMgr;
class TMasterClient;
class StreamConsumers;
class XorManager;
class TupleCache;
class NeighbourCalculator;
class StatefulRestorer;
class CkptMgrClient;

class StMgr {
 public:
  StMgr(EventLoop* eventLoop, const sp_string& _myhost, sp_int32 _data_port,
        sp_int32 _local_data_port,
        const sp_string& _topology_name, const sp_string& _topology_id,
        proto::api::Topology* _topology, const sp_string& _stmgr_id,
        const std::vector<sp_string>& _instances, const sp_string& _zkhostport,
        const sp_string& _zkroot, sp_int32 _metricsmgr_port, sp_int32 _shell_port,
        sp_int32 _ckptmgr_port, const sp_string& _ckptmgr_id,
        sp_int64 _high_watermark, sp_int64 _low_watermark,
        const sp_string& _metricscachemgr_mode);
  virtual ~StMgr();

  // All kinds of initialization like starting servers and clients
  void Init();

  // Called by tmaster client when a new physical plan is available
  void NewPhysicalPlan(proto::system::PhysicalPlan* pplan);
  void HandleStreamManagerData(const sp_string& _stmgr_id,
                               proto::stmgr::TupleStreamMessage* _message);
  void HandleInstanceData(sp_int32 _task_id, bool _local_spout,
                          proto::system::HeronTupleSet* _message);
  // Called when an instance does checkpoint and sends its checkpoint
  // to the stmgr to save it
  void HandleStoreInstanceStateCheckpoint(
      const proto::ckptmgr::InstanceStateCheckpoint& _message,
      const proto::system::Instance& _instance);
  void DrainInstanceData(sp_int32 _task_id, proto::system::HeronTupleSet2* _tuple);
  // Send checkpoint message to this task_id
  void DrainDownstreamCheckpoint(sp_int32 _task_id,
                                proto::ckptmgr::DownstreamStatefulCheckpoint* _message);

  const proto::system::PhysicalPlan* GetPhysicalPlan() const;

  // Forward the call to the StmgrServer
  virtual void StartBackPressureOnServer(const sp_string& _other_stmgr_id);
  // Forward the call to the StmgrServer
  virtual void StopBackPressureOnServer(const sp_string& _other_stmgr_id);
  // Used by the server to tell the client to send the back pressure related
  // messages
  void SendStartBackPressureToOtherStMgrs();
  void SendStopBackPressureToOtherStMgrs();
  void StartBackPressureOnSpouts();
  void AttemptStopBackPressureFromSpouts();
  void StartTMasterClient();
  bool DidAnnounceBackPressure();
  bool DidOthersAnnounceBackPressure();
  const NetworkOptions&  GetStmgrServerNetworkOptions() const;
  const NetworkOptions&  GetInstanceServerNetworkOptions() const;
  void HandleDeadStMgrConnection(const sp_string& _stmgr);
  void HandleAllStMgrClientsRegistered();
  void HandleDeadInstance(sp_int32 _task_id);
  void HandleAllInstancesConnected();
  void HandleCkptMgrRegistration();

  // Handle checkpoint message coming from an upstream task to a downstream task
  void HandleDownStreamStatefulCheckpoint(
                                const proto::ckptmgr::DownstreamStatefulCheckpoint& _message);

  // Handle RestoreInstanceStateResponse message from local instance
  void HandleRestoreInstanceStateResponse(sp_int32 _task_id, const proto::system::Status& _status,
                                          const std::string& _checkpoint_id);

 private:
  void OnTMasterLocationFetch(proto::tmaster::TMasterLocation* _tmaster, proto::system::StatusCode);
  void OnMetricsCacheLocationFetch(
         proto::tmaster::MetricsCacheLocation* _tmaster, proto::system::StatusCode);
  void FetchTMasterLocation();
  void FetchMetricsCacheLocation();
  // A wrapper that calls FetchTMasterLocation. Needed for RegisterTimer
  void CheckTMasterLocation(EventLoop::Status);
  void UpdateProcessMetrics(EventLoop::Status);

  // Utility function to create checkpoint mgr client
  void CreateCheckpointMgrClient();
  // Called when ckpt mgr saves the state of an instance
  void HandleSavedInstanceState(const proto::system::Instance& _instance,
                                const std::string& _checkpoint_id);
  // Called when ckpt mgr reteives the state of an instance
  void HandleGetInstanceState(proto::system::StatusCode _status, sp_int32 _task_id,
                              sp_string _checkpoint_id,
                              const proto::ckptmgr::InstanceStateCheckpoint& _msg);

  void CleanupStreamConsumers();
  void PopulateStreamConsumers(
      proto::api::Topology* _topology,
      const std::map<sp_string, std::vector<sp_int32> >& _component_to_task_ids);
  void PopulateXorManagers(
      const proto::api::Topology& _topology, sp_int32 _message_timeout,
      const std::map<sp_string, std::vector<sp_int32> >& _component_to_task_ids);
  void CleanupXorManagers();

  void SendInBound(sp_int32 _task_id, proto::system::HeronTupleSet2* _message);
  void ProcessAcksAndFails(sp_int32 _src_task_id,
                           sp_int32 _task_id, const proto::system::HeronControlTupleSet& _control);
  void CopyDataOutBound(sp_int32 _src_task_id, bool _local_spout,
                        const proto::api::StreamId& _streamid,
                        proto::system::HeronDataTuple* _tuple,
                        const std::vector<sp_int32>& _out_tasks);
  void CopyControlOutBound(sp_int32 _src_task_id,
                           const proto::system::AckTuple& _control, bool _is_fail);

  sp_int32 ExtractTopologyTimeout(const proto::api::Topology& _topology);

  void CreateTMasterClient(proto::tmaster::TMasterLocation* tmasterLocation);
  void StartStmgrServer();
  void StartInstanceServer();
  void CreateTupleCache();
  // This is called when we receive a valid new Tmaster Location.
  // Performs all the actions necessary to deal with new tmaster.
  void HandleNewTmaster(proto::tmaster::TMasterLocation* newTmasterLocation);
  // Broadcast the tmaster location changes to other components. (MM for now)
  void BroadcastTmasterLocation(proto::tmaster::TMasterLocation* tmasterLocation);
  void BroadcastMetricsCacheLocation(proto::tmaster::MetricsCacheLocation* tmasterLocation);

  // Called when TMaster sends a InitiateStatefulCheckpoint message with a checkpoint_id
  // This will send intiate checkpoint messages to local instances to capture their state.
  void InitiateStatefulCheckpoint(sp_string checkpoint_id);

  // Invoked when TMaster asks us to restore all our local instances state to
  // the checkpoint represented by _checkpoint_id. This starts the
  // Restore state machine
  void RestoreTopologyState(sp_string _checkpoint_id, sp_int64 _restore_txid);

  // Invoked when TMaster sends the StartStatefulProcessing request to kick
  // start the computation. We send the StartStatefulProcessing to all our
  // local instances so that they can start the processing.
  void StartStatefulProcessing(sp_string _checkpoint_id);

  // Called when Stateful Restorer restores the instance state
  void HandleStatefulRestoreDone(proto::system::StatusCode _status,
                                 std::string _checkpoint_id, sp_int64 _restore_txid);

  // Patch new physical plan with internal hydrated topology but keep new topology data:
  // - new topology state
  // - new topology/component config
  static void PatchPhysicalPlanWithHydratedTopology(proto::system::PhysicalPlan* _pplan,
                                                    proto::api::Topology* _topology);

  heron::common::HeronStateMgr* state_mgr_;
  proto::system::PhysicalPlan* pplan_;
  sp_string topology_name_;
  sp_string topology_id_;
  sp_string stmgr_id_;
  sp_string stmgr_host_;
  sp_int32 data_port_;
  sp_int32 local_data_port_;
  std::vector<sp_string> instances_;
  // Getting data from other streammgrs
  StMgrServer* stmgr_server_;
  // Used to get/send data to local instances
  InstanceServer* instance_server_;
  // Pushing data to other streammanagers
  StMgrClientMgr* clientmgr_;
  TMasterClient* tmaster_client_;
  EventLoop* eventLoop_;

  // Map of task_id to stmgr_id
  std::unordered_map<sp_int32, sp_string> task_id_to_stmgr_;
  // map of <component, streamid> to its consumers
  std::unordered_map<std::pair<sp_string, sp_string>, StreamConsumers*> stream_consumers_;
  // xor managers
  XorManager* xor_mgrs_;
  // Tuple Cache to optimize message building
  TupleCache* tuple_cache_;
  // Neighbour Calculator for stateful processing
  NeighbourCalculator* neighbour_calculator_;
  // Stateful Restorer
  StatefulRestorer* stateful_restorer_;

  // This is the topology structure
  // that contains the full component objects
  proto::api::Topology* hydrated_topology_;

  // Metrics Manager
  heron::common::MetricsMgrSt* metrics_manager_client_;

  // Checkpoint Manager
  CkptMgrClient* ckptmgr_client_;

  // Process related metrics
  heron::common::MultiAssignableMetric* stmgr_process_metrics_;

  // Stateful Restore metric
  heron::common::CountMetric* restore_initiated_metrics_;
  heron::common::MultiCountMetric* dropped_during_restore_metrics_;

  // Instance related metrics
  heron::common::MultiCountMetric* instance_bytes_received_metrics_;

  // Backpressure relarted metrics
  heron::common::TimeSpentMetric* back_pressure_metric_initiated_;

  // The time at which the stmgr was started up
  std::chrono::high_resolution_clock::time_point start_time_;
  sp_string zkhostport_;
  sp_string zkroot_;
  sp_int32 metricsmgr_port_;
  sp_int32 shell_port_;
  sp_int32 ckptmgr_port_;
  sp_string ckptmgr_id_;

  std::vector<sp_int32> out_tasks_;

  bool is_acking_enabled;
  config::TopologyConfigVars::TopologyReliabilityMode reliability_mode_;

  sp_int64 high_watermark_;
  sp_int64 low_watermark_;

  // whether MetricsCacheMgr is running
  sp_string metricscachemgr_mode_;
};

}  // namespace stmgr
}  // namespace heron

#endif  // SRC_CPP_SVCS_STMGR_SRC_MANAGER_STMGR_H_


text:
package cn.queen.java.io.file_writer;

/**
 * @version 0.1
 *
 * @author Jie Wang
 *
 * @since Nov 25, 2015
 * Implementation of a fast Writer.
 * 实现一个快速的Writer
 */
import java.io.IOException;
import java.io.Writer;
public final class Implementation extends Writer {
//常量表明这个Writer不是缓存输出
	public static final int NO_BUFFER = 0;
	//常数表明writer是缓冲的,并使用默认缓冲区大小
	public static final int DEFAULT_BUFFER = -1;
	//常数表明writer是缓冲的,是无限的;这个应用于BodyContent
	public static final int UNBOUNDED_BUFFER = -2;
	private int bufferSize;
	private boolean autoFlush;
	private Writer writer;
	private char [] cb;
	private int nextChar;
	private static int defaultCharBufferSize = 8*1024;//default默认的
	//使用default-sized输出缓冲区创建一个character-output缓冲流
	public Implementation(Writer writer){
		this(writer,defaultCharBufferSize,true);
	}
	private Implementation(int bufferSize, boolean autoFlush){
		this.bufferSize= bufferSize;
		this.autoFlush= autoFlush;
	}
	//这个方法返回缓存区的大小
	public int getBufferSize(){return bufferSize;}
	//这个方法显示JspWriter是否是自动刷新
	public boolean isAutoFlush(){return autoFlush;}
	//使用一个缓存区大小固定的输出流创建一个新的带缓存的character-output流
	public Implementation(Writer writer, int sz, boolean autoFlush){
		this(sz,autoFlush);
		if(sz<0)throw new IllegalArgumentException("Buffer size<=0");//illegal 非法的 argument 论点
		this.writer = writer;
		cb = sz == 0 ?null:new char[sz];
		nextChar = 0;
	}
	//刷新输出缓冲区的底层字符流,没有刷新流本身。该方法不是私有的,所以它可以被PrintSream调用
	private final void flushBuffer()throws IOException{
		if(bufferSize == 0)
			return;
		if(nextChar == 0)
			return;
		writer.write(cb,0,nextChar);
		nextChar = 0;
	}
	//丢弃输出缓冲区
	public final void clear(){
		nextChar = 0;
	}
	private final void bufferOverflow()throws IOException{//overflow 溢出
		throw new IOException("overflow");
	}
	//刷新流
	public final void flush()throws IOException{
		flushBuffer();
		if(writer !=null){
			writer.flush();
		}
	}
	//关闭流
	public final void close() throws IOException{
		if(writer == null)
			return;
		flush();
	}
	//未使用的缓冲区的字节数
	public final int getRemaining(){
		return bufferSize - nextChar;
	}
	//写入一个唯一的字符
	public final void write(int c) throws IOException{
		if(bufferSize == 0){
			writer.write(c);
		}else{
			if(nextChar >= bufferSize)
				if(autoFlush)
					flushBuffer();
				else
					bufferOverflow();
			cb[nextChar++] = (char) c;
		}
	}
	//我们自己的最小值的方法,以避免加载
	private final int min(int a, int b){
		return(a < b ? a : b);
	}
	//写一个字符数组的一部分
	public final void write(char cbuf[], int off, int len)throws IOException{

	/*
	写字符数组的一部分。

	参数:cbuf字符的数组

	off :抵消开始写的字符

	len:写的字符数
	*/

		if(bufferSize == 0){
			writer.write(cbuf, off ,len);
			return;
		}
		if(len == 0){
			return;
		}
		if(len >= bufferSize){
			//如果需求超过输出流缓存区的大小,刷新这个缓存区,然后直接写入数据
			if(autoFlush)
				flushBuffer();
			else
				bufferOverflow();
			writer.write(cbuf,off,len);
			return;
		}
		int b = off, t = off+len;
		while(b<t){
			int d = min(bufferSize - nextChar, t-b);
			System.arraycopy(cbuf,b,cb,nextChar,d);
			b+=d;
			nextChar += d;
			if(nextChar>= bufferSize)
				if(autoFlush)
					flushBuffer();
				else
					bufferOverflow();
		}
	}
	//写入字符数组,这个方法不能继承Writer类,因为它必须抑制I / O例外。
	public final void write(char buf[])throws IOException{
		write(buf,0,buf.length);
	}
	//写入字符串的一部分
	public final void write(String s, int off ,int len)throws IOException{
		if(bufferSize == 0){
			writer.write(s,off,len);
			return;
		}
		int b = off, t = off+len;
		while(b<t){
			int d = min(bufferSize - nextChar, t-b);
			s.getChars(b,b+d,cb,nextChar);
			b+=d;
			nextChar+=d;
			if(nextChar>= bufferSize)
				if(autoFlush)
					flushBuffer();
				else
					bufferOverflow();
		}
	}
	//写入字符,这个方法不能从writer类继承,因为它必须抑制I/O例外
	public final void write(String s)throws IOException{
		if(s!=null){
			write(s,0,s.length());
		}
	}
//重置这个类以便它可以重用
public final void recycle(Writer writer){
	this.writer = writer;
	clear();
}
}


text:
#ifndef __RESOURCEEDITORQT__LANDSCAPEEDITORSHORTCUTMANAGER__
#define __RESOURCEEDITORQT__LANDSCAPEEDITORSHORTCUTMANAGER__

#include "DAVAEngine.h"
#include "Base/Singleton.h"

#include <QShortcut>
#include <QPointer>

class LandscapeEditorShortcutManager : public DAVA::Singleton<LandscapeEditorShortcutManager>
{
public:
    LandscapeEditorShortcutManager(QWidget* shortcutsWidget);
    ~LandscapeEditorShortcutManager();

    QShortcut* GetShortcutByName(const DAVA::String& name);
    QShortcut* CreateOrUpdateShortcut(const DAVA::String& name, QKeySequence keySequence, bool autoRepeat = true, const DAVA::String& description = "");

    void SetHeightMapEditorShortcutsEnabled(bool enabled);

    void SetTileMaskEditorShortcutsEnabled(bool enabled);

    void SetBrushSizeShortcutsEnabled(bool enabled);

    void SetBrushImageSwitchingShortcutsEnabled(bool enabled);

    void SetTextureSwitchingShortcutsEnabled(bool enabled);

    void SetStrengthShortcutsEnabled(bool enabled);

    void SetAvgStrengthShortcutsEnabled(bool enabled);

private:
    DAVA::Map<DAVA::String, QShortcut*> shortcutsMap;

    void InitDefaultShortcuts();
    QPointer<QWidget> shortcutsWidget;
};

#endif /* defined(__RESOURCEEDITORQT__LANDSCAPEEDITORSHORTCUTMANAGER__) */


text:
package org.apache.jackrabbit.ocm.exception;

/** This exception is thrown during repository setup while creating the
 * custom node types.
 *
 * @author Oliver Kiessler
 * @version $Id: Exp $
 */
public class CustomNodeTypeCreationException extends JcrMappingException {

    /** Use serialVersionUID for interoperability. */
    private final static long serialVersionUID = 3991714987182739219L;

    /**
     * Constructor with message.
     *
     * @param message the message associated to the exception
     */
    public CustomNodeTypeCreationException(String message) {
        super(message);
    }

    /**
     * Constructor with throwable object.
     *
     * @param nested the associated throwable object
     */
    public CustomNodeTypeCreationException(Throwable nested) {
        super(nested);
    }

    /**
     * Constructor with message and throwable object.
     *
     * @param message the message associated to the exception
     * @param nested the associated throwable object
     */
    public CustomNodeTypeCreationException(String message, Throwable nested) {
        super(message, nested);
    }
}


text:
<?php

namespace VortechAPI\Tests\Shows;

use PHPUnit\Framework\TestCase;

require_once(__DIR__.'/../../autoloader.php');
spl_autoload_register('VortechAPI\Autoloader\Loader::load');

class GetShowsTest extends TestCase
{
    public function setUp()
    {
        $this->shows = new \Apps\Shows\GetShows();
        $this->database = new \Apps\Database\Database();
        $this->database->connect();

        // Add songs
        $songs = new \Apps\Songs\AddSongs();
        $testSongs = array();
        $testSongs[] = array('title' => 'UnitTest1', 'duration' => 99);
        $testSongs[] = array('title' => 'UnitTest2', 'duration' => 95);
        $testSongs[] = array('title' => 'UnitTest3', 'duration' => 102);
        $testSongs[] = array('title' => 'UnitTest4', 'duration' => 88);
        $songs->add($testSongs);

        // Get four songIDs
        $select = new \Apps\Database\Select();
        $sql = $select->select('SongID')->from('Songs')->where('Title LIKE :title')->result();
        $pdo = array('title' => 'UnitTest%');
        $validSongIDs = $this->database->run($sql, $pdo);

        // We'll also need to add the two People that we refer to
        $people = new \Apps\People\AddPeople();
        $json = '[{"name": "UnitTest Guitar"}, {"name": "UnitTest Bass"}]';
        $people->add($json);

        // Get the people's IDs
        $select = new \Apps\Database\Select();
        $sql = $select->select('PersonID')->from('People')->where('Name LIKE :name')->result();
        $pdo = array('name' => 'UnitTest%');
        $personIDs = $this->database->run($sql, $pdo);

        // Add two test shows
        $shows = new \Apps\Shows\AddShow();

        // Show 1
        $json1 = '{"date": "2015-01-02 00:00:00", "countryCode": "FI", "country": "UnitTest",
            "city": "Tornio", "venue": "Jesperi", "setlist": ['.$validSongIDs[2]['SongID'].',
            '.$validSongIDs[0]['SongID'].', '.$validSongIDs[1]['SongID'].', {"title": "UnitTest New Song",
                "duration": 95}, '.$validSongIDs[3]['SongID'].'], "otherBands": [
                {"name": "The Band", "website": "http://theband.com"},
                {"name": "Another One", "website": "http://www.another.fi"},
                {"name": "One More Band", "website": "http://www.one.mr"}
            ], "performers": [{"personID": '.$personIDs[0]['PersonID'].', "instruments": "Guitar"},
            {"personID": '.$personIDs[1]['PersonID'].', "instruments": "Vocals"},
            {"personID": "UnitTest New", "instruments": "Bongo"}]}';

        // Show 2
        $json2 = '{"date": "2016-02-03 00:00:00", "countryCode": "SE", "country": "UnitTest",
            "city": "Stockholm", "venue": "Debaser", "setlist": ['.$validSongIDs[0]['SongID'].',
            '.$validSongIDs[2]['SongID'].', '.$validSongIDs[1]['SongID'].',
            '.$validSongIDs[3]['SongID'].'], "otherBands": [
                {"name": "My First Band", "website": "http://mfb.com"},
                {"name": "Somewhere", "website": "http://www.somwhere.se"},
                {"name": "Tester", "website": "http://www.tes.tr"}
            ], "performers": [{"personID": '.$personIDs[0]['PersonID'].', "instruments": "Guitar"},
            {"personID": '.$personIDs[1]['PersonID'].', "instruments": "Vocals"},
            {"personID": "UnitTest New", "instruments": "Bongo"}]}';
        $this->testShowID1 = $shows->add($json1)['id'];
        $this->testShowID2 = $shows->add($json2)['id'];
    }

    public function tearDown()
    {
        $sqlBuilder = new \Apps\Database\Delete();

        $sql = $sqlBuilder->delete()->from('Shows')->where('Country = :country')->result();
        $pdo = array('country' => 'UnitTest');
        $this->database->run($sql, $pdo);

        $sql = $sqlBuilder->delete()->from('Songs')->where('Title LIKE :title')->result();
        $pdo = array('title' => 'UnitTest%');
        $this->database->run($sql, $pdo);

        $sql = $sqlBuilder->delete()->from('People')->where('Name LIKE :name')->result();
        $pdo = array('name' => 'UnitTest%');
        $this->database->run($sql, $pdo);

        $this->database->close();
    }

    public function testClassWorks()
    {
        $this->assertTrue($this->shows instanceof \Apps\Shows\GetShows);
    }

    public function testGettingOneShow()
    {
        $response = $this->shows->get($this->testShowID2);
        $result = $response['contents'];

        $this->assertFalse(empty($result), 'Result should not be empty');
        $this->assertEquals(200, $response['code'], 'Wrong response code');
        $this->assertTrue(array_key_exists('setlist', $result), 'Setlist is missing from response');
        $this->assertTrue(array_key_exists('otherBands', $result), 'Other bands are missing from response');
        $this->assertEquals('SE', $result['countryCode'], 'Country code is wrong');
        $this->assertEquals(3, count($result['otherBands']), 'Amount of bands is wrong');
        $this->assertEquals('UnitTest3', $result['setlist'][1]['songTitle'], 'Song title is wrong in index 1');
        $this->assertEquals('Tester', $result['otherBands'][2]['name'], 'Other bands is missing band');
        $this->assertEquals('UnitTest New', $result['performers'][2]['name'], 'Player name is unexpected');
    }

    public function testGettingAllShows()
    {
        $response = $this->shows->get();
        $shows = $response['contents'];

        $this->assertEquals(2, count($shows), 'Show count does not match');
        $this->assertEquals('SE', $shows[1]['countryCode'], 'Country code does not match');
        $this->assertTrue(array_key_exists('setlist', $shows[0]));
        $this->assertTrue(array_key_exists('otherBands', $shows[0]));
    }
}


text:
<?php
namespace Vifeed\PaymentBundle\Tests\Unit;

use Doctrine\ORM\EntityManager;
use Vifeed\CampaignBundle\Entity\Campaign;
use Vifeed\PlatformBundle\Entity\Platform;
use Vifeed\SystemBundle\Tests\ApiTestCase;
use Vifeed\UserBundle\Entity\User;
use Vifeed\VideoViewBundle\Entity\VideoView;

class VideoViewPaymentManagerRefundTest extends ApiTestCase
{

    /**
     *
     */
    public function testRefundByPublisher()
    {
        /** @var User $publisher */
        $publisher = self::$parameters['fixtures']['publisher'];
        /** @var User $advertiser0 */
        $advertiser0 = self::$parameters['fixtures']['advertisers'][0];
        /** @var User $advertiser1 */
        $advertiser1 = self::$parameters['fixtures']['advertisers'][1];
        /** @var Campaign $campaign0 */
        $campaign0 = self::$parameters['fixtures']['campaigns'][0];
        /** @var Campaign $campaign1 */
        $campaign1 = self::$parameters['fixtures']['campaigns'][1];

        $paymentManager = $this->getPaymentManager();
        $this->assertEquals(90, $campaign0->getBalance());
        $this->assertEquals(80, $campaign1->getBalance());
        $this->assertEquals(0, $advertiser0->getBalance());
        $this->assertEquals(0, $advertiser1->getBalance());
        $this->assertEquals(21, $publisher->getBalance());

        $refund = $paymentManager->refundAllFromPublisher($publisher);
        $this->assertInternalType('array', $refund);
        $this->assertArrayHasOnlyKeys(['paid', 'charged'], $refund);
        $this->assertEquals(30, $refund['paid']);
        $this->assertEquals(21, $refund['charged']);

        self::$em->refresh($publisher);
        self::$em->refresh($advertiser1);
        self::$em->refresh($advertiser0);
        self::$em->refresh($campaign1);
        self::$em->refresh($campaign0);

        $this->assertEquals(90, $campaign0->getBalance());
        $this->assertEquals(80, $campaign1->getBalance());
        $this->assertEquals(10, $advertiser0->getBalance());
        $this->assertEquals(20, $advertiser1->getBalance());
        $this->assertEquals(0, $publisher->getBalance());

    }

    /**
     * @return \Vifeed\PaymentBundle\Manager\VideoViewPaymentManager
     */
    protected function getPaymentManager()
    {
        return self::$container->get('vifeed.payment.video_view_payment_manager');
    }

    protected static function loadTestFixtures()
    {
        /** @var EntityManager $entityManager */
        $entityManager = self::$em;
        $paymentManager = self::$container->get('vifeed.payment.video_view_payment_manager');

        $userManager = self::$container->get('fos_user.user_manager');

        $advertiser0 = new User();
        $advertiser0->setType(User::TYPE_ADVERTISER)
                    ->setEmail('testadv1@vifeed.co')
                    ->setUsername('testadv1@vifeed.co')
                    ->setEnabled(true)
                    ->setBalance(0)
                    ->setPlainPassword('12345');
        $userManager->updateCanonicalFields($advertiser0);

        $advertiser1 = new User();
        $advertiser1->setType(User::TYPE_ADVERTISER)
                    ->setEmail('testadv2@vifeed.co')
                    ->setUsername('testadv2@vifeed.co')
                    ->setEnabled(true)
                    ->setBalance(0)
                    ->setPlainPassword('12345');
        $userManager->updateCanonicalFields($advertiser1);

        $publisher = new User();
        $publisher->setType(User::TYPE_PUBLISHER)
                  ->setEmail('testpub1@vifeed.co')
                  ->setUsername('testpub1@vifeed.co')
                  ->setBalance(0)
                  ->setEnabled(true)
                  ->setPlainPassword('12345');
        $userManager->updateCanonicalFields($publisher);

        $campaign0 = new Campaign();
        $campaign0->setUser($advertiser0)
                  ->setName('111')
                  ->setBid(1)
                  ->setGeneralBudget(100)
                  ->setBalance(100)
                  ->setDailyBudget(0)
                  ->setStatus(Campaign::STATUS_ON)
                  ->setHash('123');

        $campaign1 = new Campaign();
        $campaign1->setUser($advertiser1)
                  ->setName('222')
                  ->setBid(2)
                  ->setGeneralBudget(100)
                  ->setBalance(100)
                  ->setDailyBudget(0)
                  ->setHash('123')
                  ->setStatus(Campaign::STATUS_ON);

        $platform0 = new Platform();
        $platform0->setUser($publisher)
                  ->setUrl('123')
                  ->setName('111')
                  ->setDescription('123');

        $entityManager->persist($advertiser0);
        $entityManager->persist($advertiser1);
        $entityManager->persist($publisher);
        $entityManager->persist($campaign0);
        $entityManager->persist($campaign1);
        $entityManager->persist($platform0);

        $views = [];
        for ($i = 0; $i < 10; $i++) {

            $views[$i] = new VideoView();
            $views[$i]
                  ->setCampaign($campaign0)
                  ->setPlatform($platform0)
                  ->setCurrentTime(30)
                  ->setTimestamp((new \DateTime('yesterday'))->setTime(0, 0, 0)->format('U'))
                  ->setTrackNumber(30)
                  ->setIp(11111 + $i)
                  ->setViewerId(md5($i));
            $entityManager->persist($views[$i]);

            $views[$i + 10] = new VideoView();
            $views[$i + 10]
                  ->setCampaign($campaign1)
                  ->setPlatform($platform0)
                  ->setCurrentTime(30)
                  ->setTimestamp((new \DateTime('yesterday'))->setTime(0, 0, 0)->format('U'))
                  ->setTrackNumber(30)
                  ->setIp(11111 + $i + 10)
                  ->setViewerId(md5($i + 10));
            $entityManager->persist($views[$i + 10]);
        }

        $entityManager->flush();
        foreach ($views as $view) {
            $paymentManager->reckon($view);
        }

        self::$em->refresh($publisher);
        self::$em->refresh($advertiser0);
        self::$em->refresh($advertiser1);
        self::$em->refresh($campaign0);
        self::$em->refresh($campaign1);

        $fixtures = [
              'advertisers' => [$advertiser0, $advertiser1],
              'publisher'   => $publisher,
              'campaigns'   => [$campaign0, $campaign1],
              'platofrms'   => [$platform0],
              'views'       => $views
        ];

        return $fixtures;
    }

}


text:
.PHONY: clean instrument integration lint report test

clean:
	@rm -rf coverage lib-cov server.cov.js

instrument:
	@istanbul instrument -o lib-cov/ lib

integration:
	@./integration/run.bash

lint:
	@jshint lib bin && jshint --config ./test/.jshintrc test

report:
	@istanbul report cobertura

test: clean lint
	@istanbul cover _mocha -- './test/lib/**/*.js' './test/bin/**/*.js'