text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Templating\Helper;

use Symfony\Component\Templating\Helper\Helper;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * CodeHelper.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class CodeHelper extends Helper
{
    protected $fileLinkFormat;
    protected $rootDir;

    /**
     * Constructor.
     *
     * @param string $fileLinkFormat The format for links to source files
     * @param string $rootDir        The project root directory
     */
    public function __construct($fileLinkFormat, $rootDir)
    {
        $this->fileLinkFormat = null !== $fileLinkFormat ? $fileLinkFormat : ini_get('xdebug.file_link_format');
        $this->rootDir = str_replace('\\', '/', $rootDir).'/';
    }

    /**
     * Formats an array as a string.
     *
     * @param array $args The argument array
     *
     * @return string
     */
    public function formatArgsAsText($args)
    {
        $result = array();
        foreach ($args as $key => $item) {
            if ('object' === $item[0]) {
                $formattedValue = sprintf("object(%s)", $item[1]);
            } elseif ('array' === $item[0]) {
                $formattedValue = sprintf("array(%s)", $this->formatArgsAsText($item[1]));
            } elseif ('string'  === $item[0]) {
                $formattedValue = sprintf("'%s'", $item[1]);
            } elseif ('null' === $item[0]) {
                $formattedValue = 'null';
            } elseif ('boolean' === $item[0]) {
                $formattedValue = strtolower(var_export($item[1], true));
            } elseif ('resource' === $item[0]) {
                $formattedValue = 'resource';
            } else {
                $formattedValue = str_replace("\n", '', var_export((string) $item[1], true));
            }

            $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
        }

        return implode(', ', $result);
    }

    public function abbrClass($class)
    {
        $parts = explode('\\', $class);
        $short = array_pop($parts);

        return sprintf("%s", $class, $short);
    }

    public function abbrMethod($method)
    {
        list($class, $method) = explode('::', $method);

        $parts = explode('\\', $class);
        $short = array_pop($parts);

        return sprintf("%s::%s", $class, $short, $method);
    }

    /**
     * Formats an array as a string.
     *
     * @param array $args The argument array
     *
     * @return string
     */
    public function formatArgs($args)
    {
        $result = array();
        foreach ($args as $key => $item) {
            if ('object' === $item[0]) {
                $parts = explode('\\', $item[1]);
                $short = array_pop($parts);
                $formattedValue = sprintf("object(%s)", $item[1], $short);
            } elseif ('array' === $item[0]) {
                $formattedValue = sprintf("array(%s)", $this->formatArgs($item[1]));
            } elseif ('string'  === $item[0]) {
                $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES, $this->getCharset()));
            } elseif ('null' === $item[0]) {
                $formattedValue = 'null';
            } elseif ('boolean' === $item[0]) {
                $formattedValue = ''.strtolower(var_export($item[1], true)).'';
            } elseif ('resource' === $item[0]) {
                $formattedValue = 'resource';
            } else {
                $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES, $this->getCharset()), true));
            }

            $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
        }

        return implode(', ', $result);
    }

    /**
     * Returns an excerpt of a code file around the given line number.
     *
     * @param string $file  A file path
     * @param int    $line  The selected line number
     *
     * @return string An HTML string
     */
    public function fileExcerpt($file, $line)
    {
        if (is_readable($file)) {
            $code = highlight_file($file, true);
            // remove main code/span tags
            $code = preg_replace('#^\s*(.*)\s*#s', '\\1', $code);
            $content = preg_split('#
#', $code);

            $lines = array();
            for ($i = max($line - 3, 1), $max = min($line + 3, count($content)); $i <= $max; $i++) {
                $lines[] = '
'.self::fixCodeMarkup($content[$i - 1]).'
';
            }

            return '
'.implode("\n", $lines).'
';
        }
    }

    /**
     * Formats a file path.
     *
     * @param  string  $file   An absolute file path
     * @param  integer $line   The line number
     * @param  string  $format The output format (txt or html)
     * @param  string  $text   Use this text for the link rather than the file path
     *
     * @return string
     */
    public function formatFile($file, $line)
    {
        $file = trim($file);
        $fileStr = $file;
        if (0 === strpos($fileStr, $this->rootDir)) {
            $fileStr = str_replace($this->rootDir, '', str_replace('\\', '/', $fileStr));
            $fileStr = sprintf('kernel.root_dir/%s', $this->rootDir, $fileStr);
        }

        if (!$this->fileLinkFormat) {
            return "$file line $line";
        }

        $link = strtr($this->fileLinkFormat, array('%f' => $file, '%l' => $line));

        return sprintf('%s line %s', $link, $fileStr, $line);
    }

    public function formatFileFromText($text)
    {
        $that = $this;

        return preg_replace_callback('/in (.*?)(?: on|at)? line (\d+)/', function ($match) use ($that) {
            return 'in '.$that->formatFile($match[1], $match[2]);
        }, $text);
    }

    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        return 'code';
    }

    protected static function fixCodeMarkup($line)
    {
        //  ending tag from previous line
        $opening = strpos($line, '<span');
        $closing = strpos($line, '');
        if (false !== $closing && (false === $opening || $closing < $opening)) {
            $line = substr_replace($line, '', $closing, 7);
        }

        // missing  tag at the end of line
        $opening = strpos($line, '<span');
        $closing = strpos($line, '');
        if (false !== $opening && (false === $closing || $closing > $opening)) {
            $line .= '';
        }

        return $line;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.upscale.front.repository;

import org.slf4j.LoggerFactory;

import java.util.Optional;

import org.slf4j.Logger;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.upscale.front.domain.CollateralData;
import com.upscale.front.domain.Tenant;

/***
 *
 * @author Anurag Garg
 *
 * Spring Data JPA repository for the Collateral entity.
 *
 */

@Repository
@Transactional
public interface CollateralRepository extends JpaRepository<CollateralData, Long>{

	public final Logger log = LoggerFactory.getLogger(CollateralRepository.class);

	Optional<CollateralData> findCollateralByTenantAndName(Tenant tenant, String name);
}


text:
import __future__
import os
import sys
import subprocess
import script.rio
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import config

class Engine:
    def __init__(self, engineOptionDict, build = True, clean = False):
        self._project_name = engineOptionDict['project_name']
        self._compiler = engineOptionDict['compiler']
        self._mode = engineOptionDict['mode']
        self._precision = engineOptionDict['precision']
        self._std = engineOptionDict['std']
        self._gdb = engineOptionDict['gdb']
        self._vtune = engineOptionDict['vtune']
        self._valgrind = engineOptionDict['valgrind']
        self._rounding = engineOptionDict['rounding']

        if clean:
            self._clean(self._project_name, self._compiler, self._mode, self._precision, self._std, self._rounding)
        elif build:
            self._build(self._project_name, self._compiler, self._mode, self._precision, self._std, self._rounding)

        program_file = self._project_name + '-' + self._mode + '-' + self._compiler + '-' + self._precision + '-' + self._rounding + '.exec'
        self._binary_path = os.path.join(config.workspace, program_file)

    def _build(self, project_name, compiler, mode, precision, std, rounding):
        p = subprocess.Popen(['scons',
            'workspace=' + config.workspace,
            'project=' + project_name,
            'compiler=' + compiler,
            'mode=' + mode,
            'precision=' + precision,
            'std=' + std,
            'rounding=' + rounding],
            cwd = os.path.join(config.workspace, 'source'))
        p.wait()
        if p.returncode != 0:
            print("Compilation failed")
            sys.exit(1)

    def _clean(self, project_name, compiler, mode, precision, std, rounding):
        p = subprocess.Popen(['scons',
            'workspace=' + config.workspace,
            'project=' + project_name,
            'compiler=' + compiler,
            'mode=' + mode,
            'precision=' + precision,
            'std=' + std,
            'rounding=' + rounding,
            '-c'],
            cwd = os.path.join(config.workspace, 'source'))
        p.wait()

    def run(self, input_path, output_path, nnodes, mpi_nprocs, ncores, run_option = []):
        if mpi_nprocs == 0:
            print("run failed - not enough mpi process specified.")
            sys.exit(1)

        cmd = list()
        # Command base: mpirun specified in config file.
        if self._compiler == 'mpi':
            mpi_opt = []
            for x in  config.mpi_RUN.split(' '):
                if x == '$mpi_nprocs':
                    mpi_opt.append(str(mpi_nprocs))
                elif x == '$ncores':
                    mpi_opt.append(str(ncores))
                else:
                    mpi_opt.append(x)
            cmd = cmd + mpi_opt

        if self._gdb:
            #cmd = cmd + ['xterm', '-e', 'gdb', '--args']
            #cmd = cmd + ['lldb', '--']
            cmd = cmd + ['gdb', '--args']
        elif self._valgrind:
            #cmd = cmd + ['valgrind', '--leak-check=yes', '--track-origins=yes', '--leak-check=full', '--show-leak-kinds=all', '--log-file=valgrind-out.txt']
            cmd = cmd + ['valgrind', '--leak-check=yes', '--track-origins=yes']
        elif self._vtune:
            cmd = cmd + ['amplxe-cl', '-r', 'vtune-hs', '-collect', 'hotspots']
            #cmd = cmd + ['amplxe-cl', '-r', 'report-vtune-ma', '-collect', 'memory-access']
            #cmd = cmd + ['amplxe-cl', '-r', 'report-vtune-mc', '-collect', 'memory-consumption']
            #cmd = cmd + ['amplxe-cl', '-r', 'report-vtune-ge', '-collect', 'general-exploration']
        elif self._rounding is not None:
            if self._rounding == 'check':
                cmd = ['valgrind', '--tool=none'] + cmd
            else:
                # --rounding-mode=<random|average|upward|downward|toward_zero|farthest|float|nearest>
                if self._precision == 'quad' or self._precision.startswith('weak'):
                    if self._rounding not in ['nearest', 'upward', 'downward', 'toward_zero']:
                        print("Precision %s and rounding mode %s are not compatible." % (self._precision, self._rounding))
                        sys.exit(1)

                # For the specific verrou rounding modes, we must use verrou
                if self._rounding not in ['nearest', 'upward', 'downward', 'toward_zero']:
                    f = open("list.ex", "w")
                    ldd = subprocess.check_output(["ldd", self._binary_path])
                    for lib in ldd.split():
                        if 'libm' in str(lib) and "/" in str(lib):
                            f.write("*\t%s\n" % lib.decode("utf-8"))

                    ldd = subprocess.check_output(["ldd", "./lib/interlibmath.so"])
                    for lib in ldd.split():
                        if 'libquad' in str(lib) and "/" in str(lib):
                            f.write("*\t%s\n" % lib.decode("utf-8"))

                    f.close()
                    #os.environ['VERROU_LIBM_ROUNDING_MODE'] = "nearest"
                    os.environ['VERROU_ROUNDING_MODE'] = self._rounding
                    os.environ['LD_PRELOAD'] = "./lib/interlibmath.so"
                    cmd = ['valgrind', '--tool=verrou', '--rounding-mode=' + self._rounding, '--demangle=no', '--exclude=list.ex'] + cmd
                else:
                    # we simply use the environment variable
                    if self._rounding == 'upward':
                        run_option += ['--rounding', 'upward']
                    if self._rounding == 'downward':
                        run_option += ['--rounding', 'downward']
                    if self._rounding == 'toward_zero':
                        run_option += ['--rounding', 'toward_zero']
        '''
        # to add environment variable visible in this process + all children:
        os.environ['SCOREP_EXPERIMENT_DIRECTORY'] = project + 'weak.SDD' + str(mpi_nprocs) + '.r1'
        '''

        cmd = cmd + [self._binary_path, '-i', input_path, '-o', output_path] + run_option
        print(' '.join(cmd))
        subprocess.check_call(cmd, env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))


text:
#include "hst/environment.h"

#include <functional>
#include <memory>
#include <ostream>

#include "hst/event.h"
#include "hst/hash.h"
#include "hst/process.h"

namespace hst {

namespace {

class ExternalChoice : public Process {
  public:
    ExternalChoice(Environment* env, Process::Set ps)
        : env_(env), ps_(std::move(ps))
    {
    }

    void initials(std::function<void(Event)> op) const override;
    void afters(Event initial,
                std::function<void(const Process&)> op) const override;
    void subprocesses(std::function<void(const Process&)> op) const override;

    std::size_t hash() const override;
    bool operator==(const Process& other) const override;
    unsigned int precedence() const override { return 6; }
    void print(std::ostream& out) const override;

  private:
    Environment* env_;
    Process::Set ps_;
};

}  // namespace

const Process*
Environment::external_choice(Process::Set ps)
{
    return register_process(new ExternalChoice(this, std::move(ps)));
}

const Process*
Environment::external_choice(const Process* p, const Process* q)
{
    return external_choice(Process::Set{p, q});
}

// Operational semantics for □ Ps
//
//                  P -τ→ P'
//  1)  ────────────────────────────── P ∈ Ps
//       □ Ps -τ→ □ (Ps ∖ {P} ∪ {P'})
//
//         P -a→ P'
//  2)  ───────────── P ∈ Ps, a ≠ τ
//       □ Ps -a→ P'

void
ExternalChoice::initials(std::function<void(Event)> op) const
{
    // 1) If P ∈ Ps can perform τ, then □ Ps can perform τ.
    // 2) If P ∈ Ps can perform a ≠ τ, then □ Ps can perform a ≠ τ.
    //
    // initials(□ Ps) = ⋃ { initials(P) ∩ {τ} | P ∈ Ps }                [rule 1]
    //                ∪ ⋃ { initials(P) ∖ {τ} | P ∈ Ps }                [rule 2]
    //
    //                = ⋃ { initials(P) | P ∈ Ps }
    for (const Process* p : ps_) {
        p->initials(op);
    }
}

void
ExternalChoice::afters(Event initial,
                       std::function<void(const Process&)> op) const
{
    // afters(□ Ps, τ) = ⋃ { □ Ps ∖ {P} ∪ {P'} | P ∈ Ps, P' ∈ afters(P, τ) }
    //                                                                  [rule 1]
    // afters(□ Ps, a ≠ τ) = ⋃ { P' | P ∈ Ps, P' ∈ afters(P, a) }       [rule 2]
    if (initial == Event::tau()) {
        // We're going to build up a lot of new Ps' sets that all have the same
        // basic structure: Ps' = Ps ∖ {P} ∪ {P'}.  Each Ps' starts with Ps, so
        // go ahead and add that into our Ps' set once.
        Process::Set ps_prime(ps_);
        for (const Process* p : ps_) {
            // Set Ps' to Ps ∖ {P}
            ps_prime.erase(p);
            // Grab afters(P, τ)
            Process::Set p_afters;
            p->afters(initial, &p_afters);
            for (const Process* p_prime : p_afters) {
                // ps_prime currently contains (Ps ∖ {P}).  Add P' to produce
                // (Ps ∖ {P} ∪ {P'})
                ps_prime.insert(p_prime);
                // Create □ (Ps ∖ {P} ∪ {P'}) as a result.
                op(*env_->external_choice(ps_prime));
                // Reset Ps' back to Ps ∖ {P}.
                ps_prime.erase(p_prime);
            }
            // Reset Ps' back to Ps.
            ps_prime.insert(p);
        }
    } else {
        for (const Process* p : ps_) {
            p->afters(initial, op);
        }
    }
}

void
ExternalChoice::subprocesses(std::function<void(const Process&)> op) const
{
    for (const Process* process : ps_) {
        op(*process);
    }
}

std::size_t
ExternalChoice::hash() const
{
    static hash_scope external_choice;
    return hasher(external_choice).add(ps_).value();
}

bool
ExternalChoice::operator==(const Process& other_) const
{
    const ExternalChoice* other = dynamic_cast<const ExternalChoice*>(&other_);
    if (other == nullptr) {
        return false;
    }
    return ps_ == other->ps_;
}

void
ExternalChoice::print(std::ostream& out) const
{
    print_subprocesses(out, ps_, "□");
}

}  // namespace hst


text:
@interface CMIDIExternalSource ()
- (id) initWithEndpointRef: (MIDIEndpointRef) ref
                  andIndex: (NSUInteger) i;
@end

//------------------------------------------------------------------------------
//      Persistant list of the current endpoints
//------------------------------------------------------------------------------

NSArray      * CMIDIExternalSource_endpoints = nil;
NSDictionary * CMIDIExternalSource_endpointDictionary = nil;

void CMIDIInitializeExternalSources()
{
    if (CMIDIExternalSource_endpointDictionary != nil) return;

    CMIDIClient(); // Make sure the client exists.

    ItemCount n = MIDIGetNumberOfDestinations();
    NSMutableArray * sources = [NSMutableArray arrayWithCapacity: n];
    for (ItemCount i = 0; i < n; i++) {
        [sources addObject:[[CMIDIExternalSource alloc] initWithEndpointRef:MIDIGetSource(i)
                                                                   andIndex:i]];
    }
    CMIDIExternalSource_endpoints = sources;

    NSMutableDictionary * dict  = [NSMutableDictionary new];
    for (CMIDIExternalSource * s in sources) {
        [dict setObject:s forKey: s.name];
    }
    CMIDIExternalSource_endpointDictionary = dict;
}

//------------------------------------------------------------------------------
//      CMIDIExternalSource
//------------------------------------------------------------------------------

@implementation CMIDIExternalSource {
    NSString                 * _name;
    MIDIEndpointRef            _endpointRef;
    MIDIPortRef                _port;
    NSObject <CMIDIReceiver> * _output;
    CMIDIDataParser   * _parser;
}

- (NSString *) name    { return _name; }
- (BOOL) isInternal    { return NO; }
- (BOOL) isReceiver    { return NO; }

//------------------------------------------------------------------------------
//      Construction
//------------------------------------------------------------------------------

- (id) initWithEndpointRef: (MIDIEndpointRef) ref
                  andIndex: (NSUInteger) i

{
    if (self = [super init]) {
        _endpointRef = ref;
        _name = CMIDIEndpointName(_endpointRef);
        _parser = [CMIDIDataParser new];
        [self initPortWithIndex:i];
    }
    return self;
}

+ (instancetype) endpointWithName:(NSString *)name
{
    CMIDIInitializeExternalSources();
    return [CMIDIExternalSource_endpointDictionary objectForKey:name];
}

+ (NSArray *) endpoints
{
    CMIDIInitializeExternalSources();
    return CMIDIExternalSource_endpoints;
}

+ (NSDictionary *) dictionary
{
    CMIDIInitializeExternalSources();
    return CMIDIExternalSource_endpointDictionary;
}

- (void) dealloc
{
    MIDIPortDispose(_port);
    MIDIEndpointDispose(_endpointRef);
}

//------------------------------------------------------------------------------
//                      Output Unit
//------------------------------------------------------------------------------

- (NSObject <CMIDIReceiver> *) outputUnit { return _output; }
- (void) setOutputUnit: (NSObject <CMIDIReceiver> *) obj
{
    if (!obj || [obj respondsToSelector:@selector(respondToMIDI:)]) {
        @synchronized(self) {
            _output = obj;
        }
    }
}

//------------------------------------------------------------------------------
//                      MIDI Data Flow
//------------------------------------------------------------------------------
// Create a port and connect it to the source; the source will send MIDI to use through the read proc.

- (void) initPortWithIndex: (NSUInteger) i
{
    NSString *portName = [NSString stringWithFormat:@"Input port for source: %@",[self name]];
    void *refCon = (__bridge void *) self;
    OSStatus err;
    err = MIDIInputPortCreate(CMIDIClient(),
                                (__bridge CFStringRef) portName,
                                CMIDIExternalSource_ReadProc,
                                (void *) i,
                                &_port);
    NSAssert(err == 0,@"CoreMIDI from CMIDI");
    err = MIDIPortConnectSource(_port, _endpointRef, refCon);
    NSAssert(err == 0,@"CoreMIDI from CMIDI");
}

static
void CMIDIExternalSource_ReadProc(const MIDIPacketList *packetList,
                                  void *refCon,
                                  void *unused)
{
    NSUInteger i = (NSUInteger) refCon;
    CMIDIExternalSource * sender;
    NSObject <CMIDIReceiver> * receiver;
    @synchronized(CMIDIExternalSource_endpoints) {
        sender = CMIDIExternalSource_endpoints[i];
        if (sender) {
            receiver = sender->_output;
        }
    }

    if (receiver) {
        NSArray * messages = [sender->_parser parsePacketList:packetList];
        for (CMIDIMessage * message in messages) {
            [receiver respondToMIDI:message];
        }
    }
}

@end


text:
<?php

/*Template Name: Food-Drink Page*/

get_header(); ?>

        <?php
          $title = get_field('custom_page_title');
        ?>
        <?php if($title): ?>
          <?php echo $title;  ?>
        <?php else: ?>
          <?php echo get_the_title(); ?>
        <? endif; ?>

  <div <?php post_class('border-t border-b half-half-container food-and-drink-page u-cf'); ?> >

<?php the_field('cbox-title'); ?>

<?php the_field('cbox-p'); ?>

      <?php get_template_part('partials/promo'); ?>

  <?php if( have_rows('food_and_drink_content') ): ?>

    <?php while( have_rows('food_and_drink_content') ): the_row();

      // vars
      $image = get_sub_field('food_and_drink_image');
      $image_link = get_sub_field('food_and_drink_image_link');
      $title = get_sub_field('food_and_drink_title');
      $text = get_sub_field('food_and_drink_text');
      $menu = get_sub_field('food_and_drink_menu');
      $booking_id = get_sub_field('food_and_drink_booking_id');

    ?>

        <?php if($image_link): ?>
          <a href="<?php echo $image_link; ?>" target="_blank">
        <?php endif; ?>
            <img src="<?php echo $image['sizes']['post-thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
        <?php if($image_link): ?>

        <?php endif; ?>

<?php echo $title; ?>

<?php echo $text; ?>

        <?php if( $menu ):?>
          <a href="<?php echo $menu; ?>" target="_blank" class="btn btn-skin btn-skin-link-color btn-top-space u-inlineBlock u-textCapitalize u-textInheritColor" >View Menu
        <?php endif; ?>

        <?php if( $booking_id ):?>
          <a href="<?php echo $booking_id; ?>" class="[ btn btn-skin btn-skin-link-color btn-top-space u-inlineBlock u-textCapitalize ] resDiary-popup-btn">Book Now
        <?php endif; ?>

    <?php endwhile; ?>

  <?php endif; ?>

<?php get_footer(); ?>


text:
<?php
/**
 * File for input class of select function of db manager
 */

namespace Cayman\Manager\DbManager;

/**
 * Class for input of select function of db manager
 *
 */
class InputForSelect extends InputCommon
{
    /**
     * Select statement
     * @var string
     */
    public $sql;

    /**
     * Parameters
     * @var array
     */
    public $parameters = [];

    /**
     * Class name of records to be returned and hydrated
     * Associative arrays will be returned, if class name is not given
     * @var string
     */
    public $className;
}


text:
module Test.WebDriver.Utils where

import Data.Text (Text)
import Data.Text.Encoding as TE
import qualified Network.HTTP.Types.URI as HTTP

urlEncode :: Text -> Text
urlEncode = TE.decodeUtf8 . HTTP.urlEncode False . TE.encodeUtf8


text:
Pattern: Violation of hook rule

Issue: -

## Description

Verifies hook rules:

- **Don't call Hooks inside loops, conditions, or nested functions**. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple `useState` and `useEffect` calls.

- **Don't call Hooks from regular JavaScript functions**. Instead, you can:
	- Call Hooks from React function components.
	- Call Hooks from custom Hooks (we'll learn about them on the next page).

	By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

## Further Reading

* [React - Rules of Hooks](https://reactjs.org/docs/hooks-rules.html)


text:
// Code generated by lister-gen. DO NOT EDIT.

package v1alpha2

import (
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
	v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
)

// TCPRouteLister helps list TCPRoutes.
// All objects returned here must be treated as read-only.
type TCPRouteLister interface {
	// List lists all TCPRoutes in the indexer.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha2.TCPRoute, err error)
	// TCPRoutes returns an object that can list and get TCPRoutes.
	TCPRoutes(namespace string) TCPRouteNamespaceLister
	TCPRouteListerExpansion
}

// tCPRouteLister implements the TCPRouteLister interface.
type tCPRouteLister struct {
	indexer cache.Indexer
}

// NewTCPRouteLister returns a new TCPRouteLister.
func NewTCPRouteLister(indexer cache.Indexer) TCPRouteLister {
	return &tCPRouteLister{indexer: indexer}
}

// List lists all TCPRoutes in the indexer.
func (s *tCPRouteLister) List(selector labels.Selector) (ret []*v1alpha2.TCPRoute, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha2.TCPRoute))
	})
	return ret, err
}

// TCPRoutes returns an object that can list and get TCPRoutes.
func (s *tCPRouteLister) TCPRoutes(namespace string) TCPRouteNamespaceLister {
	return tCPRouteNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// TCPRouteNamespaceLister helps list and get TCPRoutes.
// All objects returned here must be treated as read-only.
type TCPRouteNamespaceLister interface {
	// List lists all TCPRoutes in the indexer for a given namespace.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha2.TCPRoute, err error)
	// Get retrieves the TCPRoute from the indexer for a given namespace and name.
	// Objects returned here must be treated as read-only.
	Get(name string) (*v1alpha2.TCPRoute, error)
	TCPRouteNamespaceListerExpansion
}

// tCPRouteNamespaceLister implements the TCPRouteNamespaceLister
// interface.
type tCPRouteNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all TCPRoutes in the indexer for a given namespace.
func (s tCPRouteNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.TCPRoute, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha2.TCPRoute))
	})
	return ret, err
}

// Get retrieves the TCPRoute from the indexer for a given namespace and name.
func (s tCPRouteNamespaceLister) Get(name string) (*v1alpha2.TCPRoute, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1alpha2.Resource("tcproute"), name)
	}
	return obj.(*v1alpha2.TCPRoute), nil
}


text:
require 'spec_helper'

describe ActiveXML::Collection do
  subject { ActiveXML::Collection.new(path) }
  let(:path) { Pathname.new("spec/fixtures/active_xml/example.xml") }

  it_behaves_like "active_xml"

  describe "#pluck(key)" do
    it "returns the array of objects stored in key given in param" do
      subject.pluck(:name).should == ["Foo", "Bar"]
    end
  end

  describe "#count" do
    it "returns a number of objects in collection" do
      subject.count.should == 2
    end
  end

  describe "#where" do
    it "returns Query object" do
      subject.where(id: 1).should be_a(ActiveXML::Collection::Query)
    end

    it "raises an error if more that one key:value pair passed in where" do
      expect{ subject.where(id: 1, name: "Foo") }.to raise_error(ArgumentError, "Passing more then 1 where value is currently not possible")
    end
  end

  describe "#delete_nodes" do
    it "deletes given nodes" do
      subject.delete_nodes(["id","name"])
      subject.xml.to_s.should_not include('<id>1</id>','<name>Foo</name>')
      subject.xml.to_s.should     include('<id>2</id>','<name>Bar</name>')
    end
  end

  describe "#split" do
    let(:temp_dir) { Pathname.new(Dir.mktmpdir("test_active_xml_collection")) }

    it "should create 2 files" do
      subject.split("#{temp_dir}/objects/:id")
      temp_dir.join('objects/1.xml').should exist
      temp_dir.join('objects/2.xml').should exist
    end

    it "new files should have valid content" do
      subject.split("#{temp_dir}/objects/:id")
      temp_dir.join('objects/1.xml').read.should include('<id>1</id>', '<name>Foo</name>')
    end

    it "returns hash of paths" do
      subject.split("#{temp_dir}/objects/:id").should == {
        "1" => ["#{temp_dir}/objects/1.xml"],
        "2" => ["#{temp_dir}/objects/2.xml"]
      }
    end

    it "returns hash of paths, each id has array of paths" do
      collection = ActiveXML::Collection.new("spec/fixtures/active_xml/nested_example.xml")
      collection.split("#{temp_dir}/objects/:id/:code").should == {
        "1" => [
          "#{temp_dir}/objects/1/ABC.xml",
          "#{temp_dir}/objects/1/ABCD.xml"
        ],
        "2" => [
          "#{temp_dir}/objects/2/CBA.xml",
        ]
      }
    end
  end

  describe "#split_to_array" do
    let(:temp_dir) { Pathname.new(Dir.mktmpdir("test_active_xml_collection")) }

    it "should create 2 files" do
      subject.split_to_array("#{temp_dir}/objects/:id")
      temp_dir.join('objects/1.xml').should exist
      temp_dir.join('objects/2.xml').should exist
    end

    it "new files should have valid content" do
      subject.split_to_array("#{temp_dir}/objects/:id")
      temp_dir.join('objects/1.xml').read.should include('<id>1</id>', '<name>Foo</name>')
    end

    it "returns array of Pathnames" do
      subject.split_to_array("#{temp_dir}/objects/:id").first.should be_kind_of Pathname
    end

    it "returns proper Pathname" do
      subject.split_to_array("#{temp_dir}/objects/:id").first.to_s.should == "#{temp_dir}/objects/1.xml"
    end
  end
end


text:
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package google.registry.flows;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
import static google.registry.testing.DatabaseHelper.loadRegistrar;
import static google.registry.testing.DatabaseHelper.persistResource;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import google.registry.flows.TlsCredentials.BadRegistrarIpAddressException;
import google.registry.flows.TlsCredentials.MissingRegistrarCertificateException;
import google.registry.flows.TlsCredentials.RegistrarCertificateNotConfiguredException;
import google.registry.flows.certs.CertificateChecker;
import google.registry.model.registrar.Registrar;
import google.registry.testing.AppEngineExtension;
import google.registry.testing.FakeClock;
import google.registry.util.CidrAddressBlock;
import google.registry.util.ProxyHttpHeaders;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

/** Unit tests for {@link TlsCredentials}. */
final class TlsCredentialsTest {

  @RegisterExtension
  final AppEngineExtension appEngine = AppEngineExtension.builder().withCloudSql().build();

  protected final FakeClock clock = new FakeClock();

  private final CertificateChecker certificateChecker =
      new CertificateChecker(
          ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398),
          30,
          15,
          2048,
          ImmutableSet.of("secp256r1", "secp384r1"),
          clock);

  @Test
  void testProvideClientCertificateHash() {
    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)).thenReturn("data");
    assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).hasValue("data");
  }

  @Test
  void testClientCertificateAndHash_missing() {
    TlsCredentials tls =
        new TlsCredentials(true, Optional.empty(), Optional.of("192.168.1.1"), certificateChecker);
    persistResource(
        loadRegistrar("TheRegistrar")
            .asBuilder()
            .setClientCertificate(SAMPLE_CERT, clock.nowUtc())
            .build());
    assertThrows(
        MissingRegistrarCertificateException.class,
        () -> tls.validateCertificateHash(Registrar.loadByRegistrarId("TheRegistrar").get()));
  }

  @Test
  void test_missingIpAddress_doesntAllowAccess() {
    TlsCredentials tls =
        new TlsCredentials(
            false, Optional.of("certHash"), Optional.of("127.0.0.1"), certificateChecker);
    persistResource(
        loadRegistrar("TheRegistrar")
            .asBuilder()
            .setClientCertificate(SAMPLE_CERT, clock.nowUtc())
            .setIpAddressAllowList(ImmutableSet.of(CidrAddressBlock.create("3.5.8.13")))
            .build());

    BadRegistrarIpAddressException thrown =
        assertThrows(
            BadRegistrarIpAddressException.class,
            () -> tls.validate(Registrar.loadByRegistrarId("TheRegistrar").get(), "password"));

    assertThat(thrown)
        .hasMessageThat()
        .isEqualTo("Registrar IP address 127.0.0.1 is not in stored allow list");
  }

  @Test
  void testClientCertificate_notConfigured() {
    TlsCredentials tls =
        new TlsCredentials(
            true, Optional.of("hash"), Optional.of("192.168.1.1"), certificateChecker);
    persistResource(loadRegistrar("TheRegistrar").asBuilder().build());
    assertThrows(
        RegistrarCertificateNotConfiguredException.class,
        () -> tls.validateCertificateHash(Registrar.loadByRegistrarId("TheRegistrar").get()));
  }

  @Test
  void test_validateCertificateHash_canBeConfiguredToBypassCerts() throws Exception {
    TlsCredentials tls =
        new TlsCredentials(
            false, Optional.of("certHash"), Optional.of("192.168.1.1"), certificateChecker);
    persistResource(
        loadRegistrar("TheRegistrar")
            .asBuilder()
            .setClientCertificate(null, clock.nowUtc())
            .setFailoverClientCertificate(null, clock.nowUtc())
            .build());
    // This would throw a RegistrarCertificateNotConfiguredException if cert hashes wren't bypassed.
    tls.validateCertificateHash(Registrar.loadByRegistrarId("TheRegistrar").get());
  }
}


text:
package net.doubledoordev.d3log.client;

/**
 * @author Dries007
 */
public class ClientHelper
{

}


text:
package org.apache.ignite.marshaller.optimized;

/**
 * ID mapper.
 */
public interface OptimizedMarshallerIdMapper {
    /**
     * Gets type ID for provided class name.
     * <p>
     * If {@code 0} is returned, hash code of class name will be used.
     *
     * @param clsName Class name.
     * @return Type ID.
     */
    public int typeId(String clsName);
}


text:
"""Minifier for Python code

The module exposes a single function : minify(src), where src is
a string with the original Python code.

The function returns a string with a minified version of the original :
- indentation is reduced to the minimum (1 space for each level)
- comments are removed, except on the first 2 lines
- lines starting with a string are removed (considered as doc strings), except
  if the next line doesn't start with the same indent, like in
      # --------------------------------
      def f():
          'function with docstring only'
      print('ok')
      # --------------------------------
"""

import os
import token
import tokenize
import re
import io
from keyword import kwlist

def minify(src, preserve_lines=False):

    # tokenize expects method readline of file in binary mode
    file_obj = io.BytesIO(src.encode('utf-8'))
    token_generator = tokenize.tokenize(file_obj.readline)

    out = '' # minified source
    line = 0
    last_type = None
    indent = 0 # current indentation level
    brackets = [] # stack for brackets

    # first token is script encoding
    encoding = next(token_generator).string

    file_obj = io.BytesIO(src.encode(encoding))
    token_generator = tokenize.tokenize(file_obj.readline)

    for item in token_generator:

        # update brackets stack if necessary
        if token.tok_name[item.type]=='OP':
            if item.string in '([{':
                brackets.append(item.string)
            elif item.string in '}])':
                brackets.pop()

        sline = item.start[0] # start line
        if sline == 0: # encoding
            continue

        # udpdate indentation level
        if item.type==tokenize.INDENT:
            indent += 1
        elif item.type==tokenize.DEDENT:
            indent -= 1
            continue

        if sline>line: # first token in a line

            if not brackets and item.type==tokenize.STRING:
                if last_type in [tokenize.NEWLINE, tokenize.INDENT, None]:
                    # If not inside a bracket, replace a string starting a
                    # line by the empty string.
                    # It will be removed if the next line has the same
                    # indentation.
                    out += ' '*indent+"''"
                    if preserve_lines:
                        out += '\n'*item.string.count('\n')
                    continue
            out += ' '*indent # start with current indentation
            if item.type not in [tokenize.INDENT, tokenize.COMMENT]:
                out += item.string
            elif item.type==tokenize.COMMENT and \
                line<=2 and item.line.startswith('#!'):
                # Ignore comments starting a line, except in one of the first
                # 2 lines, for interpreter path and/or encoding declaration
                out += item.string
        else:
            if item.type == tokenize.COMMENT: # ignore comments in a line
                continue
            if not brackets and item.type == tokenize.STRING and \
                last_type in [tokenize.NEWLINE, tokenize.INDENT]:
                # If not inside a bracket, ignore string after newline or
                # indent
                out += "''"
                if preserve_lines:
                    out += '\n'*item.string.count('\n')
                continue
            if item.type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP] and \
                last_type in [tokenize.NAME, tokenize.NUMBER]:
                # insert a space when needed
                if item.type != tokenize.OP \
                    or item.string not in ',()[].=:{}+&' \
                    or (last_type == tokenize.NAME and last_item.string in kwlist):
                        out += ' '
            elif item.type == tokenize.STRING and \
                item.string[0] in 'rbu' and \
                last_type in [tokenize.NAME, tokenize.NUMBER]:
                # for cases like "return b'x'"
                out += ' '
            elif item.type == tokenize.NAME \
                and last_item.type == tokenize.OP and last_item.string == '.':
                # special case : from . import X
                out += ' '
            out += item.string

        line = item.end[0]
        last_item = item
        if item.type==tokenize.NL and last_type==tokenize.COMMENT:
            # NL after COMMENT is interpreted as NEWLINE
            last_type = tokenize.NEWLINE
        else:
            last_type = item.type

    # replace lines with only whitespace by empty lines
    out = re.sub('^\s+$', '', out, re.M)

    if not preserve_lines:
        # remove empty line at the start of the script (doc string)
        out = re.sub("^''\n", '', out)

        # remove consecutive empty lines
        out = re.sub('\n( *\n)+', '\n', out)

        # remove lines with an empty string followed by a line that starts with
        # the same indent
        def repl(mo):
            if mo.groups()[0]==mo.groups()[1]:
                return '\n'+mo.groups()[1]
            return mo.string[mo.start(): mo.end()]
        out = re.sub("\n( *)''\n( *)", repl, out)

    return out


text:
RocketPath::RocketPath(int lower, int upper)
{
	int sum = 0;
	for(int i = lower; i < upper;i++)
	{
		xPositions.push_back(i);
	}

	currX = 0;
	currY = 0;

	xMin = lower;
	xMax = upper;
}

//getX i followPath se pozivaju u petlji pa imaju tu proveru da ne izadju iz opsega
//vektora znaci na svaki refresh ekrana ove 2 fije ce se pozivati

double RocketPath::getX()
{
	if(currX < xMax && currY < xMax)
	  return xPositions.at(currX);

	return 0;
}

void RocketPath::followPath(sf::CircleShape* rocket, double x, double y)
{
	if(currX < xMax && currY < xMax)
		rocket->setPosition((float) x, (float) y);

	currX++;
	currY++;
}


text:
package factom

import (
	"encoding/hex"
	"encoding/json"
)

// RawData is a simple hex encoded byte string
type RawData struct {
	Data string `json:"data"`
}

func (r *RawData) GetDataBytes() ([]byte, error) {
	return hex.DecodeString(r.Data)
}

// GetRaw requests the raw data for any binary block kept in the factomd
// database.
func GetRaw(keymr string) ([]byte, error) {
	params := hashRequest{Hash: keymr}
	req := NewJSON2Request("raw-data", APICounter(), params)
	resp, err := factomdRequest(req)
	if err != nil {
		return nil, err
	}
	if resp.Error != nil {
		return nil, resp.Error
	}

	raw := new(RawData)
	if err := json.Unmarshal(resp.JSONResult(), raw); err != nil {
		return nil, err
	}

	return raw.GetDataBytes()
}

// SendRawMsg sends a raw hex encoded byte string for factomd to send as a
// binary message on the Factom Netwrork.
func SendRawMsg(message string) (string, error) {
	param := messageRequest{Message: message}
	req := NewJSON2Request("send-raw-message", APICounter(), param)
	resp, err := factomdRequest(req)
	if err != nil {
		return "", err
	}
	if resp.Error != nil {
		return "", resp.Error
	}

	status := new(struct {
		Message string `json:"message"`
	})
	if err := json.Unmarshal(resp.JSONResult(), status); err != nil {
		return "", err
	}

	return status.Message, nil
}


text:
package com.amazonaws.services.kinesis.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.kinesis.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * PutRecordRequest Marshaller
 */
public class PutRecordRequestMarshaller implements
        Marshaller<Request<PutRecordRequest>, PutRecordRequest> {

    public Request<PutRecordRequest> marshall(PutRecordRequest putRecordRequest) {

        if (putRecordRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<PutRecordRequest> request = new DefaultRequest<PutRecordRequest>(
                putRecordRequest, "AmazonKinesis");
        request.addHeader("X-Amz-Target", "Kinesis_20131202.PutRecord");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
                    .createWriter(false, "1.1");

            jsonGenerator.writeStartObject();

            if (putRecordRequest.getStreamName() != null) {
                jsonGenerator.writeFieldName("StreamName").writeValue(
                        putRecordRequest.getStreamName());
            }
            if (putRecordRequest.getData() != null) {
                jsonGenerator.writeFieldName("Data").writeValue(
                        putRecordRequest.getData());
            }
            if (putRecordRequest.getPartitionKey() != null) {
                jsonGenerator.writeFieldName("PartitionKey").writeValue(
                        putRecordRequest.getPartitionKey());
            }
            if (putRecordRequest.getExplicitHashKey() != null) {
                jsonGenerator.writeFieldName("ExplicitHashKey").writeValue(
                        putRecordRequest.getExplicitHashKey());
            }
            if (putRecordRequest.getSequenceNumberForOrdering() != null) {
                jsonGenerator
                        .writeFieldName("SequenceNumberForOrdering")
                        .writeValue(
                                putRecordRequest.getSequenceNumberForOrdering());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
<?php

/* @var $this yii\web\View */

use yii\bootstrap\Html;
use p2m\helpers\FA;

$this->title = 'P2 New Age';
$assetDir = Yii::$app->assetManager->getPublishedUrl(
	'@vendor/p2made/yii2-startbootstrap-themes/assets/lib/new-age'
);
?>
<?= $this->render('_header.php', ['assetDir' => $assetDir]) ?>
<?= $this->render('_download.php', ['assetDir' => $assetDir]) ?>
<?= $this->render('_features.php', ['assetDir' => $assetDir]) ?>
<?= $this->render('_cta.php') ?>
<?= $this->render('_contact.php') ?>
<?= $this->render('_footer.php') ?>


text:
<?php

namespace Framework;
use Cat\Core\Engine;

final class App extends Engine
{

}


text:
package com.android.volley.toolbox;

import com.android.volley.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import static org.junit.Assert.assertNotNull;

@RunWith(RobolectricTestRunner.class)
public class StringRequestTest {

    @Test
    public void publicMethods() throws Exception {
        // Catch-all test to find API-breaking changes.
        assertNotNull(StringRequest.class.getConstructor(String.class, Response.Listener.class,
                Response.ErrorListener.class));
        assertNotNull(StringRequest.class.getConstructor(int.class, String.class,
                Response.Listener.class, Response.ErrorListener.class));
    }
}


text:
package main

import (
	log "github.com/Sirupsen/logrus"
	"os"
)

func main() {
	log.SetLevel(log.DebugLevel)
	log.SetOutput(os.Stderr)

	SetupProcessEnvironment()
	MountApiFilesystems()
	CreateApiSymlinks()

	log.Infof("Initalized system")

	config := ReadConfig()

	log.Infof("Read config file")

	grimReaper := NewGrimReaper()
	serviceManager := NewServiceManager(config, grimReaper)
	triggerRunner := NewTriggerRunner(config, grimReaper, serviceManager)

	triggerRunner.RunTrigger("init")

	go grimReaper.Run()
	go serviceManager.Run()
	go ProcessSignals(triggerRunner)

	triggerRunner.Run()
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>JOBS</title>
	<?php includeJQuery(); ?>
	<?php includeBootstrap(); ?>

	<?=$menu ?>

					Proveedor en edición
					<select id="cCliente" class="form-control">
						<option value="-1">Ninguno</option>
						<?php foreach($proveedores as $proveedor){ ?>
							<option value="<?php echo $proveedor->id; ?>"><?php echo $proveedor->nombre; ?></option>
						<?php } ?>
					</select>

				<form
					action = "Alta_cliente_ctrl/nuevoCliente"
					method = "post"
					id = "form_alta"
				>

						Nombre comercial
						<input type="text" name="nombre" placeholder="Nombre comercial" class="form-control" required>

						<input type="submit" value="Crear" class="form-control btn btn-primary">

				</form>

					<form
						action = "Alta_cliente_ctrl/editarCliente"
						method = "post"
						id = "form-edita"
					>

									Nombre comercial
									<input type="text" name="nombre" id="nombre" placeholder="Nombre comercial" class="form-control" required>

									Estado: Activo
									<button style="width: 100%;" id="btn-estado" class="btn btn-danger">Inactivar</button>

						<input type="hidden" name="id" value="-1">
						<input type="hidden" name="estadoActivo" value="1">

							<input type="submit" value="Actualizar" class="form-control btn btn-info">

					</form>

					      		 Direcciones fiscales

					      		 Direcciones operativas

					      		 Bancos

					      		 Agenda

					      		 Perfiles

					      		 Servicios

			<?=$form_seccion1; ?>
			<?=$form_agenda; ?>


text:
require 'simplecov'
require 'simplecov-rcov'

SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter

SimpleCov.start do
  add_filter '/test/'
  add_filter '/features/'
end


text:
<?php
# MantisBT - a php based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

	 /**
	  * MantisBT Core API's
	  */
	require_once( 'core.php' );

	require_once( 'filter_api.php' );
	require_once( 'csv_api.php' );
	require_once( 'columns_api.php' );

	auth_ensure_user_authenticated();

	helper_begin_long_process();

	$t_page_number = 1;
	$t_per_page = -1;
	$t_bug_count = null;
	$t_page_count = null;

	$t_nl = csv_get_newline();
 	$t_sep = csv_get_separator();

	# Get bug rows according to the current filter

	$t_filename = date("Y-m-d_H-i",time())."_".csv_get_default_filename();

	$f_project_id = helper_get_current_project();
	$t_from = gpc_get_string('d_from');
	$t_to = gpc_get_string('d_to');
	$f_bugnote_cost = gpc_get_int('bugnote_cost');
	$f_bugnote_price = gpc_get_string('bugnote_price');
	$t_bugnote_stats = bugnote_stats_get_project_array( $f_project_id, $t_from, $t_to, $f_bugnote_cost, $f_bugnote_price );
	$t_reporting_period = plugin_lang_get('reporting_period') . column_billing_get_date($t_from) . " thru " . column_billing_get_date($t_to);
	$t_sum_amt = 0;
    $t_billing_export = array();
	$t_i = 0;

	foreach ( $t_bugnote_stats as $t_item ) {
		if ($t_item['username']!="administrator"){
		    $t_billing_export[$t_i]['username'] = $t_item['realname'];
		    $t_billing_export[$t_i]['summary'] = $t_item['summary'];
		    $t_billing_export[$t_i]['bug_id'] = $t_item['bug_id'];
		    $t_billing_export[$t_i]['sum_time_tracking'] = db_minutes_to_hhmm($t_item['sum_time_tracking']);
		    if($f_bugnote_price){
			    if($f_bugnote_cost){
				    $t_billing_export[$t_i]['user_price'] = number_format($f_bugnote_cost, 2);
				    $t_billing_export[$t_i]['total_amt'] = number_format($f_bugnote_cost * $t_item['sum_time_tracking']/60, 2);
			    }else{
				    $t_billing_export[$t_i]['user_price'] = number_format($t_item['user_price'], 2);
				    $t_billing_export[$t_i]['total_amt'] = number_format(($t_item['sum_time_tracking'] * $t_item['user_price'])/60, 2);
			    }
		    }else{
			    if($f_bugnote_cost){
				    $t_billing_export[$t_i]['total_amt'] = number_format(($f_bugnote_cost * $t_item['sum_time_tracking'])/60, 2);
			    }
		    }
		    $t_i++;
	    }
	}

	# Send headers to browser to activate mime loading

	# Make sure that IE can download the attachments under https.
	header( 'Pragma: public' );

	header( 'Content-Type: text/plain; name=' . urlencode( file_clean_name( $t_filename ) ) );
	header( 'Content-Transfer-Encoding: BASE64;' );

	# Added Quotes (") around file name.
	header( 'Content-Disposition: attachment; filename="' . urlencode( file_clean_name( $t_filename ) ) . '"' );

	# Get columns to be exported
	# export the titles
	$t_first_column = true;
	ob_start();
	$t_titles = array();
	echo $t_reporting_period;
	echo $t_nl;
	if (sizeof($t_billing_export)>0){
	    foreach ( $t_billing_export[0] as $k=>$t_column ) {
		    if ( !$t_first_column ) {
			    echo $t_sep;
		    } else {
			    $t_first_column = false;
		    }
    		echo column_billing_get_title($k) ;
	    }
	    echo $t_nl;

	    $t_header = ob_get_clean();

	    # Fixed for a problem in Excel where it prompts error message "SYLK: File Format Is Not Valid"
	    # See Microsoft Knowledge Base Article - 323626
	    # http://support.microsoft.com/default.aspx?scid=kb;en-us;323626&Product=xlw
	    $t_first_three_chars = utf8_substr( $t_header, 0, 3 );
	    if ( strcmp( $t_first_three_chars, 'ID' . $t_sep ) == 0 ) {
		    $t_header = str_replace( 'ID' . $t_sep, 'Id' . $t_sep, $t_header );
	    }
	    # end of fix

	    echo $t_header;

	    # export the rows
	    foreach ( $t_billing_export as $t_row ) {
		    $t_first_column = true;
		    foreach ($t_row as $k=>$v){
    		    if ( !$t_first_column ) {
	    		    echo $t_sep;
		        } else {
			        $t_first_column = false;
		        }
		        ob_start();
		        echo column_billing_get_field($k, $v);
	        }
	        echo $t_nl;
	    }
	}else{
	    echo plugin_lang_get("no_record_csv");
    }


text:
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.client.diff;

import com.google.gwt.dom.client.Element;

import net.codemirror.lib.LineWidget;

import java.util.ArrayList;
import java.util.List;

/**
 * Manages paddings for CommentBoxes. Each line that may need to be padded owns
 * a PaddingManager instance, which maintains a padding widget whose height
 * changes as necessary. PaddingManager calculates padding by taking the
 * difference of the sum of CommentBox heights on the two sides.
 *
 * Note that in the case of an insertion or deletion gap, A PaddingManager
 * can map to a list of managers on the other side. The padding needed is then
 * calculated from the sum of all their heights.
 *
 * TODO: Let PaddingManager also take care of the paddings introduced by
 * insertions and deletions.
 */
class PaddingManager {
  private List<CommentBox> comments;
  private PaddingWidgetWrapper wrapper;
  private List<PaddingManager> others;

  PaddingManager(PaddingWidgetWrapper padding) {
    comments = new ArrayList<CommentBox>();
    others = new ArrayList<PaddingManager>();
    this.wrapper = padding;
  }

  static void link(PaddingManager a, PaddingManager b) {
    if (!a.others.contains(b)) {
      a.others.add(b);
    }
    if (!b.others.contains(a)) {
      b.others.add(a);
    }
  }

  private int getMyTotalHeight() {
    int total = 0;
    for (CommentBox box : comments) {
      /**
       * This gets the height of CM's line widget div, taking the margin and
       * the horizontal scrollbar into account.
       */
      total += box.getSelfWidgetWrapper().getElement().getParentElement().getOffsetHeight();
    }
    return total;
  }

  /**
   * If this instance is on the insertion side, its counterpart on the other
   * side will map to a group of PaddingManagers on this side, so we calculate
   * the group's total height instead of an individual one's.
   */
  private int getGroupTotalHeight() {
    if (others.size() > 1) {
      return getMyTotalHeight();
    } else {
      return others.get(0).getOthersTotalHeight();
    }
  }

  private int getOthersTotalHeight() {
    int total = 0;
    for (PaddingManager manager : others) {
      total += manager.getMyTotalHeight();
    }
    return total;
  }

  private void setPaddingHeight(int height) {
    SideBySide2.setHeightInPx(wrapper.element, height);
    wrapper.widget.changed();
  }

  void resizePaddingWidget() {
    if (others.isEmpty()) {
      return;
    }
    int myHeight = getGroupTotalHeight();
    int othersHeight = getOthersTotalHeight();
    int paddingNeeded = othersHeight - myHeight;
    if (paddingNeeded < 0) {
      for (PaddingManager manager : others.get(0).others) {
        manager.setPaddingHeight(0);
      }
      others.get(others.size() - 1).setPaddingHeight(-paddingNeeded);
    } else {
      setPaddingHeight(paddingNeeded);
      for (PaddingManager other : others) {
        other.setPaddingHeight(0);
      }
    }
  }

  /** This is unused now because threading info is ignored. */
  int getReplyIndex(CommentBox box) {
    return comments.indexOf(box) + 1;
  }

  int getCurrentCount() {
    return comments.size();
  }

  void insert(CommentBox box, int index) {
    comments.add(index, box);
  }

  void remove(CommentBox box) {
    comments.remove(box);
  }

  static class PaddingWidgetWrapper {
    private LineWidget widget;
    private Element element;

    PaddingWidgetWrapper(LineWidget w, Element e) {
      widget = w;
      element = e;
    }

    LineWidget getWidget() {
      return widget;
    }

    Element getElement() {
      return element;
    }
  }

  static class LinePaddingWidgetWrapper extends PaddingWidgetWrapper {
    private int chunkLength;
    private int otherLine;

    LinePaddingWidgetWrapper(PaddingWidgetWrapper pair, int otherLine, int chunkLength) {
      super(pair.widget, pair.element);

      this.otherLine = otherLine;
      this.chunkLength = chunkLength;
    }

    int getChunkLength() {
      return chunkLength;
    }

    int getOtherLine() {
      return otherLine;
    }
  }
}


text:
"""Plotting functions.
"""
from __future__ import division, absolute_import

import numpy as np

import pylab as pl
import seaborn as sb

sb.set(font_scale=0.7, style='white')

def recovery_performance(mixed, cost_func, true_bias, estimated_signal, true_signal, estimated_bias):
    """
    Print recovery performance statistics.

    Parameters
    ----------
    mixed : numpy.ndarray, shape=(n_samples, n_features)
        Corrupted signal to be cleaned.
    cost_func : func
        Objective function for evaluation of current bias matrix estimate.
    true_bias : numpy.ndarray, shape=(n_samples, n_features)
        True bias matrix.
    estimated_signal : numpy.ndarray, shape=(n_samples, n_features)
        Estimated signal matrix.
    true_signal : numpy.ndarray, shape=(n_samples, n_features)
        True signal matrix.
    estimated_bias: numpy.ndarray, shape=(n_samples, n_features)
        Estimated bias matrix.

    Returns
    -------
    d : dict
        Performance metrics.
    """
    d = {}
    error_cost_func_true_bias = cost_func(true_bias)
    error_cost_func_estimated_bias = cost_func(estimated_bias)
    d['Error cost function (true bias)'] = error_cost_func_true_bias
    d['Error cost function (estimated bias)'] = error_cost_func_estimated_bias
    divisor = np.sum(~np.isnan(mixed))
    d['Number of valid values in corrupted signal'] = divisor
    mean_absolute_error_true_signal = np.nansum(
        np.absolute(true_signal - (mixed - true_bias))) / divisor
    mean_absolute_error_estimated_signal = np.nansum(
        np.absolute(true_signal - estimated_signal)) / divisor
    d['Mean absolute error (true_signal)'] = mean_absolute_error_true_signal
    d['Mean absolute error (estimated_signal)'] = mean_absolute_error_estimated_signal
    mean_absolute_error_zeros = np.nansum(
        np.absolute(true_signal - mixed)) / divisor
    d['Mean absolute error (zeros)'] = mean_absolute_error_zeros
    ratio_estimated_signal_to_zeros = mean_absolute_error_estimated_signal / \
        mean_absolute_error_zeros
    d['Ratio mean absolute error (estimated signal / zeros)'] = ratio_estimated_signal_to_zeros
    return d

def show_absolute(signal, kind, unshuffled=False, unshuffle=False, map_backward=None, vmin=-4, vmax=4):
    """
    Plot the absolute values of the given signal matrix.

    Parameters
    ----------
    signal : numpy.ndarray, shape=(n_samples, n_features)
        True signal matrix.
    kind : str, values=('Bias', 'Signal')
        Type of absolute value matrix to be shown (used as annotation on plot).
    unshuffled : bool
        If the input data is unshuffled.
    unshuffle : bool
        If to unshuffle the input data.
    map_backward : dict, value=('feature', 'sample'), values=dict
        Map from new annotation to old annotion.
    vmin : int
        Minimum absolute value on color scale.
    vmax : int
        Maximum absolute value on color scale.
    """
    cmap = sb.diverging_palette(
        250, 15, s=75, l=40, as_cmap=True, center="dark")
    indices_x = np.arange(signal.shape[0], dtype=int)
    indices_y = np.arange(signal.shape[1], dtype=int)
    fig = pl.figure(figsize=(7 * (signal.shape[1] / signal.shape[0]), 7))
    ax = fig.add_subplot(111)
    if unshuffle:
        ax.set_title('{} (unshuffled)'.format(kind))
        indices_x = np.asarray([map_backward['sample'][i] for i in indices_x])
        indices_y = np.asarray([map_backward['feature'][i] for i in indices_y])
        signal = signal[indices_x]
        signal = signal[:, indices_y]
    if unshuffled:
        ax.set_title('{} (unshuffled)'.format(kind))
        indices_x = np.asarray([map_backward['sample'][i] for i in indices_x])
        indices_y = np.asarray([map_backward['feature'][i] for i in indices_y])
    else:
        ax.set_title('{}'.format(kind))
    ax_seaborn = sb.heatmap(signal, vmin=vmin, vmax=vmax, cmap=cmap, ax=ax, cbar_kws={
                            'shrink': 0.5}, xticklabels=indices_y, yticklabels=indices_x)
    ax.tick_params(axis='both', which='both', length=0)
    ax.set_xlabel('Features')
    ax.set_ylabel('Samples')

def show_dependences(signal, pairs, space, n_pairs=5, n_points=50):
    """
    Plot the signal dependences for a subset of correlated pairs.

    Parameters
    ----------
    signal : numpy.ndarray, shape=(n_samples, n_features)
        True signal matrix.
    pairs : dict, keys=('feature', 'sample'), values=numpy.ndarray, shape=(n, 2)
        Correlated pair indices.
    space : str, values=('feature', 'sample')
        Feature or sample space.
    n_pairs : int
        Number of correlated pairs to show.
    n_points : int
        Number of data point to show.
    """
    cmap = sb.diverging_palette(250, 15, s=75, l=40, n=10, center="dark")
    if space == 'feature':
        shape = signal.T.shape
    if space == 'sample':
        shape = signal.shape
    pairs = pairs[space]
    for n, i in enumerate(np.random.choice(np.arange(len(pairs), dtype=int), min(n_pairs, len(pairs)), replace=False)):
        j = np.random.choice(np.arange(shape[1], dtype=int), min(
            n_points, shape[1]), replace=False)
        if space == 'sample':
            grid = sb.jointplot(signal[np.atleast_2d(pairs[i][1]), j], signal[np.atleast_2d(
                pairs[i][0]), j], ylim=(-4, 4), xlim=(-4, 4), alpha=0.6, size=5, stat_func=None, color='black')
            grid.set_axis_labels('Sample {}'.format(
                pairs[i][1]), 'Sample {}'.format(pairs[i][0]))
        if space == 'feature':
            grid = sb.jointplot(signal[j[:, None], pairs[i][1]], signal[j[:, None], pairs[i][0]], ylim=(
                -4, 4), xlim=(-4, 4), alpha=0.6, size=5, stat_func=None, color='black')
            grid.set_axis_labels('Feature {}'.format(
                pairs[i][1]), 'Feature {}'.format(pairs[i][0]))
        pl.setp(grid.ax_marg_y.patches, color=cmap[2])
        pl.setp(grid.ax_marg_x.patches, color=cmap[-2])

def show_recovery(mixed, guess_X, true_signal, estimated_signal, true_pairs, estimated_pairs, true_stds, estimated_stds, true_directions, estimated_directions, n_pairs=5, n_points=50):
    """
    Plot the signal dependences for a subset of correlated pairs overlayed with the estimated and true values.

    Parameters
    ----------
    mixed : numpy.ndarray, shape=(n_samples, n_features)
        Corrupted signal to be cleaned.
    guess_X : numpy.ndarray, shape=(n_samples, n_features)
        Initial guess used for the final solution.
    true_signal : numpy.ndarray, shape=(n_samples, n_features)
        True signal matrix.
    estimated_signal : numpy.ndarray, shape=(n_samples, n_features)
        Estimated signal matrix.
    true_pairs : numpy.ndarray, shape=(n, 2)
        True correlated pairs.
    estimated_pairs : numpy.ndarray, shape=(n, 2)
        Estimated correlated pairs.
    true_stds : numpy.ndarray, len=n
        True standard deviations.
    estimated_stds : numpy.ndarray, len=n
        Estimated standard deviations.
    true_directions : numpy.ndarray, len=n
        True directions.
    estimated_directions : numpy.ndarray, len=n
        Estimated directions.
    n_pairs : int
        Number of correlated pairs to show.
    n_points : int
        Number of data point to show.
    """
    def pair_index(pairs, pair):
        index = np.where(np.all(pairs == pair, axis=1))
        try:
            index = index[0][0]
        except IndexError:
            index = None
        return index

    fig = pl.figure(figsize=(5, 5 * n_pairs))
    pairs = np.vstack([true_pairs, estimated_pairs])
    np.random.shuffle(pairs)

    for i in xrange(n_pairs):
        ax = fig.add_subplot(n_pairs, 1, i + 1)
        for j in xrange(n_points):
            ax.plot(mixed[pairs[i][1]][j], mixed[pairs[i][0]]
                    [j], 'o', color='red', alpha=0.6)
            ax.plot(estimated_signal[pairs[i][1]][j],
                    estimated_signal[pairs[i][0]][j], 'D', color='blue', alpha=0.6)
            ax.plot(guess_X[pairs[i][1]][j], guess_X[pairs[i][0]]
                    [j], 'o', color='brown', alpha=0.6)
            ax.plot(true_signal[pairs[i][1]][j], true_signal[pairs[i]
                                                             [0]][j], 'o', color='green', alpha=0.6)
            ax.plot([true_signal[pairs[i][1]][j], mixed[pairs[i][1]][j]], [
                    true_signal[pairs[i][0]][j], mixed[pairs[i][0]][j]], '-', color='red', alpha=0.6)
            ax.plot([true_signal[pairs[i][1]][j], estimated_signal[pairs[i][1]][j]], [
                    true_signal[pairs[i][0]][j], estimated_signal[pairs[i][0]][j]], '-', color='blue', alpha=0.6)
        if pairs[i] in true_pairs:
            direction = true_directions[pair_index(true_pairs, pairs[i])]
            std_b, std_a = true_stds[pair_index(true_pairs, pairs[i])]
            std_b = std_b * -1 * direction
            m = -std_b / float(std_a)
            ax.plot(list(ax.get_xlim()), [
                    m * p + 0.0 for p in ax.get_xlim()], '-', color='orange', alpha=0.6)
        if pairs[i] in estimated_pairs:
            direction = estimated_directions[pair_index(
                estimated_pairs, pairs[i])]
            std_b, std_a = estimated_stds[pair_index(
                estimated_pairs, pairs[i])]
            std_b = std_b * -1 * direction
            m = -std_b / float(std_a)
            ax.plot(list(ax.get_xlim()), [
                    m * p + 0.0 for p in ax.get_xlim()], '--', color='black', alpha=0.6)
        sb.despine()
        ax.set_xlabel('Sample {}'.format(pairs[i][1]))
        ax.set_ylabel('Sample {}'.format(pairs[i][0]))
        ax.set_ylim(-4, 4)
        ax.set_xlim(-4, 4)

def show_independences(signal, pairs, space, n_pairs=5, n_points=50):
    """
    Plot the signal dependences for a subset of uncorrelated pairs.

    Parameters
    ----------
    signal : numpy.ndarray, shape=(n_samples, n_features)
        True signal matrix.
    pairs : dict, keys=('feature', 'sample'), values=numpy.ndarray, shape=(n, 2)
        Correlated pair indices.
    space : str, values=('feature', 'sample')
        Feature or sample space.
    n_pairs : int
        Number of correlated pairs to show.
    n_points : int
        Number of data point to show.
    """
    if space == 'feature':
        shape = signal.T.shape
    if space == 'sample':
        shape = signal.shape
    true_pairs = set()
    for pair in pairs[space]:
        true_pairs.add((pair[0], pair[1]))
        true_pairs.add((pair[1], pair[0]))
    all_pairs = set()
    for i in xrange(shape[0]):
        for j in range(shape[0]):
            all_pairs.add((i, j))
            all_pairs.add((j, i))
    identical = set([(i, i) for i in range(shape[0])])
    non_pairs = all_pairs - true_pairs - identical
    pairs = {space: np.asarray(list(non_pairs), dtype=int)}
    show_dependences(signal, pairs, space, n_pairs=n_pairs, n_points=n_points)

def show_dependence_structure(correlations, space, unshuffled=False, map_backward=None):
    """
    Plot a correlation matrix.

    Parameters
    ----------
    correlations : dict, keys=('feature', 'sample'), values=numpy.ndarray, shape=(n_samples, n_samples) or (n_features, n_features)
        Correlation matrix.
    space : str, values=('feature', 'sample')
        Feature or sample space.
    unshuffled : bool
        If the input data is unshuffled.
    map_backward : dict, value=('feature', 'sample'), values=dict
        Map from new annotation to old annotion.
    """
    cmap = sb.diverging_palette(
        250, 15, s=75, l=40, as_cmap=True, center="dark")
    indices = np.arange(correlations[space].shape[0], dtype=int)
    if space == 'feature':
        size = 7 * (correlations['feature'].shape[0] /
                    correlations['sample'].shape[0])
    if space == 'sample':
        size = 7
    fig = pl.figure(figsize=(size, size))
    ax = fig.add_subplot(111)
    if unshuffled:
        ax.set_title('Correlations (unshuffled)')
        indices = np.asarray([map_backward[space][i] for i in indices])
    else:
        ax.set_title('Correlations')
    sb.heatmap(correlations[space], cmap=cmap, vmin=-1, vmax=1, square=True,
               ax=ax, cbar_kws={'shrink': 0.5}, xticklabels=indices, yticklabels=indices)
    if space == 'feature':
        ax.set_xlabel('Features')
        ax.set_ylabel('Features')
    if space == 'sample':
        ax.set_xlabel('Samples')
        ax.set_ylabel('Samples')

def show_threshold(correlations, threshold, space):
    """
    Plot the number of estimated pairs at a particular correlation threshold.

    Parameters
    ----------
    correlations : dict, keys=('feature', 'sample'), values=numpy.ndarray, shape=(n_samples, n_samples) or (n_features, n_features)
        Correlation matrix.
    threshold : float
        Correlation threshold at which to cut-off (used to draw vertical line)
    space : str, values=('feature', 'sample')
        Feature or sample space.
    """
    cmap = sb.diverging_palette(250, 15, s=75, l=40, n=10, center="dark")
    fig = pl.figure(figsize=(5, 5))
    ax = fig.add_subplot(111)
    trimmed = np.trim_zeros(
        np.sort(np.tril(np.absolute(correlations[space]), -1).ravel()))
    ax.set_xlabel('Threshold')
    ax.set_ylabel('# pairs')
    x = trimmed
    y = np.arange(1, len(trimmed) + 1)
    ax.plot(x, y[::-1], '-', alpha=0.8, color='black')
    ax.axvline(threshold, min(x), max(x), linestyle='dashed', color=cmap[2])
    sb.despine()


text:
package org.hawkular.agent.monitor.extension;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.hawkular.agent.monitor.inventory.ConnectionData;
import org.hawkular.agent.monitor.inventory.Name;
import org.hawkular.agent.monitor.inventory.TypeSets;
import org.hawkular.agent.monitor.log.AgentLoggers;
import org.hawkular.agent.monitor.log.MsgLogger;
import org.hawkular.agent.monitor.protocol.dmr.DMRNodeLocation;
import org.hawkular.agent.monitor.protocol.jmx.JMXNodeLocation;
import org.hawkular.agent.monitor.protocol.platform.PlatformNodeLocation;

/**
 * This represents the monitor service extension's XML configuration in a more consumable form.
 * To build this from the actual service model, see {@link MonitorServiceConfigurationBuilder}.
 */
public class MonitorServiceConfiguration {
    private static final MsgLogger log = AgentLoggers.getLogger(MonitorServiceConfiguration.class);

    public enum StorageReportTo {
        HAWKULAR, // stores metrics to a Hawkular system
        METRICS // stores metrics to just a Hawkular-Metrics standalone system
    }

    public enum DiagnosticsReportTo {
        LOG, // stores the diagnostics data as simple log messages
        STORAGE // stores the diagnostics as metrics to the storage adapter
    }

    public static class StorageAdapterConfiguration {
        private final StorageReportTo type;
        private final String username;
        private final String password;
        private final String securityKey; // if !null, use key/secret rather than username/password to authenticate
        private final String securitySecret;
        private final String tenantId;
        private final String url;
        private final boolean useSSL;
        private final String serverOutboundSocketBindingRef;
        private final String accountsContext;
        private final String inventoryContext;
        private final String metricsContext;
        private final String feedcommContext;
        private final String keystorePath;
        private final String keystorePassword;
        private final String securityRealm;

        public StorageAdapterConfiguration(
                StorageReportTo type,
                String username,
                String password,
                String securityKey,
                String securitySecret,
                String tenantId,
                String url,
                boolean useSSL,
                String serverOutboundSocketBindingRef,
                String accountsContext,
                String inventoryContext,
                String metricsContext,
                String feedcommContext,
                String keystorePath,
                String keystorePassword,
                String securityRealm) {
            super();
            this.type = type;
            this.username = username;
            this.password = password;
            this.securityKey = securityKey;
            this.securitySecret = securitySecret;
            this.tenantId = tenantId;
            this.url = url;
            this.useSSL = useSSL;
            this.serverOutboundSocketBindingRef = serverOutboundSocketBindingRef;
            this.accountsContext = accountsContext;
            this.inventoryContext = inventoryContext;
            this.metricsContext = metricsContext;
            this.feedcommContext = feedcommContext;
            this.keystorePath = keystorePath;
            this.keystorePassword = keystorePassword;
            this.securityRealm = securityRealm;
        }

        public StorageReportTo getType() {
            return type;
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

        public String getSecurityKey() {
            return securityKey;
        }

        public String getSecuritySecret() {
            return securitySecret;
        }

        public String getTenantId() {
            return tenantId;
        }

        public String getUrl() {
            return url;
        }

        public boolean isUseSSL() {
            return useSSL;
        }

        public String getServerOutboundSocketBindingRef() {
            return serverOutboundSocketBindingRef;
        }

        public String getAccountsContext() {
            return accountsContext;
        }

        public String getInventoryContext() {
            return inventoryContext;
        }

        public String getMetricsContext() {
            return metricsContext;
        }

        public String getFeedcommContext() {
            return feedcommContext;
        }

        public String getKeystorePath() {
            return keystorePath;
        }

        public String getKeystorePassword() {
            return keystorePassword;
        }

        public String getSecurityRealm() {
            return securityRealm;
        }

    }

    public static class DiagnosticsConfiguration {
        public static final DiagnosticsConfiguration EMPTY = new DiagnosticsConfiguration(false, null, 0, null);
        private final boolean enabled;
        private final DiagnosticsReportTo reportTo;
        private final int interval;
        private final TimeUnit timeUnits;

        public DiagnosticsConfiguration(boolean enabled, DiagnosticsReportTo reportTo, int interval,
                TimeUnit timeUnits) {
            super();
            this.enabled = enabled;
            this.reportTo = reportTo;
            this.interval = interval;
            this.timeUnits = timeUnits;
        }

        public boolean isEnabled() {
            return enabled;
        }

        public DiagnosticsReportTo getReportTo() {
            return reportTo;
        }

        public int getInterval() {
            return interval;
        }

        public TimeUnit getTimeUnits() {
            return timeUnits;
        }
    }

    public static class GlobalConfiguration {

        private final boolean subsystemEnabled;
        private final String apiJndi;
        private final int numMetricSchedulerThreads;
        private final int numAvailSchedulerThreads;
        private final int numDmrSchedulerThreads;
        private final int metricDispatcherBufferSize;
        private final int metricDispatcherMaxBatchSize;
        private final int availDispatcherBufferSize;
        private final int availDispatcherMaxBatchSize;

        public GlobalConfiguration(boolean subsystemEnabled, String apiJndi, int numMetricSchedulerThreads,
                int numAvailSchedulerThreads, int numDmrSchedulerThreads, int metricDispatcherBufferSize,
                int metricDispatcherMaxBatchSize, int availDispatcherBufferSize, int availDispatcherMaxBatchSize) {
            super();
            this.subsystemEnabled = subsystemEnabled;
            this.apiJndi = apiJndi;
            this.numMetricSchedulerThreads = numMetricSchedulerThreads;
            this.numAvailSchedulerThreads = numAvailSchedulerThreads;
            this.numDmrSchedulerThreads = numDmrSchedulerThreads;
            this.metricDispatcherBufferSize = metricDispatcherBufferSize;
            this.metricDispatcherMaxBatchSize = metricDispatcherMaxBatchSize;
            this.availDispatcherBufferSize = availDispatcherBufferSize;
            this.availDispatcherMaxBatchSize = availDispatcherMaxBatchSize;
        }

    }

    public static class ProtocolConfiguration<L> {

        public static <L> Builder<L> builder() {
            return new Builder<L>();
        }

        public static class Builder<L> {
            private TypeSets<L> typeSets;
            private Map<String, EndpointConfiguration> endpoints = new LinkedHashMap<>();

            public Builder<L> endpoint(EndpointConfiguration endpoint) {
                endpoints.put(endpoint.getName(), endpoint);
                return this;
            }

            public Builder<L> typeSets(TypeSets<L> typeSets) {
                this.typeSets = typeSets;
                return this;
            }

            public ProtocolConfiguration<L> build() {
                for (EndpointConfiguration server : endpoints.values()) {
                    if (server.getResourceTypeSets() != null) {
                        for (Name resourceTypeSetName : server.getResourceTypeSets()) {
                            if (!typeSets.getResourceTypeSets().containsKey(resourceTypeSetName)) {
                                log.warnResourceTypeSetDoesNotExist(server.getName().toString(),
                                        resourceTypeSetName.toString());
                            }
                        }
                    }
                }

                return new ProtocolConfiguration<>(typeSets, endpoints);
            }
        }

        private final TypeSets<L> typeSets;
        private final Map<String, EndpointConfiguration> endpoints;

        public ProtocolConfiguration(TypeSets<L> typeSets,
                Map<String, EndpointConfiguration> managedServers) {
            super();
            this.typeSets = typeSets;
            this.endpoints = managedServers;
        }

        public TypeSets<L> getTypeSets() {
            return typeSets;
        }

        public Map<String, EndpointConfiguration> getEndpoints() {
            return endpoints;
        }
    }

    public static class EndpointConfiguration {
        private final String name;
        private final boolean enabled;
        private final Collection<Name> resourceTypeSets;
        private final ConnectionData connectionData;
        private final String securityRealm;

        public EndpointConfiguration(String name, boolean enabled, Collection<Name> resourceTypeSets,
                ConnectionData connectionData, String securityRealm) {
            super();
            this.name = name;
            this.enabled = enabled;
            this.resourceTypeSets = resourceTypeSets;
            this.connectionData = connectionData;
            this.securityRealm = securityRealm;
        }

        public Collection<Name> getResourceTypeSets() {
            return resourceTypeSets;
        }

        public boolean isEnabled() {
            return enabled;
        }

        public String getName() {
            return name;
        }

        public ConnectionData getConnectionData() {
            return connectionData;
        }

        public String getSecurityRealm() {
            return securityRealm;
        }

        public boolean isLocal() {
            return connectionData == null;
        }

    }

    private final GlobalConfiguration globalConfiguration;
    private final DiagnosticsConfiguration diagnostics;
    private final StorageAdapterConfiguration storageAdapter;
    private final ProtocolConfiguration<DMRNodeLocation> dmrConfiguration;
    private final ProtocolConfiguration<JMXNodeLocation> jmxConfiguration;
    private final ProtocolConfiguration<PlatformNodeLocation> platformConfiguration;

    public MonitorServiceConfiguration(GlobalConfiguration globalConfiguration,
            DiagnosticsConfiguration diagnostics,
            StorageAdapterConfiguration storageAdapter,
            ProtocolConfiguration<DMRNodeLocation> dmrConfiguration,
            ProtocolConfiguration<JMXNodeLocation> jmxConfiguration,
            ProtocolConfiguration<PlatformNodeLocation> platformConfiguration) {
        super();
        this.globalConfiguration = globalConfiguration;
        this.diagnostics = diagnostics;
        this.storageAdapter = storageAdapter;
        this.dmrConfiguration = dmrConfiguration;
        this.jmxConfiguration = jmxConfiguration;
        this.platformConfiguration = platformConfiguration;
    }

    public GlobalConfiguration getGlobalConfiguration() {
        return globalConfiguration;
    }

    public StorageAdapterConfiguration getStorageAdapter() {
        return storageAdapter;
    }

    public DiagnosticsConfiguration getDiagnostics() {
        return diagnostics;
    }

    public boolean isSubsystemEnabled() {
        return globalConfiguration.subsystemEnabled;
    }

    public String getApiJndi() {
        return globalConfiguration.apiJndi;
    }

    public int getNumMetricSchedulerThreads() {
        return globalConfiguration.numMetricSchedulerThreads;
    }

    public int getNumAvailSchedulerThreads() {
        return globalConfiguration.numAvailSchedulerThreads;
    }

    public int getNumDmrSchedulerThreads() {
        return globalConfiguration.numDmrSchedulerThreads;
    }

    public int getMetricDispatcherBufferSize() {
        return globalConfiguration.metricDispatcherBufferSize;
    }

    public int getMetricDispatcherMaxBatchSize() {
        return globalConfiguration.metricDispatcherMaxBatchSize;
    }

    public int getAvailDispatcherBufferSize() {
        return globalConfiguration.availDispatcherBufferSize;
    }

    public int getAvailDispatcherMaxBatchSize() {
        return globalConfiguration.availDispatcherMaxBatchSize;
    }

    public MonitorServiceConfiguration cloneWith(StorageAdapterConfiguration newStorageAdapter) {
        return new MonitorServiceConfiguration(globalConfiguration,
                diagnostics, newStorageAdapter, dmrConfiguration,
                jmxConfiguration, platformConfiguration);
    }

    public ProtocolConfiguration<DMRNodeLocation> getDmrConfiguration() {
        return dmrConfiguration;
    }

    public ProtocolConfiguration<JMXNodeLocation> getJmxConfiguration() {
        return jmxConfiguration;
    }

    public ProtocolConfiguration<PlatformNodeLocation> getPlatformConfiguration() {
        return platformConfiguration;
    }

}


text:
name: National Biodefense Analysis and Countermeasures Center
inits: NBACC
logo: /img/nbacc.png
link: http://bnbi.org
---


text:
<?php

namespace SofaChamps\Bundle\CoreBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;

class RequestProcessorCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if ($container->hasDefinition('sofachamps.component.authentication.handler.login_success_handler')) {
            $loginProcessors = new \SplPriorityQueue();
            foreach ($container->findTaggedServiceIds('sofachamps.request_processor.login') as $id => $attributes) {
                $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
                $loginProcessors->insert(new Reference($id), $priority);
            }

            $loginProcessors = iterator_to_array($loginProcessors);
            krsort($loginProcessors);

            $definition = $container->getDefinition('sofachamps.component.authentication.handler.login_success_handler');

            foreach ($loginProcessors as $processor) {
                $definition->addMethodCall('addRequestProcessor', array($processor));
            }
        }

        if ($container->hasDefinition('sofachamps.listener.registration_listener')) {
            $registrationProcessors = new \SplPriorityQueue();
            foreach ($container->findTaggedServiceIds('sofachamps.request_processor.registration') as $id => $attributes) {
                $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
                $registrationProcessors->insert(new Reference($id), $priority);
            }

            $registrationProcessors = iterator_to_array($registrationProcessors);
            krsort($registrationProcessors);

            $definition = $container->getDefinition('sofachamps.listener.registration_listener');

            foreach ($registrationProcessors as $processor) {
                $definition->addMethodCall('addRequestProcessor', array($processor));
            }
        }
    }
}


text:
namespace net {

// All section references below are to
// http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-05
// .

// A constant-time StringPiece comparison function, as suggested
// by section 6.
bool NET_EXPORT_PRIVATE StringPiecesEqualConstantTime(
    base::StringPiece str1,
    base::StringPiece str2);

}  // namespace net

#endif  // NET_SPDY_HPACK_STRING_UTIL_H_


text:
layout: post
title: Finding the balance
date: 2018-07-18 19:30:00
leader: Simon
---


text:
package net.sourceforge.plantuml.project;

public class Ressource {

	private final String code;

	private int capacity = 1;

	public Ressource(String code) {
		this.code = code;
	}

	public DayClose getDayClose() {
		return new DayCloseNone();
	}

	public final int getCapacity() {
		return capacity;
	}

	public final void setCapacity(int capacity) {
		this.capacity = capacity;
	}

}


text:
package io.mewbase.binders.impl;

import io.mewbase.binders.Binder;
import io.mewbase.binders.BinderStore;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;

/**
 * Shims are used for two main purposes ...
 *
 * 1) Instrument the Calls to the underlying class
 * 2) Implement security on a call by call basis possibly wrt Counters and other instrumentation
 */

public class BinderStoreShim implements BinderStore {

    private final String METRICS_NAME = "mewbase.binderstore";

    private final Counter openCounter;
    private final Counter getCounter;
    private final Counter delCounter;
    private final AtomicLong binderCount = new AtomicLong(0);

    private final BinderStore impl;

    public BinderStoreShim(BinderStore impl) {
        openCounter = Metrics.counter(METRICS_NAME + ".open");
        getCounter = Metrics.counter( METRICS_NAME + ".get");
        delCounter = Metrics.counter( METRICS_NAME + ".delete");
        // gauges need to wrapped and registered
        Metrics.gauge(METRICS_NAME + ".binders", binderCount);
        this.impl = impl;
    }

    @Override
    public Binder open(String name) {
        Binder b = impl.open(name);
        openCounter.increment();
        this.binders(); // force a count on the current binders
        return b;
    }

    @Override
    public Optional<Binder> get(String name) {
        Optional<Binder> ob = impl.get(name);
        getCounter.increment();
        return ob;
    }

    @Override
    public Stream<Binder> binders() {
        binderCount.set(impl.binders().count());
        return impl.binders();
    }

    @Override
    public Stream<String> binderNames() {
        return impl.binderNames();
    }

    @Override
    public Boolean delete(String name) {
        Boolean b = impl.delete(name);
        delCounter.increment();
        return b;
    }

    @Override
    public void close() throws Exception {
        impl.close();
    }
}


text:
WebSocket Echo Server as Twisted Web Resource plus WSGI/Flask
=============================================================

This is a variant of a basic WebSocket Echo server that is running as a *Twisted Web Resource*.

Running
-------

Run the server by doing

    python server.py

and open

    http://localhost:8080/

in your browser.

This will show up all WebSocket messages exchanged between clients and server.