text:
layout: post
permalink: /karekano/
title: Kare Kano DVDs
date: 2015-05-08 23:04
---

One day, I've stumbled upon [Kare Kano][kknj-anidb] anime,
but after searching for rips for a while, I did not find
a single DVDRip I would consider acceptable.

So I thought: heeey, maybe I should rip the DVD myself?

God, how wrong I was.

In this post I'm going to write about the shit
I found while working with Kare Kano DVDs.

I'm writing this post not to be informative,
but for myself to be done with this DVD.  Forever.

**Disclaimer:** for all intents and purposes the reader can assume
that the author of this post is a crazy uninformed lunatic.

## Getting the DVDs

It turns out, there are several *different* releases of Kare Kano.
At some point, I've had four different sets of DVDs downloaded:
R1, R2J, Spanish, and homemade Russian.

The Spanish one turned out to be a PAL DVD,
and anime is not supposed to be 25 or 50 fps.

Homemade russian release turned out to be R1 release without english streams
and with additional russian subtitles and sound streams.

Now, downloading the R2J release turned out to be somehow problematic.
At the time I tried to do it, in 2010, there were no seeds in any of
Kare Kano R2J torrents.  I could not even find it on some closed trackers.

When I finally found [the][kknj-nyaa] [torrent][kknj-btih] I've been looking for so long,
there was only one seeder on that torrent.
The download speed varied from 5 to 19 kilobytes per second.
And he was not even online all the time.

When I put his IP into maxmind geoIP tool, it spewed out:

    Russia, SibirTelecom, <some-small-and-distant-city>

<big>ಠ\_ಠ</big>

So I've been downloading 45 gigabytes of Kare Kano in
the course of 3 months from some guy in deep Siberia.

## How do I DVDRIP?

After reading some guides on Doom9 forums and avisynth manuals,
I decided to look for anime ripping communities.
I found #raw-providers IRC channel on Rizon, and told them I want to rip Kare Kano.

To paraphrase modestly, they strongly dismissed the idea of ripping that DVD.

They had Yousei, who was a DVDRip wizard.
Just to give you a taste of what he did: [screenshot1](yousei-gundumb-1.png), [screenshot2](yousei-gundumb-2.png).

That's a DVDRip.  There are BDs that are worse than that.
[That release][yousei-gundumb] is probably the strongest argument in favor of anime upscales.

And he told me to drop the idea of ripping Kare Kano.

## What's telecine?

We might want to know how the DVD we have was made.

Anime used to be produced using [cels][cels-wiki], which were shot on 24 fps film.
Kare Kano was produced this way.

![Gainax burning Kare Kano cels](gainax-burning-cels.jpg)
*A screenshot from video of Gainax burning Kare Kano cels; episode 19, ending*

Then we got the <sarcasm>amazing</sarcasm> thechnology of digital video distribution — [DVD][deebueedee].
Existing anime had to be digitized, and telecine does the job.

> Telecine is the process of transferring motion picture film into video and is performed in a color suite.
>
> - [Wikipedia][telecine-wiki]

But there is a problem: film has 24 fps, and DVD supports only 25 or 29.97 fps video, interlaced or progressive.

Wait?  Not exactly 30 fps?  30000/1001 fps?  What sorcery is this?  We'll look into that later.

Okay, so how does one fit 24 fps video into a 30-ish fps video?
If we look at given framerates, we'll see that 24/30 = 4/5,
so if we somehow convert 4 frames of given 24 fps video to 5 frames, we'll get 30 fps.
It is possible with [2:3 pulldown][32pulldown-wiki].

![2:3 pulldown](32pulldown.svg)
*2:3 pulldown, explained by a picture from Wikipedia*

Pulldown is producing *interlaced* video meaning there will be "combs".

I would describe the 2:3 pulldown algorithm in python pseudocode:

```python
from itertools import cycle
alternating = cycle([Even, Odd]) # alternate between even and odd output fields
pattern = cycle([2, 3])          # the name comes from this field pattern
for frame in input:
    for _ in range(next(pattern)):           # output N fields
        yield first.field(next(alternating)) # output the corresponding field
```

And to get 30-ish fps, we also need to slow down
the playback by a factor of 1000/1001 at some point.

The 2:3 pulldown pattern can be observed in first frames of Kare Kano:

<video src="whats-telecine.webm" controls loop>What's telecine</video>
*kare kano, episode 01, first seconds; picture is anamorhpic*

Well, *obviously* we can deal with that.  Avisynth has plugins for inverse telecine: [tfm][tfm], [tdecimate][tdecimate].

TFM is matching the fields, and TDecimate is throwing away unmatched and doubled frames.

Let's see how it works:

```
mpeg2source("vts_01_1.d2v")
tfm(pp=1) // don't interpolate unmatched frames
tdecimate()
trim(2518,2525)
// avs2yuv ivtc.avs -o - | ffmpeg -r 3 -i - -c:v vp9 -b:v 0 -crf 18 whats-ivtc.webm
```

<video src="whats-ivtc.webm" controls loop>What's IVTC</video>
*kare kano, episode 01, first seconds, IVTC; picture is anamorphic*

That looks promising!

However, my hope of easy Kare Kano rip died really fast.

## Gainax-style digital video effects circa 1998

For some reason, Gainax decided that adding 60-ish fps
interlaced video effects to the telecined video is a good idea.

<video src="kknj-huehuehue.webm" controls loop>Miyazawa laughing</video>
*Miyazawa laughing at Gainax digital video processing; episode 01; picture is anamorphic*

In the video clip above you can see that "ふ" hieroglyphs are always interlaced.
It is a purely interlaced 60-ish fps effect.
The "fufufu" was added in a digital way, after telecine.

This means several extremely unpleasant things.

- some parts of the video MUST be motion-interpolated and to produce constant framerate video
- some parts of the video MUST be field-interpolated to produce progressive video
- detecting digitally edited parts has to be done manually

But wait, there is more!

## Temporal Scanline Blending

The term in this headline is stolen from a handy guide [Analysing Your DVD Footage][dvd-analysis].

![a picture of two fields blending partially](blended-field.png)
*a picture of Miyazawa partially blending with the door; episode 05; picture is anamorphic*

Hm, what's that?  Let's inspect individual fields.

<video src="kknj-why.webm" controls loop>Gainax, why?</video>
*individual fields, upscaled to double size using nnedi; episode 05; picture is anamorphic*

What we see here is film frames changing in the middle of the output field.
The next field after that is slightly blended too.

I tried to fix this issue using various de-blending plugins and
writing a plugin on my own, but I failed to reverse this problem.
Partially, because there is an inevitable information loss involved:
after fields are blended in the analog world, the pixels
are quantized in 8 bit (probably?) and then lossily encoded with MPEG2.
So even if I *know* perfect blending parameters and frame change timing,
MPEG2 is introducing a lossy step, and trying to de-blend will cause
artifacts from both frames to surface.
The quantization step adds some problem to de-blending too.

I've inspected at all individual frames in the first episode
and wrote down blending parameters for all required frames.
Of course, there was a lot of automation involved.
However, I was not happy with the final de-blending result.

Pretty early into this process I discovered *why* this happens.
The blending pattern repeats approximately every 1000 frames.
The line of the blending frames moves "up" across the whole
field in a course of ~500 frames.

My hypothesis on the cause of this artifact is that during telecine process,
film has been displayed at 24.00 frames per second to a telecine machine
that took 59.94 fields per second, and sometimes frames were changing during
the field scan.  The difference in scanning speed of 1000/1001 causes
the line of blending to move along the field.

Since editing was partially done in the digital world, each digital "cut" caused
blend pattern to "reset", which invalidated the simple formula for blend position.

Quoting the "Analysing Your DVD Footage" guide on how bad it is:

> This is the nastiest of the nasty Telecine methods and
can be seen in every Gainax production from Otaku no Video
to Kare Kano and in many more late 80s to late 90s anime.
It's the reason Eva Renewal had to be made. \[...\]
>
> This stuff is nigh impossible to recover at the moment.
There are no tools available at our level which
can deal with field blending like this \[...\]
>
> It's nasty stuff - especially in pans where you can
end up with an IVTC process giving you a scene with
horizontal motion with the top half moving in one
frame and the bottom half catching it up in the next frame. Evil.

That article too has a similar explanation for how it happens.

## Film editing with scissors and office tape

Kare Kano was partially edited in film and partially in the digital world.
The first one is visible as a jagged film edge sometimes getting on the screen.
The second one sometimes appears as video cut in between frame fields.

![film edge](film-edge.png)
*a film edge visible on the screen; episode 02, picture is upscaled from one field with nnedi*

I kind of like the first artifact because it adds vintage analog
feel to the video, however it is still a video artifact.

These artifacts are *minor*, but I decided to include them anyway.

## Dot crawl

This artifact is caused by interference between luma signal and chroma signal,
due to <sarcasm>excellent</sarcasm> implementation of color television.
It happens in composite video, NTSC and PAL.

![zooom!](dot-crawl-zoom.png)
*I see dots crawling in your eyes, Miyazawa; episode 01, 300% zoom with nearest point interpolation*

You can observe the checkerboard pattern on the edge of colorful regions.
There are avisynth plugins to deal with this,
and you have to tune the "knobs" to do it right.

## Summary

The process of producing Kare Kano DVDs is a disaster.
Almost every step after film is a terrible information loss.
Artifacts are clearly visible and cannot be reversed.

Several artifacts are caused by NTSC color implementation and non-integral framerate.

- film is edited with visible cuts and gluing.
- telecine is done with incorrect framerate, causing field blends and converting video to interlaced.
  this step is the worst of all.  Literally Hitler.
- the video is then transported using composite video signal, causing dot crawl.
- video is edited digitally, adding pure interlaced 60-ish fps effects.
- video is lossily encoded using MPEG2 and packed into DVD.

I am not going to work with Kare Kano DVDs in my life again.

Fuck. That. Shit.

If you happen to know where to get Kare Kano film/negatives,
please drop an email to [m1el.2027@gmail.com](m1el.2027@gmail.com).
I am willing to scan and compile them myself.

And a comics, just for lulz:

![awesome producing comics](awesome-producing-comics.png)
*if you ever thought I have drawing skills, you might be disappointed*

[kknj-anidb]: http://anidb.net/a199
[kknj-nyaa]: http://www.nyaa.se/?page=view&tid=133764
[kknj-btih]: https://www.google.com/search?q=758AACC654A59D4364A31A0E86F69D33997D4B34
[yousei-gundumb]: https://www.google.com/search?q=D41EA91AA95709E130BFB861A1879F45F68F168A
[telecine-wiki]: http://en.wikipedia.org/wiki/Telecine
[cels-wiki]: http://en.wikipedia.org/wiki/Traditional_animation#Cels
[deebueedee]: https://translate.google.com/translate_tts?ie=UTF-8&q=DVD&tl=ja&total=1&idx=0&textlen=3
[32pulldown-wiki]: http://en.wikipedia.org/wiki/Three-two_pull_down
[tfm]: http://avisynth.org.ru/docs/english/externalfilters/tivtc_tfm.htm
[tdecimate]: http://avisynth.org.ru/docs/english/externalfilters/tivtc_tdecimate.htm
[dvd-analysis]: http://www.animemusicvideos.org/guides/avtech/videogetb2a.html


text:
var win = Ti.UI.createWindow({
	backgroundColor:'white'
});
var label = Ti.UI.createLabel();
win.add(label);
win.open();

// TODO: write your module tests here
var assetslibrary = require('ti.assetslibrary');
Ti.API.info("module is => " + assetslibrary);

label.text = assetslibrary.example();

Ti.API.info("module exampleProp is => " + assetslibrary.exampleProp);
assetslibrary.exampleProp = "This is a test value";

if (Ti.Platform.name == "android") {
	var proxy = assetslibrary.createExample({
		message: "Creating an example Proxy",
		backgroundColor: "red",
		width: 100,
		height: 100,
		top: 100,
		left: 150
	});

	proxy.printMessage("Hello world!");
	proxy.message = "Hi world!.  It's me again.";
	proxy.printMessage("Hello world!");
	win.add(proxy);
}

redpajama_set_name: RedPajamaGithub


text:
from gherkin3.token_scanner import TokenScanner
from gherkin3.parser import Parser
from gherkin3.errors import ParserError
from nose.tools import assert_equals, assert_raises

def test_parser():
    parser = Parser()
    feature = parser.parse(TokenScanner("Feature: Foo"))
    expected = {'comments': [],
     'keyword': u'Feature',
     'language': 'en',
     'location': {'column': 1, 'line': 1},
     'name': u'Foo',
     'scenarioDefinitions': [],
     'tags': [],
     'type': 'Feature'}

    assert_equals(expected, feature)

def test_parse_multiple_features():
    parser = Parser()
    f1 = parser.parse(TokenScanner("Feature: 1"))
    f2 = parser.parse(TokenScanner("Feature: 2"))

    assert_equals("1", f1['name'])
    assert_equals("2", f2['name'])

def test_parse_feature_after_parser_error():
    parser = Parser()
    with assert_raises(ParserError):
        parser.parse(TokenScanner('# a comment\n' +
                                  'Feature: Foo\n' +
                                  '  Scenario: Bar\n' +
                                  '    Given x\n' +
                                  '      ```\n' +
                                  '      unclosed docstring\n'))
    feature = parser.parse(TokenScanner('Feature: Foo\n' +
                                        '  Scenario: Bar\n' +
                                        '    Given x\n'
                                        '      """\n'
                                        '      closed docstring\n'
                                        '      """\n'))
    expected = [{
        'name': u'Bar',
        'keyword': u'Scenario',
        'tags': [],
        'steps': [{
            'text': u'x',
            'type': 'Step',
            'location': {'column': 5, 'line': 3},
            'keyword': u'Given ',
            'argument': {
                'content': u'closed docstring',
                'type': 'DocString',
                'contentType': u'',
                'location': {'column': 7, 'line': 4}}}],
        'location': {'column': 3, 'line': 2},
        'type': 'Scenario'}]

    assert_equals(expected, feature['scenarioDefinitions'])


text:
module Influxer
  module TimestampQuoting #:nodoc:
    TIME_FACTORS = {
      "ns" => 1_000_000_000,
      "ms" => 1_000,
      "s" => 1
    }.freeze

    DEFAULT_PRECISION = "ns"

    # Quote timestamp
    # rubocop: disable Metrics/MethodLength, Metrics/AbcSize
    def quote_timestamp(val, client)
      if Influxer.config.time_duration_suffix_enabled
        precision = if TIME_FACTORS.key?(client.time_precision)
          client.time_precision
        else
          DEFAULT_PRECISION
        end
        return quote_timestamp_with_suffix(val, precision)
      end

      if !TIME_FACTORS.key?(client.time_precision) &&
          !val.is_a?(Numeric)
        warn(
          "Influxer doesn't automatically cast Time and String values " \
          "to '#{client.time_precision}' precision. " \
          "Please, convert to numeric value yourself"
        )
        return val
      end

      factorize_timestamp(val, TIME_FACTORS.fetch(client.time_precision))
    end
    # rubocop: enable Metrics/MethodLength, Metrics/AbcSize

    def quote_timestamp_with_suffix(val, precision)
      "#{factorize_timestamp(val, TIME_FACTORS.fetch(precision))}#{precision}"
    end

    def quote_timestamp_for_write(val, client)
      if !TIME_FACTORS.key?(client.time_precision) &&
          !val.is_a?(Numeric)
        raise ArgumentError,
              "Influxer doesn't support quoting #{val} " \
              " with '#{client.time_precision}' precision. " \
              "Please, convert to numeric value yourself"
      end

      factorize_timestamp(val, TIME_FACTORS.fetch(client.time_precision))
    end

    def factorize_timestamp(val, factor)
      case val
      when Numeric
        (val.to_f * factor).to_i
      when String
        (Time.parse(val).to_r * factor).to_i
      when Date, DateTime
        (val.to_time.to_r * factor).to_i
      when Time
        (val.to_r * factor).to_i
      end
    end
  end
end


text:
import noticeWarning from '../lerna-sandbox-module-a/index.js';

noticeWarning('test');


text:
using MeasurementConverter.ViewModel;
using Xamarin.Forms;

namespace MeasurementConverter.View
{
    public partial class MunitConverter : ContentPage
    {
        public MunitConverter()
        {
            InitializeComponent();

            BindingContext = new MunitConverterViewModel();
        }
    }
}


text:
namespace clang {

class CompilerInvocation;
class DiagnosticConsumer;
class FileManager;
class PCHContainerOperations;

namespace include_fixer {

class IncludeFixerActionFactory : public clang::tooling::ToolAction {
public:
  /// \param SymbolIndexMgr A source for matching symbols to header files.
  /// \param Contexts The contexts for the symbols being queried.
  /// \param StyleName Fallback style for reformatting.
  /// \param MinimizeIncludePaths whether inserted include paths are optimized.
  IncludeFixerActionFactory(SymbolIndexManager &SymbolIndexMgr,
                            std::vector<IncludeFixerContext> &Contexts,
                            StringRef StyleName,
                            bool MinimizeIncludePaths = true);

  ~IncludeFixerActionFactory() override;

  bool
  runInvocation(std::shared_ptr<clang::CompilerInvocation> Invocation,
                clang::FileManager *Files,
                std::shared_ptr<clang::PCHContainerOperations> PCHContainerOps,
                clang::DiagnosticConsumer *Diagnostics) override;

private:
  /// The client to use to find cross-references.
  SymbolIndexManager &SymbolIndexMgr;

  /// Multiple contexts for files being processed.
  std::vector<IncludeFixerContext> &Contexts;

  /// Whether inserted include paths should be optimized.
  bool MinimizeIncludePaths;

  /// The fallback format style for formatting after insertion if no
  /// clang-format config file was found.
  std::string FallbackStyle;
};

/// Create replacements, which are generated by clang-format, for the
/// missing header and mising qualifiers insertions. The function uses the
/// first header for insertion.
///
/// \param Code The source code.
/// \param Context The context which contains all information for creating
/// include-fixer replacements.
/// \param Style clang-format style being used.
/// \param AddQualifiers  Whether we should add qualifiers to all instances of
/// an unidentified symbol.
///
/// \return Formatted replacements for inserting, sorting headers and adding
/// qualifiers on success; otherwise, an llvm::Error carrying llvm::StringError
/// is returned.
llvm::Expected<tooling::Replacements> createIncludeFixerReplacements(
    StringRef Code, const IncludeFixerContext &Context,
    const format::FormatStyle &Style = format::getLLVMStyle(),
    bool AddQualifiers = true);

/// Handles callbacks from sema, does the include lookup and turns it into an
/// IncludeFixerContext.
class IncludeFixerSemaSource : public clang::ExternalSemaSource {
public:
  explicit IncludeFixerSemaSource(SymbolIndexManager &SymbolIndexMgr,
                                  bool MinimizeIncludePaths,
                                  bool GenerateDiagnostics)
      : SymbolIndexMgr(SymbolIndexMgr),
        MinimizeIncludePaths(MinimizeIncludePaths),
        GenerateDiagnostics(GenerateDiagnostics) {}

  void setCompilerInstance(CompilerInstance *CI) { this->CI = CI; }
  void setFilePath(StringRef FilePath) { this->FilePath = FilePath; }

  /// Callback for incomplete types. If we encounter a forward declaration we
  /// have the fully qualified name ready. Just query that.
  bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc,
                                        clang::QualType T) override;

  /// Callback for unknown identifiers. Try to piece together as much
  /// qualification as we can get and do a query.
  clang::TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
                                    int LookupKind, Scope *S, CXXScopeSpec *SS,
                                    CorrectionCandidateCallback &CCC,
                                    DeclContext *MemberContext,
                                    bool EnteringContext,
                                    const ObjCObjectPointerType *OPT) override;

  /// Get the minimal include for a given path.
  std::string minimizeInclude(StringRef Include,
                              const clang::SourceManager &SourceManager,
                              clang::HeaderSearch &HeaderSearch) const;

  /// Get the include fixer context for the queried symbol.
  IncludeFixerContext getIncludeFixerContext(
      const clang::SourceManager &SourceManager,
      clang::HeaderSearch &HeaderSearch,
      ArrayRef<find_all_symbols::SymbolInfo> MatchedSymbols) const;

  /// Get the global matched symbols.
  ArrayRef<find_all_symbols::SymbolInfo> getMatchedSymbols() const {
    return MatchedSymbols;
  }

private:
  /// Query the database for a given identifier.
  std::vector<find_all_symbols::SymbolInfo>
  query(StringRef Query, StringRef ScopedQualifiers, tooling::Range Range);

  CompilerInstance *CI;

  /// The client to use to find cross-references.
  SymbolIndexManager &SymbolIndexMgr;

  /// The information of the symbols being queried.
  std::vector<IncludeFixerContext::QuerySymbolInfo> QuerySymbolInfos;

  /// All symbol candidates which match QuerySymbol. We only include the first
  /// discovered identifier to avoid getting caught in results from error
  /// recovery.
  std::vector<find_all_symbols::SymbolInfo> MatchedSymbols;

  /// The file path to the file being processed.
  std::string FilePath;

  /// Whether we should use the smallest possible include path.
  bool MinimizeIncludePaths = true;

  /// Whether we should generate diagnostics with fixits for missing symbols.
  bool GenerateDiagnostics = false;
};
} // namespace include_fixer
} // namespace clang

#endif // LLVM_CLANG_TOOLS_EXTRA_INCLUDE_FIXER_INCLUDEFIXER_H


text:
({
	PANELS_OWNER    : {},  // Owner relationship who creates the panel (key) owned by -> value
    PANELS_STACK    : [],  // The Panel Stack ordering
    PANELS_INSTANCE : {},  // Registered instances
    containerManager: null,  // a reference to containerManager

	initialize: function(cmp) {
        var containerManager = this.cmLib.containerManager;
        var sharedContainer  = cmp.get('v.useSharedContainer');

        this.containerManager = sharedContainer ? containerManager.getSharedInstance() : containerManager.createInstance(cmp.find('container'));
        this.initializeRegisteredPanels(cmp);
    },

    /*
    * Store internal defs
    * @private
    */
    initializeRegisteredPanels: function (cmp, newPanels) {
        this.containerManager.registerContainers(newPanels || cmp.get('v.registeredPanels') || []);
    },

    /*
    * Create panel
    * @public
    */
    createPanel: function (cmp, config) {
        var panelConfig      = config.panelConfig || {};
        var referenceElement = panelConfig.referenceElement;

        panelConfig.referenceElement = null;

        // Create panel instance
        var panel = this.createPanelInstance(cmp, config);

        if (referenceElement) {
            panel.set('v.referenceElement', referenceElement);
        }

        // Save instance config
        this.PANELS_INSTANCE[panel.getGlobalId()] = {
            panel           : panel,
            destroyCallback : config.onDestroy
        };

        // Set owner
        this.setPanelOwner(panel, config.owner);

        // Render
        this.renderPanelInstance(cmp, panel, config);

        // Stack panel
        this.stackPanel(panel);

        if (config.onCreate) {
            config.onCreate(panel);
        }
    },
    /*
    * Get Active panel
    * @public
    */
    getActivePanel: function (cmp, callback) {
        // TODO: Instead of assuming is the last one (which doesnt guarantee that is "active")
        // Change the logic on active to make sure we save that state internally
        var stack = this.PANELS_STACK;
        var panel = stack[stack.length - 1];
        if (panel && $A.util.isFunction(callback)) {
            callback(panel);
        }
        return panel;
    },
    /*
    * Sets the context in which the panel is created
    * This is mostly to figure out the the relationship between two panels
    * This function should be called before stacking a new panel
    */
    setPanelOwner: function (panel, givenOwner) {
        var owner = givenOwner;
        if (!owner) {
            var previousBody = null;
        	if (this.PANELS_STACK.length > 0) {
                var previousPanel = this.PANELS_STACK[this.PANELS_STACK.length - 1];
                previousBody = previousPanel && previousPanel.get('v.body');
        	}
            owner = $A.util.isEmpty(previousBody) ? panel.getGlobalId() : previousBody[0].getGlobalId();
        }

        this.PANELS_OWNER[panel.getGlobalId()] = owner;
    },

    /*
    * Stack a panel in our internal structures
    */
    stackPanel: function (panel) {
        var stackManager = this.smLib.stackManager;

        this.PANELS_ZINDEX++;
        this.PANELS_STACK.push(panel);
        stackManager.bringToFront(panel);
    },

    /*
     * stack an element as if it was a panel
     */
    stackElement: function (cb) {
        this.PANELS_ZINDEX++;
        cb(this.PANELS_ZOFFSET + this.PANELS_ZINDEX);
    },

    /*
    * Create panel instance
    * @private
    */
    createPanelInstance: function (cmp, config) {
        var panel = this.containerManager.createContainer({
                containerType          : config.panelType,
                containerConfig        : config.panelConfig,
                containerValueProvider : cmp
        });

        var header  = panel.get('v.header'),
            body    = panel.get('v.body'),
            footer  = panel.get('v.footer'),
            avp, i, length;

        if (!$A.util.isEmpty(body)) {
            body[0].setAttributeValueProvider(panel);
            avp = body[0];
        } else {
            avp = panel;
        }

        if (!$A.util.isEmpty(header)) {
            for (i = 0, length = header.length; i < length; i++) {
                header[i].setAttributeValueProvider(avp);
            }
        }
        if (!$A.util.isEmpty(footer)) {
            for (i = 0, length = footer.length; i < length; i++) {
                footer[i].setAttributeValueProvider(avp);
            }
        }

        return panel;
    },

    beforeShow: function(cmp, config) {
        var panelParam = config.panelInstance,
            panelId    = $A.util.isComponent(panelParam) ? panelParam.getGlobalId() : panelParam,
            panelObj   = this.PANELS_INSTANCE[panelId],
            panel      = panelObj.panel;

        var activeElement = document.activeElement;

        if (activeElement) {
            cmp.returnFocus = activeElement;
        }

        $A.assert(panelObj, 'Couldnt find instance to show');

        // de-active all other panels except the one currently shown
        this.deactivateAllPanelInstances(cmp, panel);
    },

     /*
    * Destroy panel instance
    * @private
    */
    destroyPanelInstance: function (cmp, config, doActivateNext) {
        var stack      = this.PANELS_STACK,
            panelParam = config.panelInstance,
            panelId    = $A.util.isComponent(panelParam) ? panelParam.getGlobalId() : panelParam,
            panelObj   = this.PANELS_INSTANCE[panelId],
            panel      = panelObj.panel,
            index      = stack.indexOf(panel);

        $A.assert(panelObj, 'Couldnt find instance to destroy');
        $A.assert(index > -1, 'Couldnt find the reference in the stack');

        stack.splice(index, 1);

        this.containerManager.destroyContainer(panel);

        delete this.PANELS_OWNER[panelId];
        delete this.PANELS_INSTANCE[panelId];

        if (cmp.returnFocus) {
            cmp.returnFocus.focus();
        }

        // Notify the destroy
        config.onDestroy && config.onDestroy();
        if (panelObj.destroyCallback) {
            panelObj.destroyCallback(panelId);
        }

        if (doActivateNext !== false) {
            this.activateNextPanel(cmp);
        }
    },

    /**
     * Activate the candidate panel
     * @param cmp
     * @private
     */
    activateNextPanel: function() {
        //find the panel to active
        for (var panel, i = this.PANELS_STACK.length - 1; i >= 0; i--) {
            panel = this.PANELS_STACK[i];
            if (panel && panel.isValid() && panel.get('v.visible') && !panel.destroyPending) {
                panel.setActive(true);
                break;
            }
        }
    },

    /**
     * De-activate all the panels except the active one
     * @param cmp
     */
    deactivateAllPanelInstances: function(cmp, activePanel) {
        for (var panel, i = this.PANELS_STACK.length - 1; i >= 0; i--) {
            panel = this.PANELS_STACK[i];
            if (panel && panel.isValid() && panel !== activePanel) {
                panel.setActive(false);
            }
        }
    },

    /*
    * Rendering the panel
    * We call $A.render because we want to render the component immediately
    * so we can send it back synchronously to the user
    * @private
    */
    renderPanelInstance: function (cmp, panel, config) {
        this.containerManager.renderContainer(panel, config);
    },
    notifyPanelContent: function (content, config) {
        var validInterface = config.typeOf ? content.isInstanceOf(config.typeOf) : true,
            validMethod    = content[config.action];

        if (validInterface && validMethod) {
            content[config.action](config.payload); // dispatch the method
        }
    },
    broadcastNotify: function (cmp, source, config) {
        var scope         = config.scope,
            currentTarget = config.currentTarget || this.getContainerPanelId(source),
            stack         = this.PANELS_STACK,
            owner         = this.PANELS_OWNER[currentTarget],
            panel, content, i;

        $A.assert(!scope || (scope !== 'all' || scope !== 'owner' || scope !== "self"), 'Invalid target (all || owner)');

        if (scope === 'all') {
            for (i = stack.length - 1; i >= 0; --i) {
                panel = stack[i];
                if (currentTarget !== panel.getGlobalId()) { // Dont notify itself
                	content = panel.get('v.body')[0];
                    this.notifyPanelContent(content, config);
                }
            }
        } else if (scope === 'self') {
        	if (currentTarget) {
                currentTarget = $A.getComponent(currentTarget);
                this.notifyPanelContent(currentTarget.get('v.body')[0], config);
        	}
        } else if (owner) {
            var ownerCmp = $A.getComponent(owner);
            if (ownerCmp && ownerCmp.isValid()) {
            	this.notifyPanelContent(ownerCmp, config);
            }
        }
    },
    getContainerPanelId: function (source) {
        var provider = source;
        while (provider) {
            if (provider.isInstanceOf("ui:panelType")) {
                return provider.getGlobalId();
            }
            source = provider.getAttributeValueProvider();
            provider = source !== provider ? source : null;
        }
    }
})// eslint-disable-line semi


text:
<?php

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

require_once("../../config.php");
require_once("lib.php");

$id    = required_param('id',PARAM_INT);           // forum
$group = optional_param('group',0,PARAM_INT);      // change of group
$edit  = optional_param('edit',-1,PARAM_BOOL);     // Turn editing on and off

$url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$id));
if ($group !== 0) {
    $url->param('group', $group);
}
if ($edit !== 0) {
    $url->param('edit', $edit);
}
$PAGE->set_url($url);

$forum = $DB->get_record('forum', array('id'=>$id), '*', MUST_EXIST);
$course = $DB->get_record('course', array('id'=>$forum->course), '*', MUST_EXIST);
if (! $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
    $cm->id = 0;
}

require_login($course, false, $cm);

$context = context_module::instance($cm->id);
if (!has_capability('mod/forum:viewsubscribers', $context)) {
    print_error('nopermissiontosubscribe', 'forum');
}

unset($SESSION->fromdiscussion);

add_to_log($course->id, "forum", "view subscribers", "subscribers.php?id=$forum->id", $forum->id, $cm->id);

$forumoutput = $PAGE->get_renderer('mod_forum');
$currentgroup = groups_get_activity_group($cm);
$options = array('forumid'=>$forum->id, 'currentgroup'=>$currentgroup, 'context'=>$context);
$existingselector = new forum_existing_subscriber_selector('existingsubscribers', $options);
$subscriberselector = new forum_potential_subscriber_selector('potentialsubscribers', $options);
$subscriberselector->set_existing_subscribers($existingselector->find_users(''));

if (data_submitted()) {
    require_sesskey();
    $subscribe = (bool)optional_param('subscribe', false, PARAM_RAW);
    $unsubscribe = (bool)optional_param('unsubscribe', false, PARAM_RAW);
    /** It has to be one or the other, not both or neither */
    if (!($subscribe xor $unsubscribe)) {
        print_error('invalidaction');
    }
    if ($subscribe) {
        $users = $subscriberselector->get_selected_users();
        foreach ($users as $user) {
            if (!forum_subscribe($user->id, $id)) {
                print_error('cannotaddsubscriber', 'forum', '', $user->id);
            }
        }
    } else if ($unsubscribe) {
        $users = $existingselector->get_selected_users();
        foreach ($users as $user) {
            if (!forum_unsubscribe($user->id, $id)) {
                print_error('cannotremovesubscriber', 'forum', '', $user->id);
            }
        }
    }
    $subscriberselector->invalidate_selected_users();
    $existingselector->invalidate_selected_users();
    $subscriberselector->set_existing_subscribers($existingselector->find_users(''));
}

$strsubscribers = get_string("subscribers", "forum");
$PAGE->navbar->add($strsubscribers);
$PAGE->set_title($strsubscribers);
$PAGE->set_heading($COURSE->fullname);
if (has_capability('mod/forum:managesubscriptions', $context)) {
    $PAGE->set_button(forum_update_subscriptions_button($course->id, $id));
    if ($edit != -1) {
        $USER->subscriptionsediting = $edit;
    }
} else {
    unset($USER->subscriptionsediting);
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('forum', 'forum').' '.$strsubscribers);
if (empty($USER->subscriptionsediting)) {
    echo $forumoutput->subscriber_overview(forum_subscribed_users($course, $forum, $currentgroup, $context), $forum, $course);
} else if (forum_is_forcesubscribed($forum)) {
    $subscriberselector->set_force_subscribed(true);
    echo $forumoutput->subscribed_users($subscriberselector);
} else {
    echo $forumoutput->subscriber_selection_form($existingselector, $subscriberselector);
}
echo $OUTPUT->footer();


text:
from __future__ import absolute_import

import logging

from django.conf import settings

from horizon.utils.memoized import memoized  # noqa

from openstack_dashboard.api import base

from openstack_dashboard.api.neutron import NeutronAPIDictWrapper
# a10 client that extends neutronclient.v2_0.client.Client
from a10_openstack.neutron_ext.api import client as neutron_client

LOG = logging.getLogger(__name__)

class Certificate(NeutronAPIDictWrapper):
    """Wrapper for neutron Certificates"""
    def __init__(self, apiresource):
        super(Certificate, self).__init__(apiresource)

class CertificateBinding(NeutronAPIDictWrapper):
    """Wrapper for neutron CertificateBindings"""
    def __init__(self, apiresource):
        super(CertificateBinding, self).__init__(apiresource)

def neutronclient(request):
    insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
    cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
    LOG.debug('neutronclient connection created using token "%s" and url "%s"'
              % (request.user.token.id, base.url_for(request, 'network')))
    LOG.debug('user_id=%(user)s, tenant_id=%(tenant)s' %
              {'user': request.user.id, 'tenant': request.user.tenant_id})
    c = neutron_client.Client(token=request.user.token.id,
                              auth_url=base.url_for(request, 'identity'),
                              endpoint_url=base.url_for(request, 'network'),
                              insecure=insecure,
                              ca_cert=cacert)
    return c

def certificate_list(request, **params):
    LOG.debug("certificates_list(): params=%s" % (params))
    certificates = []
    certificates = neutronclient(request).list_certificates(**params).get('certificates')
    return map(Certificate, certificates)

def certificate_get(request, certificate_id, **params):
    # TODO(mdurrant): Add option to get bindings w/ cert.
    LOG.debug("certificate_get(): certificate_id=%s, params=%s" % (certificate_id, params))
    certificate = neutronclient(request).show_certificate(certificate_id,
                                                          **params).get('certificate')
    return Certificate(certificate)

def certificate_create(request, **kwargs):
    """Create specified Certificate"""
    body = {"certificate": kwargs}
    LOG.debug("certificate_create(): kwargs=%s,body=%s" % (kwargs, body))
    certificate = neutronclient(request).create_certificate(body=body).get('certificate')
    return Certificate(certificate)

def certificate_update(request, **kwargs):
    body = {"certificate": kwargs}
    LOG.debug("certificate_update(): kwargs=%s", (kwargs))
    certificate = neutronclient(request).update_certificate(body=body).get('certificate')
    return Certificate(certificate)

def certificate_delete(request, certificate_id):
    LOG.debug("certificate_delete(): certificiate_id:%s" % certificate_id)
    # TODO(mmd): Should this return status or do we assume it always works?
    neutronclient(request).delete_certificate(certificate_id)

def certificate_bindings_list(request, **params):
    LOG.debug("certificate_bindings_list(): params={}".format(params))

    bindings = \
        neutronclient(request).list_certificate_bindings(**params).get('certificate_bindings')
    return map(CertificateBinding, bindings)

def certificate_binding_get(request, binding_id, **params):
    LOG.debug("certificate_binding_get(): binding_id=%s, params=%s" % (binding_id, params))
    binding = neutronclient(request).show_certificate_binding(binding_id,
                                                              **params).get('certificate_binding')
    return CertificateBinding(binding)

def certificate_binding_create(request, **kwargs):
    """Binding specified Certificate ID to specified VIP ID"""
    LOG.debug("certificate_binding_create(): request=%s, kwargs=%s" % (request, kwargs))
    body = {'certificate_binding': kwargs}

    binding = \
        neutronclient(request).create_certificate_binding(body=body).get('certificate_binding')
    return CertificateBinding(binding)

def certificate_binding_delete(request, binding_id):
    LOG.debug("certificate_binding_delete(): binding_id=%s" % binding_id)
    neutronclient(request).delete_certificate_binding(binding_id)


text:
package org.mlflow.sagemaker;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.mlflow.utils.SerializationUtils;

public class ScoringServerTest {
  private class TestPredictor implements Predictor {
    private final boolean succeed;
    private final Optional<String> responseContent;

    private TestPredictor(boolean succeed) {
      this.succeed = succeed;
      this.responseContent = Optional.empty();
    }

    private TestPredictor(String responseContent) {
      this.responseContent = Optional.of(responseContent);
      this.succeed = true;
    }

    @Override
    public PredictorDataWrapper predict(PredictorDataWrapper input)
        throws PredictorEvaluationException {
      if (succeed) {
        String responseText = this.responseContent.orElse("{ \"Text\" : \"Succeed!\" }");
        return new PredictorDataWrapper(responseText, PredictorDataWrapper.ContentType.Json);
      } else {
        throw new PredictorEvaluationException("Failure!");
      }
    }
  }

  private static final HttpClient httpClient = HttpClientBuilder.create().build();

  private static String getHttpResponseBody(HttpResponse response) throws IOException {
    return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
  }

  @Test
  public void testScoringServerWithValidPredictorRespondsToPingsCorrectly() throws IOException {
    TestPredictor validPredictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(validPredictor);
    server.start();

    String requestUrl = String.format("http://localhost:%d/ping", server.getPort().get());
    HttpGet getRequest = new HttpGet(requestUrl);
    HttpResponse response = httpClient.execute(getRequest);
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    server.stop();
  }

  @Test
  public void testScoringServerWithValidPredictorRespondsToVersionCorrectly() throws IOException {
    TestPredictor validPredictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(validPredictor);
    server.start();

    String requestUrl = String.format("http://localhost:%d/version", server.getPort().get());
    HttpGet getRequest = new HttpGet(requestUrl);
    HttpResponse response = httpClient.execute(getRequest);
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    String responseBody = getHttpResponseBody(response);
    Assert.assertEquals("2.0.2-SNAPSHOT", responseBody);
    server.stop();
  }

  @Test
  public void testConstructingScoringServerFromInvalidModelPathThrowsException() {
    String badModelPath = "/not/a/valid/path";
    try {
      ScoringServer server = new ScoringServer(badModelPath);
      Assert.fail("Expected constructing a model server with an invalid model path"
          + " to throw an exception, but none was thrown.");
    } catch (PredictorLoadingException e) {
      // Succeed
    }
  }

  @Test
  public void testScoringServerRepondsToInvocationOfBadContentTypeWithBadRequestCode()
      throws IOException {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    server.start();

    String requestUrl = String.format("http://localhost:%d/invocations", server.getPort().get());
    String badContentType = "not-a-content-type";
    HttpPost postRequest = new HttpPost(requestUrl);
    postRequest.addHeader("Content-type", badContentType);
    HttpEntity entity = new StringEntity("body");
    postRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(postRequest);
    Assert.assertEquals(
        HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());

    server.stop();
  }

  @Test
  public void testMultipleServersRunOnDifferentPortsSucceedfully() throws IOException {
    TestPredictor predictor = new TestPredictor(true);

    List<ScoringServer> servers = new ArrayList<>();
    for (int i = 0; i < 3; ++i) {
      ScoringServer newServer = new ScoringServer(predictor);
      newServer.start();
      servers.add(newServer);
    }

    for (ScoringServer server : servers) {
      int portNumber = server.getPort().get();
      String requestUrl = String.format("http://localhost:%d/ping", portNumber);
      HttpGet getRequest = new HttpGet(requestUrl);
      HttpResponse response = httpClient.execute(getRequest);
      Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    }

    for (ScoringServer server : servers) {
      server.stop();
    }
  }

  @Test
  public void testScoringServerWithValidPredictorRespondsToInvocationWithPredictorOutputContent()
      throws IOException {
    Map<String, String> predictorDict = new HashMap<>();
    predictorDict.put("Text", "Response");
    String predictorJson = SerializationUtils.toJson(predictorDict);
    TestPredictor predictor = new TestPredictor(predictorJson);

    ScoringServer server = new ScoringServer(predictor);
    server.start();

    String requestUrl = String.format("http://localhost:%d/invocations", server.getPort().get());
    HttpPost postRequest = new HttpPost(requestUrl);
    postRequest.addHeader("Content-type", "application/json");
    HttpEntity entity = new StringEntity("body");
    postRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(postRequest);
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    String responseBody = getHttpResponseBody(response);
    Map<String, String> responseDict = SerializationUtils.fromJson(responseBody, Map.class);
    Assert.assertEquals(predictorDict, responseDict);

    server.stop();
  }

  @Test
  public void testScoringServerRespondsWithInternalServerErrorCodeWhenPredictorThrowsException()
      throws IOException {
    TestPredictor predictor = new TestPredictor(false);

    ScoringServer server = new ScoringServer(predictor);
    server.start();

    String requestUrl = String.format("http://localhost:%d/invocations", server.getPort().get());

    HttpPost postRequestJson = new HttpPost(requestUrl);
    postRequestJson.addHeader("Content-type", "application/json");
    HttpEntity entityJson = new StringEntity("body");
    postRequestJson.setEntity(entityJson);

    HttpResponse responseJson = httpClient.execute(postRequestJson);
    Assert.assertEquals(
        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, responseJson.getStatusLine().getStatusCode());

    HttpPost postRequestCsv = new HttpPost(requestUrl);
    postRequestCsv.addHeader("Content-type", "text/csv");
    HttpEntity entityCsv = new StringEntity("body");
    postRequestCsv.setEntity(entityCsv);

    HttpResponse responseCsv = httpClient.execute(postRequestCsv);
    Assert.assertEquals(
        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, responseCsv.getStatusLine().getStatusCode());

    server.stop();
  }

  @Test
  public void testScoringServerStartsAndStopsSucceedfully() throws IOException {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);

    for (int i = 0; i < 3; ++i) {
      server.start();
      String requestUrl = String.format("http://localhost:%d/ping", server.getPort().get());
      HttpGet getRequest = new HttpGet(requestUrl);
      HttpResponse response1 = httpClient.execute(getRequest);
      Assert.assertEquals(HttpServletResponse.SC_OK, response1.getStatusLine().getStatusCode());

      server.stop();

      try {
        HttpResponse response2 = httpClient.execute(getRequest);
        Assert.fail("Expected attempt to ping an inactive server to throw an exception.");
      } catch (HttpHostConnectException e) {
        // Succeed
      }
    }
  }

  @Test
  public void testStartingScoringServerOnRandomPortAssignsNonZeroPort() {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    server.start();
    Optional<Integer> portNumber = server.getPort();
    Assert.assertEquals(true, portNumber.get() > 0);
    server.stop();
  }

  @Test
  public void testScoringServerIsActiveReturnsTrueWhenServerIsRunningElseFalse() {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    Assert.assertEquals(false, server.isActive());
    server.start();
    Assert.assertEquals(true, server.isActive());
    server.stop();
    Assert.assertEquals(false, server.isActive());
  }

  @Test
  public void testGetPortReturnsEmptyForInactiveServer() {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    Optional<Integer> portNumber = server.getPort();
    Assert.assertEquals(false, portNumber.isPresent());
  }

  @Test
  public void testGetPortReturnsPresentOptionalForActiveServer() {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    server.start();
    Assert.assertEquals(true, server.isActive());
    Optional<Integer> portNumber = server.getPort();
    Assert.assertEquals(true, portNumber.isPresent());
    server.stop();
  }

  @Test
  public void testServerStartsOnSpecifiedPortOrThrowsStateChangeException() throws IOException {
    int portNumber = 6783;
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server1 = new ScoringServer(predictor);
    server1.start(portNumber);
    Assert.assertEquals(true, server1.isActive());

    String requestUrl = String.format("http://localhost:%d/ping", server1.getPort().get());
    HttpGet getRequest = new HttpGet(requestUrl);
    HttpResponse response = httpClient.execute(getRequest);
    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

    ScoringServer server2 = new ScoringServer(predictor);
    try {
      server2.start(portNumber);
      Assert.fail(
          "Expected starting a new server on a port that is already bound to throw an exception.");
    } catch (ScoringServer.ServerStateChangeException e) {
      // Succeed
    }
    server1.stop();
    server2.stop();
  }

  @Test
  public void testAttemptingToStartActiveServerThrowsIllegalStateException() {
    TestPredictor predictor = new TestPredictor(true);
    ScoringServer server = new ScoringServer(predictor);
    server.start();
    try {
      server.start();
      Assert.fail(
          "Expected attempt to start a server that is already active to throw an exception.");
    } catch (IllegalStateException e) {
      // Succeed
    } finally {
      server.stop();
    }
  }
}


text:
@implementation BKPair

#pragma mark - Root

- (instancetype)initWithKey:(NSString *)key value:(NSNumber *)value {
    self = [super init];
    if (self) {
        self.key = key;
        self.value = value;
    }
    return self;
}

@end


text:
module Dino
  module Components
    class Led < BaseComponent
      def after_initialize(options={})
        set_pin_mode(:out)
        off
      end

      def on
        digital_write(Board::HIGH)
      end

      def off
        digital_write(Board::LOW)
      end
    end
  end
end


text:
@interface NoResultsTableViewController : TLTableViewController
@property (strong, nonatomic) IBOutlet UIButton *hideRowsButton;
- (IBAction)toggleHideRows;
@end


text:
<?php
/**
 * Registration module.
 *
 * @author gizmore
 * @version 5.0
 * @since 1.0
 */
class Module_Register extends GWF_Module
{
	##############
	### Module ###
	##############
	public function isCoreModule() { return true; }
	public function getClasses() { return array('GWF_UserActivation'); }
	public function onLoadLanguage() { $this->loadLanguage('lang/register'); }
	public function href_administrate_module() { return href('Register', 'Admin'); }

	##############
	### Config ###
	##############
	public function getConfig()
	{
		return array(
			GDO_Checkbox::make('captcha')->initial('0'),
			GDO_Checkbox::make('guest_signup')->initial('1'),
			GDO_Checkbox::make('email_activation')->initial('1'),
		    GDO_Duration::make('email_activation_timeout')->initial('72600')->min(0)->max(31536000),
		    GDO_Checkbox::make('admin_activation')->initial('0'),
			GDO_Int::make('ip_signup_count')->initial('1')->min(0)->max(100),
			GDO_Duration::make('ip_signup_duration')->initial('72600')->min(0)->max(31536000),
			GDO_Checkbox::make('force_tos')->initial('1'),
			GDO_Url::make('tos_url')->reachable()->allowLocal()->initial($this->getMethodHREF('TOS')),
			GDO_Checkbox::make('activation_login')->initial('1'),
		);
	}
	public function cfgCaptcha() { return $this->getConfigValue('captcha'); }
	public function cfgGuestSignup() { return $this->getConfigValue('guest_signup'); }
	public function cfgEmailActivation() { return $this->getConfigValue('email_activation'); }
	public function cfgEmailActivationTimeout() { return $this->getConfigValue('email_activation_timeout'); }
	public function cfgAdminActivation() { return $this->getConfigValue('admin_activation'); }
	public function cfgMaxUsersPerIP() { return $this->getConfigValue('ip_signup_count'); }
	public function cfgMaxUsersPerIPTimeout() { return $this->getConfigValue('ip_signup_duration'); }
	public function cfgTermsOfService() { return $this->getConfigValue('force_tos'); }
	public function cfgTosUrl() { return $this->getConfigValue('tos_url'); }
	public function cfgActivationLogin() { return $this->getConfigValue('activation_login'); }
	################
	### Top Menu ###
	################
	public function onRenderFor(GWF_Navbar $navbar)
	{
		if ($navbar->isRight() && GWF_Session::user()->isGhost())
		{
			$navbar->addField(GDO_Link::make('btn_register')->href($this->getMethodHREF('Form')));
// 			$navbar->addField(GDO_Link::make('btn_guest')->href($this->getMethodHREF('Guest')));
		}
	}
}


text:
<form action="//nodecasts.us12.list-manage.com/subscribe/post?u=8a372efa90d46915f6f53b7ca&id=1a729bd298" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Never miss an episode!

	Email Address
	<input type="email" value="" name="EMAIL" class="form-control required email" placeholder="Email Address" id="mce-EMAIL">

<input type="text" name="b_8a372efa90d46915f6f53b7ca_1a729bd298" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button btn btn-lg btn-info">

</form>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Insec. Inscit. menst. , 12, 5.

#### Original name
null

### Remarks
null


text:
package com.googlecode.lanterna.gui2;

import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;

/**
 * Abstract implementation of {@code Border} interface that has some of the methods filled out. If you want to create
 * your own {@code Border} implementation, should should probably extend from this.
 * @author Martin
 */
public abstract class AbstractBorder extends AbstractComposite<Border> implements Border {

    public void setComponent(Component component) {
        super.setComponent(component);
        if(component != null) {
            component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
        }
    }

    public BorderRenderer getRenderer() {
        return (BorderRenderer)super.getRenderer();
    }

    public Border setSize(TerminalSize size) {
        super.setSize(size);
        getComponent().setSize(getWrappedComponentSize(size));
        return self();
    }

    public LayoutData getLayoutData() {
        return getComponent().getLayoutData();
    }

    public Border setLayoutData(LayoutData ld) {
        getComponent().setLayoutData(ld);
        return this;
    }

    public TerminalPosition toBasePane(TerminalPosition position) {
        return super.toBasePane(position).withRelative(getWrappedComponentTopLeftOffset());
    }

    public TerminalPosition toGlobal(TerminalPosition position) {
        return super.toGlobal(position).withRelative(getWrappedComponentTopLeftOffset());
    }

    private TerminalPosition getWrappedComponentTopLeftOffset() {
        return getRenderer().getWrappedComponentTopLeftOffset();
    }

    private TerminalSize getWrappedComponentSize(TerminalSize borderSize) {
        return getRenderer().getWrappedComponentSize(borderSize);
    }
}


text:
<?php

namespace spec\Rs\VersionEye\Output;

use PhpSpec\ObjectBehavior;
use Rs\VersionEye\Output\Services;
use Symfony\Component\Console\Output\BufferedOutput;

class ServicesSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType(Services::class);
    }

    public function it_prints_a_boolean_on_follow()
    {
        $output = new BufferedOutput();

        $this->ping($output, ['success' => true, 'message' => 'pong']);

        expect($output->fetch())->toBe(<<<'EOS'
pong

EOS
        );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:autoTransition="jumpToStart"
        motion:constraintSetEnd="@+id/end"
        motion:constraintSetStart="@+id/start"
        motion:duration="10000">
        <OnSwipe
            motion:dragDirection="dragDown"
            motion:dragThreshold="1"
            motion:touchAnchorId="@+id/button"
            motion:touchAnchorSide="top" />
        <OnClick motion:targetId="@+id/button30" />
        <!--             motion:touchAnchorSide="right"-->
        <!--               motion:dragDirection="dragRight"-->
        <KeyFrameSet>
            <KeyAttribute motion:framePosition="50"
                motion:motionTarget="@+id/button2"
                android:transformPivotX="0dp"
                android:transformPivotY="0dp"/>
        </KeyFrameSet>
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@+id/button"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:rotation="0"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />
        <Constraint
            android:id="@+id/button2"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:transformPivotX="100dp"
            android:transformPivotY="100dp"
            android:rotation="0"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />

        <Constraint
            android:id="@+id/button3"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:transformPivotX="0dp"
            android:transformPivotY="0dp"
            android:rotationX="0"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />
        <Constraint
            android:id="@+id/button4"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:transformPivotX="0dp"
            android:transformPivotY="0dp"
            android:rotationY="0"
            motion:layout_constraintStart_toStartOf="parent"
            motion:layout_constraintTop_toTopOf="parent" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:id="@+id/button"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginEnd="8dp"
            android:rotation="720"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent" />
        <Constraint
            android:id="@+id/button2"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginEnd="8dp"
            android:transformPivotX="32dp"
            android:transformPivotY="32dp"
            android:rotation="3600"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent" />

        <Constraint
            android:id="@+id/button3"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:transformPivotX="0dp"
            android:transformPivotY="64dp"
            android:rotationX="3600"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent"  />
        <Constraint
            android:id="@+id/button4"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginStart="8dp"
            android:transformPivotX="64dp"
            android:transformPivotY="0dp"
            android:rotationY="3600"
            motion:layout_constraintBottom_toBottomOf="parent"
            motion:layout_constraintEnd_toEndOf="parent"  />
    </ConstraintSet>

</MotionScene>


text:
package org.apache.camel.component.atomix.cluster;

import java.util.UUID;

import io.atomix.catalyst.transport.Address;
import io.atomix.copycat.server.storage.StorageLevel;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cluster.ClusteredRoutePolicyFactory;
import org.apache.camel.impl.engine.ExplicitCamelContextNameStrategy;
import org.apache.camel.main.Main;
import org.apache.camel.main.MainListenerSupport;

public final class AtomixClientClusteredRoutePolicyFactoryMain {
    private AtomixClientClusteredRoutePolicyFactoryMain() {
    }

    public static void main(String[] args) throws Exception {
        final String id = UUID.randomUUID().toString();

        Main main = new Main();
        main.addMainListener(new MainListenerSupport() {
            @Override
            public void configure(CamelContext context) {
                try {
                    AtomixClusterService service = new AtomixClusterService();
                    service.setId("node-" + id);
                    service.setStorageLevel(StorageLevel.MEMORY);
                    service.setAddress(new Address(args[0]));
                    service.setNodes(args.length > 1 ? args[1] : args[0]);

                    context.setNameStrategy(new ExplicitCamelContextNameStrategy("camel-" + id));
                    context.addService(service);
                    context.addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace("my-ns"));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        main.addRoutesBuilder(new RouteBuilder() {
            @Override
            public void configure() {
                from("timer:clustered?delay=1000&period=1000")
                    .routeId("route-" + id)
                    .log("Route ${routeId} is running ...");
            }
        });

        main.run();
    }
}


text:
package banktorrent

import (
  "github.com/russross/meddler"
  "errors"
  "fmt"
  "strings"
  "time"
)

type ExpenseType int
// Currently supported expense types
const (
  UNKNOWN_EXPENSE ExpenseType = iota
  SIMPLE_EXPENSE
  SPLIT_EXPENSE
)

func StringToExpenseType(etype string) (ExpenseType, error) {
  switch strings.TrimSpace(etype) {
  case "simple":
    return SIMPLE_EXPENSE, nil
  case "split":
    return SPLIT_EXPENSE, nil
  }
  return UNKNOWN_EXPENSE, errors.New("Could not parse expense type")
}

func (e ExpenseType) String() (string) {
  switch e {
  case SIMPLE_EXPENSE:
    return "simple"
  case SPLIT_EXPENSE:
    return "split"
  }
  return "unknown"
}

type Expense struct {
  Id      int64   `meddler:"id,pk"`
  Amount  int     `meddler:"amount"`
  LabelId int64   `meddler:"label_id"`
  Comment string  `meddler:"comment"`
  Date    string  `meddler:"date"`
}

func GetExpenseById(db meddler.DB, id int64) (*Expense, error) {
  expense := new(Expense)
  err := meddler.Load(db, "expenses", expense, id)
  return expense, err
}

func GetExpensesByLabel(db meddler.DB, label *Label) ([]*Expense, error) {
  var expenses []*Expense
  err := meddler.QueryAll(db, &expenses, "select * from expenses where label_id = ?", label.Id)
  return expenses, err
}

// Creates the expense in the db and gives it an ID
func CreateExpense(db meddler.DB, amount *MoneyAmount, label *Label, comment string, date time.Time) (*Expense, error) {
  expense := new(Expense)
  expense.Amount = amount.Int()
  expense.LabelId = label.Id
  expense.Comment = comment
  expense.Date = date.Format(DATE_FMT)

  err := meddler.Insert(db, "expenses", expense)
  return expense, err
}

// Adds a single transaction. The entire expense amount is credited to the lender and charged to the debtor
func (e *Expense) AddSimple(db meddler.DB, lender *User, debtor *User) (*Transaction, error) {
  return addTransaction(db, lender, debtor, e.Amount, e)
}

// Adds 1 transaction per debtor. The amount is split evenly between everyone (penny errors can occur).
// This type of transaction is useful even with just 2 people (a debtor and a lender) because it behaves
// differently than a SimpleExpense. Namely, it splits the expense.Amount evenly between everyone, including
// the lender, allowing for "shared expenses" to be added easily
func (e *Expense) AddSplit(db meddler.DB, lender *User, debtors []*User) ([]*Transaction, error) {
  if len(debtors) < 1 {
    return nil, errors.New("Debtors list must have at least 1 element")
  }
  split_amount := int(float32(e.Amount) / float32(len(debtors) + 1)) //# of debtors + 1 lender
  transactions := make([]*Transaction, len(debtors))
  for index, debtor := range(debtors) {
    transaction, err := addTransaction(db, lender, debtor, split_amount, e)
    if err != nil {
      return transactions, err
    }
    transactions[index] = transaction
  }
  return transactions, nil
}

func (e *Expense) String() (string) {
  return fmt.Sprintf("Expense #%v [Amount: %v, LabelID: %v, Date: %v, Comment: %v]", e.Id, e.Amount, e.LabelId, e.Date, e.Comment)
}

func (e *Expense) Transactions(db meddler.DB) ([]*Transaction, error) {
  var transactions []*Transaction
  err := meddler.QueryAll(db, &transactions, "select * from transactions where expense_id = ?", e.Id)
  return transactions, err
}

// Removes the expense by reversing all transactions associated with it,
// and deleting the expense from the db
func (e *Expense) Remove(db meddler.DB) (error) {
  transactions, err := e.Transactions(db)
  if err != nil {
    return err
  }
  for _, transaction := range(transactions) {
    err := transaction.remove(db)
    if err != nil {
      return err
    }
  }
  // remove the expense from the db
  _, err = db.Exec("DELETE FROM expenses WHERE id = ?", e.Id)
  if err != nil {
    return err
  }
  e = nil
  return nil
}


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCIceCandidate
       (js_newRTCIceCandidate, newRTCIceCandidate, js_getCandidate,
        getCandidate, js_getSdpMid, getSdpMid, js_getSdpMLineIndex,
        getSdpMLineIndex, RTCIceCandidate, castToRTCIceCandidate,
        gTypeRTCIceCandidate)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums

foreign import javascript unsafe
        "new window[\"RTCIceCandidate\"]($1)" js_newRTCIceCandidate ::
        Nullable Dictionary -> IO RTCIceCandidate

-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate Mozilla RTCIceCandidate documentation>
newRTCIceCandidate ::
                   (MonadIO m, IsDictionary dictionary) =>
                     Maybe dictionary -> m RTCIceCandidate
newRTCIceCandidate dictionary
  = liftIO
      (js_newRTCIceCandidate
         (maybeToNullable (fmap toDictionary dictionary)))

foreign import javascript unsafe "$1[\"candidate\"]"
        js_getCandidate :: RTCIceCandidate -> IO JSString

-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.candidate Mozilla RTCIceCandidate.candidate documentation>
getCandidate ::
             (MonadIO m, FromJSString result) => RTCIceCandidate -> m result
getCandidate self
  = liftIO (fromJSString <$> (js_getCandidate (self)))

foreign import javascript unsafe "$1[\"sdpMid\"]" js_getSdpMid ::
        RTCIceCandidate -> IO JSString

-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.sdpMid Mozilla RTCIceCandidate.sdpMid documentation>
getSdpMid ::
          (MonadIO m, FromJSString result) => RTCIceCandidate -> m result
getSdpMid self = liftIO (fromJSString <$> (js_getSdpMid (self)))

foreign import javascript unsafe "$1[\"sdpMLineIndex\"]"
        js_getSdpMLineIndex :: RTCIceCandidate -> IO Word

-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate.sdpMLineIndex Mozilla RTCIceCandidate.sdpMLineIndex documentation>
getSdpMLineIndex :: (MonadIO m) => RTCIceCandidate -> m Word
getSdpMLineIndex self = liftIO (js_getSdpMLineIndex (self))


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

define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var VNetsTable = require('tabs/vnets-tab/datatable');

  /*
    CONSTANTS
   */

  var PANEL_ID = require('./vnets/panelId');
  var VNETS_TABLE_ID = PANEL_ID + "VNetsTable";
  var RESOURCE = "Cluster";
  var XML_ROOT = "CLUSTER";

  /*
    CONSTRUCTOR
   */

  function Panel(info) {
    this.title = Locale.tr("VNets");
    this.icon = "fa-globe";

    this.element = info[XML_ROOT];

    return this;
  }

  Panel.PANEL_ID = PANEL_ID;
  Panel.prototype.html = _html;
  Panel.prototype.setup = _setup;

  return Panel;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    var vnets = [];

    if (this.element.VNETS.ID != undefined){
      vnets = this.element.VNETS.ID;

      if (!$.isArray(vnets)){
        vnets = [vnets];
      }
    }

    var opts = {
      info: true,
      select: true,
      selectOptions: {
        read_only: true,
        fixed_ids: vnets
      }
    };

    this.VNetsTable = new VNetsTable(VNETS_TABLE_ID, opts);

    return this.VNetsTable.dataTableHTML;
  }

  function _setup(context) {
    this.VNetsTable.initialize();
    this.VNetsTable.refreshResourceTableSelect();

    return false;
  }
});


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

namespace Kingdom.OrTools
{
    /// <inheritdoc />
    public abstract class ProblemSolverAspectBase<TSolver, TAspect>
        : IProblemSolverAspect<TSolver, TAspect>
        where TSolver : class
        where TAspect : ProblemSolverAspectBase<TSolver, TAspect>
    {
        /// <inheritdoc />
        public IList<object> ClrCreatedObjects { get; } = new List<object>();

        /// <summary>
        /// Gets whether IsDisposed.
        /// </summary>
        protected bool IsDisposed { get; private set; }

        /// <summary>
        /// Disposes the object.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (IsDisposed || !disposing)
            {
                return;
            }

            foreach (var obj in ClrCreatedObjects)
            {
                if (obj != null && obj is IDisposable disposableObj)
                {
                    disposableObj.Dispose();
                }
            }
        }

        /// <inheritdoc />
        public void Dispose()
        {
            Dispose(true);
            IsDisposed = true;
        }
    }

    /// <inheritdoc cref="IProblemSolverAspect{TSolver,TSource,TVariable,TConstraint,TAspect}"/>
    /// <see cref="IProblemSolverAspect{TSolver,TSource,TVariable,TConstraint,TAspect}"/>
    public abstract class ProblemSolverAspectBase<TSolver, TSource, TVariable, TConstraint, TAspect>
        : ProblemSolverAspectBase<TSolver, TAspect>
            , IProblemSolverAspect<TSolver, TSource, TVariable, TConstraint, TAspect>
        where TSolver : class
        where TSource : class
        where TVariable : class
        where TConstraint : class
        where TAspect : ProblemSolverAspectBase<TSolver, TSource, TVariable, TConstraint, TAspect>
    {
        /// <inheritdoc />
        public virtual IEnumerable<TVariable> GetVariables(TSource source)
        {
            yield break;
        }

        /// <inheritdoc />
        public abstract IEnumerable<TConstraint> GetConstraints(TSource source);

        // ReSharper disable once UnusedMember.Global
        /// <summary>
        /// Gets any <typeparamref name="TVariable"/> instances corresponding with this aspect.
        /// </summary>
        protected virtual IList<TVariable> IntersectedVariables { get; } = new List<TVariable>();

        // ReSharper disable once UnusedMember.Global
        /// <summary>
        /// Get any <typeparamref name="TConstraint"/> instances corresponding with this aspect.
        /// </summary>
        protected virtual IList<TConstraint> IntersectedConstraints { get; } = new List<TConstraint>();

        /// <inheritdoc />
        public virtual IEnumerable<TVariable> IntersectVariables(TSource source, TAspect otherAspect)
        {
            yield break;
        }

        /// <inheritdoc />
        public virtual IEnumerable<TConstraint> Intersect(TSource source, TAspect otherAspect)
        {
            yield break;
        }
    }
}


text:
using namespace tippbot::model;

std::string HttpResponse::getHeader(std::string &header_name, std::string default_value)
{
	if (!hasHeader(header_name))
	{
		return default_value;
	}

	return headers_[header_name];
}

void HttpResponse::addHeader(std::string header_name, std::string header_value)
{
	boost::trim(header_value);
	if (header_name.compare("Set-Cookie") == 0)
	{
		size_t split_pos = header_value.find_first_of(";");
		if (split_pos == std::string::npos)
		{
			split_pos = size_t(header_value.length());
		}

		std::string cookie_only = header_value.substr(0, split_pos);
		std::regex cookie_expression("(\\w*)=([0-9a-zA-Z\\.]*)");
		std::smatch match;
		if (std::regex_match(cookie_only, match, cookie_expression) && match.size() == 3)
		{
			cookies_[match[1].str()] = match[2].str();
		}

	}
	else
	{
		headers_[header_name] = header_value;
	}
}

std::string HttpResponse::getCookie(std::string cookie_name)
{
	if (cookies_.find(cookie_name) != cookies_.end())
	{
		return cookies_[cookie_name];
	}

	return "";
}


text:
from __future__ import unicode_literals

import functools
import inspect
import re

from httpretty import HTTPretty
from .responses import metadata_response
from .utils import convert_regex_to_flask_path

class MockAWS(object):
    nested_count = 0

    def __init__(self, backends):
        self.backends = backends

        if self.__class__.nested_count == 0:
            HTTPretty.reset()

    def __call__(self, func):
        if inspect.isclass(func):
            return self.decorate_class(func)
        return self.decorate_callable(func)

    def __enter__(self):
        self.start()

    def __exit__(self, *args):
        self.stop()

    def start(self, reset=True):
        self.__class__.nested_count += 1
        if reset:
            for backend in self.backends.values():
                backend.reset()

        if not HTTPretty.is_enabled():
            HTTPretty.enable()

        for method in HTTPretty.METHODS:
            backend = list(self.backends.values())[0]
            for key, value in backend.urls.items():
                HTTPretty.register_uri(
                    method=method,
                    uri=re.compile(key),
                    body=value,
                )

            # Mock out localhost instance metadata
            HTTPretty.register_uri(
                method=method,
                uri=re.compile('http://169.254.169.254/latest/meta-data/.*'),
                body=metadata_response
            )

    def stop(self):
        self.__class__.nested_count -= 1

        if self.__class__.nested_count < 0:
            raise RuntimeError('Called stop() before start().')

        if self.__class__.nested_count == 0:
            HTTPretty.disable()
            HTTPretty.reset()

    def decorate_callable(self, func):
        def wrapper(*args, **kwargs):
            with self:
                result = func(*args, **kwargs)
            return result
        functools.update_wrapper(wrapper, func)
        wrapper.__wrapped__ = func
        return wrapper

    def decorate_class(self, klass):
        for attr in dir(klass):
            if attr.startswith("_"):
                continue

            attr_value = getattr(klass, attr)
            if not hasattr(attr_value, "__call__"):
                continue

            # Check if this is a classmethod. If so, skip patching
            if inspect.ismethod(attr_value) and attr_value.__self__ is klass:
                continue

            try:
                setattr(klass, attr, self(attr_value))
            except TypeError:
                # Sometimes we can't set this for built-in types
                continue
        return klass

class Model(type):
    def __new__(self, clsname, bases, namespace):
        cls = super(Model, self).__new__(self, clsname, bases, namespace)
        cls.__models__ = {}
        for name, value in namespace.items():
            model = getattr(value, "__returns_model__", False)
            if model is not False:
                cls.__models__[model] = name
        for base in bases:
            cls.__models__.update(getattr(base, "__models__", {}))
        return cls

    @staticmethod
    def prop(model_name):
        """ decorator to mark a class method as returning model values """
        def dec(f):
            f.__returns_model__ = model_name
            return f
        return dec

class BaseBackend(object):
    def reset(self):
        self.__dict__ = {}
        self.__init__()

    @property
    def _url_module(self):
        backend_module = self.__class__.__module__
        backend_urls_module_name = backend_module.replace("models", "urls")
        backend_urls_module = __import__(backend_urls_module_name, fromlist=['url_bases', 'url_paths'])
        return backend_urls_module

    @property
    def urls(self):
        """
        A dictionary of the urls to be mocked with this service and the handlers
        that should be called in their place
        """
        url_bases = self._url_module.url_bases
        unformatted_paths = self._url_module.url_paths

        urls = {}
        for url_base in url_bases:
            for url_path, handler in unformatted_paths.items():
                url = url_path.format(url_base)
                urls[url] = handler

        return urls

    @property
    def url_paths(self):
        """
        A dictionary of the paths of the urls to be mocked with this service and
        the handlers that should be called in their place
        """
        unformatted_paths = self._url_module.url_paths

        paths = {}
        for unformatted_path, handler in unformatted_paths.items():
            path = unformatted_path.format("")
            paths[path] = handler

        return paths

    @property
    def url_bases(self):
        """
        A list containing the url_bases extracted from urls.py
        """
        return self._url_module.url_bases

    @property
    def flask_paths(self):
        """
        The url paths that will be used for the flask server
        """
        paths = {}
        for url_path, handler in self.url_paths.items():
            url_path = convert_regex_to_flask_path(url_path)
            paths[url_path] = handler

        return paths

    def decorator(self, func=None):
        if func:
            return MockAWS({'global': self})(func)
        else:
            return MockAWS({'global': self})


text:
var buster = require("buster");
var fs = require("fs");

var fsWatcher = require("../lib/fs-watcher");

buster.testCase('fs-watcher', {
    setUp: function () {
        this.closer = { close: this.spy() };
        this.stub(fs, "watch").returns(this.closer);
        this.watcher = fsWatcher.create();
    },

    "watches files": function () {
        this.watcher.watch({ name: "file.txt" }, this.spy());
        assert.calledOnceWith(fs.watch, "file.txt");
    },

    "calls back when file changes": function () {
        var spy = this.spy();
        var file = { name: "file.txt" };
        this.watcher.watch(file, spy);

        fs.watch.yield("change");

        assert.calledOnceWith(spy, "change", file);
    },

    "unwatches files": function () {
        this.watcher.watch({ name: "file.txt" }, this.spy());
        this.watcher.unwatch({ name: "file.txt" });

        assert.calledOnce(this.closer.close);
    },

    "unwatches directories": function () {
        this.watcher.fileSeparator = "/";

        this.watcher.watch({ name: "files" }, this.spy());
        this.watcher.watch({ name: "files/file1.txt" }, this.spy());
        this.watcher.watch({ name: "files/file2.txt" }, this.spy());
        this.watcher.watch({ name: "filesystem.txt" }, this.spy());
        this.watcher.watch({ name: "notes/file1.txt" }, this.spy());

        this.watcher.unwatchDir({ name: "files" });

        assert.calledThrice(this.closer.close);
    },

    "closes watches": function () {
        this.watcher.watch({ name: "file1.txt" }, this.spy());
        this.watcher.watch({ name: "file2.txt" }, this.spy());
        this.watcher.end();

        assert.calledTwice(this.closer.close);
    }
});


text:
<?php
namespace ProductCatalog;

class ProductResponse
{
    /** @type ProductView*/
    public $product;

    /**
     * @param ProductView $product
     */
    public function __construct(ProductView $product)
    {
        $this->product = $product;
    }
}