text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Chapter 2: Overview of the Sampled Package</title>
<link rel="stylesheet" type="text/css" href="../../../../technotes/css/guide.css" />

Documentation Contents

< Contents

Chapter 2: Overview of the Sampled Package

Notes

Direct Audio mixers are always the default on Windows. They are
the default on Solaris if the Solaris audio mixer is enabled (see
Solaris man page for mixer). On Linux, they are the default only if
there is a device that supports mixing.

Because they are "direct," Direct Audio mixers do not
support SAMPLE_RATE control.

The default mixer can be selected via the
sound.properties file.

 This chapter provides an
introduction to the Java Sound API's digital audio architecture,
which is accessed through the javax.sound.sampled
package. First, an explanation is given of the package's focus:
playback and capture of formatted audio data. Then this chapter
describes the three fundamental components required for playback or
capture: an audio data format, a line, and a mixer.
The Line interface and its
subinterfaces are introduced briefly.

Design Goals

 Before examining the
elements of the Java Sound API, it helps to understand the
orientation of the javax.sound.sampled package.

A Focus on Data Transport

 The
javax.sound.sampled package is fundamentally concerned
with audio transport—in other words, the Java Sound API
focuses on playback and capture. The central task that the Java
Sound API addresses is how to move bytes of formatted audio data
into and out of the system. This task involves opening audio input
and output devices and managing buffers that get filled with
real-time sound data. It can also involve mixing multiple streams
of audio into one stream (whether for input or output). The
transport of sound into or out of the system has to be correctly
handled when the user requests that the flow of sound be started,
paused, resumed, or stopped.

 To support this focus on
basic audio input and output, the Java Sound API provides methods
for converting between various audio data formats, and for reading
and writing common types of sound files. However, it does not
attempt to be a comprehensive sound-file toolkit. A particular
implementation of the Java Sound API need not support an extensive
set of file types or data format conversions. Third-party service
providers can supply modules that "plug in" to an existing
implementation to support additional file types and
conversions.

Buffered and Unbuffered Handling of Audio

 The Java Sound API can
handle audio transport in both a streaming, buffered fashion and an
in-memory, unbuffered fashion. "Streaming" is used here in a
general sense to refer to real-time handling of audio bytes; it
does not refer to the specific, well-known case of sending audio
over the Internet in a certain format. In other words, a stream of
audio is simply a continuous set of audio bytes that arrive more or
less at the same rate that they are to be handled (played,
recorded, etc.). Operations on the bytes commence before all the
data has arrived. In the streaming model, particularly in the case
of audio input rather than audio output, you do not necessarily
know in advance how long the sound is and when it will finish
arriving. You simply handle one buffer of audio data at a time,
until the operation is halted. In the case of audio output
(playback), you also need to buffer data if the sound you want to
play is too large to fit in memory all at once. In other words, you
deliver your audio bytes to the sound engine in chunks, and it
takes care of playing each sample at the right time. Mechanisms are
provided that make it easy to know how much data to deliver in each
chunk.

 The Java Sound API also
permits unbuffered transport in the case of playback only, assuming
you already have all the audio data at hand and it is not too large
to fit in memory. In this situation, there is no need for the
application program to buffer the audio, although the buffered,
real-time approach is still available if desired. Instead, the
entire sound can be preloaded at once into memory for subsequent
playback. Because all the sound data is loaded in advance, playback
can start immediately, for example, as soon as the user clicks a
Start button. This can be an advantage compared to the buffered
model, where the playback has to wait for the first buffer to fill.
In addition, the in-memory, unbuffered model allows sounds to be
easily looped (cycled) or set to arbitrary positions in the
data.

 These two models for
playback are discussed further in Chapter 4, "Playing Back Audio." Buffered recording is
discussed in Chapter 5, "Capturing
Audio."

The Essentials: Format, Mixer, and Line

 To play or capture sound
using the Java Sound API, you need at least three things: formatted
audio data, a mixer, and a line. Each of these is explained
below.

What Is Formatted Audio Data?

 Formatted audio data refers
to sound in any of a number of standard formats. The Java Sound API
distinguishes between data formats and file
formats.

Data Formats

 A data format tells you how
to interpret a series of bytes of "raw" sampled audio data, such as
samples that have already been read from a sound file, or samples
that have been captured from the microphone input. You might need
to know, for example, how many bits constitute one sample (the
representation of the shortest instant of sound), and similarly you
might need to know the sound's sample rate (how fast the samples
are supposed to follow one another). When setting up for playback
or capture, you specify the data format of the sound you are
capturing or playing.

 In the Java Sound API, a
data format is represented by an AudioFormat object,
which includes the following attributes:

Encoding technique, usually pulse code modulation (PCM)

Number of channels (1 for mono, 2 for stereo, etc.)

Sample rate (number of samples per second, per channel)

Number of bits per sample (per channel)

Frame rate

Frame size in bytes

Byte order (big-endian or little-endian)

PCM is one kind of encoding of the sound waveform. The Java Sound
API includes two PCM encodings that use linear quantization of
amplitude, and signed or unsigned integer values. Linear
quantization means that the number stored in each sample is
directly proportional (except for any distortion) to the original
sound pressure at that instant and similarly proportional to the
displacement of a loudspeaker or eardrum that is vibrating with the
sound at that instant. Compact discs, for example, use linear
PCM-encoded sound. Mu-law encoding and a-law encoding are common
nonlinear encodings that provide a more compressed version of the
audio data; these encodings are typically used for telephony or
recordings of speech. A nonlinear encoding maps the original
sound's amplitude to the stored value using a nonlinear function,
which can be designed to give more amplitude resolution to quiet
sounds than to loud sounds.

 A frame contains the data
for all channels at a particular time. For PCM-encoded data, the
frame is simply the set of simultaneous samples in all channels,
for a given instant in time, without any additional information. In
this case, the frame rate is equal to the sample rate, and the
frame size in bytes is the number of channels multiplied by the
sample size in bits, divided by the number of bits in a byte.

 For other kinds of
encodings, a frame might contain additional information besides the
samples, and the frame rate might be completely different from the
sample rate. For example, consider the MP3 (MPEG-1 Audio Layer 3)
encoding, which is not explicitly mentioned in the current version
of the Java Sound API, but which could be supported by an
implementation of the Java Sound API or by a third-party service
provider. In MP3, each frame contains a bundle of compressed data
for a series of samples, not just one sample per channel. Because
each frame encapsulates a whole series of samples, the frame rate
is slower than the sample rate. The frame also contains a header.
Despite the header, the frame size in bytes is less than the size
in bytes of the equivalent number of PCM frames. (After all, the
purpose of MP3 is to be more compact than PCM data.) For such an
encoding, the sample rate and sample size refer to the PCM data
that the encoded sound will eventually be converted into before
being delivered to a digital-to-analog converter (DAC).

File Formats

 A file format specifies the
structure of a sound file, including not only the format of the raw
audio data in the file, but also other information that can be
stored in the file. Sound files come in various standard varieties,
such as WAVE (also known as WAV, and often associated with PCs),
AIFF (often associated with Macintoshes), and AU (often associated
with UNIX systems). The different types of sound file have
different structures. For example, they might have a different
arrangement of data in the file's "header." A header contains
descriptive information that typically precedes the file's actual
audio samples, although some file formats allow successive "chunks"
of descriptive and audio data. The header includes a specification
of the data format that was used for storing the audio in the sound
file. Any of these types of sound file can contain various data
formats (although usually there is only one data format within a
given file), and the same data format can be used in files that
have different file formats.

 In the Java Sound API, a
file format is represented by an AudioFileFormat
object, which contains:

The file type (WAVE, AIFF, etc.)

The file's length in bytes

The length, in frames, of the audio data contained in the file

An AudioFormat object that specifies the data format of the
audio data contained in the file

The AudioSystem class (described in Chapter 3,
"Accessing Audio System Resources")
provides methods for reading and writing sounds in different file
formats, and for converting between different data formats. Some of
the methods let you access a file's contents through a kind of
stream called an AudioInputStream. An
AudioInputStream is a subclass of the generic Java
InputStream class, which encapsulates a series of
bytes that can be read sequentially. To its superclass, the
AudioInputStream class adds knowledge of the bytes'
audio data format (represented by an AudioFormat
object). By reading a sound file as an
AudioInputStream, you get immediate access to the
samples, without having to worry about the sound file's structure
(its header, chunks, etc.). A single method invocation gives you
all the information you need about the data format and the file
type.

What Is a Mixer?

 Many application programming
interfaces (APIs) for sound make use of the notion of an audio
device. A device is often a software interface to a
physical input/output device. For example, a sound-input device
might represent the input capabilities of a sound card, including a
microphone input, a line-level analog input, and perhaps a digital
audio input.

 In the Java Sound API,
devices are represented by Mixer objects. The purpose
of a mixer is to handle one or more streams of audio input and one
or more streams of audio output. In the typical case, it actually
mixes together multiple incoming streams into one outgoing stream.
A Mixer object can represent the sound-mixing
capabilities of a physical device such as a sound card, which might
need to mix the sound coming in to the computer from various
inputs, or the sound coming from application programs and going to
outputs.

 Alternatively, a
Mixer object can represent sound-mixing capabilities
that are implemented entirely in software, without any inherent
interface to physical devices.

 In the Java Sound API, a
component such as the microphone input on a sound card is not
itself considered a device—that is, a mixer—but rather
a port into or out of the mixer. A port typically provides
a single stream of audio into or out of the mixer (although the
stream can be multichannel, such as stereo). The mixer might have
several such ports. For example, a mixer representing a sound
card's output capabilities might mix several streams of audio
together, and then send the mixed signal to any or all of various
output ports connected to the mixer. These output ports could be
(for example) a headphone jack, a built-in speaker, or a line-level
output.

 To understand the notion of
a mixer in the Java Sound API, it helps to visualize a physical
mixing console, such as those used in live concerts and recording
studios. (See illustration that follows.)

A Physical Mixing Console

 A physical mixer has
"strips" (also called "slices"), each representing a path through
which a single audio signal goes into the mixer for processing. The
strip has knobs and other controls by which you can control the
volume and pan (placement in the stereo image) for the signal in
that strip. Also, the mixer might have a separate bus for effects
such as reverb, and this bus can be connected to an internal or
external reverberation unit. Each strip has a potentiometer that
controls how much of that strip's signal goes into the reverberated
mix. The reverberated ("wet") mix is then mixed with the "dry"
signals from the strips. A physical mixer sends this final mixture
to an output bus, which typically goes to a tape recorder (or
disk-based recording system) and/or speakers.

 Imagine a live concert that
is being recorded in stereo. Cables (or wireless connections)
coming from the many microphones and electric instruments on stage
are plugged into the inputs of the mixing console. Each input goes
to a separate strip of the mixer, as illustrated. The sound
engineer decides on the settings of the gain, pan, and reverb
controls. The output of all the strips and the reverb unit are
mixed together into two channels. These two channels go to two
outputs on the mixer, into which cables are plugged that connect to
the stereo tape recorder's inputs. The two channels are perhaps
also sent via an amplifier to speakers in the hall, depending on
the type of music and the size of the hall.

 Now imagine a recording
studio, in which each instrument or singer is recorded to a
separate track of a multitrack tape recorder. After the instruments
and singers have all been recorded, the recording engineer performs
a "mixdown" to combine all the taped tracks into a two-channel
(stereo) recording that can be distributed on compact discs. In
this case, the input to each of the mixer's strips is not a
microphone, but one track of the multitrack recording. Once again,
the engineer can use controls on the strips to decide each track's
volume, pan, and reverb amount. The mixer's outputs go once again
to a stereo recorder and to stereo speakers, as in the example of
the live concert.

 These two examples
illustrate two different uses of a mixer: to capture multiple input
channels, combine them into fewer tracks, and save the mixture, or
to play back multiple tracks while mixing them down to fewer
tracks.

 In the Java Sound API, a
mixer can similarly be used for input (capturing audio) or output
(playing back audio). In the case of input, the source
from which the mixer gets audio for mixing is one or more input
ports. The mixer sends the captured and mixed audio streams to its
target, which is an object with a buffer from which an
application program can retrieve this mixed audio data. In the case
of audio output, the situation is reversed. The mixer's source for
audio is one or more objects containing buffers into which one or
more application programs write their sound data; and the mixer's
target is one or more output ports.

What Is a Line?

 The metaphor of a physical
mixing console is also useful for understanding the Java Sound
API's concept of a line.

 A line is an element of the
digital audio "pipeline"—that is, a path for moving audio
into or out of the system. Usually the line is a path into or out
of a mixer (although technically the mixer itself is also a kind of
line).

 Audio input and output ports
are lines. These are analogous to the microphones and speakers
connected to a physical mixing console. Another kind of line is a
data path through which an application program can get input audio
from, or send output audio to, a mixer. These data paths are
analogous to the tracks of the multitrack recorder connected to the
physical mixing console.

 One difference between lines
in the Java Sound API and those of a physical mixer is that the
audio data flowing through a line in the Java Sound API can be mono
or multichannel (for example, stereo). By contrast, each of a
physical mixer's inputs and outputs is typically a single channel
of sound. To get two or more channels of output from the physical
mixer, two or more physical outputs are normally used (at least in
the case of analog sound; a digital output jack is often
multichannel). In the Java Sound API, the number of channels in a
line is specified by the AudioFormat of the data that
is currently flowing through the line.

Lines in an Audio-output Configuration

 Let's now examine some
specific kinds of lines and mixers. The following diagram shows
different types of lines in a simple audio-output system that could
be part of an implementation of the Java Sound API:

A Possible Configuration of Lines for Audio Output

 In this example, an
application program has gotten access to some available inputs of
an audio-input mixer: one or more clips and source
data lines. A clip is a mixer input (a kind of line) into
which you can load audio data prior to playback; a source data line
is a mixer input that accepts a real-time stream of audio data. The
application program preloads audio data from a sound file into the
clips. It then pushes other audio data into the source data lines,
a buffer at a time. The mixer reads data from all these lines, each
of which may have its own reverberation, gain, and pan controls,
and mixes the dry audio signals with the wet (reverberated) mix.
The mixer delivers its final output to one or more output ports,
such as a speaker, a headphone jack, and a line-out jack.

 Although the various lines
are depicted as separate rectangles in the diagram, they are all
"owned" by the mixer, and can be considered integral parts of the
mixer. The reverb, gain, and pan rectangles represent processing
controls (rather than lines) that can be applied by the mixer to
data flowing through the lines.

 Note that this is just one
example of a possible mixer that is supported by the API. Not all
audio configurations will have all the features illustrated. An
individual source data line might not support panning, a mixer
might not implement reverb, and so on.

Lines in an Audio-input Configuration

 A simple audio-input system
might be similar:

A Possible Configuration of Lines for Audio Input

 Here, data flows into the
mixer from one or more input ports, commonly the microphone or the
line-in jack. Gain and pan are applied, and the mixer delivers the
captured data to an application program via the mixer's target data
line. A target data line is a mixer output, containing the mixture
of the streamed input sounds. The simplest mixer has just one
target data line, but some mixers can deliver captured data to
multiple target data lines simultaneously.

The Line Interface Hierarchy

 Now that we've seen some
functional pictures of what lines and mixers are, let's discuss
them from a slightly more programmatic perspective. Several types
of line are defined by subinterfaces of the basic Line
interface. The interface hierarchy is shown below.

The Line Interface Hierarchy

 The base interface,
Line, describes the minimal functionality common to
all lines:

Controls  Data lines and
ports often have a set of controls that affect the audio signal
passing through the line. The Java Sound API specifies control
classes that can be used to manipulate aspects of sound such as:
gain (which affects the signal's volume in decibels), pan (which
affects the sound's right-left positioning, reverb (which adds
reverberation to the sound to emulate different kinds of room
acoustics), and sample rate (which affects the rate of playback as
well as the sound's pitch).

Open or closed status
Successful opening of a line guarantees that resources have been
allocated to the line. A mixer has a finite number of lines, so at
some point multiple application programs (or the same one) might
vie for usage of the mixer's lines. Closing a line indicates that
any resources used by the line may now be released.

Events  A line generates
events when it opens or closes. Subinterfaces of Line
can introduce other types of events. When a line generates an
event, the event is sent to all objects that have registered to
"listen" for events on that line. An application program can create
these objects, register them to listen for line events, and react
to the events as desired.

We'll now examine the subinterfaces of the Line
interface.

 Ports are
simple lines for input or output of audio to or from audio devices.
As mentioned earlier, some common types of ports are the
microphone, line input, CD-ROM drive, speaker, headphone, and line
output.

 The Mixer
interface represents a mixer, of course, which as we have seen
represents either a hardware or a software device. The
Mixer interface provides methods for obtaining a
mixer's lines. These include source lines, which feed audio to the
mixer, and target lines, to which the mixer delivers its mixed
audio. For an audio-input mixer, the source lines are input ports
such as the microphone input, and the target lines are
TargetDataLines (described below), which deliver audio
to the application program. For an audio-output mixer, on the other
hand, the source lines are Clips or
SourceDataLines (described below), to which the
application program feeds audio data, and the target lines are
output ports such as the speaker.

 A Mixer is
defined as having one or more source lines and one or more target
lines. Note that this definition means that a mixer need not
actually mix data; it might have only a single source line. The
Mixer API is intended to encompass a variety of
devices, but the typical case supports mixing.

 The Mixer
interface supports synchronization; that is, you can specify that
two or more of a mixer's lines be treated as a synchronized group.
Then you can start, stop, or close all those data lines by sending
a single message to any line in the group, instead of having to
control each line individually. With a mixer that supports this
feature, you can obtain sample-accurate synchronization between
lines.

 The generic
Line interface does not provide a means to start and
stop playback or recording. For that you need a data line. The
DataLine interface supplies the following additional
media-related features beyond those of a Line:

Audio format  Each data line
has an audio format associated with its data stream.

Media position  A data line
can report its current position in the media, expressed in sample
frames. This represents the number of sample frames captured by or
rendered from the data line since it was opened.

Buffer size  This is the
size of the data line's internal buffer in bytes. For a source data
line, the internal buffer is one to which data can be written, and
for a target data line it's one from which data can be read.

Level (the current amplitude of the audio signal)

Start and stop playback or capture

Pause and resume playback or capture

Flush (discard unprocessed data from the queue)

Drain (block until all unprocessed data has been drained from
the queue, and the data line's buffer has become empty)

Active status  A data line
is considered active if it is engaged in active presentation or
capture of audio data to or from a mixer.

Events  START
and STOP events are produced when active presentation
or capture of data from or to the data line starts or stops.

 A
TargetDataLine receives audio data from a mixer.
Commonly, the mixer has captured audio data from a port such as a
microphone; it might process or mix this captured audio before
placing the data in the target data line's buffer. The
TargetDataLine interface provides methods for reading
the data from the target data line's buffer and for determining how
much data is currently available for reading.

 A
SourceDataLine receives audio data for playback. It
provides methods for writing data to the source data line's buffer
for playback, and for determining how much data the line is
prepared to receive without blocking.

 A Clip is a
data line into which audio data can be loaded prior to playback.
Because the data is pre-loaded rather than streamed, the clip's
duration is known before playback, and you can choose any starting
position in the media. Clips can be looped, meaning that upon
playback, all the data between two specified loop points will
repeat a specified number of times, or indefinitely.

 This chapter has introduced
most of the important interfaces and classes of the sampled-audio
API. Subsequent chapters show how you can access and use these
objects in your application program.

Copyright
© 1993, 2015, Oracle and/or its affiliates. All rights
reserved.

Contact
Us


text:
layout: post
date: 2016-03-08
title: "Blush Prom Style 11038 Sleeveless Sweep/Brush Train Sheath/Column"
category: Blush
tags: [Blush,Sheath/Column,Bateau,Sweep/Brush Train,Sleeveless]
---
### Blush Prom Style 11038
Just **$749.99**
###   Sleeveless Sweep/Brush Train Sheath/Column

BRANDS	Blush

Silhouette	Sheath/Column

Neckline	Bateau

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/blush/48876-blush-prom-style-11038.html](https://www.readybrides.com/en/blush/48876-blush-prom-style-11038.html)

redpajama_set_name: RedPajamaGithub


text:
/** Automatically generated file. DO NOT MODIFY */
package com.xiaozhe.logcat;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
import React from 'react';
import PropTypes from 'prop-types';

export function ViewportLoadingIndicator(props) {
  return (
    <div
      className="loading-indicator"
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        margin: 'auto',
        textAlign: 'center',
        pointerEvents: 'none',
      }}
    >
      Loading {props.percentComplete}
    </div>
  );
}

ViewportLoadingIndicator.propTypes = {
  percentComplete: PropTypes.number,
};

export default ViewportLoadingIndicator;


text:
package com.baomidou.mybatisplus.core.conditions;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.Data;
import org.assertj.core.api.Assertions;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author miemie
 * @since 2021-01-27
 */
class BaseWrapperTest {

    void logParams(AbstractWrapper<?, ?, ?> wrapper) {
        wrapper.getParamNameValuePairs().forEach((k, v) -> {
            System.out.println("key: '" + k + "'\t\tvalue: '" + v + StringPool.SINGLE_QUOTE);
            assertThat(k).startsWith(Constants.WRAPPER_PARAM);
        });
    }

    void logSqlSet(String explain, AbstractWrapper<?, ?, ?> wrapper, String targetSql) {
        System.out.printf(" ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓   ->(%s)<-   ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓%n", explain);
        System.out.println(wrapper.getSqlSet());
        Assertions.assertThat(wrapper.getSqlSet().trim()).isEqualTo(targetSql);
    }

    void logSqlWhere(String explain, AbstractWrapper<?, ?, ?> wrapper, String targetSql) {
        System.out.printf(" ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓   ->(%s)<-   ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓%n", explain);
        System.out.println(wrapper.getSqlSegment());
        assertThat(wrapper.getTargetSql().trim()).isEqualTo(targetSql);
    }

    @Data
    protected static class Entity {
        private Integer id;

        @TableField("username")
        private String name;

        private Integer roleId;
    }
}


text:
#include "jemalloc/internal/jemalloc_preamble.h"
#include "jemalloc/internal/jemalloc_internal_includes.h"

#include "jemalloc/internal/decay.h"

static const uint64_t h_steps[SMOOTHSTEP_NSTEPS] = {
#define STEP(step, h, x, y)			\
		h,
		SMOOTHSTEP
#undef STEP
};

/*
 * Generate a new deadline that is uniformly random within the next epoch after
 * the current one.
 */
void
decay_deadline_init(decay_t *decay) {
	nstime_copy(&decay->deadline, &decay->epoch);
	nstime_add(&decay->deadline, &decay->interval);
	if (decay_ms_read(decay) > 0) {
		nstime_t jitter;

		nstime_init(&jitter, prng_range_u64(&decay->jitter_state,
		    nstime_ns(&decay->interval)));
		nstime_add(&decay->deadline, &jitter);
	}
}

void
decay_reinit(decay_t *decay, nstime_t *cur_time, ssize_t decay_ms) {
	atomic_store_zd(&decay->time_ms, decay_ms, ATOMIC_RELAXED);
	if (decay_ms > 0) {
		nstime_init(&decay->interval, (uint64_t)decay_ms *
		    KQU(1000000));
		nstime_idivide(&decay->interval, SMOOTHSTEP_NSTEPS);
	}

	nstime_copy(&decay->epoch, cur_time);
	decay->jitter_state = (uint64_t)(uintptr_t)decay;
	decay_deadline_init(decay);
	decay->nunpurged = 0;
	memset(decay->backlog, 0, SMOOTHSTEP_NSTEPS * sizeof(size_t));
}

bool
decay_init(decay_t *decay, nstime_t *cur_time, ssize_t decay_ms) {
	if (config_debug) {
		for (size_t i = 0; i < sizeof(decay_t); i++) {
			assert(((char *)decay)[i] == 0);
		}
		decay->ceil_npages = 0;
	}
	if (malloc_mutex_init(&decay->mtx, "decay", WITNESS_RANK_DECAY,
	    malloc_mutex_rank_exclusive)) {
		return true;
	}
	decay->purging = false;
	decay_reinit(decay, cur_time, decay_ms);
	return false;
}

bool
decay_ms_valid(ssize_t decay_ms) {
	if (decay_ms < -1) {
		return false;
	}
	if (decay_ms == -1 || (uint64_t)decay_ms <= NSTIME_SEC_MAX *
	    KQU(1000)) {
		return true;
	}
	return false;
}

static void
decay_maybe_update_time(decay_t *decay, nstime_t *new_time) {
	if (unlikely(!nstime_monotonic() && nstime_compare(&decay->epoch,
	    new_time) > 0)) {
		/*
		 * Time went backwards.  Move the epoch back in time and
		 * generate a new deadline, with the expectation that time
		 * typically flows forward for long enough periods of time that
		 * epochs complete.  Unfortunately, this strategy is susceptible
		 * to clock jitter triggering premature epoch advances, but
		 * clock jitter estimation and compensation isn't feasible here
		 * because calls into this code are event-driven.
		 */
		nstime_copy(&decay->epoch, new_time);
		decay_deadline_init(decay);
	} else {
		/* Verify that time does not go backwards. */
		assert(nstime_compare(&decay->epoch, new_time) <= 0);
	}
}

static size_t
decay_backlog_npages_limit(const decay_t *decay) {
	/*
	 * For each element of decay_backlog, multiply by the corresponding
	 * fixed-point smoothstep decay factor.  Sum the products, then divide
	 * to round down to the nearest whole number of pages.
	 */
	uint64_t sum = 0;
	for (unsigned i = 0; i < SMOOTHSTEP_NSTEPS; i++) {
		sum += decay->backlog[i] * h_steps[i];
	}
	size_t npages_limit_backlog = (size_t)(sum >> SMOOTHSTEP_BFP);

	return npages_limit_backlog;
}

/*
 * Update backlog, assuming that 'nadvance_u64' time intervals have passed.
 * Trailing 'nadvance_u64' records should be erased and 'current_npages' is
 * placed as the newest record.
 */
static void
decay_backlog_update(decay_t *decay, uint64_t nadvance_u64,
    size_t current_npages) {
	if (nadvance_u64 >= SMOOTHSTEP_NSTEPS) {
		memset(decay->backlog, 0, (SMOOTHSTEP_NSTEPS-1) *
		    sizeof(size_t));
	} else {
		size_t nadvance_z = (size_t)nadvance_u64;

		assert((uint64_t)nadvance_z == nadvance_u64);

		memmove(decay->backlog, &decay->backlog[nadvance_z],
		    (SMOOTHSTEP_NSTEPS - nadvance_z) * sizeof(size_t));
		if (nadvance_z > 1) {
			memset(&decay->backlog[SMOOTHSTEP_NSTEPS -
			    nadvance_z], 0, (nadvance_z-1) * sizeof(size_t));
		}
	}

	size_t npages_delta = (current_npages > decay->nunpurged) ?
	    current_npages - decay->nunpurged : 0;
	decay->backlog[SMOOTHSTEP_NSTEPS-1] = npages_delta;

	if (config_debug) {
		if (current_npages > decay->ceil_npages) {
			decay->ceil_npages = current_npages;
		}
		size_t npages_limit = decay_backlog_npages_limit(decay);
		assert(decay->ceil_npages >= npages_limit);
		if (decay->ceil_npages > npages_limit) {
			decay->ceil_npages = npages_limit;
		}
	}
}

static inline bool
decay_deadline_reached(const decay_t *decay, const nstime_t *time) {
	return (nstime_compare(&decay->deadline, time) <= 0);
}

uint64_t
decay_npages_purge_in(decay_t *decay, nstime_t *time, size_t npages_new) {
	uint64_t decay_interval_ns = decay_epoch_duration_ns(decay);
	size_t n_epoch = (size_t)(nstime_ns(time) / decay_interval_ns);

	uint64_t npages_purge;
	if (n_epoch >= SMOOTHSTEP_NSTEPS) {
		npages_purge = npages_new;
	} else {
		uint64_t h_steps_max = h_steps[SMOOTHSTEP_NSTEPS - 1];
		assert(h_steps_max >=
		    h_steps[SMOOTHSTEP_NSTEPS - 1 - n_epoch]);
		npages_purge = npages_new * (h_steps_max -
		    h_steps[SMOOTHSTEP_NSTEPS - 1 - n_epoch]);
		npages_purge >>= SMOOTHSTEP_BFP;
	}
	return npages_purge;
}

bool
decay_maybe_advance_epoch(decay_t *decay, nstime_t *new_time,
    size_t npages_current) {
	/* Handle possible non-monotonicity of time. */
	decay_maybe_update_time(decay, new_time);

	if (!decay_deadline_reached(decay, new_time)) {
		return false;
	}
	nstime_t delta;
	nstime_copy(&delta, new_time);
	nstime_subtract(&delta, &decay->epoch);

	uint64_t nadvance_u64 = nstime_divide(&delta, &decay->interval);
	assert(nadvance_u64 > 0);

	/* Add nadvance_u64 decay intervals to epoch. */
	nstime_copy(&delta, &decay->interval);
	nstime_imultiply(&delta, nadvance_u64);
	nstime_add(&decay->epoch, &delta);

	/* Set a new deadline. */
	decay_deadline_init(decay);

	/* Update the backlog. */
	decay_backlog_update(decay, nadvance_u64, npages_current);

	decay->npages_limit = decay_backlog_npages_limit(decay);
	decay->nunpurged = (decay->npages_limit > npages_current) ?
	    decay->npages_limit : npages_current;

	return true;
}

/*
 * Calculate how many pages should be purged after 'interval'.
 *
 * First, calculate how many pages should remain at the moment, then subtract
 * the number of pages that should remain after 'interval'. The difference is
 * how many pages should be purged until then.
 *
 * The number of pages that should remain at a specific moment is calculated
 * like this: pages(now) = sum(backlog[i] * h_steps[i]). After 'interval'
 * passes, backlog would shift 'interval' positions to the left and sigmoid
 * curve would be applied starting with backlog[interval].
 *
 * The implementation doesn't directly map to the description, but it's
 * essentially the same calculation, optimized to avoid iterating over
 * [interval..SMOOTHSTEP_NSTEPS) twice.
 */
static inline size_t
decay_npurge_after_interval(decay_t *decay, size_t interval) {
	size_t i;
	uint64_t sum = 0;
	for (i = 0; i < interval; i++) {
		sum += decay->backlog[i] * h_steps[i];
	}
	for (; i < SMOOTHSTEP_NSTEPS; i++) {
		sum += decay->backlog[i] *
		    (h_steps[i] - h_steps[i - interval]);
	}

	return (size_t)(sum >> SMOOTHSTEP_BFP);
}

uint64_t decay_ns_until_purge(decay_t *decay, size_t npages_current,
    uint64_t npages_threshold) {
	if (!decay_gradually(decay)) {
		return DECAY_UNBOUNDED_TIME_TO_PURGE;
	}
	uint64_t decay_interval_ns = decay_epoch_duration_ns(decay);
	assert(decay_interval_ns > 0);
	if (npages_current == 0) {
		unsigned i;
		for (i = 0; i < SMOOTHSTEP_NSTEPS; i++) {
			if (decay->backlog[i] > 0) {
				break;
			}
		}
		if (i == SMOOTHSTEP_NSTEPS) {
			/* No dirty pages recorded.  Sleep indefinitely. */
			return DECAY_UNBOUNDED_TIME_TO_PURGE;
		}
	}
	if (npages_current <= npages_threshold) {
		/* Use max interval. */
		return decay_interval_ns * SMOOTHSTEP_NSTEPS;
	}

	/* Minimal 2 intervals to ensure reaching next epoch deadline. */
	size_t lb = 2;
	size_t ub = SMOOTHSTEP_NSTEPS;

	size_t npurge_lb, npurge_ub;
	npurge_lb = decay_npurge_after_interval(decay, lb);
	if (npurge_lb > npages_threshold) {
		return decay_interval_ns * lb;
	}
	npurge_ub = decay_npurge_after_interval(decay, ub);
	if (npurge_ub < npages_threshold) {
		return decay_interval_ns * ub;
	}

	unsigned n_search = 0;
	size_t target, npurge;
	while ((npurge_lb + npages_threshold < npurge_ub) && (lb + 2 < ub)) {
		target = (lb + ub) / 2;
		npurge = decay_npurge_after_interval(decay, target);
		if (npurge > npages_threshold) {
			ub = target;
			npurge_ub = npurge;
		} else {
			lb = target;
			npurge_lb = npurge;
		}
		assert(n_search < lg_floor(SMOOTHSTEP_NSTEPS) + 1);
		++n_search;
	}
	return decay_interval_ns * (ub + lb) / 2;
}


text:
layout: post
title: Arrived in Johannesburg for the SASTQB TEST-IT AFRICA 2016 International Conference
subtitle: Returning to Africa after 5 years...
bigimg: /img/johannesburg.jpg
---

In 2011, I visited Africa for the first time! The excuse was an invitation to talk in Mozambique about an integrated software development methodology.
On that visit, I actually crossed the border to South Africa, but just for a quick weekend in the Kruger National Park.

This time, it's for a full week in South Africa and after a long flight I'm ready for the [SASTQB TEST-IT AFRICA 2016 International Conference](http://www.sastqb-conf.org/).


text:
import numpy as np
import theano_wmf

np.random.seed(123)

B = np.load("test_matrix.pkl")

# convert into a surplus confidence matrix

alpha = 2.0
epsilon = 1e-6

S = B.copy()
S.data = alpha * np.log(1 + S.data / epsilon)

num_factors = 40 + 1
num_iterations = 1
batch_size = 1000
lambda_reg = 1e-5

U, V = theano_wmf.factorize(S, num_factors, batch_size, lambda_reg, num_iterations, init_std=0.01, verbose=True)


text:
//
//  ImageFilter.h
//  Sample
//
//  Created by tsuyoshi on 2013/11/04.
//  Copyright 2013 Tsuyoshi All rights reserved.
//

#ifndef __s2_image_filter__
#define __s2_image_filter__

NS_S2_BEGIN

void GaussianFilter(void *src, void *dest,  cocos2d::CCTexture2DPixelFormat format, int width, int height, int in_radius);

NS_S2_END

#endif /* __s2_gaussian_filter__ */


text:
Esto es un prueba de readme de random.

### Version
1.0.0

### Tech

No usamos proyectos de codigo abierto

### Installation

No necesita instalacion


text:
package io.advantageous.ddp;

/**
 * Thrown when we get a message from the server that we don't know how to process.
 *
 * @author geoffc@gmail.com
 * @since 1/17/14 at 7:15 PM.
 */
public class UnsupportedMessageException extends Exception {
    public UnsupportedMessageException(String rawMessage) {
        super(rawMessage);
    }
}


text:
using personManagement.Filters;
using personManagement.ViewModels;
using personManagement.Models;
using personManagement.BusinessLayer;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

namespace personManagement.Controllers
{
    public class uploadController : AsyncController
    {
        [headerFooterFilter]
        [adminFilter]
        public ActionResult Index()
        {
            return View(new fileUpload());
        }

        [adminFilter]
        public async  Task<ActionResult> upload(fileUpload fU)
        {
            int t1 = Thread.CurrentThread.ManagedThreadId;
            List<Person> persons = await Task.Factory.StartNew<List<Person>>(() => getPersons(fU));
            int t2 = Thread.CurrentThread.ManagedThreadId;
            personBusinessLayer pBL = new personBusinessLayer();
            pBL.uploadPersons(persons);
            return RedirectToAction("Index", "Person");
        }

        public List<Person> getPersons(fileUpload fU)
        {
            List<Person> persons = new List<Person>();
            StreamReader csvreader = new StreamReader(fU.fUp.InputStream);
            csvreader.ReadLine();
            while (!csvreader.EndOfStream)
            {
                var line = csvreader.ReadLine();
                var values = line.Split(',');
               Person p = new Person();
                p.name = values[0];
                p.address = values[1];
                persons.Add(p);
            }
            return persons;
        }

    }
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

using strategy::distance::services::return_type;

template
<
    typename Geometry1, typename Geometry2,
    typename Strategy = typename detail::distance::default_strategy<Geometry1, Geometry2>::type,
    typename Tag1 = typename tag_cast<typename tag<Geometry1>::type, multi_tag>::type,
    typename Tag2 = typename tag_cast<typename tag<Geometry2>::type, multi_tag>::type,
    typename StrategyTag = typename strategy::distance::services::tag<Strategy>::type,
    bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value
>
struct distance: not_implemented<Tag1, Tag2>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DISPATCH_DISTANCE_HPP


text:
/* Literal cost model to allow backward reference replacement to be efficient.
*/

#ifndef BROTLI_ENC_LITERAL_COST_H_
#define BROTLI_ENC_LITERAL_COST_H_

#include <brotli/types.h>
#include "./port.h"

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

/* Estimates how many bits the literals in the interval [pos, pos + len) in the
   ring-buffer (data, mask) will take entropy coded and writes these estimates
   to the cost[0..len) array. */
BROTLI_INTERNAL void BrotliEstimateBitCostsForLiterals(
    size_t pos, size_t len, size_t mask, const uint8_t *data, float *cost);

#if defined(__cplusplus) || defined(c_plusplus)
}  /* extern "C" */
#endif

#endif  /* BROTLI_ENC_LITERAL_COST_H_ */


text:
class RPIVideoDevice:public BaseVideoDevice {
 public:
	RPIVideoDevice();
	virtual void start();
	 virtual ~ RPIVideoDevice();
 protected:
	 virtual void init_camera();
	virtual void capture_from_camera();
	 raspicam::RaspiCam_Cv camera;
};

#endif				// RPIVideoDevice_hpp


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/user/AndroidStudioProjects/SinchJordan/android-messaging-tutorial/MessagingTutorial/build/intermediates/exploded-aar/com.android.support/appcompat-v7/19.1.0/res/values-v11/values.xml -->
    <eat-comment/>
    <style name="Theme.Base" parent="android:Theme.Holo">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>

        <!--
            A native Action Mode could be displayed (for text selection, etc) so we need to ensure
            that it is positioned correctly, so we request windowActionModeOverlay so that it
            displays over the compat Action Bar.
        -->
        <item name="android:windowActionModeOverlay">true</item>

        <!-- Attributes populated from the framework to be read by apps -->
        <item name="buttonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
        <item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
    </style>
    <style name="Theme.Base.AppCompat.Dialog.FixedSize" parent="android:Theme.Holo.Dialog">
        <item name="windowFixedWidthMajor">@dimen/dialog_fixed_width_major</item>
        <item name="windowFixedWidthMinor">@dimen/dialog_fixed_width_minor</item>
        <item name="windowFixedHeightMajor">@dimen/dialog_fixed_height_major</item>
        <item name="windowFixedHeightMinor">@dimen/dialog_fixed_height_minor</item>
        <item name="windowActionBar">false</item>

        <!-- Attributes populated from the framework to be read by apps -->
        <item name="buttonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
        <item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
    </style>
    <style name="Theme.Base.AppCompat.Dialog.Light.FixedSize" parent="android:Theme.Holo.Light.Dialog">
        <item name="windowFixedWidthMajor">@dimen/dialog_fixed_width_major</item>
        <item name="windowFixedWidthMinor">@dimen/dialog_fixed_width_minor</item>
        <item name="windowFixedHeightMajor">@dimen/dialog_fixed_height_major</item>
        <item name="windowFixedHeightMinor">@dimen/dialog_fixed_height_minor</item>
        <item name="windowActionBar">false</item>

        <!-- Attributes populated from the framework to be read by apps -->
        <item name="buttonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
        <item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
    </style>
    <style name="Theme.Base.Light" parent="android:Theme.Holo.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>

        <!--
            A native Action Mode could be displayed (for text selection, etc) so we need to ensure
            that it is positioned correctly, so we request windowActionModeOverlay so that it
            displays over the compat Action Bar.
        -->
        <item name="android:windowActionModeOverlay">true</item>

        <!-- Attributes populated from the framework to be read by apps -->
        <item name="buttonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
        <item name="selectableItemBackground">?android:attr/selectableItemBackground</item>
    </style>
    <style name="Widget.AppCompat.Base.AutoCompleteTextView" parent="android:Widget.Holo.AutoCompleteTextView"/>
    <style name="Widget.AppCompat.Base.ProgressBar" parent="android:Widget.Holo.ProgressBar"/>
    <style name="Widget.AppCompat.Base.ProgressBar.Horizontal" parent="android:Widget.Holo.ProgressBar.Horizontal"/>
    <style name="Widget.AppCompat.Light.Base.AutoCompleteTextView" parent="android:Widget.Holo.Light.AutoCompleteTextView"/>
</resources>


text:
using System.Collections.Generic;

namespace SJP.Schematic.Core;

/// <summary>
/// Defines a database view.
/// </summary>
/// <seealso cref="IDatabaseQueryable" />
public interface IDatabaseView : IDatabaseQueryable
{
    /// <summary>
    /// The definition of the view.
    /// </summary>
    /// <value>The view definition.</value>
    string Definition { get; }

    /// <summary>
    /// An ordered collection of database columns that define the view.
    /// </summary>
    /// <value>The view columns.</value>
    IReadOnlyList<IDatabaseColumn> Columns { get; }

    /// <summary>
    /// Determines whether this view is materialized or pre-computed.
    /// </summary>
    /// <value><c>true</c> if this view is materialized; otherwise, <c>false</c>.</value>
    bool IsMaterialized { get; }
}


text:
package opennlp.perceptron;

import java.util.HashMap;
import java.util.Map;

import opennlp.model.AbstractModel;
import opennlp.model.DataIndexer;
import opennlp.model.Event;
import opennlp.model.MutableContext;
import opennlp.model.OnePassDataIndexer;
import opennlp.model.Sequence;
import opennlp.model.SequenceStream;
import opennlp.model.SequenceStreamEventStream;

/**
 * Trains models for sequences using the perceptron algorithm.  Each outcome is represented as
 * a binary perceptron classifier.  This supports standard (integer) weighting as well
 * average weighting.  Sequence information is used in a simplified was to that described in:
 * Discriminative Training Methods for Hidden Markov Models: Theory and Experiments
 * with the Perceptron Algorithm. Michael Collins, EMNLP 2002.
 * Specifically only updates are applied to tokens which were incorrectly tagged by a sequence tagger
 * rather than to all feature across the sequence which differ from the training sequence.
 */
public class SimplePerceptronSequenceTrainer {

  private boolean printMessages = true;
  private int iterations;
  private SequenceStream sequenceStream;
  /** Number of events in the event set. */
  private int numEvents;

  /** Number of predicates. */
  private int numPreds;
  private int numOutcomes;

  /** List of outcomes for each event i, in context[i]. */
  private int[] outcomeList;

  private String[] outcomeLabels;

  double[] modelDistribution;

  /** Stores the average parameter values of each predicate during iteration. */
  private MutableContext[] averageParams;

  /** Mapping between context and an integer */
  private Map<String,Integer> pmap;

  private Map<String,Integer> omap;

  /** Stores the estimated parameter value of each predicate during iteration. */
  private MutableContext[] params;
  private boolean useAverage;
  private int[][][] updates;
  private int VALUE = 0;
  private int ITER = 1;
  private int EVENT = 2;

  private int[] allOutcomesPattern;
  private String[] predLabels;
  int numSequences;

  public AbstractModel trainModel(int iterations, SequenceStream sequenceStream, int cutoff, boolean useAverage) {
    this.iterations = iterations;
    this.sequenceStream = sequenceStream;
    DataIndexer di = new OnePassDataIndexer(new SequenceStreamEventStream(sequenceStream),cutoff,false);
    numSequences = 0;
    for (Sequence s : sequenceStream) {
      numSequences++;
    }
    outcomeList  = di.getOutcomeList();
    predLabels = di.getPredLabels();
    pmap = new HashMap<String,Integer>();
    for (int pli=0;pli<predLabels.length;pli++) {
      pmap.put(predLabels[pli], pli);
    }
    display("Incorporating indexed data for training...  \n");
    this.useAverage = useAverage;
    numEvents = di.getNumEvents();

    this.iterations = iterations;
    outcomeLabels = di.getOutcomeLabels();
    omap = new HashMap<String,Integer>();
    for (int oli=0;oli<outcomeLabels.length;oli++) {
      omap.put(outcomeLabels[oli], oli);
    }
    outcomeList = di.getOutcomeList();

    numPreds = predLabels.length;
    numOutcomes = outcomeLabels.length;
    if (useAverage) {
      updates = new int[numPreds][numOutcomes][3];
    }

    display("done.\n");

    display("\tNumber of Event Tokens: " + numEvents + "\n");
    display("\t    Number of Outcomes: " + numOutcomes + "\n");
    display("\t  Number of Predicates: " + numPreds + "\n");

    params = new MutableContext[numPreds];
    if (useAverage) averageParams = new MutableContext[numPreds];

    allOutcomesPattern= new int[numOutcomes];
    for (int oi = 0; oi < numOutcomes; oi++) {
      allOutcomesPattern[oi] = oi;
    }

    for (int pi = 0; pi < numPreds; pi++) {
      params[pi]=new MutableContext(allOutcomesPattern,new double[numOutcomes]);
      if (useAverage) averageParams[pi] = new MutableContext(allOutcomesPattern,new double[numOutcomes]);
      for (int aoi=0;aoi<numOutcomes;aoi++) {
        params[pi].setParameter(aoi, 0.0);
        if (useAverage) averageParams[pi].setParameter(aoi, 0.0);
      }
    }
    modelDistribution = new double[numOutcomes];

    display("Computing model parameters...\n");
    findParameters(iterations);
    display("...done.\n");

    /*************** Create and return the model ******************/
    String[] updatedPredLabels = predLabels;
    /*
    String[] updatedPredLabels = new String[pmap.size()];
    for (String pred : pmap.keySet()) {
      updatedPredLabels[pmap.get(pred)]=pred;
    }
    */
    if (useAverage) {
      return new PerceptronModel(averageParams, updatedPredLabels, outcomeLabels);
    }
    else {
      return new PerceptronModel(params, updatedPredLabels, outcomeLabels);
    }
  }

  private void findParameters(int iterations) {
    display("Performing " + iterations + " iterations.\n");
    for (int i = 1; i <= iterations; i++) {
      if (i < 10)
        display("  " + i + ":  ");
      else if (i < 100)
        display(" " + i + ":  ");
      else
        display(i + ":  ");
      nextIteration(i);
    }
    if (useAverage) {
      trainingStats(averageParams);
    }
    else {
      trainingStats(params);
    }
  }

  private void display(String s) {
    if (printMessages)
      System.out.print(s);
  }

  public void nextIteration(int iteration) {
    iteration--; //move to 0-based index
    int numCorrect = 0;
    int oei=0;
    int si=0;
    Map<String,Float>[] featureCounts = new Map[numOutcomes];
    for (int oi=0;oi<numOutcomes;oi++) {
      featureCounts[oi] = new HashMap<String,Float>();
    }
    PerceptronModel model = new PerceptronModel(params,predLabels,pmap,outcomeLabels);
    for (Sequence sequence : sequenceStream) {
      Event[] taggerEvents = sequenceStream.updateContext(sequence, model);
      Event[] events = sequence.getEvents();
      boolean update = false;
      for (int ei=0;ei<events.length;ei++,oei++) {
        if (!taggerEvents[ei].getOutcome().equals(events[ei].getOutcome())) {
          update = true;
          //break;
        }
        else {
          numCorrect++;
        }
      }
      if (update) {
        for (int oi=0;oi<numOutcomes;oi++) {
          featureCounts[oi].clear();
        }
        //System.err.print("train:");for (int ei=0;ei<events.length;ei++) {System.err.print(" "+events[ei].getOutcome());} System.err.println();
        //training feature count computation
        for (int ei=0;ei<events.length;ei++,oei++) {
          String[] contextStrings = events[ei].getContext();
          float values[] = events[ei].getValues();
          int oi = omap.get(events[ei].getOutcome());
          for (int ci=0;ci<contextStrings.length;ci++) {
            float value = 1;
            if (values != null) {
              value = values[ci];
            }
            Float c = featureCounts[oi].get(contextStrings[ci]);
            if (c == null) {
              c = value;
            }
            else {
              c+=value;
            }
            featureCounts[oi].put(contextStrings[ci], c);
          }
        }
        //evaluation feature count computation
        //System.err.print("test: ");for (int ei=0;ei<taggerEvents.length;ei++) {System.err.print(" "+taggerEvents[ei].getOutcome());} System.err.println();
        for (int ei=0;ei<taggerEvents.length;ei++) {
          String[] contextStrings = taggerEvents[ei].getContext();
          float values[] =taggerEvents[ei].getValues();
          int oi = omap.get(taggerEvents[ei].getOutcome());
          for (int ci=0;ci<contextStrings.length;ci++) {
            float value = 1;
            if (values != null) {
              value = values[ci];
            }
            Float c = featureCounts[oi].get(contextStrings[ci]);
            if (c == null) {
              c = -1*value;
            }
            else {
              c-=value;
            }
            if (c == 0f) {
              featureCounts[oi].remove(contextStrings[ci]);
            }
            else {
              featureCounts[oi].put(contextStrings[ci], c);
            }
          }
        }
        for (int oi=0;oi<numOutcomes;oi++) {
          for (String feature : featureCounts[oi].keySet()) {
            Integer pi = pmap.get(feature);
            if (pi != null) {
              //System.err.println(si+" "+outcomeLabels[oi]+" "+feature+" "+featureCounts[oi].get(feature));
              params[pi].updateParameter(oi, featureCounts[oi].get(feature));
              if (useAverage) {
                if (updates[pi][oi][VALUE] != 0) {
                  averageParams[pi].updateParameter(oi,updates[pi][oi][VALUE]*(numSequences*(iteration-updates[pi][oi][ITER])+(si-updates[pi][oi][EVENT])));
                  //System.err.println("p avp["+pi+"]."+oi+"="+averageParams[pi].getParameters()[oi]);
                }
                //System.err.println("p updates["+pi+"]["+oi+"]=("+updates[pi][oi][ITER]+","+updates[pi][oi][EVENT]+","+updates[pi][oi][VALUE]+") + ("+iteration+","+oei+","+params[pi].getParameters()[oi]+") -> "+averageParams[pi].getParameters()[oi]);
                updates[pi][oi][VALUE] = (int) params[pi].getParameters()[oi];
                updates[pi][oi][ITER] = iteration;
                updates[pi][oi][EVENT] = si;
              }
            }
          }
        }
        model = new PerceptronModel(params,predLabels,pmap,outcomeLabels);
      }
      si++;
    }
    //finish average computation
    double totIterations = (double) iterations*si;
    if (useAverage && iteration == iterations-1) {
      for (int pi = 0; pi < numPreds; pi++) {
        double[] predParams = averageParams[pi].getParameters();
        for (int oi = 0;oi<numOutcomes;oi++) {
          if (updates[pi][oi][VALUE] != 0) {
            predParams[oi] +=  updates[pi][oi][VALUE]*(numSequences*(iterations-updates[pi][oi][ITER])-updates[pi][oi][EVENT]);
          }
          if (predParams[oi] != 0) {
            predParams[oi] /=totIterations;
            averageParams[pi].setParameter(oi, predParams[oi]);
            //System.err.println("updates["+pi+"]["+oi+"]=("+updates[pi][oi][ITER]+","+updates[pi][oi][EVENT]+","+updates[pi][oi][VALUE]+") + ("+iterations+","+0+","+params[pi].getParameters()[oi]+") -> "+averageParams[pi].getParameters()[oi]);
          }
        }
      }
    }
    display(". ("+numCorrect+"/"+numEvents+") "+((double) numCorrect / numEvents) + "\n");
  }

  private void trainingStats(MutableContext[] params) {
    int numCorrect = 0;
    int oei=0;
    for (Sequence sequence : sequenceStream) {
      Event[] taggerEvents = sequenceStream.updateContext(sequence, new PerceptronModel(params,predLabels,outcomeLabels));
      for (int ei=0;ei<taggerEvents.length;ei++,oei++) {
        int max = omap.get(taggerEvents[ei].getOutcome());
        if (max == outcomeList[oei]) {
          numCorrect ++;
        }
      }
    }
    display(". ("+numCorrect+"/"+numEvents+") "+((double) numCorrect / numEvents) + "\n");
  }
}


text:
package com.github.fppt.jedismock.operations.strings;

import com.github.fppt.jedismock.operations.RedisCommand;
import com.github.fppt.jedismock.storage.RedisBase;
import com.github.fppt.jedismock.datastructures.Slice;

import java.util.List;

import static com.github.fppt.jedismock.Utils.convertToLong;

@RedisCommand("psetex")
class PSetEx extends SetEx {
    PSetEx(RedisBase base, List<Slice> params) {
        super(base, params);
    }

    @Override
    long timeoutToSet(List<Slice> params){
        return convertToLong(new String(params.get(1).data()));
    }
}


text:
<?php

class Plugin extends Common {

    protected $plugin;
    protected $link;
	protected $data;

    public function __construct() {
        parent::__construct();
        $this->plugin = $this->model("plugin");
        $this->data   = $this->plugin->where("dir=?", $this->namespace)->select(false);
		if (empty($this->data)) $this->adminMsg('插件尚未安装', url('admin/plugin'));
		if ($this->data['disable']) $this->adminMsg('插件尚未开启', url('admin/plugin'));
        $this->link   = $this->model("link");
		$this->assign(array(
            "admin_path"     => SITE_PATH . basename(VIEW_DIR) . "/admin/",
            "extension_path" => SITE_PATH . EXTENSION_PATH . "/",
        ));
    }

}


text:
/**
 * Common payload.
 */
#ifndef THEAPIPAYLOAD_h
#define THEAPIPAYLOAD_h

namespace theapi {

  class Payload {
    public:
      // Message types
      // ASCII printable characters so serial printing is simple.
      enum MsgType {
        GENERIC = 49,
        GARDEN,
        PING,
        CMD,
        ACK,
        SIGNAL,
        SOLAR,
      };
  };

}

// end namespace
#endif


text:
import logging

from rest_framework import permissions

from bluebottle.members.models import MemberPlatformSettings

logger = logging.getLogger(__name__)

class PermissionsException(Exception):
    pass

class IsOwner(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return obj.owner == request.user

class IsUser(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return obj.user == request.user

class BasePermission(permissions.BasePermission):
    """ BasePermission extends the standard BasePermission from DRF to include
    the ability to get the permissions without the request.

    Currently the `view` is being passed which then gives access to the request.

    TODO: it should be possible to get the permissions based on a `action`, `user`,
    and an optional `obj` which might be a parent type rather than the actual obj
    particularly if the permission being checked is the ability to create an obj

    """

    def get_view_model(self, view):
        model_cls = None
        try:
            model_cls = view.model
        except AttributeError:
            message = (
                'The related view `{}` does not have a model property.'.format(view.__class__.__name__),
                'Is this a legacy view using ResourcePermissions?'
            )
            raise PermissionsException(' '.join(message))

        return model_cls

    def has_object_permission(self, request, view, obj):
        """ This action is called from the views which include this permission.

        The call happens after the referenced obj has been fetched and will not be
        called if no object was found.

        Return `True` if permission is granted, `False` otherwise.
        """
        return self.has_object_action_permission(
            request.method, request.user, obj
        )

    def has_permission(self, request, view):
        """ This action is called from the views which include this permission.

        The call happens during view initialisation so it will be called with views returning
        a data set as well as a single object.

        Return `True` if permission is granted, `False` otherwise.
        """
        try:
            model_cls = self.get_view_model(view)
            return self.has_action_permission(
                request.method, request.user, model_cls
            )
        except TypeError as err:
            message = (
                '{} not implemented correctly.'.format(self.__class__.__name__),
                'Error: {}'.format(err.message)
            )
            raise PermissionsException(' '.join(message))
        except PermissionsException:
            return super(BasePermission, self).has_permission(request, view)

    def has_parent_permission(self, method, user, parent, model=None):
        """
        Check if user has permission on the parent obj

        Used by RelatedResource permission classes and for return related permissions
        """
        return True

    def has_object_action_permission(self, action, user, obj):
        """ Check if user has permission to access action on obj for the view.

        Used by both the DRF permission system and for returning permissions to the user.
        """

        message = 'has_object_action_permission() must be implemented on {}'.format(self)
        raise NotImplementedError(message)

    def has_action_permission(self, action, user, model_cls):
        """ Check if user has permission to access action for the view.

        Used by both the DRF permission system and for returning permissions to the user.
        """

        message = 'has_action_permission() must be implemented on {}'.format(self)
        raise NotImplementedError(message)

class IsOwnerOrReadOnly(BasePermission):
    def has_action_permission(self, action, user, model_cls):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return True

    def has_object_permission(self, request, view, obj):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return (request.method in permissions.SAFE_METHODS) or obj.owner == request.user

    def has_object_action_permission(self, action, user, obj):
        return (action in permissions.SAFE_METHODS) or obj.owner == user

class IsAuthenticated(BasePermission):
    def has_action_permission(self, action, user, obj):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return user.is_authenticated

    def has_object_permission(self, request, view, obj):
        """
        Return `True` if user is owner of the object granted, `False` otherwise.
        """
        return request.user.is_authenticated

    def has_object_action_permission(self, action, user, obj):
        return user.is_authenticated

class ResourcePermission(BasePermission, permissions.DjangoModelPermissions):
    perms_map = {
        'GET': ['%(app_label)s.api_read_%(model_name)s'],
        'OPTIONS': [],
        'HEAD': ['%(app_label)s.api_read_%(model_name)s'],
        'POST': ['%(app_label)s.api_add_%(model_name)s'],
        'PUT': ['%(app_label)s.api_change_%(model_name)s'],
        'PATCH': ['%(app_label)s.api_change_%(model_name)s'],
        'DELETE': ['%(app_label)s.api_delete_%(model_name)s'],
    }

    def has_object_action_permission(self, action, user, obj):
        return True

    def has_action_permission(self, action, user, model_cls):
        if model_cls:
            perms = self.get_required_permissions(action, model_cls)
            return user.has_perms(perms)
        else:
            return True

    def __repr__(self):
        return 'ResourcePermission'

class ResourceOwnerPermission(ResourcePermission):
    """ Allows access only to obj owner. """
    perms_map = {
        'GET': ['%(app_label)s.api_read_own_%(model_name)s'],
        'OPTIONS': [],
        'HEAD': ['%(app_label)s.api_read_own_%(model_name)s'],
        'POST': ['%(app_label)s.api_add_own_%(model_name)s'],
        'PUT': ['%(app_label)s.api_change_own_%(model_name)s'],
        'PATCH': ['%(app_label)s.api_change_own_%(model_name)s'],
        'DELETE': ['%(app_label)s.api_delete_own_%(model_name)s'],
    }

    def has_object_action_permission(self, action, user, obj):
        return user == obj.owner

class RelatedResourceOwnerPermission(ResourceOwnerPermission):
    """ Allows access only to obj owner of related resource.

    This class assumes the child resource has a `parent` property which will return the parent object.
    """

    def has_parent_permission(self, action, user, parent, model=None):
        return user == parent.owner

    def has_object_action_permission(self, action, user, obj):
        return self.has_parent_permission(action, user, obj.parent)

class TenantConditionalOpenClose(BasePermission):
    """ Allows access only to authenticated users. """

    def has_object_action_permission(self, action, user, obj):
        try:
            settings = MemberPlatformSettings.objects.get()
            if settings.closed:
                return user and user.is_authenticated
        except AttributeError:
            pass
        return True

    def has_action_permission(self, action, user, model_cls):
        try:
            settings = MemberPlatformSettings.objects.get()
            if settings.closed:
                return user and user.is_authenticated
        except AttributeError:
            pass
        return True

class AuthenticatedOrReadOnlyPermission(IsAuthenticated):
    """ Allow access if the user is authenticated or the request uses a safe action. """

    def has_action_permission(self, action, user, model_cls):
        if action in permissions.SAFE_METHODS:
            return True
        return user and user.is_authenticated

def OneOf(*permission_classes):
    class OneOf(BasePermission):
        permissions = permission_classes

        def has_parent_permission(self, action, user, parent, model):
            return any(
                (
                    perm().has_parent_permission(action, user, parent, model) and
                    perm().has_action_permission(action, user, model)
                ) for perm in self.permissions
            )

        def has_object_action_permission(self, action, user, obj):
            return any(
                (
                    perm().has_object_action_permission(action, user, obj) and
                    perm().has_action_permission(action, user, obj._meta.model)
                ) for perm in self.permissions
            )

        def has_action_permission(self, *args, **kwargs):
            return any(
                perm().has_action_permission(*args, **kwargs) for
                perm in self.permissions
            )

    return OneOf


text:
<?php

namespace ByCedric\Allay\Exceptions;

use Illuminate\Http\Response;

class ResourceNotFoundException extends ResourceException
{
    /**
     * Create a new resource not found exception.
     *
     * @param  string     $resource
     * @param  \Exception $previous (default: null)
     * @return void
     */
    public function __construct($resource, \Exception $previous = null)
    {
        parent::__construct(
            $resource,
            "The (requested) resource \"$resource\" was not found.",
            Response::HTTP_NOT_FOUND,
            $previous
        );
    }
}


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

<title>JsonFilter (Jackson JSON Processor)</title>
<meta name="date" content="2013-07-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element

org.codehaus.jackson.map.annotate

Annotation Type JsonFilter

@Target(value=TYPE)
@Retention(value=RUNTIME)
public @interface JsonFilter

Annotation used to indicate which logical filter is to be used
 for filtering out properties of type (class) annotated;
 association made by this annotation declaring ids of filters,
 and  ObjectMapper (or objects
 it delegates to) providing matching filters by id.
 Filters to use are of type
 BeanPropertyFilter and
 are registered through ObjectMapper

Since:

1.7

Required Element Summary

Required Elements

Modifier and Type
Required Element and Description

String
value

Id of filter to use; if empty String (""), no filter is to be used.

Element Detail

value

public abstract String value

Id of filter to use; if empty String (""), no filter is to be used.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Required |

Optional

Detail:

Element


text:
require "spec_helper"

RSpec.describe SendOtp do
  it "has a version number" do
    expect(SendOtp::VERSION).not_to be nil
  end

end


text:
package org.apache.ivory.util;

import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

@Test
public class StartupPropertiesTest {
    @BeforeClass
    public void setUp() {
        StartupProperties.get();
    }

    public void testDomain() {
        StartupProperties props = (StartupProperties) StartupProperties.get();
        assertEquals("debug", props.getDomain());
        //assertEquals("vm://localhost", props.get("broker.url"));
        assertEquals("IVORY.ENTITY.TOPIC", props.get("entity.topic"));
    }
}


text:
'use strict';

import * as State from 'core/state';

// Most of this logic has been moved to filter.model.service.js, so these act more as integration tests
describe('Service: securityGroupFilterService', function() {
  var app;
  var resultJson;

  beforeEach(() => State.initialize());

  beforeEach(function() {
    app = {
      securityGroups: {
        data: [
          { name: 'sg-1', region: 'us-east-1', account: 'test', vpcName: '', usages: {} },
          { name: 'sg-1', region: 'us-west-1', account: 'test', vpcName: 'main', usages: {} },
          { name: 'sg-2', region: 'us-east-1', account: 'prod', vpcName: '', usages: {} },
        ],
      },
    };
    resultJson = [
      {
        heading: 'us-east-1',
        vpcName: '',
        securityGroup: app.securityGroups.data[0],
        isManaged: false,
        managedResourceSummary: undefined,
      },
      {
        heading: 'us-west-1 (main)',
        vpcName: 'main',
        securityGroup: app.securityGroups.data[1],
        isManaged: false,
        managedResourceSummary: undefined,
      },
      {
        heading: 'us-east-1',
        vpcName: '',
        securityGroup: app.securityGroups.data[2],
        isManaged: false,
        managedResourceSummary: undefined,
      },
    ];
    State.SecurityGroupState.filterModel.asFilterModel.clearFilters();
  });

  describe('Updating the firewall group', function() {
    it('no filter: should be transformed', function() {
      var expected = [
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ];
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual(expected);
    });

    describe('filter by search', function() {
      it('should add searchField when filter is not prefixed with vpc:', function() {
        expect(app.securityGroups.data.length).toBe(3);
        app.securityGroups.data.forEach(group => {
          expect(group.searchField).toBeUndefined();
        });
        State.SecurityGroupState.filterModel.asFilterModel.sortFilter.filter = 'main';
        State.SecurityGroupState.filterService.updateSecurityGroups(app);
        app.securityGroups.data.forEach(group => {
          expect(group.searchField).not.toBeUndefined();
        });
      });
    });

    describe('filter by vpc', function() {
      it('should filter by vpc name as an exact match', function() {
        State.SecurityGroupState.filterModel.asFilterModel.sortFilter.filter = 'vpc:main';
        State.SecurityGroupState.filterService.updateSecurityGroups(app);
        expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
          {
            heading: 'test',
            subgroups: [
              { heading: 'sg-1', subgroups: [resultJson[1]], isManaged: false, managedResourceSummary: undefined },
            ],
          },
        ]);
      });

      it('should not match on partial vpc name', function() {
        State.SecurityGroupState.filterModel.asFilterModel.sortFilter.filter = 'vpc:main-old';
        State.SecurityGroupState.filterService.updateSecurityGroups(app);
        expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([]);
      });
    });

    describe('filtering by account type', function() {
      it('1 account filter: should be transformed showing only prod accounts', function() {
        State.SecurityGroupState.filterModel.asFilterModel.sortFilter.account = { prod: true };
        State.SecurityGroupState.filterService.updateSecurityGroups(app);
        expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
          {
            heading: 'prod',
            subgroups: [
              { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
            ],
          },
        ]);
      });

      it('All account filters: should show all accounts', function() {
        State.SecurityGroupState.filterModel.asFilterModel.sortFilter.account = { prod: true, test: true };
        State.SecurityGroupState.filterService.updateSecurityGroups(app);
        expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
          {
            heading: 'prod',
            subgroups: [
              { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
            ],
          },
          {
            heading: 'test',
            subgroups: [
              {
                heading: 'sg-1',
                subgroups: [resultJson[0], resultJson[1]],
                isManaged: false,
                managedResourceSummary: undefined,
              },
            ],
          },
        ]);
      });
    });
  });

  describe('filter by region', function() {
    it('1 region: should filter by that region', function() {
      State.SecurityGroupState.filterModel.asFilterModel.sortFilter.region = { 'us-east-1': true };

      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            { heading: 'sg-1', subgroups: [resultJson[0]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
      ]);
    });

    it('All regions: should show all load balancers', function() {
      State.SecurityGroupState.filterModel.asFilterModel.sortFilter.region = { 'us-east-1': true, 'us-west-1': true };

      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ]);
    });
  });

  describe('filtered by provider type', function() {
    beforeEach(function() {
      app.securityGroups.data[0].provider = 'aws';
      app.securityGroups.data[1].provider = 'gce';
      app.securityGroups.data[2].provider = 'aws';
    });
    it('should filter by aws if checked', function() {
      State.SecurityGroupState.filterModel.asFilterModel.sortFilter.providerType = { aws: true };
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            { heading: 'sg-1', subgroups: [resultJson[0]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
      ]);
    });

    it('should not filter if no provider type is selected', function() {
      State.SecurityGroupState.filterModel.asFilterModel.sortFilter.providerType = undefined;
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ]);
    });

    it('should not filter if all provider are selected', function() {
      State.SecurityGroupState.filterModel.asFilterModel.sortFilter.providerType = { aws: true, gce: true };
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ]);
    });
  });

  describe('group diffing', function() {
    beforeEach(function() {
      app.securityGroups.data[0].stringVal = 'original';
      app.securityGroups.data[1].stringVal = 'should be deleted';
      State.SecurityGroupState.filterModel.asFilterModel.groups = [
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ];
    });

    it('adds a group when new one provided', function() {
      app.securityGroups.data.push({
        name: 'sg-1',
        account: 'management',
        region: 'us-east-1',
        vpcName: '',
      });
      var newGroup = {
        heading: 'management',
        subgroups: [
          {
            heading: 'sg-1',
            subgroups: [
              {
                heading: 'us-east-1',
                vpcName: '',
                securityGroup: app.securityGroups.data[3],
                isManaged: false,
                managedResourceSummary: undefined,
              },
            ],
            isManaged: false,
            managedResourceSummary: undefined,
          },
        ],
      };
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        newGroup,
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ]);
    });

    it('adds a subgroup when new one provided', function() {
      app.securityGroups.data.push({
        name: 'sg-3',
        account: 'prod',
        region: 'eu-west-1',
        vpcName: '',
      });
      var newSubGroup = {
        heading: 'sg-3',
        subgroups: [
          {
            heading: 'eu-west-1',
            vpcName: '',
            securityGroup: app.securityGroups.data[3],
            isManaged: false,
            managedResourceSummary: undefined,
          },
        ],
        isManaged: false,
        managedResourceSummary: undefined,
      };
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
            newSubGroup,
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
          ],
        },
      ]);
    });

    it('adds a sub-subgroup when new one provided', function() {
      app.securityGroups.data.push({
        name: 'sg-2',
        account: 'test',
        region: 'eu-west-1',
        vpcName: '',
      });
      var newSubsubGroup = {
        heading: 'eu-west-1',
        vpcName: '',
        securityGroup: app.securityGroups.data[3],
        isManaged: false,
        managedResourceSummary: undefined,
      };
      State.SecurityGroupState.filterService.updateSecurityGroups(app);
      expect(State.SecurityGroupState.filterModel.asFilterModel.groups).toEqual([
        {
          heading: 'prod',
          subgroups: [
            { heading: 'sg-2', subgroups: [resultJson[2]], isManaged: false, managedResourceSummary: undefined },
          ],
        },
        {
          heading: 'test',
          subgroups: [
            {
              heading: 'sg-1',
              subgroups: [resultJson[0], resultJson[1]],
              isManaged: false,
              managedResourceSummary: undefined,
            },
            { heading: 'sg-2', subgroups: [newSubsubGroup], isManaged: false, managedResourceSummary: undefined },
          ],
        },
      ]);
    });
  });
});


text:
"""Install tensor2tensor."""

from setuptools import find_packages
from setuptools import setup

setup(
    name='tensor2tensor',
    version='1.9.0',
    description='Tensor2Tensor',
    author='Google Inc.',
    author_email='no-reply@google.com',
    url='http://github.com/tensorflow/tensor2tensor',
    license='Apache 2.0',
    packages=find_packages(),
    package_data={
        'tensor2tensor.data_generators': ['test_data/*'],
        'tensor2tensor.data_generators.wikisum': ['test_data/*'],
        'tensor2tensor.visualization': [
            'attention.js', 'TransformerVisualization.ipynb'
        ],
    },
    scripts=[
        'tensor2tensor/bin/t2t-trainer',
        'tensor2tensor/bin/t2t-datagen',
        'tensor2tensor/bin/t2t-decoder',
        'tensor2tensor/bin/t2t-make-tf-configs',
        'tensor2tensor/bin/t2t-exporter',
        'tensor2tensor/bin/t2t-query-server',
        'tensor2tensor/bin/t2t-insights-server',
        'tensor2tensor/bin/t2t-avg-all',
        'tensor2tensor/bin/t2t-bleu',
        'tensor2tensor/bin/t2t-translate-all',
    ],
    install_requires=[
        'bz2file',
        'flask',
        'future',
        'gevent',
        'google-api-python-client',
        'gunicorn',
        'gym',
        'h5py',
        'numpy',
        'oauth2client',
        'requests',
        'scipy',
        'sympy',
        'six',
        'tqdm',
    ],
    extras_require={
        'tensorflow': ['tensorflow>=1.9.0'],
        'tensorflow_gpu': ['tensorflow-gpu>=1.9.0'],
        'tensorflow-hub': ['tensorflow-hub>=0.1.1'],
        'tests': [
            'absl-py',
            'pytest>=3.8.0',
            'mock',
            'pylint',
            'jupyter',
            'gsutil',
            'matplotlib',
            # Need atari extras for Travis tests, but because gym is already in
            # install_requires, pip skips the atari extras, so we instead do an
            # explicit pip install gym[atari] for the tests.
            # 'gym[atari]',
        ],
        'allen': ['Pillow==5.1.0', 'pandas==0.23.0'],
    },
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Topic :: Scientific/Engineering :: Artificial Intelligence',
    ],
    dependency_links=[
        'git+https://github.com/tensorflow/cleverhans.git#egg=cleverhans'
    ],
    keywords='tensorflow machine learning',
)


text:
using System.Collections.Generic;
using System.Xml.Serialization;

namespace KayakoRestApi.Core.Tickets
{
    [XmlRoot("customfields")]
    public class TicketCustomFields
    {
        [XmlElement("group")]
        public List<TicketCustomFieldGroup> FieldGroups { get; set; }

        public TicketCustomFields()
        {
            FieldGroups = new List<TicketCustomFieldGroup>();
        }
    }
}