text:
date: 2019-06-11
has_code: true
has_comments: true
layout: post
revisions:
- date: 2019-06-13
  reason: Fixed some typos
- date: 2019-08-17
  reason: Updated to use local scripts
tags:
- python
- hearing
- qt
title: Playing pure tones with PyQt5 on Mac
---

In an [earlier post](getting-started-with-python-for-sound), I recommended using a third-
party package called [sounddevice](https://python-sounddevice.readthedocs.io/en/latest/)
for playing sounds with Python. I also mentioned that there were some alternatives with
similar functions. Overall, I still recommend sounddevice because I find it to be the most
straightforward to use and the easiest to install on macOS, Windows, and Linux. However,
[PyQt5](https://www.riverbankcomputing.com/software/pyqt/download5) is an alternative
package that may be worth looking at. PyQt5 provides bindings for
[Qt](https://www.qt.io/), software for building complete applications with graphical user
interfaces (GUIs). If you are interested in building a GUI-based Python app with an audio
component, PyQt5 seems like a smart choice.

Unfortunately, I've really struggled to use PyQt5's built-in audio features effectively.
Latency issues, clicking, and clipping can be difficult to avoid. This is much to my
chagrin: I use PyQt5 _all the time_ for building psychological experiments, so relying on
an extra package for sound playback when this is included within PyQt5 is infuriating. I
think a major problem is that there aren't enough working examples online. I guess people
don't use PyQt5 for audio as often as other tasks. In this post, I decided to try to
rectify the balance in a small way, by taking an
[already existing script](https://wiki.python.org/moin/PyQt/Playing%20a%20sound%20with%20QtMultimedia)
and fixing some of its problems. By the end, we will have a Python script that creates a
GUI from which the user can play pure tones of different frequencies and levels.

## Setup

This example is included in my GitHub repo. If you decide to clone it, I recommend
setting up a conda Python environment of the same name, as per my
[getting-started post](getting-started). You will need to install PyQt5 within this
environment. Please note that, at the time of writing, the conda
version of PyQt5 does not include all the necessary sub-components to play sounds.
Therefore, you should install it via `pip install PyQt5` instead.

## Original code

Its very likely that the original webpage will outlive _The Cracked Bassoon_, but
nevertheless, here is the example script:

```python
from math import pi, sin
import struct, sys

from PyQt4.QtCore import QBuffer, QByteArray, QIODevice, Qt
from PyQt4.QtGui import QApplication, QFormLayout, QLineEdit, QHBoxLayout, QPushButton, QSlider, QVBoxLayout, QWidget
from PyQt4.QtMultimedia import QAudio, QAudioDeviceInfo, QAudioFormat, QAudioOutput

class Window(QWidget):

    def __init__(self, parent = None):

        QWidget.__init__(self, parent)

        format = QAudioFormat()
        format.setChannels(1)
        format.setFrequency(22050)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)
        self.output = QAudioOutput(format, self)

        self.frequency = 440
        self.volume = 0
        self.buffer = QBuffer()
        self.data = QByteArray()

        self.deviceLineEdit = QLineEdit()
        self.deviceLineEdit.setReadOnly(True)
        self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName())

        self.pitchSlider = QSlider(Qt.Horizontal)
        self.pitchSlider.setMaximum(100)
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)

        self.playButton = QPushButton(self.tr("&Play"))

        self.pitchSlider.valueChanged.connect(self.changeFrequency)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.playButton.clicked.connect(self.play)

        formLayout = QFormLayout()
        formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
        formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
        formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.playButton)
        buttonLayout.addStretch()

        horizontalLayout = QHBoxLayout(self)
        horizontalLayout.addLayout(formLayout)
        horizontalLayout.addLayout(buttonLayout)

    def changeFrequency(self, value):

        self.frequency = 440 + (value * 2)

    def play(self):

        if self.output.state() == QAudio.ActiveState:
            self.output.stop()

        if self.buffer.isOpen():
            self.buffer.close()

        self.createData()

        self.buffer.setData(self.data)
        self.buffer.open(QIODevice.ReadOnly)
        self.buffer.seek(0)

        self.output.start(self.buffer)

    def changeVolume(self, value):

        self.volume = value

    def createData(self):

        # Create 2 seconds of data with 22050 samples per second, each sample
        # being 16 bits (2 bytes).

        self.data.clear()
        for i in xrange(2 * 22050):
            t = i / 22050.0
            value = int(self.volume * sin(2 * pi * self.frequency * t))
            self.data.append(struct.pack("<h", value))

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
```

## PyQt4 → PyQt5

The first issue with this example is that it was written for PyQt4, not PyQt5, so we need
to change the `import` statements.

```python
from PyQt5.QtCore import QBuffer, QByteArray, QIODevice, Qt
from PyQt5.QtWidgets import QApplication, QFormLayout, QLineEdit, QHBoxLayout, QPushButton, QSlider, QVBoxLayout, QWidget
from PyQt5.QtMultimedia import QAudio, QAudioDeviceInfo, QAudioFormat, QAudioOutput
```

Note that in addition to changing the imported base package, the `QtGui` sub-package is
now called `QtWidgets`.

A couple of methods in `QAudioFormat` have also been renamed. Lines 17–18 should read,

```python
format.setChannelCount(1)
format.setSampleRate(22050)
```

Because the `xrange` function was renamed `range` in Python 3, we also need to modify
line 89:

```python
for i in range(2 * 22050):
```

## Play a tone

Now you should be able to run this script. When you do, and see something like this:

![](/assets/images/pyqt5_puretone_gui.png)
*This is what the GUI looks like on my mac.*

First, drag the Volume slider up a bit, then press the Play button. Did you hear
something? Yes? Great!

## Playing more than once

Now click it again. Oh …

Let's do a little debugging to figure out why this script only plays a single tone. I've
added two `print` calls to the `play` method,

```python
def play(self):

    print("about to play:", self.output.state(), self.output.error())

    if self.output.state() == QAudio.ActiveState:
        self.output.stop()

    if self.buffer.isOpen():
        self.buffer.close()

    self.createData()

    self.buffer.setData(self.data)
    self.buffer.open(QIODevice.ReadOnly)
    self.buffer.seek(0)

	self.output.start(self.buffer)

    print("played:", self.output.state(), self.output.error())
```

When we rerun the script and press the Play button twice, we see the following:

```
about to play: 2 0
played: 0 0
about to play: 3 3
played: 2 1
```

The first integer on each line is the output of `self.output.state()`. From the
[docs](https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtmultimedia/qaudio.html#State),
it returns various status codes. Initially the status is 2 (stopped), then immediately
after the tone starts to play it changes to 0 (active). Some time before we press Play
again, it changes to 3 (idle), which means it "has no data and [the] buffer is empty,
this state is set after start() is called and while no audio data is available to be
processed." This all makes sense. I'm still not clear on why it changes back to 2 after
we pressed Play a second time, but whatever.

The second integer per line is the output of `self.output.error()` (see the
[docs](https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtmultimedia/qaudio.html#Error)).
No errors were raised when playing the first tone. But sometime after that—I assume when
the first tone finished playing and the status of the output changed to idle—we got an
`UnderrunError`, which means "audio data is not being fed to the audio device at a fast
enough rate." Finally, we got an `IOError` when we pressed Play again, which makes sense
because the output device was closed.

You might think that pressing Play for a third time would actually play a tone, because
the status out the output has reverted to 2. But it doesn't, presumably because of the
errors.

There is probably a correct way to close the output after the sound has ended that
prevents it producing an `UnderrunError` in the first place, but at the time of writing,
I'm still not sure what this is. However, another way get the code to play a tone each
time we press Play is to check for the error and reset the output if one is found, like
so (added to lines 70–71):

```python
if self.output.error() == QAudio.UnderrunError:
    self.output.reset()
```

Now we can hear as many tones as we like. Hooray!

## Latency issues

You might have noticed a lag between pressing the button and hearing the sound,
particularly if you have a slower computer. Let's measure it. We start by importing the
`time` module from the Python standard library (line 8),

```python
import time
```

Then we modify the `play` method for a second time:

```python
def play(self):

    now = time.time()
    print("about to play:", self.output.state(), self.output.error())

    if self.output.state() == QAudio.ActiveState:
        self.output.stop()

    if self.buffer.isOpen():
        self.buffer.close()

    if self.output.error() == QAudio.UnderrunError:
        self.output.reset()

    self.createData()

    self.buffer.setData(self.data)
    self.buffer.open(QIODevice.ReadOnly)
    self.buffer.seek(0)

    self.output.start(self.buffer)

    print("played:", self.output.state(), self.output.error())
    t = round((time.time() - now) * 1000)
    print(f"this took {t} milliseconds")
```

Running the script and pressing Play a few times produces

```
about to play: 2 0
played: 0 0
this took 53 milliseconds
about to play: 3 3
played: 0 0
this took 46 milliseconds
about to play: 3 3
played: 0 0
this took 45 milliseconds
```

Fifty milliseconds is _horrendous_ latency. We can re-write the `play` method again to
isolate the culprit.

```python
def play(self):

    now = time.time()
    print("about to play:", self.output.state(), self.output.error())

    if self.output.state() == QAudio.ActiveState:
        self.output.stop()
        t = round((time.time() - now) * 1000)
        print(f"stopping a playing tone took {t} milliseconds")

    if self.buffer.isOpen():
        self.buffer.close()
        t = round((time.time() - now) * 1000)
        print(f"closing an open buffer took {t} milliseconds")

    if self.output.error() == QAudio.UnderrunError:
        self.output.reset()
        t = round((time.time() - now) * 1000)
        print(f"resetting broken output took {t} milliseconds")

    self.createData()
    t = round((time.time() - now) * 1000)
    print(f"writing the waveform took {t} milliseconds")

    self.buffer.setData(self.data)
    self.buffer.open(QIODevice.ReadOnly)
    self.buffer.seek(0)
    t = round((time.time() - now) * 1000)
    print(f"writing the buffer took {t} milliseconds")

    self.output.start(self.buffer)

    print("played:", self.output.state(), self.output.error())
    t = round((time.time() - now) * 1000)
    print(f"playing took {t} milliseconds")
```

The above produces this:

```
about to play: 2 0
writing the waveform took 43 milliseconds
writing the buffer took 43 milliseconds
played: 0 0
playing took 60 milliseconds
about to play: 3 3
closing an open buffer took 0 milliseconds
resetting broken output took 0 milliseconds
writing the waveform took 43 milliseconds
writing the buffer took 43 milliseconds
played: 0 0
playing took 43 milliseconds
about to play: 3 3
closing an open buffer took 0 milliseconds
resetting broken output took 0 milliseconds
writing the waveform took 42 milliseconds
writing the buffer took 42 milliseconds
played: 0 0
playing took 42 milliseconds
```

Clearly, it's re-writing the waveform on each `play` call that's causing the lion's share of the lag. We could speed this up by replacing `createData` with a method that uses NumPy, as described in my previous posts. But we could also simply move this call out of the `play` method. Now the relevant portion of the code looks like this:

```python
def changeFrequency(self, value):

	self.frequency = 440 + (value * 2)
    self.createData()

def play(self):

	now = time.time()
    print("about to play:", self.output.state(), self.output.error())

    if self.output.state() == QAudio.ActiveState:
        self.output.stop()
        t = round((time.time() - now) * 1000)
        print(f"stopping a playing tone took {t} milliseconds")

    if self.buffer.isOpen():
        self.buffer.close()
        t = round((time.time() - now) * 1000)
        print(f"closing an open buffer took {t} milliseconds")

    if self.output.error() == QAudio.UnderrunError:
        self.output.reset()
        t = round((time.time() - now) * 1000)
        print(f"resetting broken output took {t} milliseconds")

    self.buffer.setData(self.data)
    self.buffer.open(QIODevice.ReadOnly)
    self.buffer.seek(0)
    t = round((time.time() - now) * 1000)
    print(f"writing the buffer took {t} milliseconds")

    self.output.start(self.buffer)

    print("played:", self.output.state(), self.output.error())
    t = round((time.time() - now) * 1000)
    print(f"playing took {t} milliseconds")

def changeVolume(self, value):

    self.volume = value
    self.createData()
```

For safety, I've also added a call to `createData` to the `__init__` method. Now we get
something like the following:

```
about to play: 2 0
writing the buffer took 0 milliseconds
played: 0 0
playing took 8 milliseconds
about to play: 3 3
closing an open buffer took 0 milliseconds
resetting broken output took 0 milliseconds
writing the buffer took 0 milliseconds
played: 0 0
playing took 0 milliseconds
```

This modification actually makes the code much less efficient because it re-writes the
waveform every time either slider moves, rather than only when it actually needs to play
another waveform. But it did eliminate (most of) the lag.

## Poor latency on initial play

Latencies are much better for the second play onwards,  but the first one is still poor.
I have not figured out the source of this, and I find it annoying as all hell. My hacky
workaround is to add a call to `play` during the `__init__` method.  Thus, upon
initialization, the object plays an empty buffer, which eats up the initial lag. Again,
this is inefficient, but it's the best I could come up with.

## Final code

Now we have a short, simple script that plays tones with sub-millisecond latencies. This
might be sufficient for some purposes, such as certain behavioral psychological
experiments. The complete code, tidied up and with comments and `print` calls removed,
is provided below.

```python
{{ site.data.code.qt-sound-example__py }}
```

To be clear, this is not good code! The latency is below 1 millisecond but this is still
not great. It wouldn't work in circumstances where timing is absolutely critical, such as
in a electrophysiology experiment, and I hate the play-silence-during-init hack. If anyone
reading this has any suggestions for further improvements, please feel free to leave a
comment below.


text:
namespace OSPRayTestScenes {

Stereo::Stereo()
{
  rendererType = "scivis";
  samplesPerPixel = 4;

  auto params = GetParam();
  cameraType = std::get<0>(params);
  stereoMode = std::get<1>(params);
}

void Stereo::SetUp()
{
  Base::SetUp();

  instances.clear();

  auto builder = ospray::testing::newBuilder("cornell_box");
  ospray::testing::setParam(builder, "rendererType", rendererType);
  ospray::testing::commit(builder);

  world = ospray::testing::buildWorld(builder);
  ospray::testing::release(builder);
  world.commit();

  camera = cpp::Camera(cameraType);
  if (cameraType == "perspective") {
    pos.z = -2.f;
    camera.setParam("aspect", imgSize.x / (float)imgSize.y);
  }
  camera.setParam("position", pos);
  camera.setParam("stereoMode", stereoMode);
  camera.setParam("transform", affine3f(one));
}

// Test Instantiations //////////////////////////////////////////////////////

TEST_P(Stereo, stereo)
{
  PerformRenderTest();
}

INSTANTIATE_TEST_SUITE_P(Camera,
    Stereo,
    ::testing::Combine(::testing::Values("perspective", "panoramic"),
        ::testing::Values(OSP_STEREO_LEFT,
            OSP_STEREO_RIGHT,
            OSP_STEREO_SIDE_BY_SIDE,
            OSP_STEREO_TOP_BOTTOM)));

} // namespace OSPRayTestScenes

redpajama_set_name: RedPajamaGithub


text:
'use strict';

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

/* eslint-env browser */
/* global socket */

var app = window.app = {

  // adds a new item to the funding array and renders the empty form
  // (does not save the item to the server)
  addItem: function addItem() {
    this.nodes.form.hide();
    this.item = new app.Model();
    this.funding.push(this.item);
    this.renderList();
    this.renderForm();
  },

  // deletes the current item from the funding array and the server
  deleteItem: function deleteItem() {
    var _this = this;

    var confirmed = confirm('Are you sure you want to delete this item?');

    if (confirmed) {

      this.nodes.form.hide();
      var i = this.funding.indexOf(this.item);
      this.item = new this.Model();
      var item = this.funding.splice(i, 1)[0];

      if (item.id) {
        socket.emit('delete', item.id, function (err, success) {
          if (err) return _this.error(err);
          _this.renderList();
        });
      }
    }
  },

  // displays an error message
  error: function error(err) {
    this.nodes.error.textContent = err.code + ': ' + err.details;
    this.nodes.error.display();
  },

  // the array of funding items (retrieved from socket)
  funding: [],

  // initialize the app and add listeners
  initialize: function initialize() {
    var _this2 = this;

    var _loop = function _loop(node) {
      _this2.nodes[node].display = function () {
        _this2.nodes[node].style.display = 'flex';
      };
      _this2.nodes[node].hide = function () {
        _this2.nodes[node].style.display = 'none';
      };
    };

    // add display/hide methods to major app nodes
    for (var node in this.nodes) {
      _loop(node);
    }

    // names of the input elements
    var inputs = ['amount', 'deadline', 'opens', 'orgAbbr', 'organization', 'rolling', 'tags', 'title', 'titleAbbr', 'url'];

    // adds new tags to the model
    var addTags = function addTags() {
      var _item$tags;

      var tags = _this2.nodes.tags.value.split(/[,;]+/g).map(function (str) {
        return str.trim();
      }).filter(function (str) {
        return str;
      });

      (_item$tags = _this2.item.tags).push.apply(_item$tags, _toConsumableArray(tags));
      _this2.nodes.tags.value = '';
      _this2.renderForm();
    };

    // deletes a tag from the model
    var deleteTag = function deleteTag(ev) {
      if (ev.target.tagName === 'IMG') {

        var i = _this2.item.tags.indexOf(ev.target.dataset.value);

        if (i !== -1) {
          _this2.item.tags.splice(i, 1);
          _this2.renderForm();
          ev.target.parentNode.remove();
        }
      }
    };

    // find the selected item and render the form for that item
    var renderForm = function renderForm(ev) {
      _this2.item = _this2.funding.find(function (fund) {
        return fund.id === ev.target.dataset.id;
      });
      _this2.renderForm();
    };

    // enable/disable deadlines depending on whether rolling is checked
    var setDeadlines = function setDeadlines() {

      var rollingChecked = _this2.nodes.rolling.checked;

      _this2.nodes.opens.value = '';
      _this2.nodes.opens.disabled = rollingChecked;
      _this2.nodes.deadline.value = '';
      _this2.nodes.deadline.disabled = rollingChecked;
      _this2.nodes.deadline.required = !rollingChecked;
    };

    // update model with selected eligibility values
    var updateEligibility = function updateEligibility(ev) {
      if (ev.target.tagName === 'INPUT') {
        _this2.item.eligibility[ev.target.value] = ev.target.checked;
      }
    };

    // update the model when a text input changes
    var updateTextProp = function updateTextProp(ev) {
      if (_this2.textProps.includes(ev.target.name)) {
        _this2.item[ev.target.name] = ev.target.value;
      }
      if (ev.target.name === 'title') {
        _this2.renderList();
      }
    };

    // add input elements to app nodes
    inputs.forEach(function (input) {
      _this2.nodes[input] = document.querySelector('[name=' + input + ']');
    });

    // create a blank model
    this.item = new this.Model();

    // add event listeners
    this.nodes.add.addEventListener('click', function () {
      return _this2.addItem();
    });
    this.nodes.addTags.addEventListener('click', function () {
      return addTags();
    });
    this.nodes.delete.addEventListener('click', function () {
      return _this2.deleteItem();
    });
    this.nodes.eligibility.addEventListener('change', function (ev) {
      return updateEligibility(ev);
    });
    this.nodes.form.addEventListener('change', function (ev) {
      return updateTextProp(ev);
    });
    this.nodes.list.addEventListener('click', function (ev) {
      return renderForm(ev);
    });
    this.nodes.rolling.addEventListener('change', function () {
      return setDeadlines();
    });
    this.nodes.save.addEventListener('click', function () {
      return _this2.saveItem();
    });
    this.nodes.tagList.addEventListener('click', function (ev) {
      return deleteTag(ev);
    });

    // get the funding list when the socket connects
    socket.on('connect', function () {
      return socket.emit('getAll', 'funding', function (err, funding) {
        if (err) {
          _this2.error(err);
        } else {
          _this2.funding = funding.map(function (data) {
            return new _this2.Model(data);
          });
          _this2.funding.sort(function (a, b) {
            if (a.title  0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck(this, Model);

    app.textProps.forEach(function (prop) {
      _this3[prop] = data[prop] || '';
    });
    this.rolling = data.rolling || false;
    this.eligibility = data.eligibility || {};
    this.tags = data.tags || [];
    this.id = data.id || '';
    this.type = 'funding';
  },

  // app nodes
  nodes: {
    add: document.getElementById('addFundingButton'),
    addTags: document.getElementById('addTagsButton'),
    delete: document.getElementById('deleteButton'),
    description: document.querySelector('textarea[name=description]'),
    eligibility: document.querySelector('#eligibility'),
    error: document.getElementById('error'),
    form: document.querySelector('form'),
    list: document.querySelector('#funding-list > ul'),
    save: document.getElementById('saveButton'),
    tagList: document.querySelector('#tags > ul')
  },

  // render the form with data from the current funding item
  renderForm: function renderForm() {
    var _this4 = this;

    var checkboxes = Array.from(document.querySelectorAll('#eligibility input'));

    this.nodes.tagList.innerHTML = '';
    checkboxes.forEach(function (box) {
      box.checked = false;
    });
    this.textProps.forEach(function (prop) {
      _this4.nodes[prop].value = _this4.item[prop];
    });
    this.nodes.rolling.checked = this.item.rolling;

    Object.keys(this.item.eligibility).forEach(function (elig) {
      var checkbox = document.querySelector('input[name=eligibility][value=' + elig + ']');
      checkbox.checked = _this4.item.eligibility[elig];
    });

    this.item.tags.forEach(function (tag) {
      _this4.nodes.tagList.insertAdjacentHTML('beforeend', '\n
\n
' + tag + '
\n          \n
\n      ');
    });

    this.nodes.form.display();
  },

  // render the list of funding items from the funding array
  renderList: function renderList() {
    var _this5 = this;

    this.nodes.list.innerHTML = '';

    this.funding.forEach(function (fund) {
      _this5.nodes.list.insertAdjacentHTML('beforeend', '\n
' + fund.title + '
\n      ');
    });
  },

  // save the current item to the server
  saveItem: function saveItem() {
    var _this6 = this;

    this.nodes.form.hide();

    socket.emit('upsert', this.item, function (err, item) {

      if (err) return _this6.error(err);

      Object.assign(_this6.item, item);

      _this6.renderList();
      _this6.renderForm();
    });
  },

  // list of text properties
  textProps: ['amount', 'deadline', 'description', 'opens', 'orgAbbr', 'organization', 'title', 'titleAbbr', 'url']

};

// initialize the app
app.initialize();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace LD28.Entities.Terrain
{
	/// <summary>
	/// This interface represents a brush used for modifying a <see cref="Terrain" />.
	/// </summary>
	public interface ITerrainBrush
	{
		/// <summary>
		/// Gets or sets the position.
		/// </summary>
		Vector2 Position { get; set; }

		/// <summary>
		/// This method checks if the given bounding box is contained by the brush.
		/// </summary>
		/// <param name="boundingBox">The bounding box.</param>
		/// <returns>The containment type.</returns>
		ContainmentType Contains(ref BoundingBox boundingBox);
	}
}


text:
<?php
namespace Czim\HelloDialog\Enums;

use MyCLabs\Enum\Enum;

class ApiType extends Enum
{
    const CONTACTS      = 'contacts';
    const NEWSLETTERS   = 'newsletter';
    const TRANSACTIONAL = 'transactional';
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { TrendComponent } from './trend.component';
import { TrendChartComponent } from './trend-chart/trend-chart.component';
import { TrendTableComponent } from './trend-table/trend-table.component';
import { LegendComponent } from '../shared/component/legend/legend.component';
import { LegendCompareAreasComponent } from '../shared/component/legend/legend-compare-areas/legend-compare-areas.component';
import { LegendInequalitiesComponent } from '../shared/component/legend/legend-inequalities/legend-inequalities.component';
import { LegendMapComponent } from '../shared/component/legend/legend-map/legend-map.component';
import { LegendRecentTrendsComponent } from '../shared/component/legend/legend-recent-trends/legend-recent-trends.component';
import { LegendTrendComponent } from '../shared/component/legend/legend-trend/legend-trend.component';
import { FTHelperService } from '../shared/service/helper/ftHelper.service';
import { IndicatorService } from '../shared/service/api/indicator.service';
import { UIService } from '../shared/service/helper/ui.service';
import { DownloadService } from '../shared/service/api/download.service';
import { LegendDataQualityComponent } from '../shared/component/legend/legend-data-quality/legend-data-quality.component';
import {
  LegendBenchmarkAgainstGoalComponent
} from '../shared/component/legend/legend-benchmark-against-goal/legend-benchmark-against-goal.component';
import { FTIndicatorSearch, IndicatorIdList } from '../typings/FT';
import { ExportCsvComponent } from '../shared/component/export-csv/export-csv.component';

const groupId = 1;
const areaTypeId = 1;
const areaCode = 'areaCodeTest';
const parentCode = 'parentCodeTest';
const profileId = 1;
const indicatorId = 1;
const areaName = 'AreaNameTest';

describe('TrendComponent', () => {
  let component: TrendComponent;
  let fixture: ComponentFixture<TrendComponent>;

  let ftHelperService: any;
  let indicatorService: any;
  let uiService: any;
  let downloadService: any;

  beforeEach(async(() => {

    ftHelperService = jasmine.createSpyObj('FTHelperService',
      ['getSearch', 'getIid', 'getFTModel', 'getFTConfig', 'getFTData', 'getCurrentGroupRoot',
        'getAreaName', 'getParentAreaCode'
      ]);
    indicatorService = jasmine.createSpyObj('IndicatorService', ['getTrendDataForAllIndicatorsInProfileGroupForChildAreas',
      'getTrendDataForSpecificIndicatorsForChildAreas']);
    downloadService = jasmine.createSpyObj('DownloadService', ['']);
    uiService = jasmine.createSpyObj('UIService', ['']);

    TestBed.configureTestingModule({
      declarations: [
        TrendComponent,
        TrendChartComponent,
        TrendTableComponent,
        LegendComponent,
        LegendCompareAreasComponent,
        LegendInequalitiesComponent,
        LegendMapComponent,
        LegendRecentTrendsComponent,
        LegendTrendComponent,
        LegendDataQualityComponent,
        LegendBenchmarkAgainstGoalComponent,
        ExportCsvComponent
      ],
      providers: [
        { provide: FTHelperService, useValue: ftHelperService },
        { provide: IndicatorService, useValue: indicatorService },
        { provide: DownloadService, useValue: downloadService },
        { provide: UIService, useValue: uiService }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TrendComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call getTrendDataForAllIndicatorsInProfileGroupForChildAreas', () => {

    // Arrange
    ftHelperService.getSearch.and.returnValue(new FTIndicatorSearchTestSupport(false));
    ftHelperService.getIid.and.returnValue(indicatorId);

    // Act
    component.getDataTrends(groupId, areaTypeId, parentCode, profileId);

    // Arrange
    expect(indicatorService.getTrendDataForAllIndicatorsInProfileGroupForChildAreas).toHaveBeenCalled();

  });

  // it('should call getTrendDataForSpecificIndicatorsForChildAreas', () => {

  //   // Arrange
  //   ftHelperService.getSearch.and.returnValue(new FTIndicatorSearchTestSupport(true));
  //   ftHelperService.getIid.and.returnValue(indicatorId);

  //   // Act
  //   component.getDataTrends(groupId, areaTypeId, parentCode, profileId);

  //   // Arrange
  //   expect(indicatorService.getTrendDataForSpecificIndicatorsForChildAreas).toHaveBeenCalled();

  // });

  it('should call getDataTrends', () => {

    ftHelperService.getFTModel.and.returnValue(model);
    ftHelperService.getCurrentGroupRoot.and.returnValue(currentGroupRoot);
    ftHelperService.getAreaName.and.returnValue(areaName);

    const getDataTrendsSpy = spyOn(component, 'getDataTrends');

    component.onOutsideEvent({});

    expect(getDataTrendsSpy).toHaveBeenCalled();
  });

});

export class FTIndicatorSearchTestSupport implements FTIndicatorSearch {

  isSeachModeDefault = false;
  isIndicatorListDefault = true;
  indicatorListIdDefault = 1;
  indicatorIdsParameterDefault = '';
  profileIdsForSearchDefault: Array<number> = [];

  constructor(isSeachModeDefault: boolean) {
    this.isSeachModeDefault = isSeachModeDefault;
  }

  isInSearchMode = function () {
    return this.isSeachModeDefault;
  }
  getIndicatorListId = function () {
    return this.indicatorListIdDefault;
  }
  isIndicatorList = function () {
    return this.isIndicatorListDefault;
  }
  getIndicatorIdList = function () {
    return new IndicatorIdListTestSupport();
  }
  getIndicatorIdsParameter = function () {
    return this.indicatorIdsParameterDefault;
  }
  getProfileIdsForSearch = function () {
    return this.profileIdsForSearchDefault;
  }
}

export class IndicatorIdListTestSupport implements IndicatorIdList {

  allIdsDefault: Array<number> = [];

  getAllIds = function () {
    return this.allIdsDefault;
  }
}

const currentGroupRoot = {
  Grouping: [
    {
      GroupId: groupId
    }]
}

const model = {
  areaTypeId: areaTypeId,
  groupId: null,
  parentCode: parentCode,
  profileId: profileId,
  parentTypeId: null,
  areaCode: areaCode,
  iid: null,
  ageId: null,
  sexId: null,
  nearestNeighbour: null,
  groupRoots: currentGroupRoot,
  filterIndicatorPeriod: null,
  yAxisSelectedIndicatorId: null,
  isNearestNeighbours: function () {
    return true;
  }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.qyu4.theallswap.View.UserMainView">
    <item
        android:id="@+id/action_my_inventory"
        android:title="@string/my_inventory"
        android:orderInCategory="100"
        android:onClick="userMyInventorySelected"/>
    <item
        android:id="@+id/action_my_trade"
        android:title="@string/my_trade"
        android:orderInCategory="100"
        android:onClick="userMyTradeSelected"/>
    <item
        android:id="@+id/action_my_friends"
        android:title="@string/my_friends"
        android:orderInCategory="100"
        android:onClick="userMyFriendsSelected"/>
    <item
        android:id="@+id/action_my_Profile"
        android:title="@string/my_profile"
        android:orderInCategory="100"
        android:onClick="userMyProfileSelected"/>
    <item
        android:id="@+id/action_search"
        android:title="@string/search"
        android:orderInCategory="100"
        android:onClick="userSearchSelected"/>
    <item
        android:id="@+id/action_previous_browse"
        android:title="@string/previous_browse"
        android:orderInCategory="100"
        android:onClick="userPreviousBrowseSelected"/>
    <item
        android:id="@+id/action_no_function"
        android:title="@string/dash_line"
        android:orderInCategory="100"
        />
    <item
        android:id="@+id/action_logout"
        android:title="@string/log_out"
        android:orderInCategory="100"
        android:onClick="userLogoutSelected"/>

</menu>


text:
import nls = require('vs/nls');
import { registerColor, editorBackground, contrastBorder, transparent, badgeForeground, badgeBackground } from 'vs/platform/theme/common/colorRegistry';
import { IDisposable, Disposable, dispose } from 'vs/base/common/lifecycle';
import { IThemeService, ITheme } from 'vs/platform/theme/common/themeService';
import { Color } from 'vs/base/common/color';

// < --- Tabs --- >

export const TAB_ACTIVE_BACKGROUND = registerColor('tab.activeBackground', {
	dark: editorBackground,
	light: editorBackground,
	hc: editorBackground
}, nls.localize('tabActiveBackground', "Active tab background color. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups."));

export const TAB_INACTIVE_BACKGROUND = registerColor('tab.inactiveBackground', {
	dark: '#2D2D2D',
	light: '#ECECEC',
	hc: null
}, nls.localize('tabInactiveBackground', "Inactive tab background color. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups."));

export const TAB_BORDER = registerColor('tab.border', {
	dark: '#252526',
	light: '#F3F3F3',
	hc: contrastBorder
}, nls.localize('tabBorder', "Border to separate tabs from each other. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups."));

export const TAB_ACTIVE_FOREGROUND = registerColor('tab.activeForeground', {
	dark: Color.white,
	light: '#333333',
	hc: Color.white
}, nls.localize('tabActiveEditorGroupActiveForeground', "Active tab foreground color in an active group. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups."));

export const TAB_INACTIVE_FOREGROUND = registerColor('tab.inactiveForeground', {
	dark: transparent(TAB_ACTIVE_FOREGROUND, 0.5),
	light: transparent(TAB_ACTIVE_FOREGROUND, 0.5),
	hc: Color.white
}, nls.localize('tabInactiveEditorGroupActiveForeground', "Inactive tab foreground color in an active group. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups."));

// < --- Editors --- >

export const EDITOR_GROUP_BACKGROUND = registerColor('editorGroup.background', {
	dark: '#2D2D2D',
	light: '#ECECEC',
	hc: null
}, nls.localize('editorGroupBackground', "Background color of an editor group. Editor groups are the containers of editors. The background color shows up when dragging editor groups around."));

export const EDITOR_GROUP_HEADER_TABS_BACKGROUND = registerColor('editorGroupHeader.tabsBackground', {
	dark: '#252526',
	light: '#F3F3F3',
	hc: null
}, nls.localize('tabsContainerBackground', "Background color of the editor group title header when tabs are enabled. Editor groups are the containers of editors."));

export const EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND = registerColor('editorGroupHeader.noTabsBackground', {
	dark: editorBackground,
	light: editorBackground,
	hc: editorBackground
}, nls.localize('editorGroupHeaderBackground', "Background color of the editor group title header when tabs are disabled. Editor groups are the containers of editors."));

export const EDITOR_GROUP_BORDER_COLOR = registerColor('editorGroup.border', {
	dark: '#444444',
	light: '#E7E7E7',
	hc: contrastBorder
}, nls.localize('editorGroupBorder', "Color to separate multiple editor groups from each other. Editor groups are the containers of editors."));

export const EDITOR_DRAG_AND_DROP_BACKGROUND = registerColor('editorGroup.dropBackground', {
	dark: Color.fromHex('#53595D').transparent(0.5),
	light: Color.fromHex('#3399FF').transparent(0.18),
	hc: null
}, nls.localize('editorDragAndDropBackground', "Background color when dragging editors around. The color should have transparency so that the editor contents can still shine through."));

// < --- Panels --- >

export const PANEL_BACKGROUND = registerColor('panel.background', {
	dark: editorBackground,
	light: editorBackground,
	hc: editorBackground
}, nls.localize('panelBackground', "Panel background color. Panels are shown below the editor area and contain views like output and integrated terminal."));

export const PANEL_BORDER_COLOR = registerColor('panel.border', {
	dark: Color.fromHex('#808080').transparent(0.35),
	light: Color.fromHex('#808080').transparent(0.35),
	hc: contrastBorder
}, nls.localize('panelBorder', "Panel border color on the top separating to the editor. Panels are shown below the editor area and contain views like output and integrated terminal."));

export const PANEL_ACTIVE_TITLE_COLOR = registerColor('panelTitle.activeForeground', {
	dark: '#E7E7E7',
	light: '#424242',
	hc: Color.white
}, nls.localize('panelActiveTitleForeground', "Title color for the active panel. Panels are shown below the editor area and contain views like output and integrated terminal."));

export const PANEL_INACTIVE_TITLE_COLOR = registerColor('panelTitle.inactiveForeground', {
	dark: transparent(PANEL_ACTIVE_TITLE_COLOR, 0.5),
	light: transparent(PANEL_ACTIVE_TITLE_COLOR, 0.75),
	hc: Color.white
}, nls.localize('panelInactiveTitleForeground', "Title color for the inactive panel. Panels are shown below the editor area and contain views like output and integrated terminal."));

export const PANEL_ACTIVE_TITLE_BORDER = registerColor('panelTitle.activeBorder', {
	dark: PANEL_BORDER_COLOR,
	light: PANEL_BORDER_COLOR,
	hc: contrastBorder
}, nls.localize('panelActiveTitleBorder', "Border color for the active panel title. Panels are shown below the editor area and contain views like output and integrated terminal."));

// < --- Status --- >

export const STATUS_BAR_FOREGROUND = registerColor('statusBar.foreground', {
	dark: '#FFFFFF',
	light: '#FFFFFF',
	hc: '#FFFFFF'
}, nls.localize('statusBarForeground', "Status bar foreground color. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_BACKGROUND = registerColor('statusBar.background', {
	dark: '#007ACC',
	light: '#007ACC',
	hc: null
}, nls.localize('statusBarBackground', "Standard status bar background color. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_NO_FOLDER_BACKGROUND = registerColor('statusBar.noFolderBackground', {
	dark: '#68217A',
	light: '#68217A',
	hc: null
}, nls.localize('statusBarNoFolderBackground', "Status bar background color when no folder is opened. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_ITEM_ACTIVE_BACKGROUND = registerColor('statusBarItem.activeBackground', {
	dark: Color.white.transparent(0.18),
	light: Color.white.transparent(0.18),
	hc: Color.white.transparent(0.18)
}, nls.localize('statusBarItemActiveBackground', "Status bar item background color when clicking. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_ITEM_HOVER_BACKGROUND = registerColor('statusBarItem.hoverBackground', {
	dark: Color.white.transparent(0.12),
	light: Color.white.transparent(0.12),
	hc: Color.white.transparent(0.12)
}, nls.localize('statusBarItemHoverBackground', "Status bar item background color when hovering. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_PROMINENT_ITEM_BACKGROUND = registerColor('statusBarItem.prominentBackground', {
	dark: '#388A34',
	light: '#388A34',
	hc: '#3883A4'
}, nls.localize('statusBarProminentItemBackground', "Status bar prominent items background color. Prominent items stand out from other status bar entries to indicate importance. The status bar is shown in the bottom of the window."));

export const STATUS_BAR_PROMINENT_ITEM_HOVER_BACKGROUND = registerColor('statusBarItem.prominentHoverBackground', {
	dark: '#369432',
	light: '#369432',
	hc: '#369432'
}, nls.localize('statusBarProminentItemHoverBackground', "Status bar prominent items background color when hovering. Prominent items stand out from other status bar entries to indicate importance. The status bar is shown in the bottom of the window."));

// < --- Activity Bar --- >

export const ACTIVITY_BAR_BACKGROUND = registerColor('activityBar.background', {
	dark: '#333333',
	light: '#2C2C2C',
	hc: '#000000'
}, nls.localize('activityBarBackground', "Activity bar background color. The activity bar is showing on the far left or right and allows to switch between views of the side bar."));

export const ACTIVITY_BAR_FOREGROUND = registerColor('activityBar.foreground', {
	dark: Color.white,
	light: Color.white,
	hc: Color.white
}, nls.localize('activityBarForeground', "Activity bar foreground color (e.g. used for the icons). The activity bar is showing on the far left or right and allows to switch between views of the side bar."));

export const ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND = registerColor('activityBar.dropBackground', {
	dark: Color.white.transparent(0.12),
	light: Color.white.transparent(0.12),
	hc: Color.white.transparent(0.12),
}, nls.localize('activityBarDragAndDropBackground', "Drag and drop feedback color for the activity bar items. The color should have transparency so that the activity bar entries can still shine through. The activity bar is showing on the far left or right and allows to switch between views of the side bar."));

export const ACTIVITY_BAR_BADGE_BACKGROUND = registerColor('activityBarBadge.background', {
	dark: badgeBackground,
	light: badgeBackground,
	hc: badgeBackground
}, nls.localize('activityBarBadgeBackground', "Activity notification badge background color. The activity bar is showing on the far left or right and allows to switch between views of the side bar."));

export const ACTIVITY_BAR_BADGE_FOREGROUND = registerColor('activityBarBadge.foreground', {
	dark: badgeForeground,
	light: badgeForeground,
	hc: badgeForeground
}, nls.localize('activityBarBadgeForeground', "Activity notification badge foreground color. The activity bar is showing on the far left or right and allows to switch between views of the side bar."));

// < --- Side Bar --- >

export const SIDE_BAR_BACKGROUND = registerColor('sideBar.background', {
	dark: '#252526',
	light: '#F3F3F3',
	hc: '#000000'
}, nls.localize('sideBarBackground', "Side bar background color. The side bar is the container for views like explorer and search."));

export const SIDE_BAR_TITLE_FOREGROUND = registerColor('sideBarTitle.foreground', {
	dark: '#BBBBBB',
	light: '#6f6f6f',
	hc: '#FFFFFF'
}, nls.localize('sideBarTitleForeground', "Side bar title foreground color. The side bar is the container for views like explorer and search."));

export const SIDE_BAR_SECTION_HEADER_BACKGROUND = registerColor('sideBarSectionHeader.background', {
	dark: Color.fromHex('#808080').transparent(0.2),
	light: Color.fromHex('#808080').transparent(0.2),
	hc: null
}, nls.localize('sideBarSectionHeaderBackground', "Side bar section header background color. The side bar is the container for views like explorer and search."));

// < --- Title Bar --- >

export const TITLE_BAR_ACTIVE_FOREGROUND = registerColor('titleBar.activeForeground', {
	dark: '#CCCCCC',
	light: '#333333',
	hc: '#FFFFFF'
}, nls.localize('titleBarActiveForeground', "Title bar foreground when the window is active. Note that this color is currently only supported on macOS."));

export const TITLE_BAR_INACTIVE_FOREGROUND = registerColor('titleBar.inactiveForeground', {
	dark: transparent(TITLE_BAR_ACTIVE_FOREGROUND, 0.6),
	light: transparent(TITLE_BAR_ACTIVE_FOREGROUND, 0.6),
	hc: null
}, nls.localize('titleBarInactiveForeground', "Title bar foreground when the window is inactive. Note that this color is currently only supported on macOS."));

export const TITLE_BAR_ACTIVE_BACKGROUND = registerColor('titleBar.activeBackground', {
	dark: '#3C3C3C',
	light: '#DDDDDD',
	hc: '#000000'
}, nls.localize('titleBarActiveBackground', "Title bar background when the window is active. Note that this color is currently only supported on macOS."));

export const TITLE_BAR_INACTIVE_BACKGROUND = registerColor('titleBar.inactiveBackground', {
	dark: transparent(TITLE_BAR_ACTIVE_BACKGROUND, 0.6),
	light: transparent(TITLE_BAR_ACTIVE_BACKGROUND, 0.6),
	hc: null
}, nls.localize('titleBarInactiveBackground', "Title bar background when the window is inactive. Note that this color is currently only supported on macOS."));

// < --- Notifications --- >

export const NOTIFICATIONS_FOREGROUND = registerColor('notification.foreground', {
	dark: '#EEEEEE',
	light: '#EEEEEE',
	hc: '#FFFFFF'
}, nls.localize('notificationsForeground', "Notifications foreground color. Notifications slide in from the top of the window."));

export const NOTIFICATIONS_BACKGROUND = registerColor('notification.background', {
	dark: '#333333',
	light: '#2C2C2C',
	hc: '#000000'
}, nls.localize('notificationsBackground', "Notifications background color. Notifications slide in from the top of the window."));

/**
 * Base class for all themable workbench components.
 */
export class Themable extends Disposable {
	private _toUnbind: IDisposable[];
	private theme: ITheme;

	constructor(
		protected themeService: IThemeService
	) {
		super();

		this._toUnbind = [];
		this.theme = themeService.getTheme();

		// Hook up to theme changes
		this._toUnbind.push(this.themeService.onThemeChange(theme => this.onThemeChange(theme)));
	}

	protected get toUnbind() {
		return this._toUnbind;
	}

	protected onThemeChange(theme: ITheme): void {
		this.theme = theme;

		this.updateStyles();
	}

	protected updateStyles(): void {
		// Subclasses to override
	}

	protected getColor(id: string, modify?: (color: Color, theme: ITheme) => Color): string {
		let color = this.theme.getColor(id);

		if (color && modify) {
			color = modify(color, this.theme);
		}

		return color ? color.toString() : null;
	}

	public dispose(): void {
		this._toUnbind = dispose(this._toUnbind);

		super.dispose();
	}
}


text:
author: Michael Paquier
lastmod: 2016-07-11
date: 2016-07-11 06:40:13+00:00
layout: post
type: post
slug: postgres-9-6-feature-highlight-pg-blocking-pids
title: 'Postgres 9.6 feature highlight - pg_blocking_pids'
categories:
- PostgreSQL-2
tags:
- postgres
- postgresql
- 9.6
- lock
- monitoring

---

pg\_blocking\_pids is one of those things that makes the life of analysis
tasks easier in Postgres. It has been introduced in 9.6 with the following
commit:

    commit: 52f5d578d6c29bf254e93c69043b817d4047ca67
    author: Tom Lane <tgl@sss.pgh.pa.us>
    date: Mon, 22 Feb 2016 14:31:43 -0500
    Create a function to reliably identify which sessions block which others.

    This patch introduces "pg_blocking_pids(int) returns int[]", which returns
    the PIDs of any sessions that are blocking the session with the given PID.
    Historically people have obtained such information using a self-join on
    the pg_locks view, but it's unreasonably tedious to do it that way with any
    modicum of correctness, and the addition of parallel queries has pretty
    much broken that approach altogether.  (Given some more columns in the view
    than there are today, you could imagine handling parallel-query cases with
    a 4-way join; but ugh.)

    [...]

You can refer to the
[commit text](https://git.postgresql.org/pg/commitdiff/52f5d578d6c29bf254e93c69043b817d4047ca67)
in full to get more details regarding why this function is better than a
join on the system catalogs pg\_locks (self join with one portion being the
waiter, and the other the holder, doing field-by-field comparisons), from which
is a short summary:

  * Better understanding of which lock mode blocks the other.
  * When multiple sessions are queuing to wait for a lock, only the one
  at the head is reported.
  * With parallel queries, all the PIDs of the parallel sessions are
  reported. Note that it is possible in this case that duplicated PIDs
  are reported here because for example multiple waiters are blocked by
  the same PID.

Note that the primary reason for its introduction is to simplify the isolation
testing facility that has been querying directly pg\_locks to get information
on the lock status between lock holders and waiters.

This function takes in input the PID of a session, and returns a set of PIDS
taking a lock that this session whose PID is used in input is waiting for.
So let's take an example, here is a session 1:

    =# CREATE TABLE tab_locked (a int);
    CREATE TABLE
    =# SELECT pg_backend_pid();
     pg_backend_pid
    ----------------
              68512
    (1 row)

And a session 2:

    =# BEGIN;
    BEGIN
    =# LOCK tab_locked IN ACCESS EXCLUSIVE MODE;
    LOCK TABLE
    =# SELECT pg_backend_pid();
     pg_backend_pid
    ----------------
              69223
    (1 row)

Finally by coming back to session 1, let's stuck it:

    =# INSERT INTO tab_locked VALUES (1);
    -- Hey I am stuck here

Then here comes pg\_blocking\_pids, one can fetch the following result,
reporting that the session taking the lock on table 'tab_locked' is blocking
the session trying to insert a tuple:

    =# SELECT pg_blocking_pids(68512);
     pg_blocking_pids
    ------------------
     {69223}
    (1 row)

... Which is not something complicated in itself, but it is surely going to
save a lot of typing or simplify a couple of extensions that have been doing
the same kind of work. Now, looking at the code in lockfuncs.c, this code is
actually far faster because it does directly lookups of the PGPROC entries
to gather the information regarding what the blocking information.

An even more interesting thing is the introduction of GetBlockerStatusData(),
which allows fetching the locking status data of a blocked PID to be able
to use that in a reporting function or any other facility. This is definitely
useful for people working on monitoring facilities aimed to track activity
of Postgres instances.


text:
@extends('dashboard')
@section('main')

<?php
$individual= User::find(Auth::user()->id);

//$individual=Individual::account()->find($account->id);
?>
<h1 class="page-title"User Account

Basic Information

Profile

Change Password

            	<form id="edit-profile" class="form-horizontal">
												<fieldset>

														First Name

															<input type="text" class="input-xlarge" id="firstname" value="{{ $individual->first_name }}">

														Middle Name

															<input type="text" class="input-xlarge" id="firstname" value="{{ $individual->middle_name }}">

														Last Name

															<input type="text" class="input-xlarge" id="lastname" value="{{ $individual->last_name }}">

														Change Photo

															<input type="file" id="files" name="files[]" multiple />
															<output id="list"></output>

															<button type="reset" class="btn">Reset</button>
															<button type="submit" class="btn">Add</button>

												</fieldset>
											</form>

		            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
		            Password changed successfully!

                <form class="form-horizontal" id="my_f" action="" method="POST">

								Current Password*

								<input type="hidden" value="{{url('password/change')}}" id="urlPass" />
								<input type="hidden" value="{{url('password/pax')}}" id="urlPax" />
								<input type="password" class="input-xlarge" id="olpax"  value="" required>

								New Password

								<input type="password" class="input-xlarge" id="npax" value="">

								Confirm Password

								<input type="password" class="input-xlarge" id="cpax" value="">

								<button type="button" style="display: none" class="btn btn-primary" id="chbtn">Reset</button>

                	</form>

@stop


text:
package apollo.xml_handlers;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.nio.file.Path;

public class XmlElementFactory {

    public Element createRootXmlElement(Path pathToXml){
        Document document = null;

        try{
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(pathToXml.toFile());
        }  catch (ParserConfigurationException | IOException | SAXException e) {
            e.printStackTrace();
        }

        return document.getDocumentElement();
    }
}


text:
package zutil.osal.linux.app;

import zutil.Timer;
import zutil.converter.Converter;
import zutil.log.LogUtil;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Makes the Linux ARP cache available as Java api
 * <p>
 * Created by Ziver on 2015-05-19.
 */
public class ProcNetArp {
    private static final Logger logger = LogUtil.getLogger();
    private static final String PROC_PATH = "/proc/net/arp";
    private static final int TTL = 500; // update stats every 0.5 second

    private static HashMap<InetAddress, ArpEntry> arpTable = new HashMap<>();
    private static Timer updateTimer = new Timer(TTL);

    private synchronized static void update() {
        if (!updateTimer.hasTimedOut())
            return;

        try {
            BufferedReader in = new BufferedReader(new FileReader(PROC_PATH));
            parse(in);
            in.close();
        } catch (IOException e) {
            logger.log(Level.SEVERE, null, e);
        }
    }
    protected static void parse(BufferedReader in) throws IOException {
        updateTimer.start();
        String line;
        in.readLine(); // Skipp headers
        while ((line = in.readLine()) != null) {
            String[] str = line.split("\\s+");

            if (str.length >= 6) {
                InetAddress ip = InetAddress.getByName(str[0]);
                if (!arpTable.containsKey(ip))
                    arpTable.put(ip, new ArpEntry());
                ArpEntry entry = arpTable.get(ip);
                entry.ip = ip;
                entry.hwAddress = Converter.hexToByte(str[3].replaceAll(":", ""));
                entry.netIf = str[5];
            } else
                logger.warning(PROC_PATH + " contains unrecognized format");
        }
    }

    public static Collection<ArpEntry> getAllArpEntries() {
        update();
        return arpTable.values();
    }

    public static ArpEntry getArpEntry(InetAddress ip) {
        update();
        return arpTable.get(ip);
    }

    public static class ArpEntry {
        private InetAddress ip;
        private byte[] hwAddress;
        private String netIf;

        public InetAddress getIp() {
            return ip;
        }

        public byte[] getHwAddress() {
            return hwAddress;
        }

        public String getHwAddressString() {
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < hwAddress.length; i++) {
                if (i != 0)
                    str.append(':');
                str.append(Converter.toHexString(hwAddress[i]));
            }
            return str.toString();
        }

        public String getNetworkInterface() {
            return netIf;
        }
    }

    public static void main(String[] args) {
        for (ArpEntry entry : getAllArpEntries()) {
            System.out.println(entry.getIp().getHostAddress() + " => " + entry.getHwAddressString());
        }
    }
}


text:
package com.github.moreaunicolas.util.function;

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

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.Supplier;

import com.github.moreaunicolas.test.UtilityClassAssert;
import org.junit.Test;

public class UncheckedSupplierTests {

    private static final String MESSAGE = "OOPS!";

    @Test
    public void supplierWrapperShouldDelegateToWrappedSupplier() {
        Supplier<String> wrapper = UncheckedSupplier.from(() -> "42");

        String actual = wrapper.get();

        assertThat(actual).isEqualTo("42");
    }

    @Test
    public void supplierWrapperShouldRethrowRuntimeExceptions() {
        RuntimeException runtimeException = new RuntimeException(MESSAGE);
        Supplier<Object> wrapper = UncheckedSupplier.from(() -> {
            throw runtimeException;
        });

        Throwable throwable = catchThrowable(wrapper::get);

        assertThat(throwable).isSameAs(runtimeException);
    }

    @Test
    public void supplierWrapperShouldWrapIOExceptions() {
        IOException ioException = new IOException(MESSAGE);
        Supplier<Object> wrapper = UncheckedSupplier.from(() -> {
            throw ioException;
        });

        Throwable throwable = catchThrowable(wrapper::get);

        assertThat(throwable)
                .isInstanceOf(UncheckedIOException.class)
                .hasCause(ioException);
    }

    @Test
    public void supplierWrapperShouldWrapCheckedExceptions() {
        Exception exception = new Exception(MESSAGE);
        Supplier<Object> wrapper = UncheckedSupplier.from(() -> {
            throw exception;
        });

        Throwable throwable = catchThrowable(wrapper::get);

        assertThat(throwable)
                .isInstanceOf(RuntimeException.class)
                .hasCause(exception);
    }

    @Test
    public void isUtilityClass() throws NoSuchMethodException {
        UtilityClassAssert.assertThat(UncheckedSupplier.class)
                .isUtilityClass();
    }
}


text:
angular.module('Starscream.Services').factory('userService', function () {

    var key = "user";

    return {
        SetUser: function (email, name, token, remember, expires, claims) {
            var user = {
                email: email,
                name: name,
                token: token,
                expires: expires,
                claims: claims
            };

            var userString = JSON.stringify(user);

            if (remember) {
                window.localStorage.setItem(key, userString);
            } else {
                window.sessionStorage.setItem(key, userString);
            }
        },
        GetUser: function () {
            var user;
            var userFromLocalStorage = window.localStorage.getItem(key);
            if (userFromLocalStorage) {
                user = JSON.parse(userFromLocalStorage);
            } else {
                var userFromSession = window.sessionStorage.getItem(key);
                if (!userFromSession) return false;
                user = JSON.parse(userFromSession);
            }
            var expires = new Date(user.expires);
            var isExpired = expires < new Date();
            if (isExpired) {
                this.RemoveUser();
                return false;
            }
            return user;
        },
        RemoveUser: function () {
            window.sessionStorage.removeItem("user");
            window.localStorage.removeItem("user");
        },

    };
});


text:
var log = function(msg) {
    $("body").append("<h1>"+msg+"</h1>");
};

App = {
    getAnimals: function() {
        var endpoint = $(".endpoint").val()+"/animals";
        log("click"+endpoint);
        $.get(endpoint, function(data) {
            log("retrieved");
            $.each(data, function(i, animal) {$(".animals").text(animal.name);});
        }).fail(
            function(xhr, text, error) {
                log("failed");
            $(".animals").text("Bob retrieval failed! text='" + text + "' error='" + error + "' status='" + xhr.status + "' response='" + xhr.responseText + "'");
            console.log("error: %o %o %o", xhr, text, error)
        });
    }
};

$(function() {
    log("loaded");
    $(".getAnimals").on("click", App.getAnimals);
    log("bound");
});


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Quiz</title>

    <meta name="description" content="A framework for easily creating beautiful presentations using HTML">
    <meta name="author" content="Hakim El Hattab">

    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>

    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

          <link rel="stylesheet" href="reveal.js/css/reveal.css">

          <link rel="stylesheet" href="reveal.js/css/theme/solarized.css" id="theme">

          <link rel="stylesheet" href="reveal.js/lib/css/zenburn.css">

        <textarea data-template>
# Quiz

https://djcordhose.github.io/ai/2019_quiz.html

    </textarea>

    <textarea data-template>

### 12 Fragen
## Zwei Teams spielen gegeneinander
### Bei schnellen Antworten zählt die schnellste richtige, keine zweite Antwort möglich

_Bildet jetzt Teams_

    </textarea>

            <textarea data-template>
### Welcher Code funktioniert?

    w = tf.constant([[1.5], [-2], [1]], dtype='float32')
    x = tf.constant([[10, 6, 8]], dtype='float32')
    b = tf.constant([6], dtype='float32')

    y = tf.matmul(x, w) + b
</textarea>

        <textarea data-template>
### Was war die erste Millionen-Stadt?

https://twitter.com/i/status/1107595419557740549

https://observablehq.com/@johnburnmurdoch/bar-chart-race-the-most-populous-cities-in-the-world

https://flourish.studio/2019/03/21/bar-chart-race/

https://twitter.com/mbostock/status/1108852672839315456

</textarea>

    <textarea data-template>
### Wie viele 5en? (die schnellste Antwort zählt)

Theory of attention: https://static.googleusercontent.com/media/research.google.com/en//bigpicture/ML_Visualization_NeurIPS_Tutorial.pdf

</textarea>

        <textarea data-template>
### Was ist das besondere an diesen Fisch, der gegen den Strom schwimmt?

https://twitter.com/chubicki/status/1000457946734759936

</textarea>

    <textarea data-template>
### Emergenz

Was ist auf diesem Bild? schnellste richtige Antwort gewinnt

https://eggbertsplace.github.io/principles-of-gestalt/#slide=4

P. Sinha & T. Adelson (1997)

</textarea>

    <textarea data-template>
### Logik

_Warum ist das ein schwacher Witz?_

</textarea>

    <textarea data-template>
### Info-Runde: Bias 1

</textarea>

    <textarea data-template>
### Sequentielle Wahrnehmung #1

Wie viele? Die schnellste richtige Antwort gewinnt

https://twitter.com/SteveFranconeri/status/996309506425544705

</textarea>

    <textarea data-template>
### Wissenschaft

_Welcher dieser vermeintlichen Fakten ist wissenschaftlich nicht belegbar?_

1. Alkohol tötet Gehirnzellen
1. Glas ist eine sehr zähe Flüssigkeit
1. Wir stammen vom Affen ab
1. Wir nutzen nur 10% unserer Hirn-Kapazität

https://www.verywellmind.com/myths-about-the-brain-2794884
https://thebestschools.org/magazine/25-popular-science-myths-debunked/

</textarea>

    <textarea data-template>
### Welches ist das häufigste Element in der Erdkruste

https://research.google.com/bigpicture/elements/

</textarea>

    <textarea data-template>
### Sequentielle Wahrnehmung #2

Wie viele? Die schnellste richtige Antwort gewinnt

https://twitter.com/SteveFranconeri/status/996309506425544705

</textarea>

    <textarea data-template>
### Rein Logisch betrachtet

Ein Geschäftspartner kündigt an, mich überraschend nächste Woche an einem der Werktage um exakt 9 Uhr morgens anzurufen.

An welchem Tag wird er anrufen?

</textarea>

    <textarea data-template>
### Statistik

Im zweiten Weltkriegt zeigten von der US Navy untersuchte Flugzeuge hier Treffer durch Beschuss

_Wo würdest du die Panzerung verstärken?_

https://twitter.com/ricfulop/status/1101976862325174276

</textarea>

    <textarea data-template>
### Wahrnehmung ist mehrdeutig

Handtasche oder Dackel? schnellste richtige Antwort gewinnt

https://twitter.com/dumb_hannah/status/891678558841708544

</textarea>

    <textarea data-template>
### Statistik

Nehmen wir an, 90% aller Statistiker sind schütern und nur 5% aller Verkäufer

_Du triffst einen schüchternen Menschen, ist er eher Statistiker oder Verkäufer?_

</textarea>

    <textarea data-template>
### Info-Runde: Bias 2

</textarea>

    <textarea data-template>
### Psychologie

_Welcher dieser vermeintlichen Fakten ist wissenschaftlich nicht belegbar?_

1. Power Posing (TED Talk von Harvard Psychologin Amy Cuddy) ist effektiv
1. Wir haben unterschiedliche Lernstile (Audio, Visuell, etc.)
1. Man kann Menschen in linke/rechte Gehirnhälfe-Typen einteilen
1. Männer kommen vom Mars, Frauen von der Venus

https://www.scienceofpeople.com/myths-pop-psychology/

https://www.mindful.org/7-common-pop-psychology-myths-might-spreading/

https://www.verywellmind.com/myths-about-the-brain-2794884

https://hackspirit.com/scientist-debunks-10-popular-psychology-myths-people-believe/

</textarea>

    <textarea data-template>
### Sequentielle Wahrnehmung #3

Was und wie oft? Die schnellste richtige Antwort gewinnt

_4x Abholer_

</textarea>


text:
module.exports = {
  API_ROOT: rootUrl + 'api' //jshint ignore: line
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sber. Akad. Wiss. Wien, Math. -naturw. Kl. , Abt. 1 118: 1182 (1909)

#### Original name
Aschersonia sclerotioides Henn.

### Remarks
null


text:
require "test_helper"

class MinutesControllerTest < ActionController::TestCase
  setup do
    @minute = minutes(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:minutes)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create minute" do
    assert_difference("Minute.count") do
      post :create, minute: {date: @minute.date, status: @minute.status, text: @minute.text}
    end

    assert_redirected_to minute_path(assigns(:minute))
  end

  test "should show minute" do
    get :show, id: @minute
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @minute
    assert_response :success
  end

  test "should update minute" do
    patch :update, id: @minute, minute: {date: @minute.date, status: @minute.status, text: @minute.text}
    assert_redirected_to minute_path(assigns(:minute))
  end

  test "should destroy minute" do
    assert_difference("Minute.count", -1) do
      delete :destroy, id: @minute
    end

    assert_redirected_to minutes_path
  end
end


text:
package org.commcare.preferences;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.commons.io.FilenameUtils;
import org.commcare.dalvik.R;
import org.commcare.util.LogTypes;
import org.commcare.utils.FileExtensionNotFoundException;
import org.commcare.utils.FileUtil;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import androidx.preference.EditTextPreferenceDialogFragmentCompat;

import static androidx.appcompat.app.AppCompatActivity.RESULT_OK;

public class FilePreferenceDialogFragmentCompat extends EditTextPreferenceDialogFragmentCompat {

    public static final int REQUEST_FILE = 1;
    private EditText mSavedFilePathText;
    private EditText mDisplayText;

    public static FilePreferenceDialogFragmentCompat newInstance(String key) {
        final FilePreferenceDialogFragmentCompat fragment = new FilePreferenceDialogFragmentCompat();
        final Bundle b = new Bundle(1);
        b.putString(ARG_KEY, key);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);
        mSavedFilePathText = view.findViewById(android.R.id.edit);
        mDisplayText = view.findViewById(R.id.display_field);
        view.findViewById(R.id.filefetch).setOnClickListener(v -> {
            MainConfigurablePreferences.startFileBrowser(FilePreferenceDialogFragmentCompat.this,
                    REQUEST_FILE,
                    Localization.get("no.file.browser.title"));
        });
        if (mSavedFilePathText.getText() != null) {
            File f = new File(mSavedFilePathText.getText().toString());
            if (f.exists()) {
                mDisplayText.setText(f.getName());
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_FILE) {
            if (resultCode == RESULT_OK && intent != null) {
                Uri uri = intent.getData();
                if (uri != null) {
                    try {
                        String fileName = FileUtil.getFileName(getContext(), uri);
                        File destination = new File(getContext().getExternalCacheDir(), fileName);
                        InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
                        FileUtil.copyFile(inputStream, destination);
                        validateFile(destination.getAbsolutePath());
                    } catch (FileExtensionNotFoundException e) {
                        Logger.exception("Error while fetching file ", e);
                        Toast.makeText(getActivity(), Localization.get("file.selection.invalid.extension"), Toast.LENGTH_LONG).show();
                        return;
                    }  catch (IOException e) {
                        Logger.exception("Error while fetching file ", e);
                        Toast.makeText(getActivity(), Localization.get("file.selection.failed"), Toast.LENGTH_LONG).show();
                        return;
                    }
                } else {
                    Toast.makeText(getActivity(), Localization.get("file.selection.failed"), Toast.LENGTH_LONG).show();
                }
            } else {
                //No file selected
                Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show();
            }
        }
    }

    private String getNewPathFromUri(Uri uri) throws IOException {
        // We can't get access to filePath but only the uri and
        // since we are going to use this path later on in some other
        // activity stack which will not have permissions for this uri
        // we need to copy the file internally and pass the filepath of the new file
        String filePath = getContext().getFilesDir().getAbsolutePath() + "/temp/" + FileUtil.getFileName(uri.toString());
        File file = new File(filePath);
        InputStream fileStream = getContext().getContentResolver().openInputStream(uri);
        FileUtil.ensureFilePathExists(file);
        FileUtil.copyFile(fileStream, file);
        return filePath;
    }

    @Override
    public void onDialogClosed(boolean positiveResult) {
        if (positiveResult && validateFile(mSavedFilePathText.getText().toString())) {
            super.onDialogClosed(positiveResult);
        }
    }

    /**
     * Checks whether a file with given filepath is a valid file
     *
     * @param filePath filepath of file that needs to be validated
     * @return true if filepath represents a valid file or if filepath is empty, false otherwise.
     */
    private boolean validateFile(String filePath) {
        String fileType = ((FilePreference)getPreference()).getFileType();
        if (filePath != null && !filePath.isEmpty()) {
            if (fileType == null || FilenameUtils.getExtension(filePath).contentEquals(fileType)) {
                File f = new File(filePath);
                if (f.exists()) {
                    if (!mSavedFilePathText.getText().toString().contentEquals(filePath)) {
                        mSavedFilePathText.setText(filePath);
                        mDisplayText.setText(f.getName());
                    }
                    return true;
                } else {
                    Toast.makeText(getActivity(), Localization.get("file.not.exist"), Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getActivity(), Localization.get("file.wrong.type", fileType), Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show();
            // We still want to reset the preference to empty file path
            return true;
        }
        return false;
    }
}


text:
Originally published: 2011-07-27 15:23:24
Last updated: 2011-07-27 15:23:29
Author: mJack

This small program lets a user delete a directory on their Windows system.
Also good for learning from.


text:
namespace Boilerplate.Web.Mvc.OpenGraph
{
    /// <summary>
    /// An object representing a website. This object type is part of the Open Graph standard.
    /// See http://ogp.me/
    /// </summary>
    public class OpenGraphWebsite : OpenGraphMetadata
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="OpenGraphWebsite"/> class.
        /// </summary>
        /// <param name="title">The title of the object as it should appear in the graph.</param>
        /// <param name="image">The default image.</param>
        /// <param name="url">The canonical URL of the object, used as its ID in the graph.</param>
        public OpenGraphWebsite(string title, OpenGraphImage image, string url = null)
            : base(title, image, url)
        {
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the namespace of this open graph type.
        /// </summary>
        public override string Namespace { get { return "website: http://ogp.me/ns/website#"; } }

        /// <summary>
        /// Gets the type of your object. Depending on the type you specify, other properties may also be required.
        /// </summary>
        public override OpenGraphType Type { get { return OpenGraphType.Website; } }

        #endregion
    }
}


text:
@echo off
@SETLOCAL
SET BASEDIR=%cd%

SET CONDA_BIN=%2

call %CONDA_BIN% create -y -n symdiff_build python=3.7
if %errorlevel% neq 0 exit /b %errorlevel%

call %CONDA_BIN% install -y -n symdiff_build cmake tk
if %errorlevel% neq 0 exit /b %errorlevel%

call %CONDA_BIN% activate symdiff_build
if %errorlevel% neq 0 exit /b %errorlevel%

SET PATH="c:\msys64\usr\bin;%PATH%"
c:\msys64\usr\bin\bash %~dp0\setup_appveyor.sh %1
if %errorlevel% neq 0 exit /b %errorlevel%


text:
'use strict'

var path   = require('path')
  , http   = require('http')
  , events = require('events')
  , chai   = require('chai')
  , expect = chai.expect
  , helper = require('../../../lib/agent_helper')
  , NAMES  = require('../../../../lib/metrics/names.js')
  , instrumentOutbound = require('../../../../lib/transaction/tracer/instrumentation/outbound.js')
  , hashes             = require('../../../../lib/util/hashes')

describe("instrumentOutbound", function () {
  var agent
    , HOSTNAME = 'localhost'
    , PORT     = 8890

  before(function () {
    agent = helper.loadMockedAgent()
  })

  after(function () {
    helper.unloadAgent(agent)
  })

  describe("when working with http.createClient", function () {
    before(function () {
      // capture the deprecation warning here
      http.createClient()
    })

    function test(expectedPort, expectedHost, port, host) {
      var client = http.createClient(port, host)
      expect(client.port).equal(expectedPort)
      expect(client.host).equal(expectedHost)
    }

    it("should provide default port and hostname", function () {
      test(80, 'localhost')
    })

    it("should accept port and provide default hostname", function () {
      test(8089, 'localhost', 8089)
    })

    it("should accept port and hostname", function () {
      test(8089, 'me', 8089, 'me')
    })

    it("should set default port on null port", function () {
      test(80, 'me', null, 'me')
    })

    it("should provide default port and hostname on nulls", function () {
      test(80, 'localhost', null, null)
    })
  })

  it("should strip query parameters from path in transaction trace segment", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function (transaction) {
      var path  = '/asdf'
        , name  = NAMES.EXTERNAL.PREFIX + HOSTNAME + ':' + PORT + path

      req.path  = '/asdf?a=b&another=yourself&thing&grownup=true'
      instrumentOutbound(agent, req, HOSTNAME, PORT)
      expect(transaction.getTrace().root.children[0].name).equal(name)
    })
  })

  it("should save query parameters from path if capture is defined", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function (transaction) {
      agent.config.capture_params = true
      req.path  = '/asdf?a=b&another=yourself&thing&grownup=true'
      instrumentOutbound(agent, req, HOSTNAME, PORT)
      expect(transaction.getTrace().root.children[0].parameters).deep.equal({
        "a"                            : "b",
        "nr_exclusive_duration_millis" : null,
        "another"                      : "yourself",
        "thing"                        : true,
        "grownup"                      : "true"
      })
    })
  })

  it("should not accept an undefined path", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function () {
      expect(function () {
        instrumentOutbound(agent, req, HOSTNAME, PORT)
      }).to.throw(Error)
    })
  })

  it("should accept a simple path with no parameters", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function (transaction) {
      var path  = '/newrelic'
        , name  = NAMES.EXTERNAL.PREFIX + HOSTNAME + ':' + PORT + path
      req.path  = path
      instrumentOutbound(agent, req, HOSTNAME, PORT)
      expect(transaction.getTrace().root.children[0].name).equal(name)
    })
  })

  it("should purge trailing slash", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function (transaction) {
      var path  = '/newrelic/'
        , name  = NAMES.EXTERNAL.PREFIX + HOSTNAME + ':' + PORT + '/newrelic'
      req.path  = path
      instrumentOutbound(agent, req, HOSTNAME, PORT)
      expect(transaction.getTrace().root.children[0].name).equal(name)
    })
  })

  it("should throw if hostname is undefined", function () {
    var req  = new events.EventEmitter()
      , undef

    helper.runInTransaction(agent, function () {
      req.path = '/newrelic'
      expect(function TestUndefinedHostname() {
        instrumentOutbound(agent, req, undef, PORT)
      }).to.throw(Error)
    })
  })

  it("should throw if hostname is null", function () {
    var req  = new events.EventEmitter()

    helper.runInTransaction(agent, function () {
      req.path = '/newrelic'
      expect(function TestUndefinedHostname() {
        instrumentOutbound(agent, req, null, PORT)
      }).to.throw(Error)
    })
  })

  it("should throw if hostname is an empty string", function () {
    var req  = new events.EventEmitter()
    helper.runInTransaction(agent, function () {
      req.path = '/newrelic'
      expect(function TestUndefinedHostname() {
        instrumentOutbound(agent, req, '', PORT)
      }).to.throw(Error)
    })
  })

  it("should throw if port is undefined", function () {
    var req  = new events.EventEmitter()
      , undef

    helper.runInTransaction(agent, function () {
      req.path = '/newrelic'
      expect(function TestUndefinedHostname() {
        instrumentOutbound(agent, req, 'hostname', undef)
      }).to.throw(Error)
    })
  })
})

describe('should add data from cat header to segment', function () {
  var encKey = 'gringletoes'
  var server
  var agent

  var app_data = [
    '123#456',
    'abc',
    0,
    0,
    -1,
    'xyz'
  ]

  before(function (done) {
    agent = helper.instrumentMockedAgent(
      {cat: true},
      {encoding_key: encKey, trusted_account_ids: [123]}
    )
    server = http.createServer(function(req, res) {
      res.writeHead(200, {
        'x-newrelic-app-data': hashes.obfuscateNameUsingKey(JSON.stringify(app_data), encKey)
      })
      res.end()
      req.resume()
    })
    server.listen(4123, done)
  })

  after(function (done) {
    helper.unloadAgent(agent)
    server.close(done)
  })

  function addSegment() {
    var transaction = agent.getTransaction()
    transaction.webSegment = {
      getDurationInMillis: function fake() {
        return 1000;
      }
    }
  }

  it('should use config.obfuscatedId as the x-newrelic-id header', function(done) {
    helper.runInTransaction(agent, function() {
      addSegment()
      http.get({host : 'localhost', port : 4123}, function(res) {
        var segment = agent.tracer.getSegment()

        expect(segment.catId).equal('123#456')
        expect(segment.catTransaction).equal('abc')
        expect(segment.name).equal('ExternalTransaction/localhost:4123/123#456/abc')
        expect(segment.parameters.transaction_guid).equal('xyz')
        res.resume()
        agent.getTransaction().end()
        done()
      }).end()
    })
  })

  it('should not explode with invalid data', function(done) {
    helper.runInTransaction(agent, function() {
      addSegment()
      http.get({host : 'localhost', port : 4123}, function(res) {
        var segment = agent.tracer.getSegment()

        expect(segment.catId).equal('123#456')
        expect(segment.catTransaction).equal('abc')

        // TODO: port in metric is a known bug. issue #142
        expect(segment.name).equal('ExternalTransaction/localhost:4123/123#456/abc')
        expect(segment.parameters.transaction_guid).equal('xyz')
        res.resume()
        agent.getTransaction().end()
        done()
      }).end()
    })
  })
})


text: /*# sourceMappingURL=hero.styles.css.map */


text:
using Newtonsoft.Json;
using System;

namespace Monaco.Editor
{

    /// <summary>
    /// Enable highlighting of matching brackets.
    /// Defaults to 'always'.
    /// </summary>
    [JsonConverter(typeof(MatchBracketsConverter))]
    public enum MatchBrackets { Always, Near, Never };

    internal class MatchBracketsConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(MatchBrackets) || t == typeof(MatchBrackets?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            switch (value)
            {
                case "always":
                    return MatchBrackets.Always;
                case "near":
                    return MatchBrackets.Near;
                case "never":
                    return MatchBrackets.Never;
            }
            throw new Exception("Cannot unmarshal type MatchBrackets");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (MatchBrackets)untypedValue;
            switch (value)
            {
                case MatchBrackets.Always:
                    serializer.Serialize(writer, "always");
                    return;
                case MatchBrackets.Near:
                    serializer.Serialize(writer, "near");
                    return;
                case MatchBrackets.Never:
                    serializer.Serialize(writer, "never");
                    return;
            }
            throw new Exception("Cannot marshal type MatchBrackets");
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. eur. (Erlanga) 1: 337 (1822)

#### Original name
Stictis mollis Pers.

### Remarks
null


text:
import java.util.ArrayList;
import java.util.Scanner;

public class Paragraph {
  private ArrayList<String> sentences;

  public Paragraph() {
    sentences = new ArrayList<String>();
  }
  public void addSentence(String sentence) {
    sentences.add(sentence);
  }
  public void addTerminalInputSentence() {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a sentence:  ");
    String data = scanner.nextLine();
    addSentence(data);
  }
  public String toString() {
    String data = "";

    for (String sentence : sentences) {
      data = data + sentence + "\n";
    }
    return data;
  }
  public int numberOfSentences() {
    return sentences.size();
  }

  public void insert(String sentence, int index) {
    sentences.add(index, sentence);
  }

  public String remove(String sentence) {
    if (sentences.remove(sentence)) {return sentence;}
    else {return "";}
  }

  public void menu() {
    boolean needtoquit = false;

    while(!needtoquit) {
        System.out.println("\nList of selections:");
        System.out.println("addSentence");
        System.out.println("addTerminalInputSentence");
        System.out.println("toString");
        System.out.println("numberOfSentences");
        System.out.println("insert");
        System.out.println("remove");
        System.out.println("quit\n");

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a selection: ");
        String data = scanner.nextLine();

        if (data.equals("addSentence")) {
            addTerminalInputSentence();
        }
        else if (data.equals("addTerminalInputSentence")) {
            addTerminalInputSentence();
        }
        else if (data.equals("toString")) {
            System.out.println(toString());
        }
        else if (data.equals("numberOfSentences")) {
            System.out.println(numberOfSentences());
        }
        else if (data.equals("insert")) {
            System.out.print("Enter a sentence to insert: ");
            String data3 = scanner.nextLine();
            insert(data3, (sentences.size()));
        }
        else if (data.equals("remove")) {
            System.out.print("Enter a sentence to remove: ");
            String data2 = scanner.nextLine();
            remove(data2);
        }
        else if (data.equals("quit")) {
            needtoquit = true;
            System.out.println("You have quit.");
        }
    }
  }
}


text:
package com.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;

import com.implementations.TextTwist;
import com.implementations.list.TextTwistList;
import com.utils.GeradorMainEnsaio4;

public class TestLT4 {

    private static TextTwistList dictonaryList;

    private static BufferedReader sample;
    private static BufferedReader consult;

    private static PrintWriter resultsForList;

    static long startTime;
    private static String tempo_de_carga;
    private static String tempo_de_consulta;
    long endTime = System.nanoTime();

    private static Runtime runtime;
    private static String consumo_de_memoria;
    private static final long BYTE = 8L;
    private static final long KBYTE = 1024 * BYTE;
    private static final long MEGABYTE = 1024 * KBYTE;

    /**
     * Todo trecho de codigo referente ao calculo de consumo de memoria foi
     * copiado do seguinte link:
     * http://www.vogella.com/tutorials/JavaPerformance
     * /article.html#memory_overview
     */
    public static void main(String[] args) throws FileNotFoundException {

        // gerar arquivo com a classe GeradorMain
        GeradorMainEnsaio4.generateSample();
        dictonaryList = new TextTwistList();
        resultsForList = new PrintWriter("content/resultsForListTest4");

        resultsForList.println("Test metrics:");
        resultsForList.println(">>> words to search: 500.000");
        resultsForList.println(">>> words to load: 50.000.000");
        resultsForList.println("============================");
        resultsForList.println();

        openExperimentFiles();
        populateStructure(dictonaryList);
        performSearch(dictonaryList, resultsForList);

        resultsForList.println("============================");
        resultsForList.println();

        resultsForList.println(tempo_de_carga);
        resultsForList.println(tempo_de_consulta);
        calculateSpentMemory();
        resultsForList.println(consumo_de_memoria);
        resultsForList.close();
        closeExperimentFiles();
        dictonaryList = null;
        resultsForList = null;

        System.out.println("End search");
    }

    private static void populateStructure(TextTwist structure) {
        runtime = Runtime.getRuntime();

        startTime = System.currentTimeMillis();

        try {
            String sCurrentLine;
            int i = 0;
            while ((sCurrentLine = sample.readLine()) != null) {
                System.out.println(i++);
                sCurrentLine = sCurrentLine.trim();
                structure.insertInDictionary(sCurrentLine);

            }
            structure.insertInDictionary("MARIA");

        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        tempo_de_carga = "tempo_de_carga : " + (endTime - startTime) / 1000.0 + "s";

    }

    private static void performSearch(TextTwist structure, PrintWriter results) {
        runtime = Runtime.getRuntime();

        startTime = System.currentTimeMillis();

        try {
            String sCurrentLine;
            while ((sCurrentLine = consult.readLine()) != null) {
                String result = "<" + sCurrentLine.trim() + "> : ";
                sCurrentLine = sCurrentLine.toUpperCase();
                result += structure.searchWord(sCurrentLine) ? "S" : "N";
                results.println(result);
                System.out.println(result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        tempo_de_consulta = "tempo_de_consulta : " + (endTime - startTime) / 1000.0 + "s";

    }

    private static long bytesToMegabytes(long bytes) {
        return bytes / MEGABYTE;
    }

    private static void calculateSpentMemory() {
        // Run the garbage collector
        runtime.gc();
        // Calculate the used memory
        long memory = runtime.totalMemory() - runtime.freeMemory();
        consumo_de_memoria = "consumo_de_memoria: " + bytesToMegabytes(memory) + "MB";
    }

    private static void openExperimentFiles() throws FileNotFoundException {
        sample = new BufferedReader(new FileReader("content/sample_ensaio4.txt"));
        consult = new BufferedReader(new FileReader("content/consults_ensaio4.txt"));
    }

    private static void closeExperimentFiles() {
        try {
            if (sample != null) {
                sample.close();
            }
            sample = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
            if (consult != null) {
                consult.close();
            }
            consult = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}


text:
<?php declare(strict_types=1); # -*- coding: utf-8 -*-

namespace ChriCo\Fields\Element;

/**
 * Class Element
 *
 * @package ChriCo\Fields\Element
 */
class Element implements
    ElementInterface,
    LabelAwareInterface,
    ErrorAwareInterface,
    DescriptionAwareInterface
{
    use ErrorAwareTrait;
    use DescriptionAwareTrait;
    use LabelAwareTrait;

    protected array $attributes = [];

    protected array $options = [];

    /**
     * @var callable|null
     */
    protected $validator = null;

    /**
     * @var callable|null
     */
    protected $filter = null;

    /**
     * @param string $name
     */
    public function __construct(string $name)
    {
        $this->withAttribute('name', $name);
        $this->withAttribute('id', $name);
    }

    /**
     * @param string $key
     * @param bool|int|string $value
     *
     * @return Element
     */
    public function withAttribute(string $key, $value): ElementInterface
    {
        $this->attributes[$key] = $value;

        return $this;
    }

    /**
     * @return string
     */
    public function id(): string
    {
        return (string) $this->attribute('id');
    }

    /**
     * @param string $key
     *
     * @return bool|int|mixed|string
     */
    public function attribute(string $key)
    {
        if (!isset($this->attributes[$key])) {
            return '';
        }

        return $this->attributes[$key];
    }

    /**
     * @return bool
     */
    public function isDisabled(): bool
    {
        $disabled = $this->attribute('disabled');

        return is_bool($disabled) && $disabled;
    }

    /**
     * @return string
     */
    public function name(): string
    {
        return (string) $this->attribute('name');
    }

    /**
     * @return string
     */
    public function type(): string
    {
        return (string) $this->attribute('type');
    }

    /**
     * @return bool|int|mixed|string
     */
    public function value()
    {
        $value = $this->attribute('value');

        return $this->filter($value);
    }

    /**
     * @param string $value
     *
     * @return Element
     */
    public function withValue($value): Element
    {
        $this->withAttribute('value', $value);

        return $this;
    }

    /**
     * @return array
     */
    public function attributes(): array
    {
        return $this->attributes;
    }

    /**
     * @param array $attributes
     *
     * @return Element
     */
    public function withAttributes(array $attributes = []): Element
    {
        $this->attributes = array_merge(
            $this->attributes,
            $attributes
        );

        return $this;
    }

    /**
     * @return array
     */
    public function options(): array
    {
        return $this->options;
    }

    /**
     * @param array $options
     *
     * @return Element
     */
    public function withOptions(array $options = []): Element
    {
        $this->options = array_merge(
            $this->options,
            $options
        );

        return $this;
    }

    /**
     * @param string $key
     * @param int|string $value
     *
     * @return Element
     */
    public function withOption(string $key, $value): Element
    {
        $this->options[$key] = $value;

        return $this;
    }

    /**
     * @param string $key
     *
     * @return int|mixed|string
     */
    public function option(string $key)
    {
        if (!isset($this->options[$key])) {
            return '';
        }

        return $this->options[$key];
    }

    /**
     * @param callable $callable
     *
     * @return $this
     */
    public function withFilter(callable $callable): Element
    {
        $this->filter = $callable;

        return $this;
    }

    public function filter($value)
    {
        if ($this->filter) {
            $value = ($this->filter)($value);
        }

        return $value;
    }

    /**
     * @param callable $callable
     *
     * @return $this
     */
    public function withValidator(callable $callable): Element
    {
        $this->validator = $callable;

        return $this;
    }

    public function validate(): bool
    {
        $value = $this->value();

        $valid = true;
        if ($this->validator) {
            $error = ($this->validator)($value);
            if (is_wp_error($error)) {
                $this->withErrors($error->get_error_messages());
                $valid = false;
            }
        }

        return $valid;
    }
}