text:
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, RequestFactory

from rest_framework import status

from ..views import DeviceTokenSetter

class APITest(TestCase):

    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='donaldduck', password='topsecret')
        self.payloads = {
            'ios': {
                'token': 'iosdevicetokenabcdefghijklmnopqstuvwxyz0123456789',
                'kind': 'IOS'
            },
            'android': {
                'token': 'androiddevicetokenabcdefghijklmnopqstuvwxyz0123456789',
                'kind': 'ANDROID'
            },
            'invalid_ios': {
                'token': 'androiddevicetokenabcdefghijklmnopqstuvwxyz0123456789',
                'kind': 0
            }
        }

    def get_prepared_request(self, url='/', auth=True, payload=None):
        # Default payload is 'ios'
        payload = payload if payload in self.payloads.keys() else 'ios'
        # Create an instance of a POST request.
        request = self.factory.post(url, self.payloads[payload])
        # Disable CSRF checks
        request._dont_enforce_csrf_checks = True
        # Either logged in User or AnonymousUser
        request.user = self.user if auth else AnonymousUser()
        return request

    def test_anonymous_post(self):
        request = self.get_prepared_request(auth=False)
        response = DeviceTokenSetter.as_view()(request)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_post(self):
        # Create an instance of a POST request.
        request = self.get_prepared_request(auth=True, payload='ios')
        # Use this syntax for class-based views.
        response = DeviceTokenSetter.as_view()(request)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_duplicate_post(self):
        # NOTE: This does not work on SQLite as SQLite does not support 'unique_together'
        # Create an instance of a POST request.
        request = self.get_prepared_request(auth=True, payload='ios')
        # Use this syntax for class-based views.
        response = DeviceTokenSetter.as_view()(request)
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)

    def test_invalid_ios_post(self):
        # Create an instance of a GET request.
        request = self.get_prepared_request(auth=True, payload='invalid_ios')
        response = DeviceTokenSetter.as_view()(request)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


text:
(function(wysihtml5) {
  var STYLE_STR  = "text-align: right;",
      REG_EXP = /(\s|^)text-align\s*:\s*[^;\s]+;?/gi;

  wysihtml5.commands.alignRightStyle = {
    exec: function(composer, command) {
      return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP);
    },

    state: function(composer, command) {
      return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP);
    }
  };
})(wysihtml5);

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JourneyDiary.Web.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        #region 全局异常捕获

        /// <summary>
        /// 全局异常捕获测试
        /// </summary>
        public ActionResult TestException()
        {
            throw new Exception("test ception");
        }

        #endregion

        #region 使用分布视图加载数据

        public ActionResult News()
        {
            return View();
        }

        public ActionResult RenderNews(int pageIndex = 1, int pageSize = 10)
        {

            return PartialView();
        }

        #endregion
    }
}


text:
{% extends "forum/base.html" %}{% load forum_tags %}
{% block main_content %}
{% if topic.hidden %}

 This topic is hidden.

{% endif %}
{% if topic.locked %}

 This topic is locked.

{% endif %}
<form name="editTopicForm" id="editTopicForm" action="." method="POST">
{% csrf_token %}
  <fieldset class="module aligned">

Topic

      {% if topic_form.title.errors %}{{ form.title.errors.as_ul }}{% endif %}
      {{ form.title.label_tag }}

        {{ form.title }}

      {% if form.description.errors %}{{ form.description.errors.as_ul }}{% endif %}
      {{ form.description.label_tag }}

        {{ form.description }}

  </fieldset>
  {% if user|is_moderator %}
  <fieldset class="module aligned">

Moderation

      {% if form.pinned.errors %}{{ form.pinned.errors.as_ul }}{% endif %}
      {{ form.pinned }} Pinned

      {% if form.locked.errors %}{{ form.locked.errors.as_ul }}{% endif %}
      {{ form.locked }} Locked

      {% if form.hidden.errors %}{{ form.hidden.errors.as_ul }}{% endif %}
      {{ form.hidden }} Hidden

  </fieldset>
  {% endif %}

    <input type="submit" name="submit" value="Edit Topic">
    or
    Cancel

</form>
{% endblock %}


text:
package whitespell.net.websockets.socketio.messages;

import whitespell.net.websockets.socketio.parser.Packet;

import java.util.UUID;

public class WebSocketPacketMessage extends BaseMessage {

    private final UUID sessionId;
    private final Packet packet;

    public WebSocketPacketMessage(UUID sessionId, Packet packet) {
        super();
        this.sessionId = sessionId;
        this.packet = packet;
    }

    public Packet getPacket() {
        return packet;
    }

    public UUID getSessionId() {
        return sessionId;
    }

}


text:
define([], function() {
  return {
    "PropertyPaneDescription": "Description",
    "BasicGroupName": "Group Name",
    "DescriptionFieldLabel": "Description Field",
    "TargetEmailFieldLabel": "Target Email",
    "SubjectFieldLabel": "Subject"
  }
});


text:
Bengine.extensibles.mkdwn = new function ShowdownJS() {
  this.type = "mkdwn";
  this.name = "markdown";
  this.category = "text";
  this.upload = false;
  this.accept = null;

  var thisBlock = this; // it's helpful to keep a reference to this object
  var _private = {}; // attach private methods to this

  this.destroy = function(bid) {};

  this.fetchDependencies = function() {
    return [{
      source: 'https://cdnjs.cloudflare.com/ajax/libs/showdown/1.8.5/showdown.min.js',
      type: 'application/javascript',
      integrity: null,
      inner: '',
      wait: ''
    }];
  };

  this.insertContent = function(block,content) {
    var xpreview = document.createElement("div");
    xpreview.setAttribute("class","xShowdown-show");

    var xtarea = document.createElement("textarea");
    xtarea.setAttribute("class","xShowdown");

    if(thisBlock.p.emptyObject(content)) {
      xtarea.value = `# Markdown Block

1. Markdown Cheat Sheet

Sample | Table
|---|---|
Your | Data
Goes | Here
  `;
    } else {
      xtarea.value = content;
    }

    block.appendChild(xpreview);
    block.appendChild(xtarea);

    return block;
  };

  this.afterDOMinsert = function(bid,data) {
    var show = document.getElementById(bid).children[0];
    var editor = document.getElementById(bid).children[1];

    var converter = new showdown.Converter({
	    'omitExtraWLInCodeBlocks':true,
	    'tables':true,
	    'emoji':true
    });
    show.innerHTML = converter.makeHtml(editor.value);
  };

  this.runBlock = function(bid) {
    var show = document.getElementById(bid).children[0];
    var editor = document.getElementById(bid).children[1];

    var converter = new showdown.Converter({
	    'omitExtraWLInCodeBlocks':true,
	    'tables':true,
	    'emoji':true
    });
    show.innerHTML = converter.makeHtml(editor.value);
  };

  this.runData = null;

  this.saveContent = function(bid) {
    var textstr = document.getElementById('bengine-a' + bid).children[1].value;
    return textstr;
  };

  this.saveFile = null;

  this.showContent = function(block,content) {
    var xpreview = document.createElement("div");
    xpreview.setAttribute("class","xShowdown-show");

    var xtarea = document.createElement("textarea");
    xtarea.setAttribute("class","xShowdown");
    xtarea.style = "visibility:hidden;display:none";

    try {
      xtarea.value = content['content'];
    } catch(err) {
      console.log(err);
    }

    block.appendChild(xpreview);
    block.appendChild(xtarea);

    return block;
  };

  this.styleBlock = function() {
      var stylestr = `
      .xShowdown {
	      height: 200px;
	  }

      .xShowdown, .xShowdown-show {
        display: block;
        overflow-y: auto;
        width: 100%;

        border: 1px solid black;
        border-radius: 2px;
        background-color: white;

        padding: 8px;
        margin: 0px;
        box-sizing: border-box;

        font-family: Arial, Helvetica, sans-serif;
        font-size: 1em;
        font-weight: 300;
        color: black;

          resize: none;
      }

      .xShowdown-show {
        padding: 8px;
        height: 300px;
      }
      `;

      return stylestr;
  };
};


text:
<!DOCTYPE html>

    <title>SceneJS Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <link href="css/styles.css" rel="stylesheet"/>

    SceneJS - post-processing -  blur

post-processing effect using the blur node
    in combo with a orbiting camera, skybox, reflection map


text:
namespace DevZH.AspNetCore.Authentication.WeChat
{
    public static class WeChatDefaults
    {
        // 授权名称标识
        public static readonly string AuthenticationScheme = "WeChat";
        // 获取 授权码 的链接
        public static readonly string AuthorizationEndpoint = "https://open.weixin.qq.com/connect/qrconnect";
        // 获取 身份令牌 的链接
        public static readonly string TokenEndpoint = "https://api.weixin.qq.com/sns/oauth2/access_token";
        // 获取 用户信息 的链接
        public static readonly string UserInformationEndpoint = "https://api.weixin.qq.com/sns/userinfo";
    }
}


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

    <item android:drawable="@null" android:state_enabled="true" android:state_pressed="false">

        <shape android:shape="rectangle">
            <solid android:color="@null" />
        </shape>
    </item>

    <item android:drawable="@color/colorPrimaryDark" android:state_enabled="true" android:state_pressed="true">

        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark" />
        </shape>
    </item>
</selector>


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace AppBundle\Entity;

/**
 * Description of UPS_Status
 *
 * @author Nick
 */

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="UPS_Status", indexes={@ORM\Index(name="ups_id_idx", columns={"UPS_id"}), @ORM\Index(name="ups_id_timestamp_idx", columns={"UPS_id", "timestamp"})})
 * @ORM\Entity(repositoryClass="AppBundle\Entity\UPS_StatusRepository")
 */
class UPS_Status {

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="UPS", inversedBy="UPS_Status")
     * @ORM\JoinColumn(name="UPS_id", referencedColumnName="id")
     */
    private $UPS;

    /**
     * @ORM\Column(type="string", length=200)
     */
    protected $status;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $timestamp;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     *
     */
    protected $lineVoltage;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     *
     */
    protected $loadPercentage;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     *
     */
    protected $batteryVoltage;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     *
     */
    protected $timeLeft;

    public function __toString()
    {
        return (string) $this->getName();
    }

    /**
     * Set timestamp
     *
     * @param \DateTime $timestamp
     * @ORM\PrePersist
     * @ORM\PostUpdate
     * @return Example
     */
    public function setTimestamp()
    {

        #if(!$this->timestamp){
            $this->timestamp = new \DateTime();
        #}

        return $this;
    }

    /**
     * Set UPS
     *
     * @param \AppBundle\Entity\UPS $ups
     *
     * @return UPS_Status
     */
    public function setUPS(\AppBundle\Entity\UPS $ups = null)
    {
        $this->UPS = $ups;

        return $this;
    }

    /**
     * Get UPS
     *
     * @return \AppBundle\Entity\UPS
     */
    public function getUPS()
    {
        return $this->UPS;
    }

    /**
     * Set status
     *
     * @param string $status
     *
     * @return UPS_Status
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get timestamp
     *
     * @return \DateTime
     */
    public function getTimestamp()
    {
        return $this->timestamp;
    }

    /**
     * Set lineVoltage
     *
     * @param string $lineVoltage
     *
     * @return UPS_Status
     */
    public function setLineVoltage($lineVoltage)
    {
        $this->lineVoltage = $lineVoltage;

        return $this;
    }

    /**
     * Get lineVoltage
     *
     * @return string
     */
    public function getLineVoltage()
    {
        return $this->lineVoltage;
    }

    /**
     * Set Percentage
     *
     * @param string $loadPercentage
     *
     * @return UPS_Status
     */
    public function setLoadPercentage($loadPercentage)
    {
        $this->loadPercentage = $loadPercentage;

        return $this;
    }

    /**
     * Get loadPercentage
     *
     * @return string
     */
    public function getLoadPercentage()
    {
        return $this->loadPercentage;
    }

    /**
     * Set batteryVoltage
     *
     * @param string $batteryVoltage
     *
     * @return UPS_Status
     */
    public function setBatteryVoltage($batteryVoltage)
    {
        $this->batteryVoltage = $batteryVoltage;

        return $this;
    }

    /**
     * Get batteryVoltage
     *
     * @return string
     */
    public function getBatteryVoltage()
    {
        return $this->batteryVoltage;
    }

    /**
     * Set timeLeft
     *
     * @param string $timeLeft
     *
     * @return UPS_Status
     */
    public function setTimeLeft($timeLeft)
    {
        $this->timeLeft = $timeLeft;

        return $this;
    }

    /**
     * Get timeLeft
     *
     * @return string
     */
    public function getTimeLeft()
    {
        return $this->timeLeft;
    }
}


text:
class CreatePages < ActiveRecord::Migration
  def change
    create_table :pages do |t|
      t.string :title
      t.text :body
      t.string :slug, unique: true

      t.timestamps
    end
  end
end


text:
  <carousel interval="myInterval">
    <slide ng-repeat="slide in slides" active="slide.active">

Slide {{$index}}

{{slide.text}}

    </slide>
  </carousel>

          <button class="btn btn-mini" ng-class="{'btn-info': !slide.active, 'btn-success': slide.active}" ng-disabled="slide.active" ng-click="slide.active = true">select</button>
          {{$index}}: {{slide.text}}

      Add Slide

      Interval, in milliseconds: <input type="number" ng-model="myInterval">

Enter a negative number to stop the interval.


text:
<?

defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteInterfaceMenuHelper {

	protected $pageHeaderMenuItems = array();

	/**
	 * Adds a menu item to the header menu area
	 *
	 * 	$bh->addMenuItem($menuItemID, $menuItemName, $positionInMenu, $linkAttributes, $pkgHandle = false);
	 *
	 */
	public function addPageHeaderMenuItem($menuItemID, $menuItemName, $positionInMenu, $linkAttributes, $pkgHandle = false) {
		$obj = new ConcreteInterfaceHelperMenuItem($menuItemID, $menuItemName, $positionInMenu, $linkAttributes, $pkgHandle);
		$this->pageHeaderMenuItems[] = $obj;
	}

	/**
	 * Returns current menu items
	 */
	public function getPageHeaderMenuItems($position = false) {
		if ($position) {
			$tmpItems = array();
			foreach($this->pageHeaderMenuItems as $mi) {
				if ($mi->getPosition() == $position) {
					$tmpItems[] = $mi;
				}
			}
			return $tmpItems;
		} else {
			return $this->pageHeaderMenuItems;
		}
	}

}

class ConcreteInterfaceHelperMenuItem {

	public function __construct($handle, $name, $position, $linkAttributes, $pkgHandle = false) {
		$this->handle = $handle;
		$this->name = $name;
		$this->position = $position;
		$this->linkAttributes = $linkAttributes;
		$this->pkgHandle = $pkgHandle;
	}

	protected $controller;

	public function getHandle() {return $this->handle;}
	public function getName() {return $this->name;}
	public function setName($name) {$this->name = $name;}
	public function getPosition() {return $this->position;}
	public function getLinkAttributes() {return $this->linkAttributes;}
	public function getPackageObject() {return $this->pkgHandle;}

	public function getController() {
		if (isset($this->controller)) {
			return $this->controller;
		} else {
			$class = Object::camelcase($this->handle . 'ConcreteInterfaceMenuItemController');
			if (!class_exists($class)) {
				$file1 = DIR_FILES_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $this->handle . '/' . FILENAME_MENU_ITEM_CONTROLLER;
				if ($this->pkgHandle) {
					$pkgHandle = $this->pkgHandle;
					$dir = (is_dir(DIR_PACKAGES . '/' . $pkgHandle)) ? DIR_PACKAGES : DIR_PACKAGES_CORE;
					$file2 = $dir . '/' . $pkgHandle . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $this->handle . '/' . FILENAME_MENU_ITEM_CONTROLLER;
				}
				$file3 = DIR_FILES_ELEMENTS_CORE . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $this->handle . '/' . FILENAME_MENU_ITEM_CONTROLLER;
				if (file_exists($file1)) {
					include($file1);
				} else if (isset($file2) && file_exists($file2)) {
					include($file2);
				} else {
					include($file3);
				}
			}

			$this->controller = new $class();
			$this->controller->setMenuItem($this);
			return $this->controller;
		}
	}

	public function getMenuItemFilePath($_file) {
		$f = $this->mapMenuItemFilePath($_file);
		if (is_object($f)) {
			return $f->file;
		}
	}

	public function getMenuItemFileURL($_file) {
		$f = $this->mapMenuItemFilePath($_file);
		if (is_object($f)) {
			return $f->url;
		}
	}

	protected function mapMenuItemFilePath($_file) {
		$handle = $this->handle;
		if (file_exists(DIR_FILES_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file)) {
			$file = DIR_FILES_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file;
			$url = DIR_REL . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file;
		}

		if ($this->pkgHandle) {
			if (!isset($file)) {
				$pkgHandle = $this->pkgHandle;
				$dirp = is_dir(DIR_PACKAGES . '/' . $pkgHandle) ? DIR_PACKAGES . '/' . $pkgHandle : DIR_PACKAGES_CORE . '/' . $pkgHandle;
				if (file_exists($dirp . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file)) {
					$file = $dirp . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file;
					$url = DIR_REL . '/' .DIRNAME_PACKAGES. '/' . $pkgHandle . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file;
				}
			}
		}

		if (!isset($file)) {
			if (file_exists(DIR_FILES_ELEMENTS_CORE . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' .  $handle . '/' . $_file)) {
				$file = DIR_FILES_ELEMENTS_CORE . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' .  $handle . '/' . $_file;
				$url = ASSETS_URL . '/' . DIRNAME_ELEMENTS . '/' . DIRNAME_ELEMENTS_HEADER_MENU . '/' . $handle . '/' . $_file;
			}
		}

		if (isset($file)) {
			$obj = new stdClass;
			$obj->file = $file;
			$obj->url = $url;
			return $obj;
		} else {
			return false;
		}
	}
}

class ConcreteInterfaceMenuItemController extends Controller {

	protected $menuItem;
	protected $headerItemsToCheck = array(
		'CSS' => 'view.css',
		'JAVASCRIPT' => 'view.js'
	);

	public function setMenuItem($obj) {
		$this->menuItem = $obj;
	}

	public function outputAutoHeaderItems() {
		$h = Loader::helper('html');
		if ($this->menuItem->getController()->displayItem()) {
			foreach($this->headerItemsToCheck as $t => $i) {
				$o = $this->menuItem->getMenuItemFilePath($i);
				if ($o) {
					$this->menuItem->getMenuItemFileURL($i);
					switch($t) {
						case 'CSS':
							$this->addHeaderItem($h->css($this->menuItem->getMenuItemFileURL($i)));
							break;
						case 'JAVASCRIPT':
							$this->addFooterItem($h->javascript($this->menuItem->getMenuItemFileURL($i)));
							break;
					}
				}
			}
		}
	}

	public function displayItem() {
		return true;
	}

	public function getMenuLinkHTML() {
		$attribs = '';
		if (is_array($this->menuItem->getLinkAttributes())) {
			foreach($this->menuItem->getLinkAttributes() as $key => $value) {
				if ($key == 'class') {
					$value = 'ccm-header-nav-package-item ' . $value;
				}
				$attribs .= $key . '="' . $value . '" ';
			}
		}
		$html = 'menuItem->getHandle() . '" ' . $attribs . '>' . $this->menuItem->getName() . '';
		return $html;
	}
}


text:
- Formatting changes

### v0.7.1

- Skipping tests related to duplicate query parameters. The AWS Signature V4 specs
  don't have any information on how to deal with them. (issue #10)

### v0.7.0

Fixes:

- Removed Mix.env reference that caused problems with distillery based releases.
  PR from [zeroasterisk](https://github.com/zeroasterisk) (issue #8)

### v0.6.0

Fixes:

- Enabled AWS Secure Token tests (`post-sts-token`). Use the AWS STS service to obtain
  temporary credentials and the corresponding session token. Use the temporary credentials
  to sign. The session token must be included as a request header or query string parameter
  `X-Amz-Secure-Token`.

  All AWS Signature V4 tests in the testsuite pass. (Exceptions: `post-vanilla-query-nonunreserved`
  and `post-vanilla-query-space`. These tests seem to be wrong.)

  AWS STS are supported only in request signing. They are not supported in the
  verifier (plug_sigaws).

  ([AWS STS Ref](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html))

### v0.5.0

Fixes:

- Handle normalization of path segments during signature computation (issue #6)

  The `normalize-path` tests in the AWS Signature V4 testsuite pass with
  with fix.

### v0.4.0

Fixes:

- Default to "/" when path component not present in URL

### v0.3.0

Fixes:

- aws-sig-v4-testsuite/get-header-value-multiline test fails (issue #3)

  Canonical value computation for request headers with multiline values
  was not correct. Becuase of that the corresponding AWS Signature V4 testsuite
  was failing. Fixed this issue.

- AWS testsuite URL changed - Update README.md (issue #4)

### v0.2.0

Enhancements:

- Support precomputed content hash (issue #2)

Fixes:

- Correct "cryto" to "crypto" (issue #1)


text:
function [ relations, relation_str ] = remove_relations( relations, relation_str, relations_to_remove)
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

ind = ismember(relation_str, relations_to_remove);
if (any(ind))
   relations(:, ind) = [];
   relation_str(ind) = [];
end

end


text:
using System;
using System.IO;
using System.Linq;
using AdventOfCode.Day7.Model.Components;
using AdventOfCode.Day7.Parser;
using AdventOfCode.Day7.Simulator;

namespace AdventOfCode.Day7
{
    class Program
    {
        private const string inputFileName = "PuzzleInput.txt";

        static void Main(string[] args)
        {
            Console.WriteLine("Day 7: Some Assembly Required");
            Console.WriteLine("----------------------------");

            Console.WriteLine("Reading setup from:  {0}", inputFileName);
            var input = File.ReadAllLines(inputFileName);

            Console.WriteLine("Paring instructions...");
            ICircuitParser parser = new CircuitParser();
            var components = parser.PaseComponents(input);

            Console.WriteLine("Running simulation...");
            ICircuitSimulator simulator = new CircuitSimulator();
            var result1 = simulator.RunSimulation(components);

            var a1 = result1["a"];

            Console.WriteLine("Value of a is : " + a1);
            Console.WriteLine();

            Console.WriteLine("Overriding wire b with the value of a");

            var wireB = components.Single(x => x.OutputName == "b");
            components.Remove(wireB);
            components.Add(new InputComponent(a1.ToString(), "b"));

            Console.WriteLine("Rerunning simulation");
            var result2 = simulator.RunSimulation(components);

            var a2 = result2["a"];
            Console.WriteLine("Value of a is : " + a2);

            Console.WriteLine();
            Console.WriteLine("Press any key to end...");
            Console.ReadKey();
        }
    }

}


text:
package server

import (
	"context"
	"database/sql"
	"github.com/heroiclabs/nakama-common/api"
	"google.golang.org/protobuf/types/known/timestamppb"
	"sync"
	"time"

	"go.uber.org/atomic"
	"go.uber.org/zap"
)

type LeaderboardSchedulerCallback struct {
	id          string
	leaderboard *Leaderboard
	ts          int64
	t           time.Time
}

type LeaderboardScheduler interface {
	Start(runtime *Runtime)
	Pause()
	Resume()
	Stop()
	Update()
}

type LocalLeaderboardScheduler struct {
	sync.Mutex
	logger    *zap.Logger
	db        *sql.DB
	config    Config
	cache     LeaderboardCache
	rankCache LeaderboardRankCache

	fnLeaderboardReset RuntimeLeaderboardResetFunction
	fnTournamentReset  RuntimeTournamentResetFunction
	fnTournamentEnd    RuntimeTournamentEndFunction

	endActiveTimer *time.Timer
	expiryTimer    *time.Timer
	lastEnd        int64
	lastExpiry     int64

	started bool
	queue   chan *LeaderboardSchedulerCallback
	active  *atomic.Uint32

	ctx         context.Context
	ctxCancelFn context.CancelFunc
}

func NewLocalLeaderboardScheduler(logger *zap.Logger, db *sql.DB, config Config, cache LeaderboardCache, rankCache LeaderboardRankCache) LeaderboardScheduler {
	ctx, ctxCancelFn := context.WithCancel(context.Background())
	s := &LocalLeaderboardScheduler{
		logger:    logger,
		db:        db,
		config:    config,
		cache:     cache,
		rankCache: rankCache,

		// endActiveTimer only initialized when needed.
		// expiryTimer only initialized when needed.
		// lastEnd only initialized when needed.
		// lastExpiry only initialized when needed.

		queue:  make(chan *LeaderboardSchedulerCallback, config.GetLeaderboard().CallbackQueueSize),
		active: atomic.NewUint32(1),

		ctx:         ctx,
		ctxCancelFn: ctxCancelFn,
	}

	// Ensure trimming of expired scores that don't have resets or functions attached.
	go func() {
		ticker := time.NewTicker(1 * time.Hour)
		defer ticker.Stop()

		for {
			select {
			case <-ctx.Done():
				return
			case t := <-ticker.C:
				s.rankCache.TrimExpired(t.Unix())
			}
		}
	}()

	return s
}

func (ls *LocalLeaderboardScheduler) Start(runtime *Runtime) {
	ls.logger.Info("Leaderboard scheduler start")
	ls.started = true

	// Capture callback references, if any are registered.
	ls.fnLeaderboardReset = runtime.LeaderboardReset()
	ls.fnTournamentReset = runtime.TournamentReset()
	ls.fnTournamentEnd = runtime.TournamentEnd()

	// Start the required number of callback workers.
	for i := 0; i < ls.config.GetLeaderboard().CallbackQueueWorkers; i++ {
		go ls.invokeCallback()
	}

	ls.Update()
}

func (ls *LocalLeaderboardScheduler) Pause() {
	ls.logger.Info("Leaderboard scheduler pause")

	if !ls.active.CompareAndSwap(1, 0) {
		// Already paused.
		return
	}

	ls.Lock()
	if ls.endActiveTimer != nil {
		if !ls.endActiveTimer.Stop() {
			select {
			case <-ls.endActiveTimer.C:
			default:
			}
		}
	}
	if ls.expiryTimer != nil {
		if !ls.expiryTimer.Stop() {
			select {
			case <-ls.expiryTimer.C:
			default:
			}
		}
	}
	ls.Unlock()
}

func (ls *LocalLeaderboardScheduler) Resume() {
	ls.logger.Info("Leaderboard scheduler resume")

	if !ls.active.CompareAndSwap(0, 1) {
		// Already active.
		return
	}

	ls.Update()
}

func (ls *LocalLeaderboardScheduler) Stop() {
	ls.Lock()
	ls.ctxCancelFn()
	if ls.endActiveTimer != nil {
		if !ls.endActiveTimer.Stop() {
			select {
			case <-ls.endActiveTimer.C:
			default:
			}
		}
	}
	if ls.expiryTimer != nil {
		if !ls.expiryTimer.Stop() {
			select {
			case <-ls.expiryTimer.C:
			default:
			}
		}
	}
	ls.Unlock()
}

func (ls *LocalLeaderboardScheduler) Update() {
	if !ls.started {
		// In case the update is called during runtime VM init, skip setting timers until ready.
		return
	}

	if ls.active.Load() != 1 {
		// Not active.
		return
	}

	now := time.Now().UTC()
	nowUnix := now.Unix()

	// Grab the set of known leaderboards.
	leaderboards := ls.cache.GetAllLeaderboards()

	earliestEndActive := int64(-1)
	earliestExpiry := int64(-1)

	endActiveLeaderboardIds := make([]string, 0, 1)
	expiryLeaderboardIds := make([]string, 0, 1)

	for _, l := range leaderboards {
		if l.IsTournament() {
			// Tournament.
			_, endActive, expiry := calculateTournamentDeadlines(l.StartTime, l.EndTime, int64(l.Duration), l.ResetSchedule, now)

			if l.EndTime > 0 && l.EndTime < nowUnix {
				// Tournament has ended permanently.
				continue
			}

			// Check tournament end.
			if endActive > 0 && nowUnix < endActive {
				if earliestEndActive == -1 || endActive < earliestEndActive {
					earliestEndActive = endActive
					endActiveLeaderboardIds = []string{l.Id}
				} else if endActive == earliestEndActive {
					endActiveLeaderboardIds = append(endActiveLeaderboardIds, l.Id)
				}
			}

			// Check tournament expiry.
			if expiry > 0 {
				if earliestExpiry == -1 || expiry < earliestExpiry {
					earliestExpiry = expiry
					expiryLeaderboardIds = []string{l.Id}
				} else if expiry == earliestExpiry {
					expiryLeaderboardIds = append(expiryLeaderboardIds, l.Id)
				}
			}
		} else {
			// Leaderboard.
			if l.ResetSchedule != nil {
				// Leaderboards don't end, only check for expiry.
				expiry := l.ResetSchedule.Next(now).UTC().Unix()

				if earliestExpiry == -1 || expiry < earliestExpiry {
					earliestExpiry = expiry
					expiryLeaderboardIds = []string{l.Id}
				} else if expiry == earliestExpiry {
					expiryLeaderboardIds = append(expiryLeaderboardIds, l.Id)
				}
			}
		}
	}

	endActiveDuration := time.Duration(-1)
	if earliestEndActive > -1 {
		endActiveDuration = time.Unix(earliestEndActive, 0).UTC().Sub(now)
	}

	expiryDuration := time.Duration(-1)
	if earliestExpiry > -1 {
		expiryDuration = time.Unix(earliestExpiry, 0).UTC().Sub(now)
	}

	// Replace IDs earmarked for end and expiry, and restart timers as needed.
	ls.Lock()
	if ls.endActiveTimer != nil {
		if !ls.endActiveTimer.Stop() {
			select {
			case <-ls.endActiveTimer.C:
			default:
			}
		}
	}
	if ls.expiryTimer != nil {
		if !ls.expiryTimer.Stop() {
			select {
			case <-ls.expiryTimer.C:
			default:
			}
		}
	}
	if endActiveDuration > -1 {
		ls.logger.Debug("Setting timer to run end active function", zap.Duration("end_active", endActiveDuration), zap.Strings("ids", endActiveLeaderboardIds))
		ls.endActiveTimer = time.AfterFunc(endActiveDuration, func() {
			ls.queueEndActiveElapse(time.Unix(earliestEndActive, 0).UTC(), endActiveLeaderboardIds)
		})
	}
	if expiryDuration > -1 {
		ls.logger.Debug("Setting timer to run expiry function", zap.Duration("expiry", expiryDuration), zap.Strings("ids", expiryLeaderboardIds))
		ls.expiryTimer = time.AfterFunc(expiryDuration, func() {
			ls.queueExpiryElapse(time.Unix(earliestExpiry, 0).UTC(), expiryLeaderboardIds)
		})
	}
	ls.Unlock()

	ls.logger.Info("Leaderboard scheduler update", zap.Duration("end_active", endActiveDuration), zap.Int("end_active_count", len(endActiveLeaderboardIds)), zap.Duration("expiry", expiryDuration), zap.Int("expiry_count", len(expiryLeaderboardIds)))
}

func (ls *LocalLeaderboardScheduler) queueEndActiveElapse(t time.Time, ids []string) {
	if ls.active.Load() != 1 {
		// Not active.
		return
	}

	ts := t.Unix()
	tMinusOne := time.Unix(ts-1, 0).UTC()

	// Immediately schedule the next invocation to avoid any gaps caused by time spent processing below.
	ls.Update()

	// Skip processing if there is no tournament end callback registered.
	if ls.fnTournamentEnd == nil {
		return
	}

	ls.Lock()
	if ls.lastEnd != 0 && ls.lastEnd >= ts {
		// Avoid running duplicate or delayed scheduling.
		ls.Unlock()
		return
	}
	ls.lastEnd = ts
	ls.Unlock()

	ls.logger.Info("Leaderboard scheduler end active", zap.Int("count", len(ids)))

	go func() {
		// Process the current set of tournament ends.
		for _, id := range ids {
			currentId := id
			// Will block if the queue is full.
			ls.queue <- &LeaderboardSchedulerCallback{id: currentId, ts: ts, t: tMinusOne}
		}
	}()
}

func (ls *LocalLeaderboardScheduler) queueExpiryElapse(t time.Time, ids []string) {
	if ls.active.Load() != 1 {
		// Not active.
		return
	}

	ts := t.Unix()
	tMinusOne := time.Unix(ts-1, 0).UTC()

	// Immediately schedule the next invocation to avoid any gaps caused by time spent processing below.
	ls.rankCache.TrimExpired(ts)
	ls.Update()

	ls.Lock()
	if ls.lastExpiry != 0 && ls.lastExpiry >= ts {
		// Avoid running duplicate or delayed scheduling.
		ls.Unlock()
		return
	}
	ls.lastExpiry = ts
	ls.Unlock()

	ls.logger.Info("Leaderboard scheduler expiry reset", zap.Int("count", len(ids)))

	go func() {
		// Queue the current set of leaderboard and tournament resets.
		// Executes inside a goroutine to ensure further invocation timings are not skewed.
		for _, id := range ids {
			currentId := id
			leaderboard := ls.cache.Get(id)
			if leaderboard == nil {
				// Cached entry was deleted before it reached the scheduler here.
				continue
			}
			if !leaderboard.IsTournament() && ls.fnLeaderboardReset == nil {
				// Skip further processing if there is no leaderboard reset callback registered.
				// Tournaments have some processing to do even if no callback is registered.
				continue
			}
			// Will block if queue is full.
			ls.queue <- &LeaderboardSchedulerCallback{id: currentId, leaderboard: leaderboard, ts: ts, t: tMinusOne}
		}
	}()
}

func (ls *LocalLeaderboardScheduler) invokeCallback() {
	for {
		select {
		case <-ls.ctx.Done():
			return
		case callback := <-ls.queue:
			if callback.leaderboard != nil {
				if callback.leaderboard.IsTournament() {
					// Tournament, fetch most up to date info for size etc.
					// Some processing is needed even if there is no runtime callback registered for tournament reset.
					query := `SELECT
id, sort_order, operator, reset_schedule, metadata, create_time,
category, description, duration, end_time, max_size, max_num_score, title, size, start_time
FROM leaderboard
WHERE id = $1`
					row := ls.db.QueryRowContext(ls.ctx, query, callback.id)
					tournament, err := parseTournament(row, callback.t)
					if err != nil {
						ls.logger.Error("Error retrieving tournament to invoke reset callback", zap.Error(err), zap.String("id", callback.id))
						continue
					}

					// Reset tournament size in DB to make it immediately usable for the next active period.
					if _, err := ls.db.ExecContext(ls.ctx, "UPDATE leaderboard SET size = 0 WHERE id = $1", callback.id); err != nil {
						ls.logger.Error("Could not reset leaderboard size", zap.Error(err), zap.String("id", callback.id))
					}

					if ls.fnTournamentReset != nil {
						if err := ls.fnTournamentReset(ls.ctx, tournament, int64(tournament.EndActive), int64(tournament.NextReset)); err != nil {
							ls.logger.Warn("Failed to invoke tournament reset callback", zap.Error(err))
						}
					}
				} else {
					// Leaderboard.
					// fnLeaderboardReset cannot be nil here, if it was the callback would not be queued at all.
					l := &api.Leaderboard{
						Id:            callback.leaderboard.Id,
						SortOrder:     uint32(callback.leaderboard.SortOrder),
						Operator:      OperatorIntToEnum[callback.leaderboard.Operator],
						PrevReset:     uint32(calculatePrevReset(callback.t, callback.leaderboard.StartTime, callback.leaderboard.ResetSchedule)),
						NextReset:     uint32(callback.leaderboard.ResetSchedule.Next(callback.t).UTC().Unix()),
						Metadata:      callback.leaderboard.Metadata,
						CreateTime:    &timestamppb.Timestamp{Seconds: callback.leaderboard.CreateTime},
						Authoritative: callback.leaderboard.Authoritative,
					}
					if err := ls.fnLeaderboardReset(ls.ctx, l, callback.ts); err != nil {
						ls.logger.Warn("Failed to invoke leaderboard reset callback", zap.Error(err))
					}
				}
			} else {
				query := `SELECT
id, sort_order, operator, reset_schedule, metadata, create_time,
category, description, duration, end_time, max_size, max_num_score, title, size, start_time
FROM leaderboard
WHERE id = $1`
				row := ls.db.QueryRowContext(ls.ctx, query, callback.id)
				tournament, err := parseTournament(row, callback.t)
				if err != nil {
					if err != sql.ErrNoRows {
						// Do not log if tournament was deleted before it reached the scheduler here.
						ls.logger.Error("Error retrieving tournament to invoke end callback", zap.Error(err), zap.String("id", callback.id))
					}
					continue
				}

				// fnTournamentEnd cannot be nil here, if it was the callback would not be queued at all.
				if err := ls.fnTournamentEnd(ls.ctx, tournament, int64(tournament.EndActive), int64(tournament.NextReset)); err != nil {
					ls.logger.Warn("Failed to invoke tournament end callback", zap.Error(err))
				}
			}
		}
	}
}


text:
echo "What is your name?"
read name
echo "What is your age?"
read age
echo "What is your Reddit username?"
read username

output="Your name is $name, you are $age years old, and your username is $username"
echo $output
echo $output >> logfile


text:
package org.iotp.analytics.ruleengine.annotation;

/**
 */
public interface ConfigurableComponent<T> {

  void init(T configuration);

}


text:
module MtgSearchParser
  module Parsed
    class Edition < Base

    end
  end
end


text:
@font-face {
	font-family: 'icomoon';
	src:url('../fonts/icomoon/icomoon.eot');
	src:url('../fonts/icomoon/icomoon.eot?#iefix') format('embedded-opentype'),
		url('../fonts/icomoon/icomoon.woff') format('woff'),
		url('../fonts/icomoon/icomoon.ttf') format('truetype'),
		url('../fonts/icomoon/icomoon.svg#icomoon') format('svg');
	font-weight: normal;
	font-style: normal;
}

a, a:visited {
	color: white;
	text-decoration: none;
}

a:hover, a:focus {color: #666;}

.glyph_style {
	font-size: 26px;
	float: left;
	text-align: center;
}

/* Use the following CSS code if you want to use data attributes for inserting your icons */
[data-icon]:before {
	font-family: 'icomoon';
	content: attr(data-icon);
	speak: none;
	font-weight: normal;
	font-variant: normal;
	text-transform: none;
	line-height: 1;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

/* Use the following CSS code if you want to have a class per icon */
/*
Instead of a list of all class selectors,
you can use the generic selector below, but it's slower:
[class*="icon-"] {
*/
.icon-skype, .icon-evernote, .icon-dropbox, .icon-spotify, .icon-mail, .icon-home, .icon-facebook, .icon-twitter, .icon-google-plus, .icon-tumblr, .icon-stumbleupon, .icon-twitter-2, .icon-google-drive, .icon-envelope, .icon-facebook-2, .icon-google-plus-2, .icon-google-plus-3, .icon-facebook-3, .icon-picassa, .icon-picassa-2, .icon-tumblr-2, .icon-stumbleupon-2, .icon-pinterest, .icon-pinterest-2, .icon-html5, .icon-html5-2, .icon-css3, .icon-file-xml, .icon-github, .icon-github-2, .icon-twitter-3, .icon-instagram, .icon-embed, .icon-code, .icon-youtube, .icon-youtube-2 {
	font-family: 'icomoon';
	speak: none;
	font-style: normal;
	font-weight: normal;
	font-variant: normal;
	text-transform: none;
	line-height: 1;
	-webkit-font-smoothing: antialiased;
}
.icon-skype:before {
	content: "\e000";
}
.icon-evernote:before {
	content: "\e001";
}
.icon-dropbox:before {
	content: "\e002";
}
.icon-spotify:before {
	content: "\e003";
}
.icon-mail:before {
	content: "\e004";
}
.icon-home:before {
	content: "\e005";
}
.icon-facebook:before {
	content: "\e008";
}
.icon-twitter:before {
	content: "\e009";
}
.icon-google-plus:before {
	content: "\e00a";
}
.icon-tumblr:before {
	content: "\e00b";
}
.icon-stumbleupon:before {
	content: "\e00d";
}
.icon-twitter-2:before {
	content: "\e00e";
}
.icon-google-drive:before {
	content: "\e00f";
}
.icon-envelope:before {
	content: "\e010";
}
.icon-facebook-2:before {
	content: "\e006";
}
.icon-google-plus-2:before {
	content: "\e007";
}
.icon-google-plus-3:before {
	content: "\e00c";
}
.icon-facebook-3:before {
	content: "\e011";
}
.icon-picassa:before {
	content: "\e012";
}
.icon-picassa-2:before {
	content: "\e013";
}
.icon-tumblr-2:before {
	content: "\e014";
}
.icon-stumbleupon-2:before {
	content: "\e015";
}
.icon-pinterest:before {
	content: "\e016";
}
.icon-pinterest-2:before {
	content: "\e017";
}
.icon-html5:before {
	content: "\e018";
}
.icon-html5-2:before {
	content: "\e019";
}
.icon-css3:before {
	content: "\e01a";
}
.icon-file-xml:before {
	content: "\e01b";
}
.icon-github:before {
	content: "\e01c";
}
.icon-github-2:before {
	content: "\e01d";
}
.icon-twitter-3:before {
	content: "\e01e";
}
.icon-instagram:before {
	content: "\e01f";
}
.icon-embed:before {
	content: "\e020";
}
.icon-code:before {
	content: "\e021";
}
.icon-youtube:before {
	content: "\e022";
}
.icon-youtube-2:before {
	content: "\e023";
}


text:
var MissionViewModel = function(selectedJob)
{
	var self = this;

	var _selectedJob = selectedJob;
	var missionModel = function()
	{
		var that = this;
		that.id = ko.observable();
		that.name = ko.observable();
		that.isDefault = ko.observable();
		that.projects = ko.observableArray();
		that.job = ko.observable();
	};

	self.missions = ko.observableArray();
	self.newMissionName = ko.observable();
	self.selectedMission = ko.observable();
	self.selectedMission.subscribe(function(newValue)
	{
		msgPublisher.notifySubscribers(newValue, 'selectedMissionUpdated');

	})

	self.setDefault = function(clicked)
	{
		clicked.isDefault = true;
		self.addNewMission(clicked);
	}

	self.addNewMission = function(updated, kovariable)
	{
		var newMission;
		if (typeof kovariable == 'undefined')
		{
			// existing project
			newMission = updated;
		}
		else
		{
			newMission = new missionModel();
			newMission.name(self.newMissionName());
			newMission.job(selectedJob);
		}

		$.ajax({
			type : "POST",
			dataType : "json",
			contentType : "application/json",

			url : _host + "/editMission",
			data : ko.toJSON(newMission),
			success : function(response, status, xhr)
			{
				self.newMissionName(null);
				msgPublisher.notifySubscribers(response, 'jobsFromServer');
			},
			error : function(response, status, xhr)
			{
				alert(response.responseJSON.message)
			},
		});

	}

	msgPublisher.subscribe(function(job)
	{
		if (typeof job != 'undefined')
		{
			self.missions(job.missions);
			$(job.missions).each(function(index, value)
			{
				if (value.isDefault == true)
				{
					self.selectedMission(value);
				}

			});
		}
	}, self, 'selectedJobUpdated');
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.14-4-7
description: >
    Array.prototype.indexOf returns -1 if 'length' is 0 ( length is
    object overridden with obj w/o valueOf (toString))
---*/

  // objects inherit the default valueOf method of the Object object;
  // that simply returns the itself. Since the default valueOf() method
  // does not return a primitive value, ES next tries to convert the object
  // to a number by calling its toString() method and converting the
  // resulting string to a number.
 var i = Array.prototype.indexOf.call({length: { toString: function () { return '0';}}}, 1);

assert.sameValue(i, -1, 'i');


text:
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
using namespace arangodb::rest;

namespace {
/// @brief return the default number of threads to use (upper bound)
size_t defaultNumberOfThreads() {
  // use two times the number of hardware threads as the default
  size_t result = arangodb::NumberOfCores::getValue() * 2;
  // but only if higher than 64. otherwise use a default minimum value of 32
  if (result < 32) {
    result = 32;
  }
  return result;
}

}  // namespace

namespace arangodb {

SupervisedScheduler* SchedulerFeature::SCHEDULER = nullptr;

SchedulerFeature::SchedulerFeature(application_features::ApplicationServer& server)
    : ApplicationFeature(server, "Scheduler"),
      _scheduler(nullptr) {
  setOptional(false);
  startsAfter<GreetingsFeaturePhase>();
#ifdef TRI_HAVE_GETRLIMIT
  startsAfter<FileDescriptorsFeature>();
#endif
}

SchedulerFeature::~SchedulerFeature() = default;

void SchedulerFeature::collectOptions(std::shared_ptr<options::ProgramOptions> options) {
  // Different implementations of the Scheduler may require different
  // options to be set. This requires a solution here.

  // max / min number of threads
  options->addOption("--server.maximal-threads",
                     std::string(
                         "maximum number of request handling threads to run (0 "
                         "= use system-specific default of ") +
                         std::to_string(defaultNumberOfThreads()) + ")",
                     new UInt64Parameter(&_nrMaximalThreads),
                     arangodb::options::makeDefaultFlags(arangodb::options::Flags::Dynamic));

  options->addOption("--server.minimal-threads",
                     "minimum number of request handling threads to run",
                     new UInt64Parameter(&_nrMinimalThreads),
                     arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden));

    // max / min number of threads

  // Concurrency throttling:
  options->addOption("--server.ongoing-low-priority-multiplier",
                     "controls the number of low prio requests that can be "
                     "ongoing at a given point in time, relative to the "
                     "maximum number of request handling threads",
                     new DoubleParameter(&_ongoingLowPriorityMultiplier),
                     arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden))
                     .setIntroducedIn(30800);

  options->addOption("--server.maximal-queue-size",
                     "size of the priority 3 fifo", new UInt64Parameter(&_fifo3Size));

  options->addOption("--server.unavailability-queue-fill-grade",
                     "queue fill grade from which onwards the server is considered unavailable because of overload (ratio, use a value of 0 to disable it)",
                     new DoubleParameter(&_unavailabilityQueueFillGrade))
                     .setIntroducedIn(30610).setIntroducedIn(30706);

  options->addOption(
      "--server.scheduler-queue-size",
      "number of simultaneously queued requests inside the scheduler",
      new UInt64Parameter(&_queueSize),
      arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden));

  options->addOption("--server.prio2-size", "size of the priority 2 fifo",
                     new UInt64Parameter(&_fifo2Size),
                     arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden))
                     .setIntroducedIn(30800);

  options->addOption("--server.prio1-size", "size of the priority 1 fifo",
                     new UInt64Parameter(&_fifo1Size),
                     arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden));

  // obsolete options
  options->addObsoleteOption("--server.threads", "number of threads", true);

  // renamed options
  options->addOldOption("scheduler.threads", "server.maximal-threads");
}

void SchedulerFeature::validateOptions(std::shared_ptr<options::ProgramOptions> options) {
  auto const N = NumberOfCores::getValue();

  LOG_TOPIC("2ef39", DEBUG, arangodb::Logger::THREADS)
      << "Detected number of processors: " << N;

  TRI_ASSERT(N > 0);
  if (options->processingResult().touched("server.maximal-threads") &&
      _nrMaximalThreads > 8 * N) {
    LOG_TOPIC("0a92a", WARN, arangodb::Logger::THREADS)
        << "--server.maximal-threads (" << _nrMaximalThreads
        << ") is more than eight times the number of cores (" << N
        << "), this might overload the server";
  } else if (_nrMaximalThreads == 0) {
    _nrMaximalThreads = defaultNumberOfThreads();
  }

  if (_nrMinimalThreads < 4) {
    LOG_TOPIC("bf034", WARN, arangodb::Logger::THREADS)
        << "--server.minimal-threads (" << _nrMinimalThreads << ") must be at least 4";
    _nrMinimalThreads = 4;
  }

  if (_ongoingLowPriorityMultiplier < 1.0) {
    LOG_TOPIC("0a93a", WARN, arangodb::Logger::THREADS)
        << "--server.ongoing-low-priority-multiplier (" << _ongoingLowPriorityMultiplier
        << ") is less than 1.0, setting to default (4.0)";
    _ongoingLowPriorityMultiplier = 4.0;
  }

  if (_nrMinimalThreads >= _nrMaximalThreads) {
    LOG_TOPIC("48e02", WARN, arangodb::Logger::THREADS)
        << "--server.maximal-threads (" << _nrMaximalThreads
        << ") should be at least " << (_nrMinimalThreads + 1) << ", raising it";
    _nrMaximalThreads = _nrMinimalThreads;
  }

  if (_unavailabilityQueueFillGrade < 0.0 ||
      _unavailabilityQueueFillGrade > 1.0) {
    LOG_TOPIC("055a1", FATAL, arangodb::Logger::THREADS)
        << "invalid value for --server.unavailability-queue-fill-grade";
    FATAL_ERROR_EXIT();
  }

  if (_queueSize == 0) {
    // Note that this is way smaller than the default of 4096!
    TRI_ASSERT(_nrMaximalThreads > 0);
    _queueSize = _nrMaximalThreads * 8;
    TRI_ASSERT(_queueSize > 0);
  }

  if (_fifo1Size < 1) {
    _fifo1Size = 1;
  }

  if (_fifo2Size < 1) {
    _fifo2Size = 1;
  }

  TRI_ASSERT(_queueSize > 0);
}

void SchedulerFeature::prepare() {
  TRI_ASSERT(4 <= _nrMinimalThreads);
  TRI_ASSERT(_nrMinimalThreads <= _nrMaximalThreads);
  TRI_ASSERT(_queueSize > 0);
// wait for windows fix or implement operator new
#if (_MSC_VER >= 1)
#pragma warning(push)
#pragma warning(disable : 4316)  // Object allocated on the heap may not be aligned for this type
#endif
  auto sched =
      std::make_unique<SupervisedScheduler>(server(), _nrMinimalThreads, _nrMaximalThreads,
                                            _queueSize, _fifo1Size, _fifo2Size,
                                            _fifo3Size, _ongoingLowPriorityMultiplier,
                                            _unavailabilityQueueFillGrade);
#if (_MSC_VER >= 1)
#pragma warning(pop)
#endif

  SCHEDULER = sched.get();

  _scheduler = std::move(sched);
}

void SchedulerFeature::start() {
  signalStuffInit();

  bool ok = _scheduler->start();
  if (!ok) {
    LOG_TOPIC("7f497", FATAL, arangodb::Logger::FIXME)
        << "the scheduler cannot be started";
    FATAL_ERROR_EXIT();
  }
  LOG_TOPIC("14e6f", DEBUG, Logger::STARTUP) << "scheduler has started";
}

void SchedulerFeature::stop() {
  // shutdown user jobs again, in case new ones appear
  arangodb::Task::shutdownTasks();
  signalStuffDeinit();
  _scheduler->shutdown();
}

void SchedulerFeature::unprepare() {
  SCHEDULER = nullptr;
  _scheduler.reset();
}

// ---------------------------------------------------------------------------
// Signal Handler stuff - no body knows what this has to do with scheduling
// ---------------------------------------------------------------------------

void SchedulerFeature::signalStuffInit() {
  arangodb::signals::maskAllSignals();

#ifdef _WIN32
// Windows does not support POSIX signal handling
#else
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigfillset(&action.sa_mask);

  // ignore broken pipes
  action.sa_handler = SIG_IGN;

  int res = sigaction(SIGPIPE, &action, nullptr);

  if (res < 0) {
    LOG_TOPIC("91d20", ERR, arangodb::Logger::FIXME)
        << "cannot initialize signal handler for SIGPIPE";
  }
#endif

  buildHangupHandler();
}

void SchedulerFeature::signalStuffDeinit() {
  {
    // cancel signals
    if (_exitSignals != nullptr) {
      auto exitSignals = _exitSignals;
      _exitSignals.reset();
      exitSignals->cancel();
    }

#ifndef _WIN32
    if (_hangupSignals != nullptr) {
      _hangupSignals->cancel();
      _hangupSignals.reset();
    }
#endif
  }
}

#ifdef _WIN32
bool CtrlHandler(DWORD eventType) {
  bool shutdown = false;
  std::string shutdownMessage;

  switch (eventType) {
    case CTRL_BREAK_EVENT: {
      shutdown = true;
      shutdownMessage = "control-break received";
      break;
    }

    case CTRL_C_EVENT: {
      shutdown = true;
      shutdownMessage = "control-c received";
      break;
    }

    case CTRL_CLOSE_EVENT: {
      shutdown = true;
      shutdownMessage = "window-close received";
      break;
    }

    case CTRL_LOGOFF_EVENT: {
      shutdown = true;
      shutdownMessage = "user-logoff received";
      break;
    }

    case CTRL_SHUTDOWN_EVENT: {
      shutdown = true;
      shutdownMessage = "system-shutdown received";
      break;
    }

    default: {
      shutdown = false;
      break;
    }
  }

  if (shutdown == false) {
    LOG_TOPIC("ec3b4", ERR, arangodb::Logger::FIXME)
        << "Invalid CTRL HANDLER event received - ignoring event";
    return true;
  }

  static bool seen = false;

  if (!seen) {
    LOG_TOPIC("3278a", INFO, arangodb::Logger::FIXME)
        << shutdownMessage << ", beginning shut down sequence";

    application_features::ApplicationServer::CTRL_C.store(true);

    seen = true;
    return true;
  }

  // ........................................................................
  // user is desperate to kill the server!
  // ........................................................................

  LOG_TOPIC("18daf", INFO, arangodb::Logger::FIXME) << shutdownMessage << ", terminating";
  _exit(EXIT_FAILURE);  // quick exit for windows
  return true;
}

#else

extern "C" void c_exit_handler(int signal, siginfo_t* info, void*) {
  if (signal == SIGQUIT || signal == SIGTERM || signal == SIGINT) {
    static std::atomic<bool> seen{false};

    if (!seen.exchange(true)) {
      std::string sender = info ? std::to_string(info->si_pid) : std::string("unknown");
      LOG_TOPIC("b4133", INFO, arangodb::Logger::FIXME)
          << signals::name(signal) << " received (sender pid " << sender
          << "), beginning shut down sequence";

      application_features::ApplicationServer::CTRL_C.store(true);
    } else {
      LOG_TOPIC("11ca3", FATAL, arangodb::Logger::FIXME)
          << signals::name(signal) << " received during shutdown sequence (sender pid "
          << info->si_pid << "), terminating!";
      FATAL_ERROR_EXIT();
    }
  }
}

extern "C" void c_hangup_handler(int signal, siginfo_t * info, void *) {
  if (signal == SIGHUP) {
    std::string sender = info ? std::to_string(info->si_pid) : std::string("unknown");
    LOG_TOPIC("33eae", INFO, arangodb::Logger::FIXME)
        << "hangup received, about to reopen logfile (sender pid " << sender << ")";
    LogAppender::reopen();
    LOG_TOPIC("23db2", INFO, arangodb::Logger::FIXME)
        << "hangup received, reopened logfile";
  }
}
#endif

void SchedulerFeature::buildHangupHandler() {
#ifndef _WIN32
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigfillset(&action.sa_mask);
  action.sa_flags = SA_SIGINFO;
  action.sa_sigaction = c_hangup_handler;

  int res = sigaction(SIGHUP, &action, nullptr);

  if (res < 0) {
    LOG_TOPIC("b7ed0", ERR, arangodb::Logger::FIXME)
        << "cannot initialize signal handlers for hang up";
  }
#endif
}

void SchedulerFeature::buildControlCHandler() {
#ifdef _WIN32
  {
    int result = SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, true);

    if (result == 0) {
      LOG_TOPIC("e21e8", WARN, arangodb::Logger::FIXME)
          << "unable to install control-c handler";
    }
  }
#else
  // Signal masking on POSIX platforms
  //
  // POSIX allows signals to be blocked using functions such as sigprocmask()
  // and pthread_sigmask(). For signals to be delivered, programs must ensure
  // that any signals registered using signal_set objects are unblocked in at
  // least one thread.
  arangodb::signals::unmaskAllSignals();

  struct sigaction action;
  memset(&action, 0, sizeof(action));
  sigfillset(&action.sa_mask);
  action.sa_flags = SA_SIGINFO;
  action.sa_sigaction = c_exit_handler;

  int res = sigaction(SIGINT, &action, nullptr);
  if (res == 0) {
    res = sigaction(SIGQUIT, &action, nullptr);
    if (res == 0) {
      res = sigaction(SIGTERM, &action, nullptr);
    }
  }
  if (res < 0) {
    LOG_TOPIC("e666b", ERR, arangodb::Logger::FIXME)
        << "cannot initialize signal handlers for SIGINT/SIGQUIT/SIGTERM";
  }
#endif
}

}  // namespace arangodb


text:
require "rails_helper"

RSpec.describe HouseholdMoreInfoPerMemberController do
  let(:snap_application) do
    create(:snap_application, members: [member_one, member_two])
  end

  let(:member_one) { build(:member) }
  let(:member_two) { build(:member) }

  before do
    session[:snap_application_id] = snap_application.id
  end

  describe "#update" do
    context "when valid" do
      it "updates the member attributes if they are present" do
        params = {
          step: {
            members: {
              member_one.id => { disabled: "1", in_college: "0" },
              member_two.id => { in_college: "1", disabled: "0" },
            },
          },
        }

        put :update, params: params

        expect(member_one.reload).to be_disabled
        expect(member_two.reload).to be_in_college
      end
    end

    context "when no members selected" do
      context "for disabled" do
        it "updates anyone_disabled on the application" do
          snap_application.update(anyone_disabled: true)

          params = {
            step: {
              members: {
                member_one.id => { disabled: "0" },
                member_two.id => { disabled: "0" },
              },
            },
          }

          put :update, params: params

          snap_application.reload

          expect(snap_application.anyone_disabled).to eq(false)
        end
      end

      context "for new mom" do
        it "updates anyone_new_mom on the application" do
          snap_application.update(anyone_new_mom: true)

          params = {
            step: {
              members: {
                member_one.id => { new_mom: "0" },
                member_two.id => { new_mom: "0" },
              },
            },
          }

          put :update, params: params

          snap_application.reload

          expect(snap_application.anyone_new_mom).to eq(false)
        end
      end

      context "for college" do
        it "updates anyone_in college on the application" do
          snap_application.update(anyone_in_college: true)

          params = {
            step: {
              members: {
                member_one.id => { in_college: "0" },
                member_two.id => { in_college: "0" },
              },
            },
          }

          put :update, params: params

          snap_application.reload

          expect(snap_application.anyone_in_college).to eq(false)
        end
      end

      context "living elsewhere" do
        it "updates anyone_living_elsewhere on the application" do
          snap_application.update(anyone_living_elsewhere: true)

          params = {
            step: {
              members: {
                member_one.id => { living_elsewhere: "0" },
                member_two.id => { living_elsewhere: "0" },
              },
            },
          }

          put :update, params: params

          snap_application.reload

          expect(snap_application.anyone_living_elsewhere).to eq(false)
        end
      end
    end

    context "when all members selected" do
      context "for citizenship" do
        it "updates everyone_a_citizen on the application" do
          snap_application.update(everyone_a_citizen: false)

          params = {
            step: {
              members: {
                member_one.id => { citizen: "1" },
                member_two.id => { citizen: "1" },
              },
            },
          }

          put :update, params: params

          snap_application.reload

          expect(snap_application.everyone_a_citizen).to eq(true)
        end
      end
    end
  end
end


text:
module MazeRunner
  class Step
    attr_reader :cursor, :grid, :path

    def initialize(cursor, grid, path=nil)
      @cursor = cursor
      @grid   = grid
      @path   = (path || Set.new) << cursor
    end

    def next
      grid.neighbors(cursor).
        reject { |node| path.include? node }.
        select { |node| node >= cursor }.
        map { |node| Step.new(node, grid, path.clone) }
    end
  end
end


text:
<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\Entity;

use Oro\Bundle\ConfigBundle\Config\Tree\GroupNodeDefinition;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailThread;
use Oro\Bundle\EmailBundle\Tests\Unit\ReflectionUtil;
use Symfony\Component\PropertyAccess\PropertyAccess;

/**
 * Class EmailTest
 *
 * @package Oro\Bundle\EmailBundle\Tests\Unit\Entity
 *
 * @SuppressWarnings(PHPMD.TooManyMethods)
 */
class EmailTest extends \PHPUnit\Framework\TestCase
{
    public function testIdGetter()
    {
        $entity = new Email();
        ReflectionUtil::setId($entity, 1);
        $this->assertEquals(1, $entity->getId());
    }

    public function testFromEmailAddressGetterAndSetter()
    {
        $emailAddress = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailAddress');

        $entity = new Email();
        $entity->setFromEmailAddress($emailAddress);

        $this->assertTrue($emailAddress === $entity->getFromEmailAddress());
    }

    public function testRecipientGetterAndSetter()
    {
        $toRecipient = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailRecipient');
        $toRecipient->expects($this->any())
            ->method('getType')
            ->will($this->returnValue('to'));

        $ccRecipient = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailRecipient');
        $ccRecipient->expects($this->any())
            ->method('getType')
            ->will($this->returnValue('cc'));

        $bccRecipient = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailRecipient');
        $bccRecipient->expects($this->any())
            ->method('getType')
            ->will($this->returnValue('bcc'));

        $entity = new Email();
        $entity->addRecipient($toRecipient);
        $entity->addRecipient($ccRecipient);
        $entity->addRecipient($bccRecipient);

        $recipients = $entity->getRecipients();

        $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $recipients);
        $this->assertCount(3, $recipients);
        $this->assertTrue($toRecipient === $recipients[0]);
        $this->assertTrue($ccRecipient === $recipients[1]);
        $this->assertTrue($bccRecipient === $recipients[2]);

        /** @var GroupNodeDefinition $recipients */
        $recipients = $entity->getRecipients('to');
        $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $recipients);
        $this->assertCount(1, $recipients);
        $this->assertTrue($toRecipient === $recipients->first());

        $recipients = $entity->getRecipients('cc');
        $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $recipients);
        $this->assertCount(1, $recipients);
        $this->assertTrue($ccRecipient === $recipients->first());

        $recipients = $entity->getRecipients('bcc');
        $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $recipients);
        $this->assertCount(1, $recipients);
        $this->assertTrue($bccRecipient === $recipients->first());
    }

    public function testEmailBodyGetterAndSetter()
    {
        $emailBody = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailBody');

        $entity = new Email();
        $entity->setEmailBody($emailBody);

        $this->assertTrue($emailBody === $entity->getEmailBody());
    }

    public function testBeforeSave()
    {
        $createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
        $entity = new Email();
        $entity->beforeSave();

        $this->assertEquals(Email::NORMAL_IMPORTANCE, $entity->getImportance());
        $this->assertGreaterThanOrEqual($createdAt, $entity->getCreated());
    }

    public function testIsHeadGetterAndSetter()
    {
        $entity = new Email();
        $this->assertTrue($entity->isHead());

        $entity->setHead(false);
        $this->assertFalse($entity->isHead());
    }

    /**
     * @dataProvider refsDataProvider
     * @param string $set
     * @param array $get
     */
    public function testRefsGetterAndSetter($set, $get)
    {
        $entity = new Email();
        $entity->setRefs($set);
        $this->assertEquals($get, $entity->getRefs());
    }

    /**
     * @dataProvider propertiesDataProvider
     * @param string $property
     * @param mixed  $value
     */
    public function testSettersAndGetters($property, $value)
    {
        $obj = new Email();

        $accessor = PropertyAccess::createPropertyAccessor();
        $accessor->setValue($obj, $property, $value);
        $this->assertEquals($value, $accessor->getValue($obj, $property));
    }

    /**
     * @return array
     */
    public function propertiesDataProvider()
    {
        return [
            ['subject', 'testSubject'],
            ['fromName', 'testFromName'],
            ['sentAt', new \DateTime('now', new \DateTimeZone('UTC'))],
            ['importance', Email::HIGH_IMPORTANCE],
            ['internalDate', new \DateTime('now', new \DateTimeZone('UTC'))],
            ['messageId', 'testMessageId'],
            ['xMessageId', 'testXMessageId'],
            ['thread', new EmailThread()],
            ['xThreadId', 'testxXThreadId'],
            ['multiMessageId', ['MessageId1','MessageId2']],
        ];
    }

    public function refsDataProvider()
    {
        return [
            [null, []],
            ['', []],
            ['ref', []],
            ['<ref>', ['<ref>']],
            ['<ref1><ref2>', ['<ref1>', '<ref2>']],
            ['<ref1> <ref2>', ['<ref1>', '<ref2>']],
            ['<ref1> ref2', ['<ref1>']],
        ];
    }

    public function testSetSubjectOnLongString()
    {
        $activityList = new Email();
        $activityList->setSubject(
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut sem cursus ligula consectetur iaculis. '
            . 'Sed ac viverra mi, in auctor tortor. Aliquam id est laoreet, ultricies lectus a, aliquam lectus. Aenean'
            . ' ac tristique eros. Integer vestibulum volutpat lacus, eu lobortis sapien condimentum in. Pellentesque '
            . 'a venenatis risus, id placerat nisi. Donec egestas maximus convallis. Cras eleifend leo quis neque '
            . 'rutrum suscipit. Nulla facilisi. Integer vel enim at tellus ornare condimentum. Nunc rhoncus urna nec '
            . 'scelerisque elementum. Pellentesque id ante sapien. Phasellus luctus facilisis massa, eu condimentum '
            . 'justo ultrices at. Curabitur purus diam, aliquet sit amet ante a, aliquet faucibus metus. Nam efficitur'
            . ' tincidunt urna tincidunt tincidunt. Maecenas et dictum enim. Maecenas pellentesque purus et sapien '
            . 'vulputate efficitur. Curabitur egestas gravida venenatis. Nullam efficitur nulla eu augue vestibulum, '
            . 'ut imperdiet nibh pellentesque. Cras ultrices luctus magna vel sodales. Curabituä eget nullam.'
        );

        self::assertEquals(
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut sem cursus ligula consectetur iaculis. '
            . 'Sed ac viverra mi, in auctor tortor. Aliquam id est laoreet, ultricies lectus a, aliquam lectus. Aenean'
            . ' ac tristique eros. Integer vestibulum volutpat lacus, eu lobortis sapien condimentum in. Pellentesque '
            . 'a venenatis risus, id placerat nisi. Donec egestas maximus convallis. Cras eleifend leo quis neque '
            . 'rutrum suscipit. Nulla facilisi. Integer vel enim at tellus ornare condimentum. Nunc rhoncus urna nec '
            . 'scelerisque elementum. Pellentesque id ante sapien. Phasellus luctus facilisis massa, eu condimentum '
            . 'justo ultrices at. Curabitur purus diam, aliquet sit amet ante a, aliquet faucibus metus. Nam efficitur'
            . ' tincidunt urna tincidunt tincidunt. Maecenas et dictum enim. Maecenas pellentesque purus et sapien '
            . 'vulputate efficitur. Curabitur egestas gravida venenatis. Nullam efficitur nulla eu augue vestibulum, '
            . 'ut imperdiet nibh pellentesque. Cras ultrices luctus magna vel sodales. Curabituä',
            $activityList->getSubject()
        );
    }
}


text:
#pragma once

#include <QFrame>
#include "Code/CaptureContext.h"

namespace Ui
{
class ShaderViewer;
}

class RDTreeWidgetItem;
struct ShaderDebugTrace;
struct ShaderReflection;
class ScintillaEdit;
class FindReplace;
class QTableWidgetItem;
class QKeyEvent;
class QMouseEvent;
class QComboBox;

// from Scintilla
typedef intptr_t sptr_t;

enum class VariableCategory
{
  Unknown,
  Inputs,
  Constants,
  IndexTemporaries,
  Temporaries,
  Outputs,
};

class ShaderViewer : public QFrame, public IShaderViewer, public ILogViewer
{
  Q_OBJECT

public:
  static IShaderViewer *EditShader(ICaptureContext &ctx, bool customShader, const QString &entryPoint,
                                   const QStringMap &files, IShaderViewer::SaveCallback saveCallback,
                                   IShaderViewer::CloseCallback closeCallback, QWidget *parent)
  {
    ShaderViewer *ret = new ShaderViewer(ctx, parent);
    ret->m_SaveCallback = saveCallback;
    ret->m_CloseCallback = closeCallback;
    ret->editShader(customShader, entryPoint, files);
    return ret;
  }

  static IShaderViewer *DebugShader(ICaptureContext &ctx, const ShaderBindpointMapping *bind,
                                    const ShaderReflection *shader, ShaderStage stage,
                                    ShaderDebugTrace *trace, const QString &debugContext,
                                    QWidget *parent)
  {
    ShaderViewer *ret = new ShaderViewer(ctx, parent);
    ret->debugShader(bind, shader, stage, trace, debugContext);
    return ret;
  }

  static IShaderViewer *ViewShader(ICaptureContext &ctx, const ShaderBindpointMapping *bind,
                                   const ShaderReflection *shader, ShaderStage stage, QWidget *parent)
  {
    return DebugShader(ctx, bind, shader, stage, NULL, QString(), parent);
  }

  ~ShaderViewer();

  // IShaderViewer
  virtual QWidget *Widget() override { return this; }
  virtual int CurrentStep() override;
  virtual void SetCurrentStep(int step) override;

  virtual void ToggleBreakpoint(int instruction = -1) override;

  virtual void ShowErrors(const QString &errors) override;

  // ILogViewerForm
  void OnLogfileLoaded() override;
  void OnLogfileClosed() override;
  void OnSelectedEventChanged(uint32_t eventID) override {}
  void OnEventChanged(uint32_t eventID) override;

private slots:
  // automatic slots
  void on_findReplace_clicked();
  void on_save_clicked();
  void on_intView_clicked();
  void on_floatView_clicked();

  void on_watch_itemChanged(QTableWidgetItem *item);

  // manual slots
  void readonly_keyPressed(QKeyEvent *event);
  void editable_keyPressed(QKeyEvent *event);
  void disassembly_contextMenu(const QPoint &pos);
  void disassembly_buttonReleased(QMouseEvent *event);
  void disassemble_typeChanged(int index);
  void watch_keyPress(QKeyEvent *event);
  void performFind();
  void performFindAll();
  void performReplace();
  void performReplaceAll();

  void snippet_textureDimensions();
  void snippet_selectedMip();
  void snippet_selectedSlice();
  void snippet_selectedSample();
  void snippet_selectedType();
  void snippet_samplers();
  void snippet_resources();

  void disasm_tooltipShow(int x, int y);
  void disasm_tooltipHide(int x, int y);

public slots:
  bool stepBack();
  bool stepNext();
  void runToCursor();
  void runToSample();
  void runToNanOrInf();
  void runBack();
  void run();

private:
  explicit ShaderViewer(ICaptureContext &ctx, QWidget *parent = 0);
  void editShader(bool customShader, const QString &entryPoint, const QStringMap &files);
  void debugShader(const ShaderBindpointMapping *bind, const ShaderReflection *shader,
                   ShaderStage stage, ShaderDebugTrace *trace, const QString &debugContext);

  bool eventFilter(QObject *watched, QEvent *event) override;

  const rdctype::array<ShaderVariable> *GetVariableList(VariableCategory varCat, int arrayIdx);
  void getRegisterFromWord(const QString &text, VariableCategory &varCat, int &varIdx, int &arrayIdx);

  void showVariableTooltip(VariableCategory varCat, int varIdx, int arrayIdx);
  void updateVariableTooltip();
  void hideVariableTooltip();

  VariableCategory m_TooltipVarCat = VariableCategory::Temporaries;
  int m_TooltipVarIdx = -1;
  int m_TooltipArrayIdx = -1;
  QPoint m_TooltipPos;

  Ui::ShaderViewer *ui;
  ICaptureContext &m_Ctx;
  const ShaderBindpointMapping *m_Mapping = NULL;
  const ShaderReflection *m_ShaderDetails = NULL;
  ShaderStage m_Stage;
  ScintillaEdit *m_DisassemblyView = NULL;
  QWidget *m_DisassemblyFrame = NULL;
  QComboBox *m_DisassemblyType = NULL;
  ScintillaEdit *m_Errors = NULL;
  ScintillaEdit *m_FindResults = NULL;
  QList<ScintillaEdit *> m_Scintillas;

  FindReplace *m_FindReplace;

  struct FindState
  {
    // hash identifies when the search has changed
    QString hash;

    // the range identified when the search first occurred (for incremental find/replace)
    sptr_t start = 0;
    sptr_t end = 0;

    // the current offset where to search from next time, relative to above range
    sptr_t offset = 0;

    // the last result
    QPair<int, int> prevResult;
  } m_FindState;

  SaveCallback m_SaveCallback;
  CloseCallback m_CloseCallback;

  ShaderDebugTrace *m_Trace = NULL;
  int m_CurrentStep;
  QList<int> m_Breakpoints;

  static const int CURRENT_MARKER = 0;
  static const int BREAKPOINT_MARKER = 2;
  static const int FINISHED_MARKER = 4;

  static const int INDICATOR_FINDRESULT = 0;
  static const int INDICATOR_REGHIGHLIGHT = 1;

  void addFileList();

  ScintillaEdit *MakeEditor(const QString &name, const QString &text, int lang);
  ScintillaEdit *AddFileScintilla(const QString &name, const QString &text);

  ScintillaEdit *currentScintilla();
  ScintillaEdit *nextScintilla(ScintillaEdit *cur);

  int snippetPos();
  void insertVulkanUBO();

  int instructionForLine(sptr_t line);

  void updateDebugging();

  void ensureLineScrolled(ScintillaEdit *s, int i);

  void find(bool down);

  void runTo(int runToInstruction, bool forward, ShaderEvents condition = ShaderEvents::NoEvent);

  QString stringRep(const ShaderVariable &var, bool useType);
  RDTreeWidgetItem *makeResourceRegister(const BindpointMap &bind, uint32_t idx,
                                         const BoundResource &ro, const ShaderResource &resources);
};


text:
<?php

use FR3D\SwaggerAssertions\PhpUnit\AssertsTrait;
use FR3D\SwaggerAssertions\SchemaManager;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;

/**
 * PHPUnit integration example.
 */
class LocalFileTest extends \PHPUnit_Framework_TestCase
{
    use AssertsTrait;

    /**
     * @var SchemaManager
     */
    protected static $schemaManager;

    /**
     * @var ClientInterface
     */
    protected $guzzleHttpClient;

    public static function setUpBeforeClass()
    {
        $filePath = __DIR__ . '/../fixtures/pet_store.json';

        // Use file:// for local files
        self::$schemaManager = new SchemaManager('file://' . $filePath);
    }

    protected function setUp()
    {
        $this->guzzleHttpClient = new Client(array('headers' => array('User-Agent' => 'https://github.com/Maks3w/SwaggerAssertions')));
    }

    public function testFetchPetBodyMatchDefinition()
    {
        $request = $this->guzzleHttpClient->createRequest('GET', 'http://petstore.swagger.io/v2/pet/findByStatus');
        $request->addHeader('Accept', 'application/json');

        $response = $this->guzzleHttpClient->send($request);
        $responseBody = $response->json(array('object' => true));

        $this->assertResponseBodyMatch($responseBody, self::$schemaManager, '/v2/pet/findByStatus', 'get', 200);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
  mongoose = require('mongoose'),
  MailinglistGroup = mongoose.model('MailinglistGroup'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create an mailinglistGroup
 */
exports.create = function (req, res) {
  var mailinglistGroup = new MailinglistGroup(req.body);

  mailinglistGroup.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(mailinglistGroup);
    }
  });
};

exports.removeGroups = function (req, res) {
  var items = [];
  req.body.items.forEach(function (item) {
    items.push(item._id);
  });

  MailinglistGroup.remove({ _id: { $in: items } }, function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json({ message: 'success' });
    }
  });
};

/**
 * Show the current mailinglistGroup
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var mailinglistGroup = req.mailinglistGroup ? req.mailinglistGroup.toJSON() : {};
  res.json(mailinglistGroup);
};

/**
 * Update an mailinglistGroup
 */
exports.update = function (req, res) {
  var mailinglistGroup = req.mailinglistGroup;

  mailinglistGroup.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(mailinglistGroup);
    }
  });
};

/**
 * Delete an mailinglistGroup
 */
exports.delete = function (req, res) {
  var mailinglistGroup = req.mailinglistGroup;

  mailinglistGroup.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(mailinglistGroup);
    }
  });
};

/**
 * List of MailinglistGroups
 */
exports.list = function (req, res) {
  MailinglistGroup.find().sort('-created').exec(function (err, mailinglistGroups) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(mailinglistGroups);
    }
  });
};

/**
 * MailinglistGroup middleware
 */
exports.mailinglistGroupByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'MailinglistGroup is invalid'
    });
  }

  MailinglistGroup.findById(id).exec(function (err, mailinglistGroup) {
    if (err) {
      return next(err);
    } else if (!mailinglistGroup) {
      return res.status(404).send({
        message: 'No mailinglistGroup with that identifier has been found'
      });
    }
    req.mailinglistGroup = mailinglistGroup;
    next(null, mailinglistGroup);
  });
};

exports.mailinglistGroupByName = function (req, res, next, name) {

  MailinglistGroup.findOne({ name: name }).exec(function (err, mailinglistGroup) {
    if (err) {
      return next(err);
    } else if (!mailinglistGroup) {
      return res.status(404).send({
        message: 'No mailinglistGroup with that identifier has been found'
      });
    }
    req.mailinglistGroup = mailinglistGroup;
    next(null, mailinglistGroup);
  });
};


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function, division, absolute_import, unicode_literals
try:  from __builtin__ import bytes, str, open, super, range, zip, round, int, pow, object, input
except ImportError:  pass
try:  from __builtin__ import raw_input as input
except:  pass
from getpass import getpass
from simplebitcoinfuncs import *
from simplebitcoinfuncs.hexhashes import *
from pybip38 import bip38decrypt

print()

while True:
    userseed = input("Please enter your user seed (begins with K or L) or your master xprv key:\n")
    userseed = normalize_input(userseed).replace('\r','').replace('\n','').replace(' ','')
    try:
        if userseed[0] == 'K' or userseed[0] == 'L':
            userseed = privtohex(userseed)
            assert len(userseed) == 64
        elif userseed[:4] != 'xprv':
            raise Exception(' ')
        userkey = BIP32(userseed)
    except:
        print("\nInvalid user seed entered.\n")
    else:
        break

print("\nExcellent! Your user public key appears to be:\n" + userkey.xpub)

while True:
    sharedseed = input("\nPlease enter the shared seed (begins with 6P):\n")
    sharedseed = normalize_input(sharedseed).replace('\r','').replace('\n','').replace(' ','')
    try:
        sharedseed = b58d(sharedseed)
        assert len(sharedseed) == 78
        assert sharedseed[:4] == '0142' or sharedseed[:4] == '0143'
    except:
        print("\nInvalid shared seed entered.")
    else:
        sharedseed = b58e(sharedseed)
        break

while True:
    sharedseedxpub = input("\nPlease enter the shared public key:\n")
    sharedseedxpub = normalize_input(sharedseedxpub).replace('\r','').replace('\n','').replace(' ','')
    try:
        assert sharedseedxpub[:4] == 'xpub'
        sharedseedxpub = BIP32(sharedseedxpub).xpub
        assert sharedseedxpub[:4] == 'xpub'
    except:
        print("\nInvalid shared public key entered. It should begin with 'xpub'.")
    else:
        break

while True:
    coinbasexpub = input("\nPlease enter the Coinbase public key:\n")
    coinbasexpub = normalize_input(coinbasexpub).replace('\r','').replace('\n','').replace(' ','')
    try:
        assert coinbasexpub[:4] == 'xpub'
        coinbasexpub = BIP32(coinbasexpub)
        assert coinbasexpub.xpub[:4] == 'xpub'
    except:
        print("\nInvalid Coinbase public key entered. It should begin with 'xpub'.")
    else:
        break

print("\nAlmost finished!")

while True:
    password = getpass("\nPlease enter your vault password:  ")
    try:
        password = normalize_input(password,False,True)
        sharedkey = bip38decrypt(password,sharedseed,False)
        assert sharedkey is not False
        sharedkey = privtohex(sharedkey)
        sharedkey = BIP32(sharedkey)
        assert sharedkey.xpub == sharedseedxpub
    except:
        print("\nThe password entered does not decrypt the key properly. Perhaps you mis-typed? Please try again.")
    else:
        break

while True:
    index = input("\nPlease enter the index number for the vault address (0 for first address):  ")
    try:
        index = int(index)
    except:
        print("\nYou must enter only a number.")
    else:
        break

print("\nFantastic! Here is the prerequisite information for making a multisig transaction yourself:\n")

path = "m/" + str(index)
key1 = userkey[path].pub
key2 = sharedkey[path].pub
key3 = coinbasexpub[path].pub

keylist = [int(key1,16),int(key2,16),int(key3,16)]
keylist.sort()

redeemscript = "52"

for i in range(len(keylist)):
    key = dechex(keylist[i])
    redeemscript = redeemscript + dechex(len(key)//2) + key

redeemscript = redeemscript + "53ae"

address = b58e("05" + hash160(redeemscript))

print("Address:")
print(address + "\n")

print("Redeem script:")
print(redeemscript + "\n")

print("First multisig signing key:")
print(userkey[path].wif + "\n")

print("Second multisig signing key:")
print(sharedkey[path].wif + "\n")

print('You can use a site like Coinb.in to make and sign a new multisig transaction.\nhttps://coinb.in/#newTransaction')

print()
exit()


text:
export default {
  //- builtin-prepass
  "minification.constantFolding":          require("babel-plugin-constant-folding"),

  //- builtin-pre
  strict:                                  require("./other/strict"),
  eval:                                    require("babel-plugin-eval"),
  _explode:                                require("./internal/explode"),
  _validation:                             require("./internal/validation"),
  _hoistDirectives:                        require("./internal/hoist-directives"),
  "minification.removeDebugger":           require("babel-plugin-remove-debugger"),
  "minification.removeConsole":            require("babel-plugin-remove-console"),
  "utility.inlineEnvironmentVariables":    require("babel-plugin-inline-environment-variables"),
  "minification.deadCodeElimination":      require("babel-plugin-dead-code-elimination"),
  _modules:                                require("./internal/modules"),
  "react.displayName":                     require("babel-plugin-react-display-name"),
  "es6.spec.templateLiterals":             require("./es6/spec.template-literals"),
  "es6.templateLiterals":                  require("./es6/template-literals"),
  "validation.undeclaredVariableCheck":    require("babel-plugin-undeclared-variables-check"),

  //- builtin-basic
  // this is where the bulk of the ES6 transformations take place, none of them require traversal state
  // so they can all be concatenated together for performance
  "spec.functionName":                     require("./spec/function-name"),
  "es7.classProperties":                   require("./es7/class-properties"),
  "es7.trailingFunctionCommas":            require("./es7/trailing-function-commas"),
  "es7.asyncFunctions":                    require("./es7/async-functions"),
  "es7.decorators":                        require("./es7/decorators"),
  "validation.react":                      require("./validation/react"),
  "es6.arrowFunctions":                    require("./es6/arrow-functions"),
  "spec.blockScopedFunctions":             require("./spec/block-scoped-functions"),
  "optimisation.react.constantElements":   require("babel-plugin-react-constant-elements"),
  "optimisation.react.inlineElements":     require("./optimisation/react.inline-elements"),
  "es7.comprehensions":                    require("./es7/comprehensions"),
  "es6.classes":                           require("./es6/classes"),
  asyncToGenerator:                        require("./other/async-to-generator"),
  bluebirdCoroutines:                      require("./other/bluebird-coroutines"),
  "es6.objectSuper":                       require("./es6/object-super"),
  "es7.objectRestSpread":                  require("./es7/object-rest-spread"),
  "es7.exponentiationOperator":            require("./es7/exponentiation-operator"),
  "es5.properties.mutators":               require("./es5/properties.mutators"),
  "es6.properties.shorthand":              require("./es6/properties.shorthand"),
  "es6.properties.computed":               require("./es6/properties.computed"),
  "optimisation.flow.forOf":               require("./optimisation/flow.for-of"),
  "es6.forOf":                             require("./es6/for-of"),
  "es6.regex.sticky":                      require("./es6/regex.sticky"),
  "es6.regex.unicode":                     require("./es6/regex.unicode"),
  "es6.constants":                         require("./es6/constants"),
  "es7.exportExtensions":                  require("./es7/export-extensions"),
  "spec.protoToAssign":                    require("babel-plugin-proto-to-assign"),
  "es7.doExpressions":                     require("./es7/do-expressions"),
  "es6.spec.symbols":                      require("./es6/spec.symbols"),
  "es7.functionBind":                      require("./es7/function-bind"),
  "spec.undefinedToVoid":                  require("babel-plugin-undefined-to-void"),

  //- builtin-advanced
  "es6.spread":                            require("./es6/spread"),
  "es6.parameters":                        require("./es6/parameters"),
  "es6.destructuring":                     require("./es6/destructuring"),
  "es6.blockScoping":                      require("./es6/block-scoping"),
  "es6.spec.blockScoping":                 require("./es6/spec.block-scoping"),
  reactCompat:                             require("./other/react-compat"),
  react:                                   require("./other/react"),
  regenerator:                             require("./other/regenerator"),

  // es6 syntax transformation is **forbidden** past this point since regenerator will chuck a massive
  // hissy fit

  //- builtin-modules
  runtime:                                 require("babel-plugin-runtime"),
  "es6.modules":                           require("./es6/modules"),
  _moduleFormatter:                        require("./internal/module-formatter"),

  //- builtin-trailing
  // these clean up the output and do finishing up transformations, it's important to note that by this
  // stage you can't import any new modules or insert new ES6 as all those transformers have already
  // been ran
  "es6.tailCall":                          require("./es6/tail-call"),
  _shadowFunctions:                        require("./internal/shadow-functions"),
  "es3.propertyLiterals":                  require("./es3/property-literals"),
  "es3.memberExpressionLiterals":          require("./es3/member-expression-literals"),
  "minification.memberExpressionLiterals": require("babel-plugin-member-expression-literals"),
  "minification.propertyLiterals":         require("babel-plugin-property-literals"),
  _blockHoist:                             require("./internal/block-hoist"),
  jscript:                                 require("babel-plugin-jscript"),
  flow:                                    require("./other/flow"),
  "optimisation.modules.system":           require("./optimisation/modules.system"),
};