text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"
)

type execution struct {
	DurationSeconds float64
	Hostname        string
	node            string
	body            string
	responseSeconds float64
}

var (
	lbHostPort, nodesStr, route       string
	numExecutions, maxPrime, numLoops int
	nodes                             []string
	nodesByContainerId                map[string]string = make(map[string]string)
	verbose                           bool
)

func init() {
	flag.StringVar(&lbHostPort, "lb", "localhost:8081", "host and port of load balancer")
	flag.StringVar(&nodesStr, "nodes", "localhost:8080", "comma-delimited list of nodes (host:port) balanced by the load balancer (needed to discover container id of each)")
	flag.StringVar(&route, "route", "/r/primesapp/primes", "path representing the route to the primes function")
	flag.IntVar(&numExecutions, "calls", 100, "number of times to call the route")
	flag.IntVar(&maxPrime, "max", 1000000, "maximum number to search for primes (higher number consumes more memory)")
	flag.IntVar(&numLoops, "loops", 1, "number of times to execute the primes calculation (ex: 'loops=2' means run the primes calculation twice)")
	flag.BoolVar(&verbose, "v", false, "true for more verbose output")
	flag.Parse()

	if maxPrime < 3 {
		log.Fatal("-max must be 3 or greater")
	}
	if numLoops < 1 {
		log.Fatal("-loops must be 1 or greater")
	}

	nodes = strings.Split(nodesStr, ",")
}

func executeFunction(hostPort, path string, max, loops int) (execution, error) {
	var e execution

	start := time.Now()
	resp, err := http.Get(fmt.Sprintf("http://%s%s?max=%d&loops=%d", hostPort, path, max, loops))
	e.responseSeconds = time.Since(start).Seconds()
	if err != nil {
		return e, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return e, fmt.Errorf("function returned status code: %d", resp.StatusCode)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return e, err
	}

	err = json.Unmarshal(body, &e)
	if err != nil {
		e.body = string(body) // set the body in the execution so that it is available for logging
		return e, err
	}
	e.node = nodesByContainerId[e.Hostname]

	return e, nil
}

func invokeLoadBalancer(hostPort, path string, numExecutions, max, loops int) {
	executionsByNode := make(map[string][]execution)
	fmt.Printf("All primes will be calculated up to %d, a total of %d time(s)\n", maxPrime, numLoops)
	fmt.Printf("Calling route %s %d times (through the load balancer)...\n", route, numExecutions)

	for i := 0; i < numExecutions; i++ {
		e, err := executeFunction(hostPort, path, max, loops)
		if err == nil {
			if ex, ok := executionsByNode[e.node]; ok {
				executionsByNode[e.node] = append(ex, e)
			} else {
				// Create a slice to contain the list of executions for this host
				executionsByNode[e.node] = []execution{e}
			}
			if verbose {
				fmt.Printf("  %s in-function duration: %fsec, response time: %fsec\n", e.node, e.DurationSeconds, e.responseSeconds)
			}
		} else {
			fmt.Printf("  Ignoring failed execution on node %s: %v\n", e.node, err)
			fmt.Printf("    JSON: %s\n", e.body)
		}
	}

	fmt.Println("Results (executions per node):")
	for node, ex := range executionsByNode {
		fmt.Printf("  %s %d\n", node, len(ex))
	}
}

func discoverContainerIds() {
	// Discover the Docker hostname of each node; create a mapping of hostnames to host/port.
	// This is needed because IronFunctions doesn't make the host/port available to the function (as of Mar 2017).
	fmt.Println("Discovering container ids for every node (use Docker's HOSTNAME env var as a container id)...")
	for _, s := range nodes {
		if e, err := executeFunction(s, route, 100, 1); err == nil {
			nodesByContainerId[e.Hostname] = s
			fmt.Printf("  %s %s\n", s, e.Hostname)
		} else {
			fmt.Printf("  Ignoring host %s which returned error: %v\n", s, err)
			fmt.Printf("    JSON: %s\n", e.body)
		}
	}
}

func main() {
	discoverContainerIds()
	invokeLoadBalancer(lbHostPort, route, numExecutions, maxPrime, numLoops)
}


text:
module IdHashConcern
  extend ActiveSupport::Concern

  included do
    before_create :set_id_hash
    validates :id_hash, uniqueness: true
  end

  def set_id_hash
    self.id_hash = gen_id_hash
  end

  def gen_id_hash
    id_hash = nil
    loop do
      id_hash = SecureRandom.urlsafe_base64(4)
      break unless self.class.where(id_hash: id_hash).exists?
    end

    id_hash
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>open-api-tool</title>

sign key
24位司机码


text:
"""Chromium presubmit script for src/net.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into gcl.
"""

def GetPreferredTryMasters(project, change):
  masters = {
    'tryserver.chromium': {
      'linux_chromium_rel': set(['defaulttests']),
      'mac_chromium_rel': set(['defaulttests']),
      'win_rel': set(['sync_integration_tests']),
    }
  }
  # Changes that touch NSS files will likely need a corresponding OpenSSL edit.
  # Conveniently, this one glob also matches _openssl.* changes too.
  if any('nss' in f.LocalPath() for f in change.AffectedFiles()):
    masters['tryserver.chromium'].setdefault(
      'linux_redux', set()).add('defaulttests')
  return masters


text:
class Repositext
  class Validation
    class Validator
      # Validates that all subtitle mark sequences (two or more subtitle marks
      # in a row with no content) are valid.
      class SubtitleMarkSequenceSyntax < Validator

        class InvalidSubtitleMarkSequenceError < StandardError; end

        # Runs all validations for self
        def run
          content_at_file = @file_to_validate
          outcome = subtitle_mark_sequences_valid?(content_at_file)
          log_and_report_validation_step(outcome.errors, outcome.warnings)
        end

      private

        # Checks that all subtitle mark sequences are valid
        def subtitle_mark_sequences_valid?(content_at_file)
          # Early return if content doesn't contain any subtitle_marks
          return Outcome.new(true, nil)  if !content_at_file.contents.index('@')

          invalid_subtitle_mark_sequences = find_invalid_subtitle_mark_sequences(
            content_at_file.contents
          )
          if invalid_subtitle_mark_sequences.empty?
            Outcome.new(true, nil)
          else
            Outcome.new(
              false, nil, [],
              invalid_subtitle_mark_sequences.map { |(error, line, excerpt)|
                Reportable.error(
                  {
                    filename: content_at_file.filename,
                    line: line,
                    context: excerpt,
                  },
                  [error]
                )
              }
            )
          end
        end

        def find_invalid_subtitle_mark_sequences(content)
          r = []
          # split on para boundaries for location info
          content.split(/\n/).each_with_index { |para, line_idx|
            if para =~ /@\s+@/
              # Space inside subtitle mark sequence.
              r << ["Space inside subtitle mark sequence:", line_idx + 1, para]
            elsif para =~ /@\s+$/
              # Space between subtitle mark and trailing eagle.
              r << ["Space between subtitle mark and trailing eagle:", line_idx + 1, para]
            end
          }
          r
        end

      end
    end
  end
end


text:
package ch.epfl.data.squall.api.sql.util;

import java.util.List;
import java.util.Set;

import ch.epfl.data.squall.components.Component;

/*
 * A utility class for extracting different hierarchy-(topology-)related information
 */
public class HierarchyExtractor {

    private static boolean contains(Set<String> biggerSet,
	    Set<String> smallerSet) {
	if (biggerSet.size() < smallerSet.size())
	    return false;
	for (final String smallerElem : smallerSet)
	    if (!biggerSet.contains(smallerElem))
		return false;
	return true;
    }

    public static Component getLCM(Component first, Component second) {
	Component resultComp = first;
	List<String> resultAnc = ParserUtil.getSourceNameList(resultComp);
	while (!resultAnc.contains(second.getName())) {
	    resultComp = resultComp.getChild();
	    resultAnc = ParserUtil.getSourceNameList(resultComp);
	}
	return resultComp;
    }

    public static Component getLCM(List<Component> compList) {
	Component resultLCM = getLCM(compList.get(0), compList.get(1));
	for (int i = 2; i < compList.size(); i++)
	    resultLCM = getLCM(resultLCM, compList.get(i));
	return resultLCM;
    }

    /*
     * Is component a child (not necessarily first generation) of all
     * orCompNames? Used in Cost-based optimizer
     */
    public static boolean isLCM(Component component, Set<String> orCompNames) {
	// dealing with parents
	final Component[] parents = component.getParents();
	if (parents == null)
	    // if I don't have parents I can't be LCM (I am DataSourceComponent)
	    return false;

	for (int i = 0; i < parents.length; i++) {
	    final Component parent = parents[i];
	    final Set<String> parentAncestors = ParserUtil
		    .getSourceNameSet(parent);
	    if (contains(parentAncestors, orCompNames))
		// my parent is LCM (or its parent)
		return false;
	}

	// if I contain all the mentioned sources, and none of my parent does
	// so, than I am LCM
	final Set<String> compAncestors = ParserUtil
		.getSourceNameSet(component);
	return contains(compAncestors, orCompNames);
    }

}


text:
<?php

namespace Show\Hydrator;

use Zend\Stdlib\Hydrator\ClassMethods;
use DateTime;

class ClassMethodsWithDateTimeAwareness extends ClassMethods
{
    /**
     * Extract values from an object with class methods
     *
     * Extracts the getter/setter of the given $object.
     *
     * @param  object $object
     * @return array
     * @throws Exception\BadMethodCallException for a non-object $object
     */
    public function extract($object)
    {
        $attributes = parent::extract($object);
        foreach ($attributes as $key => $value) {
            if ($value instanceof DateTime) {
                if (strpos($key, 'datetime')) {
                    $attributes[$key] = $value->format('Y-m-d H:i:s');
                } else {
                    $attributes[$key] = $value->format('Y-m-d');
                }
            }
        }
        return $attributes;
    }

    /**
     * Hydrate an object by populating getter/setter methods
     *
     * Hydrates an object by getter/setter methods of the object.
     *
     * @param  array $data
     * @param  object $object
     * @return object
     * @throws Exception\BadMethodCallException for a non-object $object
     */
    public function hydrate(array $data, $object)
    {
        foreach ($data as $key => $value) {
            if (preg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', $value))  {
                $data[$key] = new DateTime($value);
            }
            elseif (preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value))  {
                $data[$key] = new DateTime($value);
            }
        }
        $object = parent::hydrate($data, $object);
        return $object;
    }
}


text:
<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/dashboard">  Scrum Dashboard

<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/issues">  Issues

<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/stories">  Story

<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/sprint">  Sprint

<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/timesheet">  Timesheets

<a href="<?php echo base_url();?>Menus/SubMenu/<?php echo $this->session->userdata('project_id')?>/reports">  Reports


text:
package com.sastix.cms.common.services.web;

import com.sastix.cms.common.content.exceptions.ResourceNotFound;
import com.sastix.cms.common.exception.CommonException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@ControllerAdvice
public class ExceptionHandlingController {

    @ExceptionHandler({CommonException.class})
    public void handleBadRequests(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        log.error("Bad request: {} from {}, Exception: {} {}",
                request.getRequestURI(),
                request.getRemoteHost(),
                e.getStackTrace()[0].toString(),
                e.getLocalizedMessage());

        response.sendError(HttpStatus.BAD_REQUEST.value(), e.getLocalizedMessage());
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)  // 404
    @ExceptionHandler(ResourceNotFound.class)
    public void handleNoTFound() {
        // Nothing to do
    }
}


text:
import { createMatchPathAsync } from "../match-path-async";
import * as Tests from "./data/match-path-data";

describe("match-path-async", () => {
  Tests.tests.forEach((t) =>
    it(t.name, (done) => {
      const matchPath = createMatchPathAsync(
        t.absoluteBaseUrl,
        t.paths,
        t.mainFields,
        t.addMatchAll
      );
      matchPath(
        t.requestedModule,
        (_path, callback) => callback(undefined, t.packageJson),
        (path, callback) =>
          callback(undefined, t.existingFiles.indexOf(path) !== -1),
        t.extensions,
        (_err, result) => {
          expect(result).toBe(t.expectedPath);
          done();
        }
      );
    })
  );
});


text:
from itertools import chain
from django.utils.encoding import force_text
from django.utils.html import format_html

import json
from django import forms
from django.forms.widgets import TextInput, FileInput, Select
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe

#from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.encoding import force_unicode
from django.conf import settings

class FoundationCheckboxSelectMultipleWidget(forms.CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        html = super(FoundationCheckboxSelectMultipleWidget, self).render(name, value, attrs, choices)
        return mark_safe(html.replace('
', '
'))

class FoundationRadioSelectWidget(forms.RadioSelect):
    def render(self, name, value, attrs=None, choices=()):
        html = super(FoundationRadioSelectWidget, self).render(name, value, attrs, choices)
        return mark_safe(html.replace('
', '
'))

class FoundationURLWidget(TextInput):
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))

        html = """

                    URL

                    <input%s />

        """
        return mark_safe(html % flatatt(final_attrs))

class FoundationImageWidget(FileInput):
    html = """

                <input%(flat_attrs)s />

    """

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))

        final_attrs.update({
            'MEDIA_URL': settings.MEDIA_URL,
            'flat_attrs': flatatt(final_attrs),
        })

        return mark_safe(self.html % final_attrs)

class FoundationThumbnailWidget(FoundationImageWidget):
    html = """

                <input%(flat_attrs)s />

    """

class CheckOtherWidget(forms.widgets.MultiWidget):
    def __init__(self, attrs=None):
        widgets = [forms.CheckboxInput(),
                   forms.TextInput()]
        super(CheckOtherWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return json.loads(value)
        else:
            return ['', '']

class SelectSelectedDisableFirst(forms.widgets.Select):
    """
    Select con el primer elemento Selected y Disabled

    """

    def render_option(self, selected_choices, option_value, option_label, selected_disabled=False):
        if option_value is None:
            option_value = ''
        option_value = force_text(option_value)
        if option_value in selected_choices:
            selected_html = mark_safe(' selected="selected"')
            if not self.allow_multiple_selected:
                # Only allow for a single selection.
                selected_choices.remove(option_value)
        elif selected_disabled:
            selected_html = ' selected="selected" disabled'
        else:
            selected_html = ''
        return format_html('<option value="{}"{}>{}</option>',
                           option_value,
                           selected_html,
                           force_text(option_label))

    def render_options(self, choices, selected_choices):
        # Normalize to strings.
        selected_choices = set(force_text(v) for v in selected_choices)
        output = []
        for option_value, option_label in chain(self.choices, choices):
            if isinstance(option_label, (list, tuple)):
                output.append(format_html('<optgroup label="{}">', force_text(option_value)))
                for option in option_label:
                    output.append(self.render_option(selected_choices, *option))
                output.append('</optgroup>')
            elif len(output) < 1:
                # Asume que el primer elemento no tiene valor y es Selected Disabled
                output.append(self.render_option(selected_choices, option_value, option_label, selected_disabled=True))
            else:
                output.append(self.render_option(selected_choices, option_value, option_label))
        return '\n'.join(output)

class HTML5DateWidget(TextInput):
    input_type = "date"

class HTML5TimeWidget(TextInput):
    input_type = "time"

DYNAFORM_FIELDS = (
    ("BooleanField",                "BooleanField"),
    ("CharField",                   "CharField"),
    ("ChoiceField",                 "ChoiceField"),
    ("DateField",                   "DateField"),
    ("DateTimeField",               "DateTimeField"),
    ("DecimalField",                "DecimalField"),
    ("EmailField",                  "EmailField"),
    ("FileField",                   "FileField"),
    ("FloatField",                  "FloatField"),
    ("ImageField",                  "ImageField"),
    ("IntegerField",                "IntegerField"),
    ("RegexField",                  "RegexField"),
    ("SlugField",                   "SlugField"),
    ("TimeField",                   "TimeField"),
    ("URLField",                    "URLField"),
    ("NullBooleanField",            "NullBooleanField"),
    ("MultipleChoiceField",         "MultipleChoiceField"),
    ("ModelChoiceField",            "ModelChoiceField"),
    ("ModelMultipleChoiceField",    "ModelMultipleChoiceField"),
    ("ReCaptchaField",              "ReCaptchaField"),
    ("LinkbCaptchaField",           "LinkbCaptchaField")
)

DYNAFORM_WIDGETS = (
("Simple", (
    ("TextInput"                 ,"TextInput"),
    ("PasswordInput"             ,"PasswordInput"),
    ("HiddenInput"               ,"HiddenInput"),
    ("DateInput"                 ,"DateInput"),
    ("DateTimeInput"             ,"DateTimeInput"),
    ("TimeInput"                 ,"TimeInput"),
    ("Textarea"                  ,"Textarea"),
    )
),
("Multiples", (
    ("CheckboxInput"             ,"CheckboxInput"),
    ("Select"                    ,"Select"),
    ("SelectSelectedDisableFirst","SelectSelectedDisableFirst"),
    ("NullBooleanSelect"         ,"NullBooleanSelect"),
    ("SelectMultiple"            ,"SelectMultiple"),
    ("RadioSelect"               ,"RadioSelect"),
    ("CheckboxSelectMultiple"    ,"CheckboxSelectMultiple"),
#    ("ModelChoiceField"          ,"ModelChoiceField"),
#    ("ModelMultipleChoiceField"  ,"ModelMultipleChoiceField"),
    )
),
("Fechas", (
    ("SplitDateTimeWidget"       ,"SplitDateTimeWidget"),
    ("SelectDateWidget"          ,"SelectDateWidget"),
    ("HTML5DateWidget"           ,"HTML5DateWidget"),
    ("HTML5TimeWidget"           ,"HTML5TimeWidget"),
    )
),
("Archivos/Imagenes", (
    ("FileInput", "FileInput"),
    ("ClearableFileInput", "ClearableFileInput"),
    )
),
("Foundation", (
    ("FoundationRadioSelectWidget", "FoundationRadioSelectWidget"),
    ("FoundationCheckboxSelectMultipleWidget", "FoundationCheckboxSelectMultipleWidget"),
    ("FoundationURLWidget", "FoundationURLWidget"),
    ("FoundationImageWidget", "FoundationImageWidget"),
    ("FoundationThumbnailWidget", "FoundationThumbnailWidget"),
    )
),
)


text:
//
//  Audio.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 09/11/2021.
//  Copyright © 2021 Thomas Harte. All rights reserved.
//

#include "Audio.hpp"

#include "Flags.hpp"

#define LOG_PREFIX "[Audio] "
#include "../../Outputs/Log.hpp"

#include <cassert>
#include <tuple>

using namespace Amiga;

Audio::Audio(Chipset &chipset, uint16_t *ram, size_t word_size, float output_rate) :
	DMADevice<4>(chipset, ram, word_size) {

	// Mark all buffers as available.
	for(auto &flag: buffer_available_) {
		flag.store(true, std::memory_order::memory_order_relaxed);
	}

	speaker_.set_input_rate(output_rate);
	speaker_.set_high_frequency_cutoff(7000.0f);
}

// MARK: - Exposed setters.

void Audio::set_length(int channel, uint16_t length) {
	assert(channel >= 0 && channel < 4);
	channels_[channel].length = length;
}

void Audio::set_period(int channel, uint16_t period) {
	assert(channel >= 0 && channel < 4);
	channels_[channel].period = period;
}

void Audio::set_volume(int channel, uint16_t volume) {
	assert(channel >= 0 && channel < 4);
	channels_[channel].volume = (volume & 0x40) ? 64 : (volume & 0x3f);
}

template <bool is_external> void Audio::set_data(int channel, uint16_t data) {
	assert(channel >= 0 && channel < 4);
	channels_[channel].wants_data = false;
	channels_[channel].data = data;

	// TODO: "the [PWM] counter is reset when ... AUDxDAT is written", but
	// does that just mean written by the CPU, or does it include DMA?
	// My guess is the former. But TODO.
	if constexpr (is_external) {
		channels_[channel].reset_output_phase();
	}
}

template void Audio::set_data<false>(int, uint16_t);
template void Audio::set_data<true>(int, uint16_t);

void Audio::set_channel_enables(uint16_t enables) {
	channels_[0].dma_enabled = enables & 1;
	channels_[1].dma_enabled = enables & 2;
	channels_[2].dma_enabled = enables & 4;
	channels_[3].dma_enabled = enables & 8;
}

void Audio::set_modulation_flags(uint16_t flags) {
	channels_[3].attach_period = flags & 0x80;
	channels_[2].attach_period = flags & 0x40;
	channels_[1].attach_period = flags & 0x20;
	channels_[0].attach_period = flags & 0x10;

	channels_[3].attach_volume = flags & 0x08;
	channels_[2].attach_volume = flags & 0x04;
	channels_[1].attach_volume = flags & 0x02;
	channels_[0].attach_volume = flags & 0x01;
}

void Audio::set_interrupt_requests(uint16_t requests) {
	channels_[0].interrupt_pending = requests & uint16_t(InterruptFlag::AudioChannel0);
	channels_[1].interrupt_pending = requests & uint16_t(InterruptFlag::AudioChannel1);
	channels_[2].interrupt_pending = requests & uint16_t(InterruptFlag::AudioChannel2);
	channels_[3].interrupt_pending = requests & uint16_t(InterruptFlag::AudioChannel3);
}

// MARK: - DMA and mixing.

bool Audio::advance_dma(int channel) {
	if(!channels_[channel].wants_data) {
		return false;
	}

	if(channels_[channel].should_reload_address) {
		channels_[channel].data_address = pointer_[size_t(channel)];
		channels_[channel].should_reload_address = false;
	}

	set_data<false>(channel, ram_[channels_[channel].data_address & ram_mask_]);

	if(channels_[channel].state != Channel::State::WaitingForDummyDMA) {
		++channels_[channel].data_address;
	}

	return true;
}

void Audio::output() {
	constexpr InterruptFlag::FlagT interrupts[] = {
		InterruptFlag::AudioChannel0,
		InterruptFlag::AudioChannel1,
		InterruptFlag::AudioChannel2,
		InterruptFlag::AudioChannel3,
	};
	Channel *const modulands[] = {
		&channels_[1],
		&channels_[2],
		&channels_[3],
		nullptr,
	};

	for(int c = 0; c < 4; c++) {
		if(channels_[c].output(modulands[c])) {
			posit_interrupt(interrupts[c]);
		}
	}

	// Spin until the next buffer is available if just entering it for the first time.
	// Contention here should be essentially non-existent.
	if(!sample_pointer_) {
		while(!buffer_available_[buffer_pointer_].load(std::memory_order::memory_order_relaxed));
	}

	// Left.
	static_assert(std::tuple_size<AudioBuffer>::value % 2 == 0);
	buffer_[buffer_pointer_][sample_pointer_] = int16_t(
		(
			channels_[1].output_level * channels_[1].output_enabled +
			channels_[2].output_level * channels_[2].output_enabled
		) << 7
	);

	// Right.
	buffer_[buffer_pointer_][sample_pointer_ + 1] = int16_t(
		(
			channels_[0].output_level * channels_[0].output_enabled +
			channels_[3].output_level * channels_[3].output_enabled
		) << 7
	);
	sample_pointer_ += 2;

	if(sample_pointer_ == buffer_[buffer_pointer_].size()) {
		const auto &buffer = buffer_[buffer_pointer_];
		auto &flag = buffer_available_[buffer_pointer_];

		flag.store(false, std::memory_order::memory_order_release);
		queue_.enqueue([this, &buffer, &flag] {
			speaker_.push(buffer.data(), buffer.size() >> 1);
			flag.store(true, std::memory_order::memory_order_relaxed);
		});

		buffer_pointer_ = (buffer_pointer_ + 1) % BufferCount;
		sample_pointer_ = 0;
	}
}

// MARK: - Per-channel logic.

/*
	Big spiel on the state machine:

	Commodore's Hardware Rerefence Manual provides the audio subsystem's state
	machine, so I've just tried to reimplement it verbatim. It's depicted
	diagrammatically in the original source as a finite state automata, the
	below is my attempt to translate that into text.

	000 State::Disabled:

		-> State::Disabled				(000)
			if: N/A
			action: percntrld

		-> State::PlayingHigh			(010)
			if: AUDDAT, and not AUDxON, and not AUDxIP
			action: percntrld, AUDxIR, volcntrld, pbudld1

		-> State::WaitingForDummyDMA	(001)
			if: AUDxON
			action: percntrld, AUDxDR, lencntrld, dmasen*

		*	NOTE: except for this case, dmasen is true only when
			LENFIN = 1. Also, AUDxDSR = (AUDxDR and dmasen).

	001 State::WaitingForDummyDMA:

		-> State::WaitingForDummyDMA	(001)
			if: N/A
			action: None

		-> State::Disabled				(000)
			if: not AUDxON
			action: None

		-> State::WaitingForDMA			(101)
			if: AUDxON, and AUDxDAT
			action:
				1. AUDxIR
				2. if not lenfin, then lencount

	101 State::WaitingForDMA:

		-> State::WaitingForDMA			(101)
			if: N/A
			action: None

		-> State:Disabled				(000)
			if: not AUDxON
			action: None

		-> State::PlayingHigh			(010)
			if: AUDxON, and AUDxDAT
			action:
				1. volcntrld, percntrld, pbufld1
				2. if napnav, then AUDxDR

	010 State::PlayingHigh

		-> State::PlayingHigh			(010)
			if: N/A
			action: percount, and penhi

		-> State::PlayingLow			(011)
			if: perfin
			action:
				1. if AUDxAP, then pbufld2
				2. if AUDxAP and AUDxON, then AUDxDR
				3. percntrld
				4. if intreq2 and AUDxON and AUDxAP, then AUDxIR
				5. if AUDxAP and AUDxON, then AUDxIR
				6. if lenfin and AUDxON and AUDxDAT, then lencntrld
				7. if (not lenfin) and AUDxON and AUDxDAT, then lencount
				8. if lenfin and AUDxON and AUDxDAT, then intreq2

				[note that 6–8 are shared with the Low -> High transition]

	011 State::PlayingLow

		-> State::PlayingLow			(011)
			if: N/A
			action: percount, and not penhi

		-> State::Disabled				(000)
			if: perfin and not (AUDxON or not AUDxIP)
			action: None

		-> State::PlayingHigh			(010)
			if: perfin and (AUDxON or not AUDxIP)
			action:
				1. pbufld1
				2. percntrld
				3. if napnav and AUDxON, then AUDxDR
				4. if napnav and AUDxON and intreq2, AUDxIR
				5. if napnav and not AUDxON, AUDxIR
				6. if lenfin and AUDxON and AUDxDAT, then lencntrld
				7. if (not lenfin) and AUDxON and AUDxDAT, then lencount
				8. if lenfin and AUDxON and AUDxDAT, then intreq2

				[note that 6-8 are shared with the High -> Low transition]

	Definitions:

		AUDxON		DMA on "x" indicates channel number (signal from DMACON).

		AUDxIP		Audio interrupt pending (input to channel from interrupt circuitry).

		AUDxIR		Audio interrupt request (output from channel to interrupt circuitry).

		intreq1		Interrupt request that combines with intreq2 to form AUDxIR.

		intreq2		Prepare for interrupt request. Request comes out after the
					next 011->010 transition in normal operation.

		AUDxDAT		Audio data load signal. Loads 16 bits of data to audio channel.

		AUDxDR		Audio DMA request to Agnus for one word of data.

		AUDxDSR		Audio DMA request to Agnus to reset pointer to start of block.

		dmasen		Restart request enable.

		percntrld	Reload period counter from back-up latch typically written
					by processor with AUDxPER (can also be written by attach mode).

		percount	Count period counter down one latch.

		perfin		Period counter finished (value = 1).

		lencntrld	Reload length counter from back-up latch.

		lencount	Count length counter down one notch.

		lenfin		Length counter finished (value = 1).

		volcntrld	Reload volume counter from back-up latch.

		pbufld1		Load output buffer from holding latch written to by AUDxDAT.

		pbufld2		Like pbufld1, but only during 010->011 with attach period.

		AUDxAV		Attach volume. Send data to volume latch of next channel
					instead of to D->A converter.

		AUDxAP		Attach period. Send data to period latch of next channel
					instead of to the D->A converter.

		penhi		Enable the high 8 bits of data to go to the D->A converter.

		napnav		/AUDxAV * /AUDxAP + AUDxAV -- no attach stuff or else attach
					volume. Condition for normal DMA and interrupt requests.
*/

//
// Non-action fallback transition and setter, plus specialised begin_state declarations.
//

template <Audio::Channel::State end> void Audio::Channel::begin_state(Channel *) {
	state = end;
}
template <> void Audio::Channel::begin_state<Audio::Channel::State::PlayingHigh>(Channel *);
template <> void Audio::Channel::begin_state<Audio::Channel::State::PlayingLow>(Channel *);

template <
	Audio::Channel::State begin,
	Audio::Channel::State end> bool Audio::Channel::transit(Channel *moduland) {
	begin_state<end>(moduland);
	return false;
}

//
//	Audio::Channel::State::Disabled
//

template <> bool Audio::Channel::transit<
	Audio::Channel::State::Disabled,
	Audio::Channel::State::PlayingHigh>(Channel *moduland) {
	begin_state<State::PlayingHigh>(moduland);

	// percntrld
	period_counter = period;

	// [AUDxIR]: see return result.

	// volcntrld
	volume_latch = volume;
	reset_output_phase();

	// pbufld1
	data_latch = data;
	wants_data = true;
	if(moduland && attach_volume) moduland->volume = uint8_t(data_latch);

	// AUDxIR.
	return true;
}

template <> bool Audio::Channel::transit<
	Audio::Channel::State::Disabled,
	Audio::Channel::State::WaitingForDummyDMA>(Channel *moduland) {
	begin_state<State::WaitingForDummyDMA>(moduland);

	// percntrld
	period_counter = period;

	// AUDxDR
	wants_data = true;

	// lencntrld
	length_counter = length;

	// dmasen / AUDxDSR
	should_reload_address = true;

	return false;
}

template <> bool Audio::Channel::output<Audio::Channel::State::Disabled>(Channel *moduland) {
	// if AUDDAT, and not AUDxON, and not AUDxIP.
	if(!wants_data && !dma_enabled && !interrupt_pending) {
		return transit<State::Disabled, State::PlayingHigh>(moduland);
	}

	// if AUDxON.
	if(dma_enabled) {
		return transit<State::Disabled, State::WaitingForDummyDMA>(moduland);
	}

	return false;
}

//
//	Audio::Channel::State::WaitingForDummyDMA
//

template <> bool Audio::Channel::transit<
	Audio::Channel::State::WaitingForDummyDMA,
	Audio::Channel::State::WaitingForDMA>(Channel *moduland) {
	begin_state<State::WaitingForDMA>(moduland);

	// AUDxDR
	wants_data = true;

	// if not lenfin, then lencount
	if(length != 1) {
		-- length_counter;
	}

	// AUDxIR
	return true;
}

template <> bool Audio::Channel::output<Audio::Channel::State::WaitingForDummyDMA>(Channel *moduland) {
	// if not AUDxON
	if(!dma_enabled) {
		return transit<State::WaitingForDummyDMA, State::Disabled>(moduland);
	}

	// if AUDxON and AUDxDAT
	if(dma_enabled && !wants_data) {
		return transit<State::WaitingForDummyDMA, State::WaitingForDMA>(moduland);
	}

	return false;
}

//
//	Audio::Channel::State::WaitingForDMA
//

template <> bool Audio::Channel::transit<
	Audio::Channel::State::WaitingForDMA,
	Audio::Channel::State::PlayingHigh>(Channel *moduland) {
	begin_state<State::PlayingHigh>(moduland);

	// volcntrld
	volume_latch = volume;
	reset_output_phase();

	// percntrld
	period_counter = period;

	// pbufld1
	data_latch = data;
	if(moduland && attach_volume) moduland->volume = uint8_t(data_latch);

	// if napnav
	if(attach_volume || !(attach_volume || attach_period)) {
		// AUDxDR
		wants_data = true;
	}

	return false;
}

template <> bool Audio::Channel::output<Audio::Channel::State::WaitingForDMA>(Channel *moduland) {
	// if: not AUDxON
	if(!dma_enabled) {
		return transit<State::WaitingForDummyDMA, State::Disabled>(moduland);
	}

	// if: AUDxON, and AUDxDAT
	if(dma_enabled && !wants_data) {
		return transit<State::WaitingForDummyDMA, State::PlayingHigh>(moduland);
	}

	return false;
}

//
//	Audio::Channel::State::PlayingHigh
//

void Audio::Channel::decrement_length() {
	// if lenfin and AUDxON and AUDxDAT, then lencntrld
	// if (not lenfin) and AUDxON and AUDxDAT, then lencount
	// if lenfin and AUDxON and AUDxDAT, then intreq2
	if(dma_enabled && !wants_data) {
		-- length_counter;

		if(!length_counter) {
			length_counter = length;
			will_request_interrupt = true;
			should_reload_address = true;	// This feels logical to me; it's a bit
											// of a stab in the dark though.
		}
	}
}

template <> bool Audio::Channel::transit<
	Audio::Channel::State::PlayingHigh,
	Audio::Channel::State::PlayingLow>(Channel *moduland) {
	begin_state<State::PlayingLow>(moduland);

	bool wants_interrupt = false;

	// if AUDxAP
	if(attach_period) {
		// pbufld2
		data_latch = data;
		if(moduland) moduland->period = data_latch;

		// [if AUDxAP] and AUDxON
		if(dma_enabled) {
			// AUDxDR
			wants_data = true;

			// [if AUDxAP and AUDxON] and intreq2
			if(will_request_interrupt) {
				will_request_interrupt = false;

				// AUDxIR
				wants_interrupt = true;
			}
		} else {
			// i.e. if AUDxAP and AUDxON, then AUDxIR
			wants_interrupt = true;
		}
	}

	// percntrld
	period_counter = period;

	decrement_length();

	return wants_interrupt;
}

template <> void Audio::Channel::begin_state<Audio::Channel::State::PlayingHigh>(Channel *) {
	state = Audio::Channel::State::PlayingHigh;

	// penhi.
	output_level = int8_t(data_latch >> 8);
}

template <> bool Audio::Channel::output<Audio::Channel::State::PlayingHigh>(Channel *moduland) {
	// This is a reasonable guess as to the exit condition for this node;
	// Commodore doesn't document.
	if(period_counter == 1) {
		return transit<State::PlayingHigh, State::PlayingLow>(moduland);
	}

	// percount.
	-- period_counter;

	return false;
}

//
//	Audio::Channel::State::PlayingLow
//

template <> bool Audio::Channel::transit<
	Audio::Channel::State::PlayingLow,
	Audio::Channel::State::Disabled>(Channel *moduland) {
	begin_state<State::Disabled>(moduland);

	// Clear the slightly nebulous 'if intreq2 occurred' state.
	will_request_interrupt = false;

	return false;
}

template <> bool Audio::Channel::transit<
	Audio::Channel::State::PlayingLow,
	Audio::Channel::State::PlayingHigh>(Channel *moduland) {
	begin_state<State::PlayingHigh>(moduland);

	bool wants_interrupt = false;

	// volcntrld
	volume_latch = volume;
	reset_output_phase();	// Is this correct?

	// percntrld
	period_counter = period;

	// pbufld1
	data_latch = data;
	if(moduland && attach_volume) moduland->volume = uint8_t(data_latch);

	// if napnav
	if(attach_volume || !(attach_volume || attach_period)) {
		// [if napnav] and AUDxON
		if(dma_enabled) {
			// AUDxDR
			wants_data = true;

			// [if napnav and AUDxON] and intreq2
			if(will_request_interrupt) {
				will_request_interrupt = false;
				wants_interrupt = true;
			}
		} else {
			// AUDxIR
			wants_interrupt = true;
		}
	}

	decrement_length();

	return wants_interrupt;
}

template <> void Audio::Channel::begin_state<Audio::Channel::State::PlayingLow>(Channel *) {
	state = Audio::Channel::State::PlayingLow;

	// Output low byte.
	output_level = int8_t(data_latch & 0xff);
}

template <> bool Audio::Channel::output<Audio::Channel::State::PlayingLow>(Channel *moduland) {
	-- period_counter;

	if(!period_counter) {
		const bool dma_or_no_interrupt = dma_enabled || !interrupt_pending;
		if(dma_or_no_interrupt) {
			return transit<State::PlayingLow, State::PlayingHigh>(moduland);
		} else {
			return transit<State::PlayingLow, State::Disabled>(moduland);
		}
	}

	return false;
}

//
// Dispatcher
//

bool Audio::Channel::output(Channel *moduland) {
	// Update pulse-width modulation.
	output_phase = output_phase + 1;
	if(output_phase == 64) {
		reset_output_phase();
	} else {
		output_enabled &= output_phase != volume_latch;
	}

	switch(state) {
		case State::Disabled:			return output<State::Disabled>(moduland);
		case State::WaitingForDummyDMA:	return output<State::WaitingForDummyDMA>(moduland);
		case State::WaitingForDMA:		return output<State::WaitingForDMA>(moduland);
		case State::PlayingHigh:		return output<State::PlayingHigh>(moduland);
		case State::PlayingLow:			return output<State::PlayingLow>(moduland);

		default:
			assert(false);
		break;
	}

	return false;
}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <link rel="stylesheet" href="/assets/css/normalize.css"/>
  <link rel="stylesheet" href="/assets/css/bulma.css"/>
  <link rel="stylesheet" href="/assets/css/custom.css"/>
  <link rel="stylesheet" href="/assets/css/syntax.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto" rel="stylesheet">

  <link rel="shortcut icon" href="/assets/images/icon-xin.png">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

  <title>

      LeetCode题目1. Two Sum · wangxin

  </title>

              <input class="input is-small" type="text" placeholder="Find an article" id="search-text">

                Search

        Archive
        categories
        Tags

LeetCode题目1. Two Sum

    18 February, 2018. It was a Sunday.

开始LeetCode刷题之路,首先进行题目1. Two Sum的求解

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

思路

使用简单的双重循环遍历所有的可能组合,遇到满足条件的则返回对应的角标

Java求解的代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int a[]=new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if((nums[i]+nums[j])==target){
                    a[0]=i;
                    a[1]=j;
                    return a;
                }
            }
        }
        return null;
    }
}

Please enable JavaScript to view the comments powered by Disqus.

                  Sponsored

                Article classification

    		Life 2

    		leetcode 4

    		python 2

    		java 2

    		jekyll 2

    		linux 4

                  Recommended Websites

                      leetcode

                      csdn blog

                      IT home

        Copyright (C) wangxin1248, All Rights Reserved.

        Made with wangxin, Jekyll. Hosted on Github


text:
from absl import app
from absl import flags
from absl import logging

from acme import specs
from acme.utils import counting
from acme.utils import loggers
from ml_collections.config_flags import config_flags

import pathlib
import sys

ROOT_PATH = pathlib.Path(__file__).resolve().parent.parent
sys.path.append(str(ROOT_PATH))

from src import utils
from src.ope import dfiv

flags.DEFINE_string(
    'dataset_path',
    str(ROOT_PATH.joinpath('offline_dataset').joinpath('stochastic')),
    'Path to offline dataset directory.')

# Network flags.
flags.DEFINE_string('value_layer_sizes', '50,50',
                    'Value net hidden layer sizes.')
flags.DEFINE_string('instrumental_layer_sizes', '50,50',
                    'Instrumental net layer sizes.')

# Agent flags
flags.DEFINE_integer('batch_size', 1024, 'Batch size.')
flags.DEFINE_float('value_learning_rate', 1e-4, 'learning rate for the treatment_net update')
flags.DEFINE_float('instrumental_learning_rate', 1e-3, 'learning rate for the instrumental_net update')
flags.DEFINE_float('stage1_reg', 1e-5, 'ridge regularizer for stage 1 regression')
flags.DEFINE_float('stage2_reg', 1e-5, 'ridge regularizer for stage 2 regression')
flags.DEFINE_float('instrumental_reg', 1e-5, 'ridge regularizer instrumental')
flags.DEFINE_float('value_reg', 1e-5, 'ridge regularizer for value_reg')

flags.DEFINE_integer('instrumental_iter', 1, 'number of iteration for instrumental function')
flags.DEFINE_integer('value_iter', 1, 'number of iteration for value function')

flags.DEFINE_integer('max_dev_size', 10*1024, 'Maximum dev dataset size.')
flags.DEFINE_integer('evaluate_every', 100, 'Evaluation period.')
flags.DEFINE_integer('evaluate_init_samples', 1000, 'Number of initial samples for evaluation.')

flags.DEFINE_integer('max_steps', 100000, 'Max number of steps.')
flags.DEFINE_float('d_tm1_weight', 0.01,  # 0.01 for cartpole, 0.03 for catch and mountain_car.
                   'Weights of terminal states.')

flags.DEFINE_boolean('learner2', True, 'Run Learner2 that learns '
                     'curr_feature - discount * next_feature in the 1st stage.')

config_flags.DEFINE_config_dict('problem_config', utils.get_problem_config(),
                                'ConfigDict instance for problem config.')
FLAGS = flags.FLAGS

def main(_):
  problem_config = FLAGS.problem_config

  # Load the offline dataset and environment.
  dataset, dev_dataset, environment = utils.load_data_and_env(
      task_name=problem_config['task_name'],
      noise_level=problem_config['noise_level'],
      near_policy_dataset=problem_config['near_policy_dataset'],
      dataset_path=FLAGS.dataset_path,
      batch_size=FLAGS.batch_size,
      max_dev_size=FLAGS.max_dev_size)
  environment_spec = specs.make_environment_spec(environment)

  # Create the networks to optimize.
  value_func, instrumental_feature = dfiv.make_ope_networks(
      problem_config['task_name'], environment_spec,
      value_layer_sizes=FLAGS.value_layer_sizes,
      instrumental_layer_sizes=FLAGS.instrumental_layer_sizes)

  # Load pretrained target policy network.
  target_policy_net = utils.load_policy_net(
      task_name=problem_config['task_name'],
      noise_level=problem_config['noise_level'],
      near_policy_dataset=problem_config['near_policy_dataset'],
      dataset_path=FLAGS.dataset_path,
      environment_spec=environment_spec)

  counter = counting.Counter()
  learner_counter = counting.Counter(counter, prefix='learner')
  logger = loggers.TerminalLogger('learner')

  # The learner updates the parameters (and initializes them).
  learner_cls = dfiv.DFIVLearner
  if FLAGS.learner2:
    learner_cls = dfiv.DFIV2Learner
  learner = learner_cls(
      value_func=value_func,
      instrumental_feature=instrumental_feature,
      policy_net=target_policy_net,
      discount=problem_config['discount'],
      value_learning_rate=FLAGS.value_learning_rate,
      instrumental_learning_rate=FLAGS.instrumental_learning_rate,
      stage1_reg=FLAGS.stage1_reg,
      stage2_reg=FLAGS.stage2_reg,
      value_reg=FLAGS.value_reg,
      instrumental_reg=FLAGS.instrumental_reg,
      instrumental_iter=FLAGS.instrumental_iter,
      value_iter=FLAGS.value_iter,
      dataset=dataset,
      d_tm1_weight=FLAGS.d_tm1_weight,
      counter=learner_counter,
      logger=logger)

  eval_counter = counting.Counter(counter, 'eval')
  eval_logger = loggers.TerminalLogger('eval')

  while True:
    learner.step()
    steps = learner.state['num_steps'].numpy()

    if steps % FLAGS.evaluate_every == 0:
      eval_results = {}
      if dev_dataset is not None:
        eval_results = {'dev_mse': learner.cal_validation_err(dev_dataset)}
      eval_results.update(utils.ope_evaluation(
          value_func=value_func,
          policy_net=target_policy_net,
          environment=environment,
          num_init_samples=FLAGS.evaluate_init_samples,
          discount=problem_config['discount'],
          counter=eval_counter))
      eval_logger.write(eval_results)

    if steps >= FLAGS.max_steps:
      break

if __name__ == '__main__':
  app.run(main)


text:
<!DOCTYPE html>

<title th:text="#{signupPage.title}"></title>

Completa il tuo profilo

Errore!

Errore!

										Si è verificato un problema durante il processo di registrazione.

										Torna alla pagina di registrazione


text:
id: guides-using-filters
title: Filters
sidebar_label: Applying filters to Searchkit
slug: /sdk/customisations/filters
keywords: [Elasticsearch Filters, Searchkit Filters, Search Filters]
description: Searchkit custom filters
---

There are a few scenarios where you want to apply a filter to a search.

## User Filters

When you want to apply filters to your search and don't want them to be displayed as facets. Some examples could include:

- Adding a search box in UI which applies to one field
- Adding a date range component to UI

### Adding a filter to Searchkit Config

Within the Searchkit config, there is a filters array which allows you to configure one or more filters for your search. Below is an example of adding a term filter to search.

```javascript
const moviesSearchConfig = {
  host: 'http://localhost:9200',
  index: 'movies',
  hits: {
    fields: ['actors', 'writers'],
  },
  filters: [
    new TermFilter({
      identifier: 'type',
      field: 'type',
      label: 'type',
    }),
  ],
};

const request = Searchkit(config);
const response = await request
  .setFilters([{identifier: 'type', value: 'test'}])
  .execute({
    hits: {
      size: 10,
      from: 0,
    },
  });
```

and Searchkit will return all hit results that have a field type with a value of "test".

If you're using `@searchkit/client`, you will be able to apply the filter like so

```javascript
const CustomFilterComponent = () => {
  const api = useSearchkit();

  return (
    <div>
      <a
        onClick={() => {
          api.toggleFilter({identifier: 'type', value: 'test'});
          api.search();
        }}>
        Toggle test filter
      </a>
    </div>
  );
};
```

## Base Filters

When you want to add a filter to a search where it is not shown within the UI & the user should not be able to remove it.

You can add lucene base filters to the search. This will be appended to the elasticsearch filter and will not appear within the `summary` response. Useful for restricting content to particular users.

This is done at the searchkit request execution phase.

```js
const response = await request.execute(
  {
    hits: {
      size: 10,
    },
  },
  [{term: {status: 'published'}}], // optional second argument with an array of lucene clauses
);
```

## Update elasticsearch query

For those edge cases where the above doesn't apply and you need raw access to the elasticsearch query to add any additional filters, you can use the `postProcessRequest` function. You can do this within the `searchkitConfig` configuration.

```javascript
const searchkitConfig = {
  host: 'http://localhost:9200',
  index: 'my_index',
  hits: {
    fields: [],
  },
  query: new MultiMatchQuery({fields: []}),
  postProcessRequest: (body) => {
    return {...body, min_score: 10};
  },
};
```


text:
/*
 * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.IoT.Model
{
    ///
    /// Container for the parameters to the ListPrincipalPolicies operation.
    /// Lists the policies attached to the specified principal. If you use an Amazon Cognito
    /// identity, the ID needs to be in Amazon
    /// Cognito Identity format.
    ///
    public partial class ListPrincipalPoliciesRequest : AmazonIoTRequest
    {
        private bool? _ascendingOrder;
        private string _marker;
        private int? _pageSize;
        private string _principal;

        ///
        /// Gets and sets the property AscendingOrder.
        /// <para>
        /// Specifies the order for results. If true, results are returned in ascending creation
        /// order.
        /// </para>
        ///
        public bool AscendingOrder
        {
            get { return this._ascendingOrder.GetValueOrDefault(); }
            set { this._ascendingOrder = value; }
        }

        // Check to see if AscendingOrder property is set
        internal bool IsSetAscendingOrder()
        {
            return this._ascendingOrder.HasValue;
        }

        ///
        /// Gets and sets the property Marker.
        /// <para>
        /// The marker for the next set of results.
        /// </para>
        ///
        public string Marker
        {
            get { return this._marker; }
            set { this._marker = value; }
        }

        // Check to see if Marker property is set
        internal bool IsSetMarker()
        {
            return this._marker != null;
        }

        ///
        /// Gets and sets the property PageSize.
        /// <para>
        /// The result page size.
        /// </para>
        ///
        public int PageSize
        {
            get { return this._pageSize.GetValueOrDefault(); }
            set { this._pageSize = value; }
        }

        // Check to see if PageSize property is set
        internal bool IsSetPageSize()
        {
            return this._pageSize.HasValue;
        }

        ///
        /// Gets and sets the property Principal.
        /// <para>
        /// The principal.
        /// </para>
        ///
        public string Principal
        {
            get { return this._principal; }
            set { this._principal = value; }
        }

        // Check to see if Principal property is set
        internal bool IsSetPrincipal()
        {
            return this._principal != null;
        }

    }
}


text:
package de.schunterkino.kinoapi.dolby;

public enum DecodeMode {
	Invalid, Auto, N_A, LRDiscrete, ProLogic, ProLogic2, FourDiscreteSur
}


text:
///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Image Copyright (c) 2008 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-12-19
// Updated : 2010-09-29
// Licence : This source is under MIT License
// File    : gli/gli.hpp
///////////////////////////////////////////////////////////////////////////////////////////////////

/*! \mainpage OpenGL Image
 *
 */

#ifndef GLI_GLI_INCLUDED
#define GLI_GLI_INCLUDED

#define GLI_VERSION					30
#define GLI_VERSION_MAJOR			0
#define GLI_VERSION_MINOR			3
#define GLI_VERSION_PATCH			0
#define GLI_VERSION_REVISION		2

#include "./core/texture2d.hpp"
#include "./core/size.hpp"
#include "./core/operation.hpp"
#include "./core/generate_mipmaps.hpp"

#endif//GLI_GLI_INCLUDED


text:
package org.apache.activemq.artemis.tests.integration.mqtt.imported;

import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTConnectionManager;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTInterceptor;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTSession;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet;
import org.apache.felix.resolver.util.ArrayMap;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MQTTInterceptorPropertiesTest extends MQTTTestSupport {

   @Override
   @Before
   public void setUp() throws Exception {
      Field sessions = MQTTSession.class.getDeclaredField("SESSIONS");
      sessions.setAccessible(true);
      sessions.set(null, new ConcurrentHashMap<>());

      Field connectedClients = MQTTConnectionManager.class.getDeclaredField("CONNECTED_CLIENTS");
      connectedClients.setAccessible(true);
      connectedClients.set(null, new ConcurrentHashSet<>());
      super.setUp();
   }

   private static final String ADDRESS = "address";
   private static final String MESSAGE_TEXT = "messageText";
   private static final String RETAINED = "retained";

   private boolean checkMessageProperties(MqttMessage message, Map<String, Object> expectedProperties) {
      System.out.println("Checking properties in interceptor");
      try {
         assertNotNull(message);
         assertNotNull(server.getNodeID());
         MqttFixedHeader header = message.fixedHeader();
         assertNotNull(header.messageType());
         assertEquals(header.qosLevel().value(), AT_MOST_ONCE);
         assertEquals(header.isRetain(), expectedProperties.get(RETAINED));
      } catch (Throwable t) {
         collector.addError(t);
      }
      return true;
   }

   @Rule
   public ErrorCollector collector = new ErrorCollector();

   @Test(timeout = 60000)
   public void testCheckInterceptedMQTTMessageProperties() throws Exception {
      final String addressQueue = name.getMethodName();
      final String msgText = "Test intercepted message";
      final boolean retained = true;

      Map<String, Object> expectedProperties = new ArrayMap<>();
      expectedProperties.put(ADDRESS, addressQueue);
      expectedProperties.put(MESSAGE_TEXT, msgText);
      expectedProperties.put(RETAINED, retained);

      final MQTTClientProvider subscribeProvider = getMQTTClientProvider();
      initializeConnection(subscribeProvider);

      subscribeProvider.subscribe(addressQueue, AT_MOST_ONCE);

      final CountDownLatch latch = new CountDownLatch(1);
      MQTTInterceptor incomingInterceptor = new MQTTInterceptor() {
         @Override
         public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException {
            System.out.println("incoming");
            if (packet.getClass() == MqttPublishMessage.class) {
               return checkMessageProperties(packet, expectedProperties);
            } else {
               return true;
            }

         }
      };

      MQTTInterceptor outgoingInterceptor = new MQTTInterceptor() {
         @Override
         public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException {
            System.out.println("outgoing");
            if (packet.getClass() == MqttPublishMessage.class) {
               return checkMessageProperties(packet, expectedProperties);
            } else {
               return true;
            }
         }
      };
      server.getRemotingService().addIncomingInterceptor(incomingInterceptor);
      server.getRemotingService().addOutgoingInterceptor(outgoingInterceptor);

      Thread thread = new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               byte[] payload = subscribeProvider.receive(10000);
               assertNotNull("Should get a message", payload);
               latch.countDown();
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
      thread.start();

      final MQTTClientProvider publishProvider = getMQTTClientProvider();
      initializeConnection(publishProvider);
      publishProvider.publish(addressQueue, msgText.getBytes(), AT_MOST_ONCE, retained);

      latch.await(10, TimeUnit.SECONDS);
      subscribeProvider.disconnect();
      publishProvider.disconnect();
   }
}


text:
package com.google.cloud.tools.opensource.dependencies;

import com.google.common.collect.ImmutableList;
import java.util.List;
import org.eclipse.aether.artifact.DefaultArtifact;

class UpdateReport {

  /**
   * Generate a prioritized and ordered list of
   * necessary dependency updates. This captures the state of a published
   * artifact in Maven Central. It does not capture updates that may have already been
   * made at head but not published to Maven central, or dependencies
   * that have been updated but not yet incorporated in the tree.
   */
  public static void main(String[] args) {

    if (args.length != 1 || !args[0].contains(":")) {
      System.err.println("Usage: java " + UpdateReport.class.getCanonicalName()
          + " groupdId:artifactId:version");
      return;
    }

    try {
      DefaultArtifact artifact = new DefaultArtifact(args[0]);

      DependencyGraphBuilder dependencyGraphBuilder = new DependencyGraphBuilder();
      DependencyGraph graph =
          dependencyGraphBuilder.buildFullDependencyGraph(ImmutableList.of(artifact));
      List<Update> updates = graph.findUpdates();

      if (updates.isEmpty()) {
        System.out.println(args[0] + " is consistent.");
        System.out.println();
      } else {
        System.out.println("Upgrades needed for " + args[0] +":");
        System.out.println();
        for (Update update : updates) {
          System.out.println(update);
        }
      }
    } catch (IllegalArgumentException ex) {
      System.err.println("Bad Maven coordinates " + args[0]);
      return;
    }
  }

}


text:
<?php

namespace ZendPdf\Resource;

use ZendPdf as Pdf;
use ZendPdf\InternalType;
use ZendPdf\ObjectFactory;

/**
 * Resource extractor class is used to detach resources from original PDF document.
 *
 * It provides resources sharing, so different pages or other PDF resources can share
 * its dependent resources (e.g. fonts or images) or other resources still use them without duplication.
 * It also reduces output PDF size, required memory for PDF processing and
 * processing time.
 *
 * The same extractor may be used for different source documents, several
 * extractors may be used for constracting one target document, but extractor
 * must not be shared between target documents.
 *
 * @package Zend_Pdf
 */
class Extractor {
	/**
	 * PDF objects factory.
	 *
	 * @var \ZendPdf\ObjectFactory
	 */
	protected $_factory;

	/**
	 * Reusable list of already processed objects
	 *
	 * @var array
	 */
	protected $_processed;

	/**
	 * Object constructor.
	 */
	public function __construct() {
		$this->_factory = Pdf\ObjectFactory::createFactory ( 1 );
		$this->_processed = array ();
	}

	/**
	 * Clone page, extract it and dependent objects from the current document,
	 * so it can be used within other docs
	 *
	 * return \ZendPdf\Page
	 */
	public function clonePage(Pdf\Page $page) {
		return $page->clonePage ( $this->_factory, $this->_processed );
	}
}


text:
@include('flare::admin.sections.head')

                    {!! Flare::config('admin_title') !!}

                    @if (count($errors) > 0)

                                Whoops! There were some problems with your input.

                                    @foreach ($errors->all() as $error)

{{ $error }}

                                    @endforeach

                    @endif

                    @if (session('status'))

                                {{ session('status') }}

                    @endif

                    <form class="form-horizontal" role="form" method="POST" action="{{ route('flare::email') }}">
                        {!! csrf_field() !!}

                                <input type="email" class="form-control" placeholder="Email Address" name="email" value="{{ old('email') }}">

                            <button type="submit" class="btn btn-default pull-right">
                                Reset Password
                            </button>

                    </form>

                        Login

@include('flare::admin.sections.foot')


text:
{{ if or .Params.toc (and .Site.Params.toc (ne .Params.toc false)) }}

{{ T "toc" }}

  {{ $globalAutoCollapseToc := .Site.Params.autoCollapseToc | default false }}

    {{.TableOfContents}}

{{- end }}


text:
#include <config.h>

#if defined(HAVE_LIBPNG) && defined(HAVE_LIBART)

#include <stdio.h>
#include <png.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#include <glib/gstdio.h>
#include <gtk/gtk.h>

#include "intl.h"
#include "filter.h"
#include "render_libart.h"
#include "dialibartrenderer.h"
#include "message.h"
#include "dialogs.h"

/* ugly, but better tahn crashin on non-interactive use */
#include "../../app/app_procs.h"

/* parses a string of the form "[0-9]*x[0-9]*" and transforms it into
   two long values width and height. */
static void
parse_size(gchar *size, long *width, long *height)
{
  if (size) {
    gchar** array = g_strsplit(size, "x", 3);
    *width  = (array[0])? strtol(array[0], NULL, 10): 0;
    *height = (array[1])? strtol(array[1], NULL, 10): 0;
    g_strfreev(array);
  }
  else {
    *width  = 0;
    *height = 0;
  }
}

/* the dots per centimetre to render this diagram at */
/* this matches the setting `100%' setting in dia. */
#define DPCM 20

/* the height of the band to use when rendering.  Smaller bands mean
 * rendering is slower, but less memory is used.  Setting this to G_MAXINT
 * should get the renderer to use one pass. */
#define BAND_HEIGHT 50

struct png_callback_data {
  DiagramData *data;
  gchar *filename;
  gchar *size;			/* for command line option --size */
};

/* Static data.  When the dialog is not reentrant, you could have all data
   be static.  I don't like it that way, though:)  I only hold static that
   which pertains to the dialog itself (including the aspect ratio, as that
   is used to connect the two entries). */
static GtkWidget *export_png_dialog;
static GtkSpinButton *export_png_width_entry, *export_png_height_entry;
static GtkWidget *export_png_okay_button, *export_png_cancel_button;
static real export_png_aspect_ratio;

/* The heart of the png exporter.
   Deals with a bit of dialog handling and all the rendering and writing.
   The dialog is not used when dia is non-interactive (export mode)
*/
static void
export_png_ok(GtkButton *button, gpointer userdata)
{
  struct png_callback_data *cbdata = (struct png_callback_data *)userdata;
  DiagramData *data = cbdata->data;
  DiaRenderer *renderer;
  DiaLibartRenderer *la_renderer;
  Rectangle *ext = &data->extents;
  Rectangle visible;
  guint32 width, height, band, row, i;
  real band_height;
  guint32 imagewidth = 0, imageheight = 0;
  long req_width, req_height;
  real imagezoom;

  FILE *fp;
  png_structp png;
  png_infop info;
  png_color_8 sig_bit;
  png_bytep *row_ptr;

  width  = (guint32) ((ext->right - ext->left) * DPCM * data->paper.scaling);
  height = (guint32) ((ext->bottom - ext->top) * DPCM * data->paper.scaling);

  if (button != NULL) {
    /* We don't want multiple clicks:) */
    gtk_widget_hide(export_png_dialog);

    imagewidth = gtk_spin_button_get_value_as_int(export_png_width_entry);
    imageheight = gtk_spin_button_get_value_as_int(export_png_height_entry);
  } else {
    if (cbdata && cbdata->size) {
      float ratio = (float) width/(float) height;

      parse_size(cbdata->size, &req_width, &req_height);
      if (req_width && !req_height) {
	imagewidth  = req_width;
	imageheight = req_width / ratio;
      } else if (req_height && !req_width) {
	imagewidth  = req_height * ratio;
	imageheight = req_height;
      } else if (req_width && req_height) {
	imagewidth  = req_width;
	imageheight = req_height;
      }
    } else {
      imagewidth  = width;
      imageheight = height;
    }
  }

  /* Subtract one to ensure all pixels are inside bitmap (see bug #413275 */
  imagezoom = ((real)(imageheight - 1)/height) * DPCM * data->paper.scaling;

  /* we render in bands to try to keep memory consumption down ... */
  band = MIN(imageheight, BAND_HEIGHT);
  band_height = (real)band / imagezoom;

  visible = *ext;
  visible.bottom = MIN(visible.bottom,
		       visible.top + band_height);

  renderer = new_libart_renderer(dia_transform_new (&visible, &imagezoom), 0);
  la_renderer = DIA_LIBART_RENDERER (renderer);
  dia_renderer_set_size(renderer, NULL, imagewidth, band);

  fp = g_fopen(cbdata->filename, "wb");
  if (fp == NULL) {
    message_error(_("Can't open output file %s: %s\n"), cbdata->filename, strerror(errno));
    goto error;
  }

  png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
				NULL, NULL, NULL);
  if (!png) {
    fclose(fp);
    message_error(_("Could not create PNG write structure"));
    goto error;
  }

  /* allocate/initialise the image information data */
  info = png_create_info_struct(png);
  if (!info) {
    fclose(fp);
    png_destroy_write_struct(&png, (png_infopp)NULL);
    message_error(_("Could not create PNG header info structure"));
    goto error;
  }

  /* set error handling ... */
  if (setjmp(png_jmpbuf(png))) {
    fclose(fp);
    png_destroy_write_struct(&png, &info);
    message_error(_("Error occurred while writing PNG"));
    goto error;
  }
  /* the compiler said these may be clobbered by setjmp, so we set it again
   * here. */
  if (button != NULL) {
    imagewidth = gtk_spin_button_get_value_as_int(export_png_width_entry);
    imageheight = gtk_spin_button_get_value_as_int(export_png_height_entry);
  } else {
    if (cbdata && cbdata->size) {
      float ratio = (float) width/(float) height;

      parse_size(cbdata->size, &req_width, &req_height);
      if (req_width && !req_height) {
	imagewidth  = req_width;
	imageheight = req_width / ratio;
      } else if (req_height && !req_width) {
	imagewidth  = req_height * ratio;
	imageheight = req_height;
      } else if (req_width && req_height) {
	imagewidth  = req_width;
	imageheight = req_height;
      }
    } else {
      imagewidth  = width;
      imageheight = height;
    }
  }
  band = MIN(imageheight, BAND_HEIGHT);

  png_init_io(png, fp);

  /* header fields */
  png_set_IHDR(png, info, imagewidth, imageheight, 8,
	       PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
	       PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  sig_bit.red = 8;
  sig_bit.green = 8;
  sig_bit.blue = 8;
  png_set_sBIT(png, info, &sig_bit);

  png_set_pHYs(png, info,
	       imagewidth/width*DPCM*100,
	       imageheight/height*DPCM*100,
	       PNG_RESOLUTION_METER);

  png_write_info(png, info);
  png_set_shift(png, &sig_bit);
  png_set_packing(png);

  row_ptr = g_new(png_bytep, band);

  for (row = 0; row < imageheight; row += band) {
    /* render band */
    for (i = 0; i < imagewidth*band; i++) {
      la_renderer->rgb_buffer[3*i]   = 0xff * data->bg_color.red;
      la_renderer->rgb_buffer[3*i+1] = 0xff * data->bg_color.green;
      la_renderer->rgb_buffer[3*i+2] = 0xff * data->bg_color.blue;
    }
    data_render(data, renderer, &visible, NULL,NULL);
    /* write rows to png file */
    for (i = 0; i < band; i++)
      row_ptr[i] = la_renderer->rgb_buffer + 3 * i * imagewidth;
    png_write_rows(png, row_ptr, MIN(band, imageheight - row));

    visible.top    += band_height;
    visible.bottom += band_height;
  }
  g_free(row_ptr);
  png_write_end(png, info);
  png_destroy_write_struct(&png, &info);
  fclose(fp);

 error:
  g_object_unref(renderer);
  if (button != NULL) {
    g_signal_handlers_disconnect_matched (GTK_OBJECT(export_png_okay_button),
					  G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, userdata);
    g_signal_handlers_disconnect_matched (GTK_OBJECT(export_png_cancel_button),
					  G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, userdata);
  }
  g_free(cbdata->filename);
  g_free(cbdata);
  return;
}

/* Stuff to do when cancelling:
   disconnect signals (since the dialog persists)
   hide dialog
   free callback data
*/
static void
export_png_cancel(GtkButton *button, gpointer userdata)
{
  struct png_callback_data *cbdata = (struct png_callback_data *)userdata;

  g_signal_handlers_disconnect_matched (GTK_OBJECT(export_png_okay_button),
					G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, userdata);
  g_signal_handlers_disconnect_matched (GTK_OBJECT(export_png_cancel_button),
					G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, userdata);

  gtk_widget_hide(export_png_dialog);
  g_free(cbdata->filename);
  g_free(cbdata);
}

/* Adjust the aspect ratio */
static void
export_png_ratio(GtkAdjustment *limits, gpointer userdata)
{
  /* This variable makes sure that we don't have a loopback effect. */
  static gboolean in_progress;
  if (in_progress) return;
  in_progress = TRUE;
  if (userdata == export_png_height_entry) {
    gtk_spin_button_set_value(GTK_SPIN_BUTTON(userdata),
			      (int)((real)gtk_spin_button_get_value_as_int(export_png_width_entry))/export_png_aspect_ratio);
  } else {
    gtk_spin_button_set_value(GTK_SPIN_BUTTON(userdata),
			      (int)((real)gtk_spin_button_get_value_as_int(export_png_height_entry))*export_png_aspect_ratio);
  }
  in_progress = FALSE;
}

static void
export_png(DiagramData *data, const gchar *filename,
           const gchar *diafilename, void* user_data)
{
  /* Create the callback data.  Can't be stack allocated, as the function
     returns before the callback is called.  Must be freed by the
     final callbacks. */
  struct png_callback_data *cbdata =
    (struct png_callback_data *) g_new0(struct png_callback_data, 1);
  Rectangle *ext = &data->extents;
  guint32 width, height;

  /* Note that this dialog, while not modal, is no reentrant, as it creates
     a single dialog and uses that every time.  Trying to do two exports at
     the same time will lead to confusion.
  */

  if (export_png_dialog == NULL && user_data == NULL && app_is_interactive()) {
    /* Create a dialog */
    export_png_dialog = dialog_make(_("PNG Export Options"),
				    _("Export"), NULL,
				    &export_png_okay_button,
				    &export_png_cancel_button);
    /* Add two integer entries */
    export_png_width_entry =
      dialog_add_spinbutton(export_png_dialog, _("Image width:"),
			    0.0, 10000.0, 0);
    export_png_height_entry =
      dialog_add_spinbutton(export_png_dialog, _("Image height:"),
			    0.0, 10000.0, 0);

    /* Make sure that the aspect ratio stays the same */
    g_signal_connect(GTK_OBJECT(gtk_spin_button_get_adjustment(export_png_width_entry)),
		       "value_changed",
		     G_CALLBACK(export_png_ratio), (gpointer)export_png_height_entry);
    g_signal_connect(GTK_OBJECT(gtk_spin_button_get_adjustment(export_png_height_entry)),
		       "value_changed",
		       G_CALLBACK(export_png_ratio), (gpointer)export_png_width_entry);

  }

  /* Store pertinent data in callback data structure */
  cbdata->data = data;
  cbdata->filename = g_strdup(filename);

  if (user_data == NULL && app_is_interactive()) {
    /* Find the default size */
    width  = (guint32) ((ext->right - ext->left) * DPCM * data->paper.scaling);
    height = (guint32) ((ext->bottom - ext->top) * DPCM * data->paper.scaling);

    /* Store aspect ratio */
    export_png_aspect_ratio = ((real)width)/height;

    /* Set the default size */
    gtk_spin_button_set_value(export_png_width_entry, (float)width);
    /* This is set from the aspect ratio */
    /*  gtk_spin_button_set_value(export_png_height_entry, (float)height);*/

    /* Set OK and Cancel buttons to call the relevant callbacks with cbdata */
    g_signal_connect(GTK_OBJECT(export_png_okay_button), "clicked",
		     G_CALLBACK(export_png_ok), (gpointer)cbdata);
    g_signal_connect(GTK_OBJECT(export_png_cancel_button), "clicked",
		     G_CALLBACK(export_png_cancel), (gpointer)cbdata);

    /* Show the whole thing */
    gtk_widget_show_all(export_png_dialog);
  } else {
    cbdata->size = (gchar *) user_data;
    export_png_ok(NULL, cbdata);
  }
}

static const gchar *extensions[] = { "png", NULL };
DiaExportFilter png_export_filter = {
  N_("PNG (anti-aliased)"),
  extensions,
  export_png,
  NULL,
  "png-libart"
};

#endif


text:
package openstack

import (
	"fmt"
	"time"

	"github.com/golang/glog"
	"github.com/gophercloud/gophercloud"
	os "github.com/gophercloud/gophercloud/openstack"
	cinder "github.com/gophercloud/gophercloud/openstack/blockstorage/v2/volumes"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers"
	sg "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/groups"
	sgr "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/kops/dnsprovider/pkg/dnsprovider"
	"k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/pkg/cloudinstances"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/util/pkg/vfs"
)

const TagNameEtcdClusterPrefix = "k8s.io/etcd/"
const TagNameRolePrefix = "k8s.io/role/"
const TagClusterName = "KubernetesCluster"

// readBackoff is the backoff strategy for openstack read retries.
var readBackoff = wait.Backoff{
	Duration: time.Second,
	Factor:   1.5,
	Jitter:   0.1,
	Steps:    4,
}

// writeBackoff is the backoff strategy for openstack write retries.
var writeBackoff = wait.Backoff{
	Duration: time.Second,
	Factor:   1.5,
	Jitter:   0.1,
	Steps:    5,
}

type OpenstackCloud interface {
	fi.Cloud

	// Region returns the region which cloud will run on
	Region() string

	// SetVolumeTags will set the tags for the Cinder volume
	SetVolumeTags(id string, tags map[string]string) error

	// GetCloudTags will return the tags attached on cloud
	GetCloudTags() map[string]string

	// ListVolumes will return the Cinder volumes which match the options
	ListVolumes(opt cinder.ListOpts) ([]cinder.Volume, error)

	// CreateVolume will create a new Cinder Volume
	CreateVolume(opt cinder.CreateOpts) (*cinder.Volume, error)

	//ListSecurityGroups will return the Neutron security groups which match the options
	ListSecurityGroups(opt sg.ListOpts) ([]sg.SecGroup, error)

	//CreateSecurityGroup will create a new Neutron security group
	CreateSecurityGroup(opt sg.CreateOpts) (*sg.SecGroup, error)

	//ListSecurityGroupRules will return the Neutron security group rules which match the options
	ListSecurityGroupRules(opt sgr.ListOpts) ([]sgr.SecGroupRule, error)

	//CreateSecurityGroupRule will create a new Neutron security group rule
	CreateSecurityGroupRule(opt sgr.CreateOpts) (*sgr.SecGroupRule, error)

	//ListNetworks will return the Neutron networks which match the options
	ListNetworks(opt networks.ListOptsBuilder) ([]networks.Network, error)

	//CreateNetwork will create a new Neutron network
	CreateNetwork(opt networks.CreateOptsBuilder) (*networks.Network, error)

	//ListRouters will return the Neutron routers which match the options
	ListRouters(opt routers.ListOpts) ([]routers.Router, error)

	//CreateRouter will create a new Neutron router
	CreateRouter(opt routers.CreateOptsBuilder) (*routers.Router, error)
}

type openstackCloud struct {
	cinderClient  *gophercloud.ServiceClient
	neutronClient *gophercloud.ServiceClient
	tags          map[string]string
	region        string
}

var _ fi.Cloud = &openstackCloud{}

func NewOpenstackCloud(tags map[string]string) (OpenstackCloud, error) {
	config := vfs.OpenstackConfig{}

	authOption, err := config.GetCredential()
	if err != nil {
		return nil, err
	}
	provider, err := os.AuthenticatedClient(authOption)
	if err != nil {
		return nil, fmt.Errorf("error building openstack authenticated client: %v", err)
	}

	endpointOpt, err := config.GetServiceConfig("Cinder")
	if err != nil {
		return nil, err
	}
	cinderClient, err := os.NewBlockStorageV2(provider, endpointOpt)
	if err != nil {
		return nil, fmt.Errorf("error building cinder client: %v", err)
	}

	endpointOpt, err = config.GetServiceConfig("Neutron")
	if err != nil {
		return nil, err
	}
	neutronClient, err := os.NewNetworkV2(provider, endpointOpt)
	if err != nil {
		return nil, fmt.Errorf("error building neutron client: %v", err)
	}
	region := endpointOpt.Region

	c := &openstackCloud{
		cinderClient:  cinderClient,
		neutronClient: neutronClient,
		tags:          tags,
		region:        region,
	}
	return c, nil
}

func (c *openstackCloud) Region() string {
	return c.region
}

func (c *openstackCloud) ProviderID() kops.CloudProviderID {
	return kops.CloudProviderOpenstack
}

func (c *openstackCloud) DNS() (dnsprovider.Interface, error) {
	return nil, fmt.Errorf("openstackCloud::DNS not implemented")
}

func (c *openstackCloud) FindVPCInfo(id string) (*fi.VPCInfo, error) {
	return nil, fmt.Errorf("openstackCloud::FindVPCInfo not implemented")
}

func (c *openstackCloud) DeleteInstance(i *cloudinstances.CloudInstanceGroupMember) error {
	return fmt.Errorf("openstackCloud::DeleteInstance not implemented")
}

func (c *openstackCloud) DeleteGroup(g *cloudinstances.CloudInstanceGroup) error {
	return fmt.Errorf("openstackCloud::DeleteGroup not implemented")
}

func (c *openstackCloud) GetCloudGroups(cluster *kops.Cluster, instancegroups []*kops.InstanceGroup, warnUnmatched bool, nodes []v1.Node) (map[string]*cloudinstances.CloudInstanceGroup, error) {
	return nil, fmt.Errorf("openstackCloud::GetCloudGroups not implemented")
}

func (c *openstackCloud) SetVolumeTags(id string, tags map[string]string) error {
	if len(tags) == 0 {
		return nil
	}
	if id == "" {
		return fmt.Errorf("error setting tags to unknown volume")
	}
	glog.V(4).Infof("setting tags to cinder volume %q: %v", id, tags)

	opt := cinder.UpdateOpts{Metadata: tags}
	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		_, err := cinder.Update(c.cinderClient, id, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error setting tags to cinder volume %q: %v", id, err)
		}
		return true, nil
	})
	if err != nil {
		return err
	} else if done {
		return nil
	} else {
		return wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) GetCloudTags() map[string]string {
	return c.tags
}

func (c *openstackCloud) ListVolumes(opt cinder.ListOpts) ([]cinder.Volume, error) {
	var volumes []cinder.Volume

	done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {
		allPages, err := cinder.List(c.cinderClient, opt).AllPages()
		if err != nil {
			return false, fmt.Errorf("error listing volumes %v: %v", opt, err)
		}

		vs, err := cinder.ExtractVolumes(allPages)
		if err != nil {
			return false, fmt.Errorf("error extracting volumes from pages: %v", err)
		}
		volumes = vs
		return true, nil
	})
	if err != nil {
		return volumes, err
	} else if done {
		return volumes, nil
	} else {
		return volumes, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) CreateVolume(opt cinder.CreateOpts) (*cinder.Volume, error) {
	var volume *cinder.Volume

	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		v, err := cinder.Create(c.cinderClient, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error creating volume %v: %v", opt, err)
		}
		volume = v
		return true, nil
	})
	if err != nil {
		return volume, err
	} else if done {
		return volume, nil
	} else {
		return volume, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) ListSecurityGroups(opt sg.ListOpts) ([]sg.SecGroup, error) {
	var groups []sg.SecGroup

	done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {
		allPages, err := sg.List(c.neutronClient, opt).AllPages()
		if err != nil {
			return false, fmt.Errorf("error listing security groups %v: %v", opt, err)
		}

		gs, err := sg.ExtractGroups(allPages)
		if err != nil {
			return false, fmt.Errorf("error extracting security groups from pages: %v", err)
		}
		groups = gs
		return true, nil
	})
	if err != nil {
		return groups, err
	} else if done {
		return groups, nil
	} else {
		return groups, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) CreateSecurityGroup(opt sg.CreateOpts) (*sg.SecGroup, error) {
	var group *sg.SecGroup

	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		g, err := sg.Create(c.neutronClient, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error creating security group %v: %v", opt, err)
		}
		group = g
		return true, nil
	})
	if err != nil {
		return group, err
	} else if done {
		return group, nil
	} else {
		return group, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) ListSecurityGroupRules(opt sgr.ListOpts) ([]sgr.SecGroupRule, error) {
	var rules []sgr.SecGroupRule

	done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {
		allPages, err := sgr.List(c.neutronClient, opt).AllPages()
		if err != nil {
			return false, fmt.Errorf("error listing security group rules %v: %v", opt, err)
		}

		rs, err := sgr.ExtractRules(allPages)
		if err != nil {
			return false, fmt.Errorf("error extracting security group rules from pages: %v", err)
		}
		rules = rs
		return true, nil
	})
	if err != nil {
		return rules, err
	} else if done {
		return rules, nil
	} else {
		return rules, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) CreateSecurityGroupRule(opt sgr.CreateOpts) (*sgr.SecGroupRule, error) {
	var rule *sgr.SecGroupRule

	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		r, err := sgr.Create(c.neutronClient, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error creating security group rule %v: %v", opt, err)
		}
		rule = r
		return true, nil
	})
	if err != nil {
		return rule, err
	} else if done {
		return rule, nil
	} else {
		return rule, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) ListNetworks(opt networks.ListOptsBuilder) ([]networks.Network, error) {
	var ns []networks.Network

	done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {
		allPages, err := networks.List(c.neutronClient, opt).AllPages()
		if err != nil {
			return false, fmt.Errorf("error listing networks: %v", err)
		}

		r, err := networks.ExtractNetworks(allPages)
		if err != nil {
			return false, fmt.Errorf("error extracting networks from pages: %v", err)
		}
		ns = r
		return true, nil
	})
	if err != nil {
		return ns, err
	} else if done {
		return ns, nil
	} else {
		return ns, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) CreateNetwork(opt networks.CreateOptsBuilder) (*networks.Network, error) {
	var n *networks.Network

	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		r, err := networks.Create(c.neutronClient, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error creating network: %v", err)
		}
		n = r
		return true, nil
	})
	if err != nil {
		return n, err
	} else if done {
		return n, nil
	} else {
		return n, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) ListRouters(opt routers.ListOpts) ([]routers.Router, error) {
	var rs []routers.Router

	done, err := vfs.RetryWithBackoff(readBackoff, func() (bool, error) {
		allPages, err := routers.List(c.neutronClient, opt).AllPages()
		if err != nil {
			return false, fmt.Errorf("error listing routers: %v", err)
		}

		r, err := routers.ExtractRouters(allPages)
		if err != nil {
			return false, fmt.Errorf("error extracting routers from pages: %v", err)
		}
		rs = r
		return true, nil
	})
	if err != nil {
		return rs, err
	} else if done {
		return rs, nil
	} else {
		return rs, wait.ErrWaitTimeout
	}
}

func (c *openstackCloud) CreateRouter(opt routers.CreateOptsBuilder) (*routers.Router, error) {
	var r *routers.Router

	done, err := vfs.RetryWithBackoff(writeBackoff, func() (bool, error) {
		v, err := routers.Create(c.neutronClient, opt).Extract()
		if err != nil {
			return false, fmt.Errorf("error creating router: %v", err)
		}
		r = v
		return true, nil
	})
	if err != nil {
		return r, err
	} else if done {
		return r, nil
	} else {
		return r, wait.ErrWaitTimeout
	}
}


text:
namespace test
{

class windebug_output : public test_output
{
public:
    explicit windebug_output(bool striplf, bool use_tiny_mode);

	void start() override;
	void start_class(const std::string &class_name) override;
	void start_function(const std::string &class_name, const std::string &function_name) override;
	void end_function(const std::string &class_name, const std::string &function_name) override;
	void end_class(const std::string &class_name, const test_class_statistics &stats) override;
	void end(int class_count, const test_class_statistics &stats) override;

	void output_success(const std::string &message, int line, const char *file) override;
	void output_failure(const std::string &message, int line, const char *file) override;
	void output_exception(const std::string &message, const std::string &exceptiontext, int line, const char *file) override;
	void output_message(const std::string &message, int line, const char *file) override;
    void output_expected_fail(const std::string &expected, const std::string &message, int line = 0, const char *file = nullptr);

private:
	std::stringstream buffer;
	std::unique_ptr<test_output> generator;
	bool strip_lf;

	void dump_buffer();
    void dump_string(const std::string &message) const;
};

}

#endif


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.cyc.kb.client.services (Core Client Implementation 1.1.1 API)</title>
<meta name="date" content="2018-01-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.cyc.kb.client.services

Classes

AssertionServiceImpl

BinaryPredicateServiceImpl

ContextServiceImpl

FactServiceImpl

FirstOrderCollectionServiceImpl

KbApiServiceImpl

KbCollectionServiceImpl

KbFunctionServiceImpl

KbIndividualServiceImpl

KbPredicateServiceImpl

KbServiceImpl

KbTermServiceImpl

RelationServiceImpl

RuleServiceImpl

SecondOrderCollectionServiceImpl

SentenceServiceImpl

SymbolServiceImpl

VariableServiceImpl


text:
<dc:title>ATLANTIC MARINE CONSTR. CO. v. UNITED STATES DIST.</dc:title>
<dc:language>en-US</dc:language>
<dc:creator opf:file-as="NYPL" opf:role="aut">NYPL</dc:creator>
<dc:publisher>NYPL</dc:publisher>
<dc:date opf:event="publication">2015-01-15</dc:date>
<dc:rights>Copyright ©2015 by Cornell Law and NYPL</dc:rights>


text:
/*
 * Closeable.cpp
 *
 *  Created on: 2015/10/23
 *      Author: tsubaki
 */

#include "Closeable.h"

Closeable::Closeable() {
	// TODO Auto-generated constructor stub

}

Closeable::~Closeable() {
	// TODO Auto-generated destructor stub
}

void Closeable::close() throw (IOException) {
	// noop
}


text:
<script>
var Beverage = function(){};
Beverage.prototype.boilWater = function(){ console.log( '把水煮沸' ); };
/**
 * 抽象约束
 * 如果子类没有覆盖方法,throw Error,缺点是错误后置,执行时候才能发现
 */
Beverage.prototype.brew = function(){ throw new Error( '子类必须重写brew 方法' ); };
Beverage.prototype.pourInCup = function(){ throw new Error( '子类必须重写pourInCup 方法' ); };
Beverage.prototype.addCondiments = function(){ throw new Error( '子类必须重写addCondiments 方法' ); };
/**
 * 钩子方法
 */
Beverage.prototype.customerWantsCondiments = function(){
    return true; // 默认需要调料
};
Beverage.prototype.init = function(){
    this.boilWater();
    this.brew();
    this.pourInCup();
	if ( this.customerWantsCondiments() ){ // 如果挂钩返回true,则需要调料
		this.addCondiments();
	}
};

var CoffeeWithHook = function(){};
CoffeeWithHook.prototype = new Beverage();
CoffeeWithHook.prototype.brew = function(){ console.log( '用沸水冲泡咖啡' ); };
CoffeeWithHook.prototype.pourInCup = function(){ console.log( '把咖啡倒进杯子' ); };
CoffeeWithHook.prototype.addCondiments = function(){ console.log( '加糖和牛奶' ); };
CoffeeWithHook.prototype.customerWantsCondiments = function(){
	return window.confirm( '请问需要调料吗?' );
};
var coffeeWithHook = new CoffeeWithHook();
coffeeWithHook.init();

</script>