text:
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');

// see this link for more info on what all of this means
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
module.exports = {
  webpack_assets_file_path: 'webpack-stats.json',

  assets: {
    images: {
      extensions: [
        'jpeg',
        'jpg',
        'png',
        'gif',
        'svg'
      ],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser
    },
    style_modules: {
      extension: 'scss',
      development: true,
      filter: function(m, regex, options) {
        if (options.environment === 'production') {
          return regex.test(m.name);
        }
        //filter by modules with '.scss' inside name string, that also have name and moduleName that end with 'ss'(allows for css, less, sass, and scss extensions)
        //this ensures that the proper scss module is returned, so that namePrefix variable is no longer needed
        return (regex.test(m.name) && m.name.slice(-2) === 'ss' && m.reasons[0].moduleName.slice(-2) === 'ss');
      },
      naming: function(m) {
        //find index of '/src' inside the module name, slice it and resolve path
        var srcIndex = m.name.indexOf('/src');
        var name = '.' + m.name.slice(srcIndex);
        if (name) {
          // Resolve the e.g.: "C:\"  issue on windows
          const i = name.indexOf(':');
          if (i >= 0) {
            name = name.slice(i + 1);
          }
        }
        return name;
      },
      parser: function(m, options) {
        if (m.source) {
          var regex = options.environment === 'production' ? /module\.exports = ((.|\n)+);/ : /exports\.locals = ((.|\n)+);/;
          var match = m.source.match(regex);
          return match ? JSON.parse(match[1]) : {};
        }
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
---
id: 5a94fe8569fb03452672e464
title: Create Grids within Grids
challengeType: 0
videoUrl: https://scrimba.com/p/pByETK/c6N78Ap
forumTopicId: 301128
localeTitle: Создание гридов в сетках
---

## Description

Включение элемента в сетку влияет только на поведение его прямых потомков. Поэтому, превратив прямого потомка в сетку, у вас есть сетка внутри сетки. Например, задав свойства display и grid-template-columns элемента с классом item3 , вы создаете сетку в своей сетке.

## Instructions

Поверните элемент с классом item3 в сетку с двумя столбцами с шириной auto и 1fr используя 1fr display и grid-template-columns .

## Tests

```yml
tests:
  - text: <code>item3</code> class should have a <code>grid-template-columns</code> property with <code>auto</code> and <code>1fr</code> as values.
    testString: assert(code.match(/.item3\s*?{[\s\S]*grid-template-columns\s*?:\s*?auto\s*?1fr\s*?;[\s\S]*}/gi));
  - text: <code>item3</code> class should have a <code>display</code> property with the value of <code>grid</code>.
    testString: assert(code.match(/.item3\s*?{[\s\S]*display\s*?:\s*?grid\s*?;[\s\S]*}/gi));

```

## Challenge Seed

```html
<style>
  .container {
    font-size: 1.5em;
    min-height: 300px;
    width: 100%;
    background: LightGray;
    display: grid;
    grid-template-columns: auto 1fr;
    grid-template-rows: auto 1fr auto;
    grid-gap: 10px;
    grid-template-areas:
      "advert header"
      "advert content"
      "advert footer";
  }
  .item1 {
    background: LightSkyBlue;
    grid-area: header;
  }

  .item2 {
    background: LightSalmon;
    grid-area: advert;
  }

  .item3 {
    background: PaleTurquoise;
    grid-area: content;
    /* enter your code below this line */

    /* enter your code above this line */
  }

  .item4 {
    background: lightpink;
    grid-area: footer;
  }

  .itemOne {
    background: PaleGreen;
  }

  .itemTwo {
    background: BlanchedAlmond;
  }

</style>

<div class="container">
  <div class="item1">header</div>
  <div class="item2">advert</div>
  <div class="item3">
    <div class="itemOne">paragraph1</div>
    <div class="itemTwo">paragraph2</div>
  </div>
  <div class="item4">footer</div>
</div>

```

## Solution

```html
var code = ".item3 {grid-template-columns: auto 1fr; display: grid;}"
```


text:
<?php

namespace Rhubarb\Crown\Sendables\Email;

use Rhubarb\Crown\Logging\Log;
use Rhubarb\Crown\Mime\MimeDocument;
use Rhubarb\Crown\Mime\MimePartBinaryFile;
use Rhubarb\Crown\Mime\MimePartText;
use Rhubarb\Crown\Sendables\Sendable;

/**
 * Represents and channels delivery of an email.
 *
 * This class is abstract as the getText(), getSubject() and getHtml() methods must be implemented to satisfy
 * the implementation.
 */
abstract class Email extends Sendable
{
    private $sender;

    private $attachments = [];

    /**
     * Adds an attachment
     *
     * @param string $path The path to the local file
     * @param string $newName Optionally specify a new name for the file.
     * @return $this
     */
    public function addAttachment($path, $newName = "")
    {
        if ($newName == "") {
            $newName = basename($path);
        }

        $file = new \stdClass();
        $file->path = $path;
        $file->name = $newName;

        $this->attachments[] = $file;

        return $this;
    }

    public function getAttachments()
    {
        return $this->attachments;
    }

    /**
     * Returns the Reply-To recipient for the email.
     *
     * Defaults to calling getSender()
     *
     * @return EmailRecipient
     */
    public function getReplyToRecipient()
    {
        return $this->getSender();
    }

    /**
     * @return string
     */
    abstract public function getSubject();

    /**
     * @return string
     */
    abstract public function getHtml();

    /**
     * @return EmailRecipient
     */
    public function getSender()
    {
        if ($this->sender == null) {
            return $this->getDefaultSender();
        }

        return $this->sender;
    }

    /**
     * Returns a default sender when none is supplied.
     *
     * @return EmailRecipient
     */
    protected function getDefaultSender()
    {
        $emailSettings = EmailSettings::singleton();

        return $emailSettings->defaultSender;
    }

    /**
     * @param EmailRecipient|string $senderEmail Email address as a string, or an EmailRecipient instance
     * @param string $name The name of the sender. This is ignored if passing an EmailRecipient instance for $senderEmail
     * @return $this
     */
    public function setSender($senderEmail, $name = null)
    {
        if (!($senderEmail instanceof EmailRecipient)) {
            $senderEmail = new EmailRecipient($senderEmail, $name);
        }
        $this->sender = $senderEmail;

        return $this;
    }

    public function addRecipientByEmail($recipientEmail, $recipientName = "")
    {
        $this->addRecipient(new EmailRecipient($recipientEmail, $recipientName));

        return $this;
    }

    public function addRecipientsByEmail($recipients)
    {
        if (!is_array($recipients)){
            $recipients = [$recipients];
        }

        foreach ($recipients as $recipient) {
            $this->addRecipientByEmail($recipient);
        }

        return $this;
    }

    public function getRecipientList()
    {
        return implode(", ", $this->getRecipients());
    }

    public function getRecipients()
    {
        $emailSettings = EmailSettings::singleton();

        if ($emailSettings->onlyRecipient) {
            // Only send emails to a test recipient, to prevent emailing real customers from a development environment
            return [$emailSettings->onlyRecipient];
        }

        return parent::getRecipients();
    }

    public function getSendableType()
    {
        return "Email";
    }

    /**
     * Gets a MimeDocument to represent this email.
     *
     * @return MimeDocument
     */
    public function getMimeDocument()
    {
        $textPart = false;
        $htmlPart = false;

        $html = $this->getHtml();
        $text = $this->getText();
        $subject = $this->getSubject();

        $contentType = $this->getContentType();

        /**
         * @var string|bool Tracks which part should contain the text and html parts.
         */
        $alternativePart = false;

        if (count($this->attachments) > 0) {
            $mime = new MimeDocument("multipart/mixed", crc32($html) . crc32($text) . crc32($subject));
        } else {
            $mime = new MimeDocument("multipart/alternative", crc32($html) . crc32($text) . crc32($subject));

            // The outer mime part is our alternative part
            $alternativePart = $mime;
        }

        if ($text != "") {
            $textPart = new MimePartText("text/plain");
            $textPart->setTransformedBody($text);
        }

        if ($html != "") {
            $htmlPart = new MimePartText("text/html");

            if($contentType != ""){
                $htmlPart->addHeader("Content-Type", $contentType);
            }

            $htmlPart->setTransformedBody($html);
        }

        if ($text != "" && $html != "") {
            if (count($this->attachments) > 0) {
                // As this email has attachments we need to create an alternative part to store the text and html
                $alternativePart = new MimeDocument("multipart/alternative");

                $mime->addPart($alternativePart);
            }

            $alternativePart->addPart($textPart);
            $alternativePart->addPart($htmlPart);
        } else {
            if ($text != "") {
                $mime->addPart($textPart);
            }

            if ($html != "") {
                $mime->addPart($htmlPart);
            }
        }

        foreach ($this->attachments as $attachment) {
            $mime->addPart(MimePartBinaryFile::fromLocalPath($attachment->path, $attachment->name));
        }

        $mime->addHeader("To", $this->getRecipientList());
        $mime->addHeader("From", $this->getSender()->getRfcFormat());
        $mime->addHeader("Subject", $this->getSubject());
        $mime->addHeader("Reply-To", $this->getReplyToRecipient());

        return $mime;
    }

    /**
     * Returns a string value which will set the Content-Type header for the html part of the email.
     *
     * @return string
     */
    protected function getContentType(){
        return "";
    }

    public function getBodyRaw()
    {
        $html = $this->getHtml();
        $text = $this->getText();

        if ($html != "" || count($this->attachments) > 0) {
            $mime = $this->getMimeDocument();

            return $mime->getTransformedBody();
        } else {
            return $text;
        }
    }

    /**
     * Returns the headers as a string.
     */
    public function getMailHeadersAsString()
    {
        $headerString = "";

        foreach ($this->getMailHeaders() as $header => $value) {
            $headerString .= $header . ": " . $value . "\r\n";
        }

        return trim($headerString);
    }

    /**
     * Returns the mail headers as an array of key value pairs.
     *
     * @return array
     */
    public function getMailHeaders()
    {
        $headers = [];

        $html = $this->getHtml();
        $text = $this->getText();
        $subject = $this->getSubject();

        if ($html != "" || count($this->attachments) > 0) {
            $mime = new MimeDocument("multipart/alternative", crc32($html) . crc32($text) . crc32($subject));
            $headers = $mime->getHeaders();
        } else {
            $headers["Content-Type"] = "text/plain; charset=utf-8";
        }

        $headers["From"] = (string)$this->getSender();
        $headers["Subject"] = $subject;

        return $headers;
    }

    public function getProviderClassName()
    {
        return EmailProvider::class;
    }

    protected function logSending()
    {
        $subject = $this->getSubject();
        $html = $this->getHtml();
        $text = $this->getText();

        Log::debug("Sending email `" . $subject . "` to recipients: " . $this->getRecipientList(), "EMAIL");

        Log::bulkData(
            "Email content",
            "EMAIL",
            $this->getMailHeadersAsString() . "\r\n\r\n" .
            ($html != "") ? $html : $text
        );
    }
}


text:
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[additional_info_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[additional_info_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[additional_info_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[nozzle_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[nozzle_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[nozzle_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_count_reports_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_count_reports_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_count_reports_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_reports_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_reports_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_reports_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_time_reports_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_time_reports_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[production_time_reports_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[z_cass_npm_hdr_by_board]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[z_cass_npm_hdr]')
AND
    name = 'trx_productid'
go
SELECT
    object_id,
    max_length,
    name
FROM
    sys.columns
WHERE
    object_id = OBJECT_ID(N'[dbo].[z_cass_npm_hdr_raw]')
AND
    name = 'trx_productid'
go
go


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

/**
 * @fileoverview ... TODO ihab.awad
 * @author kpreid@switchb.org
 * @author ihab.awad@gmail.com
 * @author jasvir@gmail.com
 * \@requires document, setTimeout, XMLHttpRequest
 * \@overrides window
 * \@provides caja
 */

var caja = (function () {
  var cajaBuildVersion = '5669';
  var defaultServer = 'https://caja.appspot.com/';
  var defaultFrameGroup;
  var readyQueue = [];
  var registeredImports = [];
  var nextId = 0;

  var UNREADY = 'UNREADY', PENDING = 'PENDING', READY = 'READY';
  var state = UNREADY;
  var globalConfig = undefined;

  var GUESS = 'GUESS';

  var ajaxCounter = 1;
  var unsafe = false;

  var loaderDocument;
  function proxyFetchMaker(proxyServer) {
    return function (url, mime, callback) {
      if (!url) {
        callback(undefined);
        return;
      }
      var rndName = 'caja_ajax_' + ajaxCounter++;
      window[rndName] = function (result) {
        try {
          callback(result);
        } finally {
          // GC yourself
          window[rndName] = undefined;
        }
      };
      // TODO(jasvir): Make it so this does not pollute the host page
      // namespace but rather just the loaderFrame
      installSyncScript(rndName,
        (proxyServer ? String(proxyServer) : caja['server'])
        + '/proxy?url=' + encodeURIComponent(url.toString())
        + '&input-mime-type=' + encodeURIComponent(mime)
        + '&callback=' + encodeURIComponent(rndName)
        + '&alt=json-in-script');
    };
  }

  function xhrFetcher(url, mime, callback) {
    var request = new XMLHttpRequest();
    request.open('GET', url.toString(), true);
    request.overrideMimeType(mime);
    request.onreadystatechange = function() {
      if(request.readyState == 4) {
        callback({ "html": request.responseText });
      }
    };
    request.send();
  }

  var uriPolicies = {
    'net': {
      'rewriter': {
        'NO_NETWORK': function () { return null; },
        'ALL': function (uri) { return String(uri); }
      },
      'fetcher': {
        'USE_XHR': xhrFetcher,
        'USE_AS_PROXY': proxyFetchMaker
      },
      'NO_NETWORK': {
        'rewrite': function () { return null; },
        'fetch': function(url, mime, callback) {
          setTimeout(function() {
            // TODO(kpreid): correct error response (define one if needed)
            callback({});
          }, 0);
        }
      },
      'ALL': {
        'rewrite': function (uri) { return String(uri); },
        'fetch': proxyFetchMaker(undefined)
      },
      'only': policyOnly
    },

    'ATTRIBUTETYPES': undefined,
    'LOADERTYPES': undefined,
    'URIEFFECTS': undefined
  };

  var caja = {
    // Normal entry points
    'initialize': initialize,
    'load': load,
    'whenReady': whenReady,

    // URI policies
    'policy': uriPolicies,

    // Reference to the taming frame in the default frameGroup
    'iframe': null,

    // Reference to the USELESS object for function invocation (for testing)
    'USELESS': undefined,

    // Taming functions for the default frameGroup
    'tame': premature,
    'tamesTo': premature,
    'reTamesTo': premature,
    'untame': premature,
    'unwrapDom': premature,
    'markReadOnlyRecord': premature,
    'markFunction': premature,
    'markCtor': premature,
    'markXo4a': premature,
    'grantMethod': premature,
    'grantRead': premature,
    'grantReadWrite': premature,
    'adviseFunctionBefore': premature,
    'adviseFunctionAfter': premature,
    'adviseFunctionAround': premature,
    'makeDefensibleObject___': premature,
    'makeDefensibleFunction___': premature,

    // Esoteric functions
    'initFeralFrame': initFeralFrame,
    'makeFrameGroup': makeFrameGroup,
    'configure': makeFrameGroup,
    'disableSecurityForDebugger': disableSecurityForDebugger,
    'Q': premature,

    // Used by related tools; not for users to call on a routine basis
    // Initialized to helper functions because they may be called by external
    // clients before caja.initialize() is called.
    'console': {
      'error': makeLogMethod('error'),
      'info': makeLogMethod('info'),
      'log': makeLogMethod('log'),
      'warn': makeLogMethod('warn')
    },

    // unused, removed by Closure
    closureCanary: 1
  };

  // Internal functions made available to FrameGroup maker
  var cajaInt = {
    'documentBaseUrl': documentBaseUrl,
    'getId': getId,
    'getImports': getImports,
    'joinUrl': joinUrl,
    'loadCajaFrame': loadCajaFrame,
    'prepareContainerDiv': prepareContainerDiv,
    'unregister': unregister,
    'readPropertyAsHostFrame': readPropertyAsHostFrame
  };

  //----------------

  function makeLogMethod(m) {
    return function() {
      globalConfig &&
        globalConfig.console[m].apply(globalConfig.console, arguments);
    };
  }

  function premature() {
    throw new Error('Calling taming function before Caja is ready');
  }

  function disableSecurityForDebugger(value) {
    unsafe = !!value;
    if (defaultFrameGroup) {
      defaultFrameGroup['disableSecurityForDebugger'](value);
    }
  }

  /**
   * Returns a URI policy that allows one URI and denies the rest.
   */
  function policyOnly(allowedUri) {
    allowedUri = String(allowedUri);
    return {
      'rewrite': function (uri) {
        uri = String(uri);
        return uri === allowedUri ? uri : null;
      }
    };
  }

  /**
   * Creates the default frameGroup with the given config.
   * See {@code makeFrameGroup} for config parameters.
   */
  function initialize(config /*, opt_onSuccess, opt_onFailure */) {
    if (state !== UNREADY) {
      throw new Error('Caja cannot be initialized more than once');
    }
    var onSuccess = arguments[1];
    var onFailure = arguments[2];
    state = PENDING;
    makeFrameGroup(config, function (frameGroup) {
      defaultFrameGroup = frameGroup;
      caja['iframe'] = frameGroup['iframe'];
      caja['USELESS'] = frameGroup['USELESS'];
      for (var i in caja) {
        if (caja[i] === premature) {
          caja[i] = frameGroup[i];
        }
      }
      frameGroup['disableSecurityForDebugger'](unsafe);
      state = READY;
      var detail = {};
      detail['es5Mode'] = true;  // legacy API -- non-ES5 mode is dead
      if ("function" === typeof onSuccess) {
        onSuccess(detail);
      }
      whenReady(null);
    }, function(err) {
      state = UNREADY;
      onFailure(err);
    });
  }

  /**
   * Creates a guest frame in the default frameGroup.
   */
  function load(div, uriPolicy, loadDone, domOpts) {
    uriPolicy = uriPolicy || caja['policy']['net']['NO_NETWORK'];
    if (state === UNREADY) {
      initialize({});
    }
    whenReady(function () {
      defaultFrameGroup['makeES5Frame'](div, uriPolicy, loadDone, domOpts);
    });
  }

  /**
   * Defers func until the default frameGroup is ready.
   */
  function whenReady(opt_func) {
    if (typeof opt_func === 'function') {
      readyQueue.push(opt_func);
    }
    if (state === READY) {
      for (var i = 0; i < readyQueue.length; i++) {
        setTimeout(readyQueue[i], 0);
      }
      readyQueue = [];
    }
  }

  /**
   * Create a Caja frame group. A frame group maintains a relationship with a
   * Caja server and some configuration parameters. Most Web pages will only
   * need to create one frame group.
   *
   * Recognized configuration parameters are:
   *
   *     server - the URL to a Caja server. Except for unique cases,
   *         this must be the server from which the "caja.js" script was
   *         sourced.
   *
   *     resources - the URL to a directory containing the resource files.
   *         If not specified, it defaults to the value of 'server'.
   *
   *     debug - whether debugging is supported. At the moment, debug support
   *         means that the files loaded by Caja are un-minified to help with
   *         tracking down problems.
   *
   *     es5Mode - Legacy option; must be true if specified.
   *
   *     maxAcceptableSeverity - Severity of browser bugs greater than
   *         this level cause failure.
   *
   *     forceES5Mode - Legacy option; must be true if specified.
   *
   *     console - Optional user-supplied alternative to the browser's native
   *         'console' object.
   *
   *     targetAttributePresets - Optional structure giving default and
   *         whitelist for the 'target' parameter of anchors and forms.
   *
   *     log - Optional user-supplied alternative to the browser's native
   *         'console.log' function.
   *
   *     flashbridge - Optional, location of flashbridge.swf.  This needs
   *         to be on the same domain as the host page.
   *
   * @param config an object literal containing configuration parameters.
   * @param frameGroupReady function to be called back with a reference to
   *     the newly created frame group.
   */
  function makeFrameGroup(config, frameGroupReady, onFailure) {
    initFeralFrame(window);
    globalConfig = config = resolveConfig(config);
    caja['server'] = config['server'];
    trySES(config, frameGroupReady, onFailure);
  }

  /**
   * Returns a full config based on the given partial config.
   */
  function resolveConfig(partial) {
    partial = partial || {};
    var full = {};
    full['server'] = String(
      partial['server'] || partial['cajaServer'] || defaultServer);
    full['resources'] = String(partial['resources'] || full['server']);
    full['debug'] = !!partial['debug'];
    // es5Mode and forceES5Mode are legacy
    if ('forceES5Mode' in partial && partial['forceES5Mode'] !== true
        && partial['forceES5Mode'] !== undefined) {
      throw new Error('forceES5Mode: false is no longer supported');
    }
    if ('es5Mode' in partial && partial['es5Mode'] !== true
        && partial['es5Mode'] !== undefined) {
      throw new Error('es5Mode: false is no longer supported');
    }
    var severity = String(partial['maxAcceptableSeverity'] ||
        'SAFE_SPEC_VIOLATION');
    if (severity === 'NO_KNOWN_EXPLOIT_SPEC_VIOLATION') {
      // Special severity level which SES itself no longer implements
      // TODO(kpreid): Should acceptNoKnownExploitProblems be part of our
      // public interface?
      severity = 'SAFE_SPEC_VIOLATION';
      full['acceptNoKnownExploitProblems'] = true;
    }
    full['maxAcceptableSeverity'] = severity;

    if (partial['console']) {
      // Client supplies full 'console' object, which we use
      full['console'] = partial['console'];
    } else if (partial['log']) {
      // Deprecated API: Client supplies 'log' function, from which we
      // build a 'console' object of sorts
      full['console'] = {
        'log': partial['log'],
        'warn': partial['log'],
        'error': partial['log'],
        'info': partial['log']
      };
    } else if (window['console']
        && typeof(window['console']['log']) === 'function') {
      // Platform supplies console object, which we use
      full['console'] = window['console'];
    } else {
      // Cannot find any logging functions; create no-op stubs
      full['console'] = {
        'log': function() {},
        'warn': function() {},
        'error': function() {},
        'info': function() {}
      };
    }

    if (partial['targetAttributePresets']) {
      if (!partial['targetAttributePresets']['default']) {
        throw 'targetAttributePresets must contain a default';
      }
      if (!partial['targetAttributePresets']['whitelist']) {
        throw 'targetAttributePresets must contain a whitelist';
      }
      if (partial['targetAttributePresets']['whitelist']['length'] === 0) {
        throw 'targetAttributePresets.whitelist array must be nonempty';
      }
      full['targetAttributePresets'] = partial['targetAttributePresets'];
    }
    if (typeof(partial['cajolingServiceClient']) === 'object'){
      full['cajolingServiceClient'] = partial['cajolingServiceClient'];
    }
    return full;
  }

  function initFeralFrame(feralWin) {
    if (feralWin['Object']['FERAL_FRAME_OBJECT___'] === feralWin['Object']) {
      return;
    }
    feralWin['___'] = {};
    feralWin['Object']['FERAL_FRAME_OBJECT___'] = feralWin['Object'];
  }

  //----------------

  function trySES(config, frameGroupReady, onFailure) {
    function frameInit(frameWin) {
      var ses = frameWin['ses'] || (frameWin['ses'] = {});
      ses['maxAcceptableSeverityName'] = config['maxAcceptableSeverity'];
      if (config['acceptNoKnownExploitProblems']) {
        ses['acceptableProblems'] = {
          'DEFINING_READ_ONLY_PROTO_FAILS_SILENTLY': { 'permit': true },

          // we don't use partly-unmodifiable arrays, and the repair for push
          // is too slow to use unless necessary (i.e. PUSH_IGNORES_FROZEN)
          'PUSH_IGNORES_SEALED': { 'permit': true, 'doNotRepair': true },
          'UNSHIFT_IGNORES_SEALED': { 'permit': true },
          'SPLICE_IGNORES_SEALED': { 'permit': true },
          'SHIFT_IGNORES_SEALED': { 'permit': true },
          'PUSH_DOES_NOT_THROW_ON_FROZEN_ARRAY':
              { 'permit': true, 'doNotRepair': true },
          'ARRAYS_DELETE_NONCONFIGURABLE': { 'permit': true },
          'ARRAYS_MODIFY_READONLY': { 'permit': true },

          // safe given that we use exactly one SES frame
          'FREEZE_IS_FRAME_DEPENDENT': { 'permit': true },
          'SYNTAX_ERRORS_ARENT_ALWAYS_EARLY': { 'permit': true },

          // Only affects code with strict nested function defs, which
          // violates the ES5.1 recommendation stated at
          // http://wiki.ecmascript.org/doku.php?id=conventions:recommendations_for_implementors.
          // Thus, the NESTED_STRICT_FUNCTIONS_LEAK
          // doesn't affect SES as long as SES remains
          // compatible with ES5 implementations that follow that
          // recommendation.
          'NESTED_STRICT_FUNCTIONS_LEAK': { 'permit': true }
        };
      }
      ses['mitigateSrcGotchas'] = function() {
        throw new EvalError('This function is a placeholder that should ' +
                            'have been replaced by the real ' +
                            'ses.mitigateSrcGotchas.');
      };
    }

    var sesMaker = makeFrameMaker(config, 'ses-single-frame', frameInit);

    loadCajaFrame(config, 'utility-frame', function (mitigateWin) {
      var mitigateSrcGotchas = mitigateWin['ses']['mitigateSrcGotchas'];
      sesMaker['make'](function (tamingWin) {
        if (tamingWin['ses']['ok']()) {
          var fg = tamingWin['SESFrameGroup'](
              cajaInt, config, tamingWin, window,
              { 'mitigateSrcGotchas': mitigateSrcGotchas });
          frameGroupReady(fg);
        } else {
          var err = new Error('Caja: Browser is unsupported');
          if ("function" === typeof onFailure) {
            onFailure(err);
          } else {
            throw err;
          }
        }
      });
    });
  }

  //----------------

  /**
   * Returns an object that wraps loadCajaFrame() with preload support.
   * Calling frameMaker.preload() will start creation of a new frame now,
   * and make it available to a later call to frameMaker.make().
   */
  // TODO(kpreid): With the death of ES5/3 we no longer ever create multiple
  // frames of a kind. However, this is still used to effectively load
  // ses-frame and utility-frame in parallel. Simplify.
  function makeFrameMaker(config, filename, opt_frameCreated) {
    var IDLE = 'IDLE', LOADING = 'LOADING', WAITING = 'WAITING';
    var preState = IDLE, preWin, preReady;
    var self = {
      'preload': function () {
        if (preState === IDLE) {
          preState = LOADING;
          preWin = null;
          loadCajaFrame(config, filename, function (win) {
            preWin = win;
            consumeIfReady();
          }, opt_frameCreated);
        }
      },
      'make': function (onReady) {
        if (preState === LOADING) {
          preState = WAITING;
          preReady = onReady;
          consumeIfReady();
        } else {
          loadCajaFrame(config, filename, onReady, opt_frameCreated);
        }
      }
    };
    self['preload']();
    return self;

    function consumeIfReady() {
      if (preState === WAITING && preWin) {
        var win = preWin, ready = preReady;
        preState = IDLE;
        preWin = null;
        preReady = null;
        ready(win);
      }
    }
  }

  //----------------

  function loadCajaFrame(config, filename, frameReady, opt_frameCreated) {
    var frameWin = createFrame(filename);
    // debuggable or minified.  ?debug=1 inhibits compilation in shindig
    var suffix = config['debug'] ? '.js?debug=1' : '.opt.js?debug=1';
    var url = joinUrl(
      config['resources'],
      cajaBuildVersion + '/' + filename + suffix);
    // The particular interleaving of async events shown below has been found
    // necessary to get the right behavior on Firefox 3.6. Otherwise, the
    // iframe silently fails to invoke the cajaIframeDone___ callback.
    setTimeout(function () {
      frameWin['cajaIframeDone___'] = function () {
        versionCheck(config, frameWin, filename);
        frameReady(frameWin);
      };
      if (opt_frameCreated) { opt_frameCreated(frameWin); }
      // TODO(jasvir): Test what the latency doing this on all browsers is
      // and why its necessary
      setTimeout(function () {
        installAsyncScript(frameWin, url);
      }, 0);
    }, 0);
  }

  // Throws an error if frameWin has the wrong Caja version
  function versionCheck(config, frameWin, filename) {
    if (cajaBuildVersion !== frameWin['cajaBuildVersion']) {
      var message = 'Version error: caja.js version ' + cajaBuildVersion +
        ' does not match ' + filename + ' version ' +
        frameWin['cajaBuildVersion'] + '.';

      var majorCajaVersion = String(cajaBuildVersion).split(/[mM]/)[0];
      var majorWinVersion =
        String(frameWin['cajaBuildVersion']).split(/[mM]/)[0];
      if (majorCajaVersion === majorWinVersion) {
        message += '  Continuing because major versions match.';
        config['console']['log'](message);
      } else {
        config['console']['log'](message);
        throw new Error(message);
      }
    }
  }

  /**
   * opt_container may be absent, an element, or a Document. If absent
   * then no DOM or related APIs are given to the guest.
   */
  function prepareContainerDiv(opt_container, feralWin, domOpts) {
    domOpts = domOpts || {};
    var opt_idClass = domOpts ? domOpts['idClass'] : void 0;
    var idClass = opt_idClass || ('caja-guest-' + nextId++ + '___');
    if (opt_container && opt_container.nodeType === 9 /* Document */) {
      caja['console']['warn']('Warning: Using a document, rather than an ' +
          'element, as a Caja virtual document container is an experimental ' +
          'feature and may not operate correctly or support all features.');
      initFeralFrame(opt_container.defaultView);
    }
    return {
      'idClass': idClass,
      'opt_div': opt_container
    };
  }

  // Creates a new iframe and returns its contentWindow.
  function createFrame(opt_className) {
    var frame = document.createElement('iframe');
    frame.style.display = "none";
    frame.width = 0;
    frame.height = 0;
    frame.className = opt_className || '';
    var where = document.getElementsByTagName('script')[0];
    where.parentNode.insertBefore(frame, where);
    return frame.contentWindow;
  }

  function installAsyncScript(frameWin, scriptUrl) {
    var frameDoc = frameWin['document'];
    var script = frameDoc.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.src = scriptUrl;
    frameDoc.body.appendChild(script);
  }

  // TODO(jasvir): This should pulled into a utility js file
  function escapeAttr(s) {
    var ampRe = /&/g;
    var ltRe = /[<]/g;
    var gtRe = />/g;
    var quotRe = /\"/g;
    return ('' + s).replace(ampRe, '&')
      .replace(ltRe, '<')
      .replace(gtRe, '>')
      .replace(quotRe, '"');
  }

  function installSyncScript(name, url) {
     if (!loaderDocument) {
       loaderDocument = createFrame('loader-frame').document;
     }
     // TODO(jasvir): This assignment pins the parent's handler
     // function and, iiuc, this reference is never cleared out.
     var result = ''
       + ('<script>var $name = parent.window["$name"];<\/script>'
           .replace(/[$]name/g, name))
       + ('<script type="text/javascript" src="$url"><\/script>'
           .replace(/[$]url/g, escapeAttr(url)));
     loaderDocument.write(result);
   }

  function joinUrl(base, path) {
    base = base.replace(/\/+$/, '');
    path = path.replace(/^\/+/, '');
    return base + '/' + path;
  }

  function documentBaseUrl() {
    // TODO(kpreid): Why aren't we using document.baseURI?
    var bases = document.getElementsByTagName('base');
    if (bases.length == 0) {
      return document.location.toString();
    } else if (bases.length == 1) {
      var href = bases[0].href;
      if (typeof href !== 'string') {
        throw new Error('Caja loader error: <base> without a href.');
      }
      return href;
    } else {
      throw new Error('Caja loader error: document contains multiple <base>.');
    }
  }

  //----------------

  /**
   * Enforces {@code typeof specimen === typename}, in which case
   * specimen is returned.
   * <p>
   * If not, throws an informative TypeError
   * <p>
   * opt_name, if provided, should be a name or description of the
   * specimen used only to generate friendlier error messages.
   */
  function enforceType(specimen, typename, opt_name) {
    if (typeof specimen !== typename) {
      throw new TypeError('expected ' + typename + ' instead of ' +
          typeof specimen + ': ' + (opt_name || specimen));
    }
    return specimen;
  }

  /**
   * Read the given property of the given object. Exists only to work
   * around browser bugs where the answer depends on who's asking the
   * question.
   */
  function readPropertyAsHostFrame(object, property) {
    return object[property];
  }

  /**
   * Gets or assigns the id associated with this (assumed to be)
   * imports object, registering it so that
   * <tt>getImports(getId(imports)) === imports</tt>.
   * <p>
   * This system of registration and identification allows us to
   * cajole html such as
   * <pre><a onmouseover="alert(1)">Mouse here</a></pre>
   * into html-writing JavaScript such as<pre>
   * IMPORTS___.document.innerHTML = "
   *  <a onmouseover=\"
   *    (function(IMPORTS___) {
   *      IMPORTS___.alert(1);
   *    })(___.getImports(" + ___.getId(IMPORTS___) + "))
   *  \">Mouse here</a>
   * ";
   * </pre>
   * If this is executed by a plugin whose imports is assigned id 42,
   * it generates html with the same meaning as<pre>
   * <a onmouseover="___.getImports(42).alert(1)">Mouse here</a>
   * </pre>
   * <p>
   * An imports is not registered and no id is assigned to it until the
   * first call to <tt>getId</tt>. This way, an imports that is never
   * registered, or that has been <tt>unregister</tt>ed since the last
   * time it was registered, will still be garbage collectable.
   */
  // TODO(kpreid): I think this is dead after ES5/3
  function getId(imports) {
    enforceType(imports, 'object', 'imports');
    var id;
    if ('id___' in imports) {
      id = enforceType(imports['id___'], 'number', 'id');
    } else {
      id = imports['id___'] = registeredImports.length;
    }
    registeredImports[id] = imports;
    return id;
  }

  /**
   * Gets the imports object registered under this id.
   * <p>
   * If it has been <tt>unregistered</tt> since the last
   * <tt>getId</tt> on it, then <tt>getImports</tt> will fail.
   */
  // TODO(kpreid): I think this is dead after ES5/3
  function getImports(id) {
    var result = registeredImports[enforceType(id, 'number', 'id')];
    if (result === void 0) {
      throw new Error('Internal: imports#', id, ' unregistered');
    }
    return result;
  }

  /**
   * If you know that this <tt>imports</tt> no longer needs to be
   * accessed by <tt>getImports</tt>, then you should
   * <tt>unregister</tt> it so it can be garbage collected.
   * <p>
   * After unregister()ing, the id is not reassigned, and the imports
   * remembers its id. If asked for another <tt>getId</tt>, it
   * reregisters itself at its old id.
   */
  // TODO(kpreid): I think this is dead after ES5/3
  function unregister(imports) {
    enforceType(imports, 'object', 'imports');
    if ('id___' in imports) {
      var id = enforceType(imports['id___'], 'number', 'id');
      registeredImports[id] = void 0;
    }
  }

  return caja;
})();

// Exports for closure compiler.
if (typeof window !== 'undefined') {
  window['caja'] = caja;
}


text:
import argparse
parser = argparse.ArgumentParser(prog="single.py", description="Run Starfish fitting model in parallel.")
# Even though these arguments aren't being used, we need to add them.
parser.add_argument("--generate", action="store_true", help="Write out the data, mean model, and residuals for current parameter settings.")
# parser.add_argument("--initPhi", action="store_true", help="Create *phi.json files for each order using values in config.yaml")
parser.add_argument("--optimize", action="store_true", help="Optimize the parameters.")
args = parser.parse_args()

from Starfish import astroseismic_align as AA

if args.optimize:
    AA.optimize()

if args.generate:
    # Save the residuals as a large JSON file, using the known parameters
    AA.generate()


text: ['mobile-api_search-webserver-read-master-vir']


text:
Simple Go statsd client.

Key features:
 - Can do the sampling before building the measurement key, which can save
   Sprintf()s.
 - Fills UDP packets before sending them.

See example_test.go for usage.

Installation:

    `go get github.com/realzeitmedia/g2s2`


text:
package org.dlangplugin.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface DLangTemplateThisParameter extends DLangCompositeElement {

  @NotNull
  DLangTemplateTypeParameter getTemplateTypeParameter();

}


text:
import uuid

from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest.test import attr

CONF = config.CONF

class FloatingIPDetailsNegativeTestJSON(base.BaseV2ComputeTest):
    _interface = 'json'

    @classmethod
    def setUpClass(cls):
        super(FloatingIPDetailsNegativeTestJSON, cls).setUpClass()
        cls.client = cls.floating_ips_client

    @attr(type=['negative', 'gate'])
    def test_get_nonexistent_floating_ip_details(self):
        # Negative test:Should not be able to GET the details
        # of non-existent floating IP
        # Creating a non-existent floatingIP id
        if CONF.service_available.neutron:
            non_exist_id = str(uuid.uuid4())
        else:
            non_exist_id = data_utils.rand_int_id(start=999)
        self.assertRaises(exceptions.NotFound,
                          self.client.get_floating_ip_details, non_exist_id)

class FloatingIPDetailsNegativeTestXML(FloatingIPDetailsNegativeTestJSON):
    _interface = 'xml'


text:
from datetime import timedelta

from django.db import models
from django.db.models import functions

from yawn.utilities import logger

class Worker(models.Model):
    """Information about current and past workers"""
    #
    # NOTE: consider instead taking an advisory lock for each worker,
    # and using it to check if a worker is still connected.
    # See `pg_try_advisory_lock` and `select * from pg_locks where locktype = 'advisory'`
    # That would give more immediate feedback, but its not clear we need to be faster.
    #
    ACTIVE = 'active'
    EXITED = 'exited'
    LOST = 'lost'
    STATUS_CHOICES = [(x, x) for x in (ACTIVE, EXITED, LOST)]

    name = models.TextField(blank=False)
    status = models.TextField(choices=STATUS_CHOICES, default=ACTIVE)
    start_timestamp = models.DateTimeField(default=functions.Now)
    last_heartbeat = models.DateTimeField(default=functions.Now)

    @staticmethod
    def find_lost(timeout):
        from yawn.task.models import Execution

        # Make a sparse index so looking up active workers is fast:
        # CREATE INDEX yawn_worker_active ON yawn_worker (status) WHERE status = 'active'
        lost = Worker.objects.filter(
            status=Worker.ACTIVE, last_heartbeat__lt=functions.Now() - timedelta(seconds=timeout)
        )
        for worker in lost:
            logger.warning('Marking %r as lost', worker)
            worker.status = Worker.LOST
            worker.save()

            executions = worker.execution_set.filter(status=Execution.RUNNING)

            for execution in executions:
                logger.warning('Marking %r as lost', execution)
                execution.mark_finished(lost=True)

    def __str__(self):
        return self.name

class Queue(models.Model):
    """Arbitrary tag defining where tasks run."""

    name = models.TextField(unique=True)

    _default = None

    def __str__(self):
        return self.name

    @classmethod
    def get_default_queue(cls):
        if not cls._default:
            cls._default = Queue.objects.get_or_create(name='default')[0]
        return cls._default

class Message(models.Model):
    """The order of tasks waiting to be processed, like messages on a queue"""

    # I hope we never get to 9 Quintillion (9,223,372,036,854,775,807) messages
    id = models.BigAutoField(primary_key=True)

    queue = models.ForeignKey(Queue, models.PROTECT)
    task = models.ForeignKey('Task', models.PROTECT)


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.							  */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib.  */
/*----------------------------------------------------------------------------*/

#include "Jaguar.h"
//#include "NetworkCommunication/UsageReporting.h"
#include "LiveWindow/LiveWindow.h"

/**
 * Common initialization code called by all constructors.
 */
void Jaguar::InitJaguar()
{
	/**
	 * Input profile defined by Luminary Micro.
	 *
	 * Full reverse ranges from 0.671325ms to 0.6972211ms
	 * Proportional reverse ranges from 0.6972211ms to 1.4482078ms
	 * Neutral ranges from 1.4482078ms to 1.5517922ms
	 * Proportional forward ranges from 1.5517922ms to 2.3027789ms
	 * Full forward ranges from 2.3027789ms to 2.328675ms
	 */
	SetBounds(2.31, 1.55, 1.507, 1.454, .697);
	SetPeriodMultiplier(kPeriodMultiplier_1X);
	SetRaw(m_centerPwm);
	SetZeroLatch();

	HALReport(HALUsageReporting::kResourceType_Jaguar, GetChannel());
	LiveWindow::GetInstance()->AddActuator("Jaguar", GetChannel(), this);
}

/**
 * Constructor for a Jaguar connected via PWM
 * @param channel The PWM channel that the Jaguar is attached to. 0-9 are on-board, 10-19 are on the MXP port
 */
Jaguar::Jaguar(uint32_t channel) : SafePWM(channel)
{
	InitJaguar();
}

Jaguar::~Jaguar()
{
}

/**
 * Set the PWM value.
 *
 * The PWM value is set using a range of -1.0 to 1.0, appropriately
 * scaling the value for the FPGA.
 *
 * @param speed The speed value between -1.0 and 1.0 to set.
 * @param syncGroup Unused interface.
 */
void Jaguar::Set(float speed, uint8_t syncGroup)
{
	SetSpeed(speed);
}

/**
 * Get the recently set value of the PWM.
 *
 * @return The most recently set value for the PWM between -1.0 and 1.0.
 */
float Jaguar::Get()
{
	return GetSpeed();
}

/**
 * Common interface for disabling a motor.
 */
void Jaguar::Disable()
{
	SetRaw(kPwmDisabled);
}

/**
 * Write out the PID value as seen in the PIDOutput base object.
 *
 * @param output Write out the PWM value as was found in the PIDController
 */
void Jaguar::PIDWrite(float output)
{
	Set(output);
}


text:
$data = array( 'message' => 'Hello World!' );

//------------------------------
// The recipient registration IDs
// that will receive the push
// (Should be stored in your DB)
//
// Read about it here:
// http://developer.android.com/google/gcm/
//------------------------------

$ids = array( $_REQUEST['id'] );

//------------------------------
// Call our custom GCM function
//------------------------------

sendGoogleCloudMessage(  $data, $ids );

//------------------------------
// Define custom GCM function
//------------------------------

function sendGoogleCloudMessage( $data, $ids )
{
    //------------------------------
    // Replace with real GCM API
    // key from Google APIs Console
    //
    // https://code.google.com/apis/console/
    //------------------------------

    $apiKey = 'AIzaSyAc2H-sxDnTpjARpA7N1NqAS1qsgI9nLyQ';

    //------------------------------
    // Define URL to GCM endpoint
    //------------------------------

    $url = 'https://android.googleapis.com/gcm/send';

    //------------------------------
    // Set GCM post variables
    // (Device IDs and push payload)
    //------------------------------

    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data,
                    );

    //------------------------------
    // Set CURL request headers
    // (Authentication and type)
    //------------------------------

    $headers = array(
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

    //------------------------------
    // Initialize curl handle
    //------------------------------

    $ch = curl_init();

    //------------------------------
    // Set URL to GCM endpoint
    //------------------------------

    curl_setopt( $ch, CURLOPT_URL, $url );

    //------------------------------
    // Set request method to POST
    //------------------------------

    curl_setopt( $ch, CURLOPT_POST, true );

    //------------------------------
    // Set our custom headers
    //------------------------------

    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

    //------------------------------
    // Get the response back as
    // string instead of printing it
    //------------------------------

    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    //------------------------------
    // Set post data as JSON
    //------------------------------

    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );

    //------------------------------
    // Actually send the push!
    //------------------------------

    $result = curl_exec( $ch );

    //------------------------------
    // Error? Display it!
    //------------------------------

    if ( curl_errno( $ch ) )
    {
        echo 'GCM error: ' . curl_error( $ch );
    }

    //------------------------------
    // Close curl handle
    //------------------------------

    curl_close( $ch );

    //------------------------------
    // Debug GCM response
    //------------------------------

    echo $result;
}


text:
//=============================================================================================================

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "projectorsview.h"

#include <fiff/fiff_proj.h>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QCheckBox>
#include <QGridLayout>
#include <QFrame>
#include <QSettings>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace DISPLIB;
using namespace FIFFLIB;

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

ProjectorsView::ProjectorsView(const QString& sSettingsPath,
                               QWidget *parent,
                               Qt::WindowFlags f)
: AbstractView(parent, f)
, m_pEnableDisableProjectors(Q_NULLPTR)
{
    m_sSettingsPath = sSettingsPath;
    this->setWindowTitle("Projectors");
    this->setMinimumWidth(330);
    this->setMaximumWidth(330);

    loadSettings();
    redrawGUI();
}

//=============================================================================================================

ProjectorsView::~ProjectorsView()
{
    saveSettings();
}

//=============================================================================================================

QList<FIFFLIB::FiffProj> ProjectorsView::getProjectors() const
{
    return m_pProjs;
}

//=============================================================================================================

void ProjectorsView::setProjectors(const QList<FIFFLIB::FiffProj>& projs)
{
    m_pProjs = projs;

    for(int i = 0; i < m_pProjs.size(); ++i) {
        if(!m_mapProjActive.contains(m_pProjs.at(i).desc)) {
            m_mapProjActive.insert(m_pProjs.at(i).desc, m_pProjs.at(i).active);
        } else {
            m_pProjs[i].active = m_mapProjActive[m_pProjs.at(i).desc];
        }
    }

    redrawGUI();
}

//=============================================================================================================

void ProjectorsView::redrawGUI()
{
    if(m_pProjs.isEmpty()) {
        return;
    }

    m_qListProjCheckBox.clear();

    // Projection Selection
    QGridLayout *topLayout = new QGridLayout;

    bool bAllActivated = true;

    qint32 i = 0;

    for(i; i < m_pProjs.size(); ++i) {
        QCheckBox* checkBox = new QCheckBox(m_pProjs.at(i).desc);

        if(m_pProjs.at(i).active == false) {
            bAllActivated = false;
        }

        m_qListProjCheckBox.append(checkBox);

        connect(checkBox, &QCheckBox::toggled,
                this, &ProjectorsView::onCheckProjStatusChanged);

        checkBox->setChecked(m_pProjs.at(i).active);

        topLayout->addWidget(checkBox, i, 0);
    }

    QFrame* line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);

    topLayout->addWidget(line, i+1, 0);

    m_pEnableDisableProjectors = new QCheckBox("Enable all");
    m_pEnableDisableProjectors->setChecked(bAllActivated);
    topLayout->addWidget(m_pEnableDisableProjectors, i+2, 0);
    connect(m_pEnableDisableProjectors, static_cast<void (QCheckBox::*)(bool)>(&QCheckBox::clicked),
        this, &ProjectorsView::onEnableDisableAllProj);

    this->setLayout(topLayout);

    onCheckProjStatusChanged();
}

//=============================================================================================================

void ProjectorsView::saveSettings()
{
    if(m_sSettingsPath.isEmpty()) {
        return;
    }

    QSettings settings("MNECPP");

    settings.beginGroup(m_sSettingsPath + QString("/ProjectorsView/projectorsActive"));

    QMap<QString,bool>::const_iterator iProj = m_mapProjActive.constBegin();
    while (iProj != m_mapProjActive.constEnd()) {
         settings.setValue(iProj.key(), iProj.value());
         ++iProj;
    }

    settings.endGroup();
}

//=============================================================================================================

void ProjectorsView::loadSettings()
{
    if(m_sSettingsPath.isEmpty()) {
        return;
    }

    QSettings settings("MNECPP");

    settings.beginGroup(m_sSettingsPath + QString("/ProjectorsView/projectorsActive"));

    QStringList keys = settings.childKeys();
    foreach (QString key, keys) {
        m_mapProjActive[key] = settings.value(key).toBool();
    }
    settings.endGroup();
}

//=============================================================================================================

void ProjectorsView::updateGuiMode(GuiMode mode)
{
    switch(mode) {
        case GuiMode::Clinical:
            break;
        default: // default is research mode
            break;
    }
}

//=============================================================================================================

void ProjectorsView::updateProcessingMode(ProcessingMode mode)
{
    switch(mode) {
        case ProcessingMode::Offline:
            break;
        default: // default is realtime mode
            break;
    }
}

//=============================================================================================================

void ProjectorsView::onEnableDisableAllProj(bool status)
{
    //Set all checkboxes to status
    for(int i = 0; i<m_qListProjCheckBox.size(); i++) {
        m_qListProjCheckBox.at(i)->setChecked(status);
    }

    //Set all projection activation states to status
    for(int i = 0; i < m_pProjs.size(); ++i) {
        m_pProjs[i].active = status;
        m_mapProjActive[m_pProjs.at(i).desc] = status;

    }

    if(m_pEnableDisableProjectors) {
        m_pEnableDisableProjectors->setChecked(status);
    }

    emit projSelectionChanged(m_pProjs);

    saveSettings();
}

//=============================================================================================================

void ProjectorsView::onCheckProjStatusChanged()
{
    bool bAllActivated = true;

    for(qint32 i = 0; i < m_qListProjCheckBox.size(); ++i) {
        if(m_qListProjCheckBox.at(i)->isChecked() == false) {
            bAllActivated = false;
        }

        m_pProjs[i].active = m_qListProjCheckBox.at(i)->isChecked();
        m_mapProjActive[m_pProjs.at(i).desc] = m_qListProjCheckBox.at(i)->isChecked();
    }

    if(m_pEnableDisableProjectors) {
        m_pEnableDisableProjectors->setChecked(bAllActivated);
    }

    emit projSelectionChanged(m_pProjs);

    saveSettings();
}


text:
package cn.wayne.mamypoko.mode.noeat;

import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.wayne.mamypoko.R;
import cn.wayne.mamypoko.base.BaseChildActivity;
import cn.wayne.mamypoko.net.MamyClient;
import cn.wayne.mamypoko.ui.EmptyView;
import cn.wayne.mamypoko.ui.NoScrollListView;

public class NoeatDetailActivity extends BaseChildActivity {
    public static final String FOOD_ID = "id";
    public static final String FOOD_NAME = "name";
    private EmptyView mEmptyView;
    private NoScrollListView mListView;
    private NoeatDetailAdapter mAdapter;
    private SimpleDraweeView mDraweeView;
    private String mFoodId;
    private String mFoodName;
    private List<NoeatDetailModel.DetailImage.DataEntity> mData;

    @Override
    protected int setContentViewID() {
        return R.layout.activity_noeat_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        mEmptyView = getView(R.id.empty_view);
        mListView = getView(android.R.id.list);
        mDraweeView = getView(R.id.draweee_image);
        mEmptyView.setErrorType(EmptyView.NETWORK_LOADING_ANIM);
    }

    @Override
    protected void initEvent() {
        mEmptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyView.setErrorType(EmptyView.NETWORK_LOADING_ANIM);
                reqeustData();
            }
        });
    }

    @Override
    protected void initData() {
        mData = new ArrayList<>();
        mAdapter = new NoeatDetailAdapter(this,mData);
        mListView.setAdapter(mAdapter);
        mFoodId = getIntent().getStringExtra(FOOD_ID);
        mFoodName = getIntent().getStringExtra(FOOD_NAME);
        setPageTitle(mFoodName);
        reqeustData();
    }

    private void reqeustData() {
        //http://www.qubaobei.com/ios/cf/eat_view2.php?id=2&o_user_id=4325690
        RequestParams params = new RequestParams();
        params.put("id",mFoodId);
        params.put("o_user_id","4325690");
        MamyClient.get("ios/cf/eat_view2.php?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Gson gson = new Gson();
                JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(responseBody)));
                Type type = new TypeToken<NoeatDetailModel>() {
                }.getType();
                NoeatDetailModel model = gson.fromJson(reader, type);
                mDraweeView.setImageURI(Uri.parse(model.getData().getImg()));
                List<NoeatDetailModel.DetailImage.DataEntity> mList = model.getData().getData();
                mData.addAll(mList);
                mAdapter.notifyDataSetChanged();
                mEmptyView.setErrorType(EmptyView.HIDE_LAYOUT);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                mEmptyView.setErrorType(EmptyView.NETWORK_ERROR);
            }
        });
    }

    @Override
    protected boolean isRightShow() {
        return false;
    }

    @Override
    protected boolean isMoreShow() {
        return false;
    }

    @Override
    protected int setRightBtnIcon() {
        return 0;
    }

    @Override
    protected String setPageTitle() {
        return "";
    }
}


text:
using Google.Cloud.Dlp.V2;
using System;
using Xunit;

namespace GoogleCloudSamples
{
    public class InspectTemplateDeleteTests : IClassFixture<DlpTestFixture>
    {
        private DlpTestFixture Fixture { get; }
        public InspectTemplateDeleteTests(DlpTestFixture fixture)
        {
            Fixture = fixture;
        }

        [Fact]
        public void TestInspectTemplateDelete()
        {
            // Creation
            var name = $"my-inspect-template-{TestUtil.RandomName()}";
            var displayName = $"My display name {Guid.NewGuid()}";
            var description = $"My description {Guid.NewGuid()}";
            var fullName = $"projects/{Fixture.ProjectId}/inspectTemplates/{name}";

            var template = InspectTemplateCreate.Create(Fixture.ProjectId, name, displayName, description, Likelihood.Possible, 5, true);
            InspectTemplateDelete.Delete(Fixture.ProjectId, template.Name);

            var list = InspectTemplateList.List(Fixture.ProjectId);
            Assert.DoesNotContain(list, t => t.Name == fullName);
        }
    }
}


text: angular.module('todoList', ['listController', 'taskService'])


text:
#include "pagespeed/opt/ads/ads_attribute.h"

#include "pagespeed/kernel/base/string_util.h"

namespace net_instaweb {
namespace ads_attribute {

// Names of attributes used in adsbygoogle snippets.
const char kDataAdClient[] = "data-ad-client";
const char kDataAdChannel[] = "data-ad-channel";
const char kDataAdSlot[] = "data-ad-slot";
const char kDataAdFormat[] = "data-ad-format";

// Names of attributes used in showads snippets.
const char kGoogleAdClient[] = "google_ad_client";
const char kGoogleAdChannel[] = "google_ad_channel";
const char kGoogleAdSlot[] = "google_ad_slot";
const char kGoogleAdFormat[] = "google_ad_format";
const char kGoogleAdWidth[] = "google_ad_width";
const char kGoogleAdHeight[] = "google_ad_height";
const char kGoogleAdOutput[] = "google_ad_output";

GoogleString LookupAdsByGoogleAttributeName(
    StringPiece show_ads_attribute_name) {
  StringPieceVector items;
  SplitStringPieceToVector(show_ads_attribute_name, "_", &items,
                           false); /* don't omit empty */
  // TODO(chenyu): check if 'show_ads_attribute_name' is valid.
  if (items.size() < 2 || items.at(0) != "google") {
    return "";
  }

  GoogleString result = "data";
  for (int i = 1, n = items.size(); i < n; ++i) {
    StrAppend(&result, "-", items.at(i));
  }
  return result;
}

}  // namespace ads_attribute
}  // namespace net_instaweb


text:
package com.sciencelk.services;

import com.sciencelk.dataaccess.exceptions.ItemNotFoundException;
import com.sciencelk.dto.CategoryDetails;

import java.util.List;

/**
 * *
 * Created by SasithaG on 7/12/2015.
 */
public interface CategoryServiceInterface {

    List<CategoryDetails> getAllCategories() throws ItemNotFoundException;

    CategoryDetails getCategoryById(int id) throws ItemNotFoundException;
}


text:
Write a program that will take a decimal number, and convert it to the appropriate sequence of events for a secret handshake.

> There are 10 types of people in the world: Those who understand
> binary, and those who don't.

You and your fellow cohort of those in the "know" when it comes to
binary decide to come up with a secret "handshake".

```
1 = wink
10 = double blink
100 = close your eyes
1000 = jump

10000 = Reverse the order of the operations in the secret handshake.
```

```
handshake = SecretHandshake.new 9
handshake.commands # => ["wink","jump"]

handshake = SecretHandshake.new "11001"
handshake.commands # => ["jump","wink"]
```

The program should consider strings specifying an invalid binary as the
value 0.

## Source

Bert, in Mary Poppins [view source](http://www.imdb.com/character/ch0011238/quotes)


text:
<?php

namespace MusicBrainz\Value\Property;

use MusicBrainz\Helper\ArrayAccess;
use MusicBrainz\Value\Resource;

/**
 * Provides a getter for the resource.
 */
trait ResourceTrait
{
    /**
     * The resource
     *
     * @var Resource
     */
    private Resource $resource;

    /**
     * Returns the resource.
     *
     * @return Resource
     */
    public function getResource(): Resource
    {
        return $this->resource;
    }

    /**
     * Sets the recource by extracting it from a given input array.
     *
     * @param array  $input An array returned by the webservice
     *
     * @return void
     */
    private function setResourceFromArray(array $input): void
    {
        $this->resource = is_null($resource = ArrayAccess::getString($input, 'resource'))
            ? new Resource()
            : new Resource($resource);
    }
}