text:
// Copyright (c) 2014, 2015 Adobe Systems Incorporated. All rights reserved.
//
// 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.

/*jslint node: true, nomen: true, vars:true, white:true */

(function () {
    "use strict";

    // node app -f plugins/my-plugin
    // where app is the path to app in generator-core, and plugins/my-plugin is the path to your plugin's folder

    var _G,// Generator
        Q = require("q");

    function stringify(object) {
        try {
            return JSON.stringify(object, null, "    ");
        } catch (e) {
            console.error(e);
        }
        return String(object);
    }

    function printDebug(doc) {
        var psd = stringify(doc);

        _G.evaluateJSXFile(__dirname+'/jsx/copy.jsx', { clipboard: psd });
    }

    function error(err) {
        console.error('[svgOMG] Error: ', err);
    }

    var MENU_GENERATOR_DOM = 'GENERATOR-DOM',
        MENU_GENERATOR_SUBDOM = 'GENERATOR-SUBDOM',
        generatorPlus = require("./generatorPlus.js"),
        docInfoFlags = {
            compInfo:             true,
            imageInfo:            true,
            layerInfo:            true,
            expandSmartObjects:   false,
            getTextStyles:        true,
            getFullTextStyles:    true,
            getCompLayerSettings: true,
            selectedLayers:       false,
            getDefaultLayerFX:    true,
            getPathData:          true
        },
        _docInfoCache = {},
        isListeningToGenerator = false;

    function findLayerIdForIndex (layers, index) {
        var i,
            ret;
        for (i = 0; i < layers.length; i++) {
            if (layers[i].index === index) {
                return layers[i].id;
            }
            if (layers[i].layers && layers[i].layers.length > 0) {
                ret = findLayerIdForIndex(layers[i].layers, index);
                if (isFinite(ret)) {
                    return ret;
                }
            }
        }
    }

    function onGeneratorDOMMenuClick(event) {
        if (event.generatorMenuChanged.name === MENU_GENERATOR_DOM ||
            event.generatorMenuChanged.name === MENU_GENERATOR_SUBDOM) {

            _G.evaluateJSXFile(__dirname+"/jsx/changeColorMode.jsx", {}).then(function (origMode) {
                if (typeof origMode === "string") {
                    origMode = JSON.parse(origMode);
                }
                _G.getDocumentInfo(null, docInfoFlags).then(
                    function (gDoc) {
                        var doc = JSON.parse(JSON.stringify(gDoc)),
                            subTree = false,
                            layerId;

                        if (event.generatorMenuChanged.name === MENU_GENERATOR_SUBDOM && doc.selection.length > 0) {
                            //get the selected layer's id and use it to get the sub-tree
                            subTree = true;
                            layerId = findLayerIdForIndex (doc.layers, doc.selection[0]);

                            console.log("***** LayerId: " + layerId + " from " + doc.selection[0]);
                        }

                        generatorPlus.patchGenerator(doc, _G, undefined, undefined, subTree, layerId, 1.0).then(function () {
                            printDebug(doc);
                        });
                    },
                    error);
                _G.evaluateJSXFile(__dirname+"/jsx/changeColorMode.jsx", { colorMode: origMode.colorMode });
            });
        }
    }

    function init(generator) {
        _G = generator;

        //TBD: only do this when debug is enabled in config

        _G.addMenuItem(MENU_GENERATOR_DOM, "Copy svgOM", true, false);
        _G.addMenuItem(MENU_GENERATOR_SUBDOM, "Copy svgOM for layer", true, false);
        _G.onPhotoshopEvent("generatorMenuChanged", onGeneratorDOMMenuClick);
    }

    function invalidateDocInfoCache() {
        _docInfoCache = {};
    }

    function getCachedDocInfo(generator, docId) {
        if (!isListeningToGenerator) {
            isListeningToGenerator = true;
            generator.onPhotoshopEvent("imageChanged", invalidateDocInfoCache);
            generator.onPhotoshopEvent("generatorMenuChanged", invalidateDocInfoCache);
        }

        _docInfoCache[docId] = _docInfoCache[docId] || {};

        var cacheInfo = _docInfoCache[docId],
            docInfoDeferred = Q.defer();

        if (cacheInfo._lastDocInfo) {
            return Q.resolve(cacheInfo._lastDocInfo);
        } else {
            if (cacheInfo._lastDocInfoPromise) {
                return cacheInfo._lastDocInfoPromise;
            } else {
                cacheInfo._lastDocInfoPromise = docInfoDeferred.promise;

                generator.evaluateJSXFile(__dirname + "/jsx/normalizeDoc.jsx", {}).then(function (origMode) {
                    if (typeof origMode === "string") {
                        origMode = JSON.parse(origMode);
                    }
                    generator.getDocumentInfo(docId, docInfoFlags).then(function (doc) {
                        cacheInfo._lastDocInfoPromise = undefined;
                        cacheInfo._lastDocInfo = doc;
                        docInfoDeferred.resolve(doc);
                    }, function (err) {
                        docInfoDeferred.reject(err);
                    }).finally(function () {
                        generator.evaluateJSXFile(__dirname + "/jsx/normalizeDoc.jsx", { historyPos: origMode.historyPos, colorMode: origMode.colorMode });
                    });
                });
                return cacheInfo._lastDocInfoPromise;
            }
        }
    }

    function getGeneratorSVG(generator, params) {
        var deferedResult = Q.defer(),
            OMG = require("./svgOMGenerator.js"),
            svgWriter = require("./svgWriter.js"),
            layerSpec,
            layerScale,
            targetWidth,
            targetHeight,
            docId,
            compId,
            constrainToDocBounds,
            cropRect,
            clipToArtboardBounds,
            artboardBounds,
            isArtboard;

        compId = params.compId;
        layerSpec = params.layerSpec;
        layerScale = params.layerScale;
        targetWidth = params.targetWidth;
        targetHeight = params.targetHeight;
        constrainToDocBounds = params.constrainToDocBounds;
        cropRect = params.cropRect;
        clipToArtboardBounds = params.clipToArtboardBounds;
        artboardBounds = params.artboardBounds;
        docId = params.documentId;
        isArtboard = params.isArtboard;

        generator.evaluateJSXString("app.activeDocument.id").then(function (activeDocId) {
            if (docId !== activeDocId) {
                deferedResult.reject("svgOMG only works on the active document");
            } else {
                getCachedDocInfo(generator, docId).then(
                    function (document) {
                        var doc = JSON.parse(JSON.stringify(document)),
                            cropToSingleLayer = (typeof layerSpec === "number"),
                            svgWriterErrors = [];
                        generatorPlus.patchGenerator(doc, generator, compId, cropToSingleLayer, constrainToDocBounds,
                                                    layerSpec, layerScale, svgWriterErrors).then(function () {
                            if (layerSpec === "all") {
                                layerSpec = null;
                            }
                            var svgOM = OMG.extractSVGOM(doc, { layerSpec: layerSpec }),
                                svgOut = svgWriter.printSVG(svgOM, {
                                    trimToArtBounds: cropToSingleLayer,
                                    preserveAspectRatio: "xMidYMid",
                                    scale: layerScale,
                                    targetWidth: targetWidth,
                                    targetHeight: targetHeight,
                                    constrainToDocBounds: constrainToDocBounds,
                                    cropRect: cropRect,
                                    clipToArtboardBounds: clipToArtboardBounds,
                                    artboardBounds: artboardBounds,
                                    isArtboard: isArtboard
                                }, svgWriterErrors);

                            deferedResult.resolve({
                                svgText: svgOut,
                                errors: svgWriterErrors
                            });
                        });
                    },
                    function (err) {
                        console.warn("error with SVGOMG: " + err);
                        deferedResult.reject(err);
                    });
            }
        });
        return deferedResult.promise;
    }

    module.exports.init = init;
    module.exports.getGeneratorSVG = getGeneratorSVG;

}());


text:
// Agent/ArchiveFolderOpen.cpp

#include "StdAfx.h"

#include "Agent.h"

void CArchiveFolderManager::LoadFormats()
{
  if (!_codecs)
  {
    _compressCodecsInfo = _codecs = new CCodecs;
    _codecs->Load();
  }
}

int CArchiveFolderManager::FindFormat(const UString &type)
{
  FOR_VECTOR (i, _codecs->Formats)
    if (type.IsEqualToNoCase(_codecs->Formats[i].Name))
      return i;
  return -1;
}

STDMETHODIMP CArchiveFolderManager::OpenFolderFile(IInStream *inStream,
    const wchar_t *filePath, const wchar_t *arcFormat,
    IFolderFolder **resultFolder, IProgress *progress)
{
  CMyComPtr<IArchiveOpenCallback> openArchiveCallback;
  if (progress)
  {
    CMyComPtr<IProgress> progressWrapper = progress;
    progressWrapper.QueryInterface(IID_IArchiveOpenCallback, &openArchiveCallback);
  }
  CAgent *agent = new CAgent();
  CMyComPtr<IInFolderArchive> archive = agent;
  RINOK(agent->Open(inStream, filePath, arcFormat, NULL, openArchiveCallback));
  return agent->BindToRootFolder(resultFolder);
}

/*
HRESULT CAgent::FolderReOpen(
    IArchiveOpenCallback *openArchiveCallback)
{
  return ReOpenArchive(_archive, _archiveFilePath);
}
*/

/*
STDMETHODIMP CArchiveFolderManager::GetExtensions(const wchar_t *type, BSTR *extensions)
{
  *extensions = 0;
  int formatIndex = FindFormat(type);
  if (formatIndex <  0)
    return E_INVALIDARG;
  // Exts[0].Ext;
  return StringToBstr(_codecs.Formats[formatIndex].GetAllExtensions(), extensions);
}
*/

static void AddIconExt(const CCodecIcons &lib, UString &dest)
{
  FOR_VECTOR (i, lib.IconPairs)
  {
    if (!dest.IsEmpty())
      dest += L' ';
    dest += lib.IconPairs[i].Ext;
  }
}

STDMETHODIMP CArchiveFolderManager::GetExtensions(BSTR *extensions)
{
  LoadFormats();
  *extensions = 0;
  UString res;
  FOR_VECTOR (i, _codecs->Libs)
    AddIconExt(_codecs->Libs[i], res);
  AddIconExt(_codecs->InternalIcons, res);
  return StringToBstr(res, extensions);
}

STDMETHODIMP CArchiveFolderManager::GetIconPath(const wchar_t *ext, BSTR *iconPath, Int32 *iconIndex)
{
  *iconPath = 0;
  *iconIndex = 0;
#ifdef _WIN32
  LoadFormats();
  FOR_VECTOR (i, _codecs->Libs)
  {
    const CCodecLib &lib = _codecs->Libs[i];
    int ii;
    if (lib.FindIconIndex(ext, ii))
    {
      *iconIndex = ii;
      return StringToBstr(fs2us(lib.Path), iconPath);
    }
  }
  int ii;
  if (_codecs->InternalIcons.FindIconIndex(ext, ii))
  {
    FString path;
    if (NWindows::NDLL::MyGetModuleFileName(path))
    {
      *iconIndex = ii;
      return StringToBstr(fs2us(path), iconPath);
    }
  }
#endif
  return S_OK;
}

/*
STDMETHODIMP CArchiveFolderManager::GetTypes(BSTR *types)
{
  LoadFormats();
  UString typesStrings;
  FOR_VECTOR(i, _codecs.Formats)
  {
    const CArcInfoEx &ai = _codecs.Formats[i];
    if (ai.AssociateExts.Size() == 0)
      continue;
    if (i != 0)
      typesStrings += L' ';
    typesStrings += ai.Name;
  }
  return StringToBstr(typesStrings, types);
}
STDMETHODIMP CArchiveFolderManager::CreateFolderFile(const wchar_t * type,
    const wchar_t * filePath, IProgress progress)
{
  return E_NOTIMPL;
}
*/

redpajama_set_name: RedPajamaGithub


text:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/theme_list"
    android:name="com.cs371mproject.ambientnights.ThemeListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    tools:context=".ThemeListActivity"
    tools:layout="@android:layout/list_content" />


text:
Edit Graph

        <form class="form-horizontal" data-ng-submit="update()" novalidate>
            <fieldset>

                    Graph Name

                        <input type="text" data-ng-model="graph.name" id="name" class="form-control" placeholder="Graph Name..." required>

                    Text

                        <textarea type="text" data-ng-model="graph.text" name="text" id="text" class="form-control" placeholder="Sentences must be line-separated..."  rows="12" required></textarea>

                        Text language:
                        <select data-ng-model="graph.language" class="form-control">
                            <option value="spanish">ES</option>
                            <option value="english">EN</option>
                            <option value="auto">Auto</option>
                        </select>

                        Text Percentage in summary:
                        <input type="number" min="1" max="100" data-ng-model="graph.textPercent" name="textPercent" id="textPercent" class="form-control" placeholder="1-100" required/>

                    <input type="submit" value="Update" class="btn btn-default">

            </fieldset>
        </form>


text:
namespace {

using content::NavigationHandle;
using content::NavigationThrottle;
using content::WebContents;
using password_manager::IsWellKnownChangePasswordUrl;
using password_manager::PasswordChangeSuccessTracker;
using password_manager::WellKnownChangePasswordResult;
using password_manager::WellKnownChangePasswordState;

bool IsTriggeredByGoogleOwnedUI(NavigationHandle* handle) {
  ui::PageTransition page_transition = handle->GetPageTransition();
  // `PAGE_TRANSITION_FROM_API` covers cases where Chrome is opened as a CCT.
  // This happens on Android if Chrome is opened from the Password Check(up) in
  // Chrome settings or the Google Password Manager app.
  if (page_transition & ui::PAGE_TRANSITION_FROM_API)
    return true;

  // In case where the user clicked on a link, we require that the origin is
  // either chrome://settings or https://passwords.google.com.
  if (ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_LINK)) {
    url::Origin origin = handle->GetInitiatorOrigin().value_or(url::Origin());
    return origin == url::Origin::Create(GURL(chrome::kChromeUISettingsURL)) ||
           origin ==
               url::Origin::Create(GURL(chrome::kGooglePasswordManagerURL));
  }

  return false;
}

}  // namespace

// static
std::unique_ptr<WellKnownChangePasswordNavigationThrottle>
WellKnownChangePasswordNavigationThrottle::MaybeCreateThrottleFor(
    NavigationHandle* handle) {
  // Don't handle navigations in subframes or main frames that are in a nested
  // frame tree (e.g. portals, fenced frames)
  if (!handle->GetParentFrameOrOuterDocument() &&
      IsWellKnownChangePasswordUrl(handle->GetURL()) &&
      IsTriggeredByGoogleOwnedUI(handle)) {
    return std::make_unique<WellKnownChangePasswordNavigationThrottle>(handle);
  }

  return nullptr;
}

WellKnownChangePasswordNavigationThrottle::
    WellKnownChangePasswordNavigationThrottle(NavigationHandle* handle)
    : NavigationThrottle(handle),
      request_url_(handle->GetURL()),
      source_id_(handle->GetWebContents()
                     ->GetPrimaryMainFrame()
                     ->GetPageUkmSourceId()) {
  // If this is a prerender navigation, we're only constructing the throttle
  // so it can cancel the prerender.
  if (handle->IsInPrerenderedMainFrame())
    return;

  affiliation_service_ =
      AffiliationServiceFactory::GetForProfile(Profile::FromBrowserContext(
          handle->GetWebContents()->GetBrowserContext()));
  if (affiliation_service_->GetChangePasswordURL(request_url_).is_empty()) {
    well_known_change_password_state_.PrefetchChangePasswordURLs(
        affiliation_service_, {request_url_});
  }
}

WellKnownChangePasswordNavigationThrottle::
    ~WellKnownChangePasswordNavigationThrottle() = default;

NavigationThrottle::ThrottleCheckResult
WellKnownChangePasswordNavigationThrottle::WillStartRequest() {
  // The logic in Redirect will navigate the primary FrameTree if we're in a
  // prerender. We don't have a way to navigate the prerendered page so just
  // cancel the prerender.
  if (navigation_handle()->IsInPrerenderedMainFrame()) {
    return NavigationThrottle::CANCEL;
  }

  auto url_loader_factory = navigation_handle()
                                ->GetWebContents()
                                ->GetBrowserContext()
                                ->GetDefaultStoragePartition()
                                ->GetURLLoaderFactoryForBrowserProcess();
  // In order to avoid bypassing Sec-Fetch-Site headers and extracting user data
  // across redirects, we need to set both the initiator origin and network
  // isolation key when fetching the well-known non-existing resource.
  // See the discussion in blink-dev/UN1BRg4qTbs for more details.
  // TODO(crbug.com/1127520): Confirm that this works correctly within
  // redirects.
  network::ResourceRequest::TrustedParams trusted_params;
  trusted_params.isolation_info = net::IsolationInfo::CreatePartial(
      net::IsolationInfo::RequestType::kOther,
      navigation_handle()->GetIsolationInfo().network_isolation_key());
  well_known_change_password_state_.FetchNonExistingResource(
      url_loader_factory.get(), request_url_,
      navigation_handle()->GetInitiatorOrigin(), std::move(trusted_params));
  return NavigationThrottle::PROCEED;
}

NavigationThrottle::ThrottleCheckResult
WellKnownChangePasswordNavigationThrottle::WillFailRequest() {
  return NavigationThrottle::PROCEED;
}

NavigationThrottle::ThrottleCheckResult
WellKnownChangePasswordNavigationThrottle::WillProcessResponse() {
  // PostTask because the Throttle needs to be deferred before the status code
  // is set. After setting the status code Resume() can be called synchronous
  // and thereby before the throttle is deferred. This would result in a crash.
  base::SequencedTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &WellKnownChangePasswordState::SetChangePasswordResponseCode,
          weak_ptr_factory_.GetWeakPtr(),
          navigation_handle()->GetResponseHeaders()->response_code()));
  return NavigationThrottle::DEFER;
}

const char* WellKnownChangePasswordNavigationThrottle::GetNameForLogging() {
  return "WellKnownChangePasswordNavigationThrottle";
}

void WellKnownChangePasswordNavigationThrottle::OnProcessingFinished(
    bool is_supported) {
  GURL redirect_url = affiliation_service_->GetChangePasswordURL(request_url_);

  // Extend the information of precisely what kind of flow the manual
  // password change flow is.
  raw_ptr<PasswordChangeSuccessTracker> password_change_success_tracker =
      password_manager::PasswordChangeSuccessTrackerFactory::
          GetForBrowserContext(
              navigation_handle()->GetWebContents()->GetBrowserContext());

  // If affiliation service returns .well-known/change-password as change
  // password url - show it even if Chrome doesn't detect it as supported.
  if (is_supported || redirect_url == request_url_) {
    RecordMetric(WellKnownChangePasswordResult::kUsedWellKnownChangePassword);
    password_change_success_tracker->OnChangePasswordFlowModified(
        request_url_,
        PasswordChangeSuccessTracker::StartEvent::kManualWellKnownUrlFlow);
    Resume();
    return;
  }

  if (redirect_url.is_valid()) {
    RecordMetric(WellKnownChangePasswordResult::kFallbackToOverrideUrl);
    password_change_success_tracker->OnChangePasswordFlowModified(
        request_url_,
        PasswordChangeSuccessTracker::StartEvent::kManualChangePasswordUrlFlow);
    Redirect(redirect_url);
  } else {
    RecordMetric(WellKnownChangePasswordResult::kFallbackToOriginUrl);
    password_change_success_tracker->OnChangePasswordFlowModified(
        request_url_,
        PasswordChangeSuccessTracker::StartEvent::kManualHomepageFlow);
    Redirect(request_url_.DeprecatedGetOriginAsURL());
  }
  CancelDeferredNavigation(NavigationThrottle::CANCEL);
}

void WellKnownChangePasswordNavigationThrottle::Redirect(const GURL& url) {
  content::OpenURLParams params =
      content::OpenURLParams::FromNavigationHandle(navigation_handle());
  params.url = url;
  params.transition = ui::PAGE_TRANSITION_CLIENT_REDIRECT;

  WebContents* web_contents = navigation_handle()->GetWebContents();
  if (!web_contents)
    return;

  base::SequencedTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::BindOnce(
                     [](base::WeakPtr<content::WebContents> web_contents,
                        const content::OpenURLParams& params) {
                       if (!web_contents)
                         return;
                       web_contents->OpenURL(params);
                     },
                     web_contents->GetWeakPtr(), std::move(params)));
}

void WellKnownChangePasswordNavigationThrottle::RecordMetric(
    WellKnownChangePasswordResult result) {
  ukm::builders::PasswordManager_WellKnownChangePasswordResult(source_id_)
      .SetWellKnownChangePasswordResult(static_cast<int64_t>(result))
      .Record(ukm::UkmRecorder::Get());
}


text:
This example shows how to use the [Logz.io Log4j 1.2 Appender](https://github.com/logzio/logzio-log4j-appender) inside your Tomcat version 8 application server to centralize your logs.

While this example prints logs both to the console & remotely to Logz.io, the end goal should just be to send remote logs to Logz.io and not to the console or a file.  This will have the best performance of minimizing I/O, as well as the benefit of not having to manage log rotations or disk space.

### High level steps
At a high level, here are the steps (review [Dockerfile](Dockerfile) for more specifics):
- Convert Tomcat to use the Log4j framework
  - Install the JULI libraries
  - Install the log4j library
  - Remove the default logging.properties file
- Install the Logz.io libraries and dependencies (review [pom.xml](pom.xml))
- Update your *log4j.properties* file to include the *LogzioAppender* and desired properties (review [log4j.properties](log4j.properties))

### Requirements
To run this example, you must:
- have the ability to clone this Docker repo (https://github.com/rentacenter/logzio.git)
- have installed [Docker](https://www.docker.com/)
- have the ability for Docker to pull images from [Docker Hub](https://hub.docker.com/)
- have a [logz.io](http://logz.io) account
- have the ability to communicate to *listener.logz.io* over secure *port 8071*

### Build the example
```shell
$ docker build -t logz/tomcat8-example:1 .
```

### Run the example
```shell
$ docker run -e 'LOGZIO_TOKEN=<put your logz.io token here>' -e 'ENVIRONMENT=dev' logz/tomcat8-example:1
```


text:
//FISHING
angular.module('kylenolan.net').controller('PhotographyController', ['$scope', '$rootScope', '$anchorScroll', '$location', 'Lightbox', 'loadingHandler', function ($scope, $rootScope, $anchorScroll, $location, Lightbox, loadingHandler) {

  var ctrl = this;

  console.log("photography controller reporting for duty.");
  $rootScope.showNav = true;

  /* Loader Fading */

  loadingHandler.denyLoaderFade();

  $scope.$on('$viewContentLoaded', function(event) {
    loadingHandler.tryLoaderFade();
  });

  $scope.allowLoaderFade = function() {
    loadingHandler.allowLoaderFade();
  }

  /* End Loader */

  ctrl.photoPics = [];
  var photosRaw = [
    {index:    27,  title: "",   caption: "Christ of the Abyss statue, Key Largo, FL"},
    {index:    10,  title: "",   caption: "Saint John, USVI"},
    {index:    9,  title: "",   caption: "Nature path near Waterlemon Cay, Saint John"},
    {index:    26,  title: "",   caption: "Antler coral in Key Largo, FL"},
    {index:    16,  title: "",   caption: "Green sea turtle at Waterlemon Cay, Saint John"},
    {index:    13,  title: "",   caption: "Sunken freighter off the coast of Sain Thomas, USVI"},
    {index:    12,  title: "",   caption: "View from the Red Hook ferry just before sunset"},
    {index:    22,  title: "",   caption: "Turtle grass on Saint John, USVI"},
    {index:    5,  title: "",   caption: "Sunset on the Intracoastal Waterway in Melbourne, FL"},
    {index:    25,  title: "",   caption: "Stingray on the move in Key Largo, FL"},
    {index:    14,  title: "",   caption: "Tiny reef fish at Waterlmeon Cay, Saint John"},
    {index:    24,  title: "",   caption: "Butterfly flish in shallow water at Saint John"},
    {index:    11,  title: "",   caption: "Sunset on the return ferry to Red Hook, Saint Thomas"},
    {index:    7,  title: "",   caption: "View of Long Bay from Charlotte Amelie, Saint Thomas"},
    {index:    8,  title: "",   caption: "Rocky shore on Saint John, USVI"},
    {index:    19,  title: "",   caption: "Permit jack at Waterlmeon Cay, Saint John"},
    {index:    18,  title: "",   caption: "Green sea turtle transporting some remora on Saint John"},
    {index:    20,  title: "",   caption: "An urchin minefield near Waterlemon Cay, Saint John"},
    {index:    6,  title: "",   caption: "Changing seasons on Spring Brook Trail in Camden, ME"},
    {index:    21,  title: "",   caption: "Flouder sighting on Saint John, USVI"},
    {index:    1,  title: "",   caption: "Sunset over the river in Melbourne, FL"},
    {index:    2,  title: "",   caption: "Ocala National Forest, FL"},
    {index:    15,  title: "",   caption: "A grassy area on the ocean floor near Saint Thomas"},
    {index:    3,  title: "",   caption: "Getting ready for a night of fishing on the Intracoastal Waterway in Melbourne, FL"},
    {index:    17,  title: "",   caption: "A green sea turtle on Saint John, USVI"},
    {index:    4,  title: "",   caption: "View of the Boston skyline from Quincy Quarries"},
    {index:    23,  title: "",   caption: "Turtle grass on Saint John, USVI"}
  ];

  for (var i=0; i<photosRaw.length; i++)
  {
    ctrl.photoPics.push(
        {
            'url': "img/photography/full/photography ("+photosRaw[i].index+").jpg",
            'thumbUrl': "img/photography/thumbs/photography ("+photosRaw[i].index+").jpg",
            'title': photosRaw[i].title,
            'caption': photosRaw[i].caption
        }
    );
  }

  $scope.openLightboxModal = function (arr, index) {
    Lightbox.openModal(arr, index);
  };

}]);


text:
This is not an officially supported Google product

This repository contains a micro controller friendly implimentation of a
data framing layer, in C.

## How to use this library

CMake and Bazel build files have been included for your convenience.

 Lib only
 ```shell
  cmake CMakeLists.txt
  make all
 ```
Unit Tests
``` shell
  cmake CMakeLists.txt
  make unit_tests
  ./src/unit_tests/unit_tests
  ```

See unit tests for example usage.

## Source Code Headers

Every file containing source code must include copyright and license
information. This includes any JS/CSS files that you might be serving out to
browsers. (This is to help well-intentioned people avoid accidental copying that
doesn't comply with the license.)

Apache header:

    Copyright 2018 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

        https://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.


text:
<?php

/* CmarMeetingBundle:Group:edit.html.twig */
class __TwigTemplate_275184cdf4128f251e69cbb3a1304b7b extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "CmarMeetingBundle::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        // line 3
        echo "Meeting edit
";
    }

    // line 6
    public function block_body($context, array $blocks = array())
    {
        // line 7
        echo "<form action=\"";
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("index_update", array("id" => $this->getAttribute($this->getContext($context, "meeting"), "id"))), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderEnctype($this->getContext($context, "edit_form"));
        echo ">
    ";
        // line 8
        echo $this->env->getExtension('form')->renderWidget($this->getContext($context, "edit_form"));
        echo "

        <button type=\"submit\">Edit</button>

</form>

        env, $this->env->getExtension('routing')->getPath("index"), "html", null, true);
        echo "\">
            Back to the list

";
    }

    public function getTemplateName()
    {
        return "CmarMeetingBundle:Group:edit.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
{-# LANGUAGE UnicodeSyntax #-}
import Utils
import Lambdas
import Data.Set
import Prelude hiding (readFile)
import Data.ByteString (readFile)

main :: IO ()
main = do
    input ← readFile "task2.in"
    let λ = parseBS parseLambda input
    let free = freeVars λ
    writeFile "task2.out" $ unlines $ elems free


text:
class DatagramIteratorEOF : public std::runtime_error
{
  public:
    DatagramIteratorEOF(const std::string &what) : std::runtime_error(what) { }
};

// A DatagramIterator lets you step trough a datagram by reading a single value at a time.
class DatagramIterator
{
  protected:
    DatagramHandle m_dg;
    dgsize_t m_offset;

    void check_read_length(dgsize_t length)
    {
        if(m_offset + length > m_dg->size()) {
            std::stringstream error;
            error << "dgi tried to read past dg end, offset+length(" << m_offset + length << ")"
                  << " buf_size(" << m_dg->size() << ")" << std::endl;
            throw DatagramIteratorEOF(error.str());
        };
    }
  public:
    // constructor
    DatagramIterator(DatagramHandle dg, dgsize_t offset = 0) : m_dg(dg), m_offset(offset)
    {
        check_read_length(0); //shortcuts, yay
    }

    // read_bool reads the next byte from the datagram and returns either false or true.
    bool read_bool()
    {
        uint8_t val = read_uint8();
        return val != false; // returns either 1 or 0
    }

    // read_int8 reads a byte from the datagram,
    // returning a signed 8-bit integer.
    int8_t read_int8()
    {
        check_read_length(1);
        int8_t r = *(int8_t*)(m_dg->get_data() + m_offset);
        m_offset += 1;
        return r;
    }

    // read_int16 reads 2 bytes from the datagram,
    // returning a signed 16-bit integer in native endianness.
    int16_t read_int16()
    {
        check_read_length(2);
        int16_t r = *(int16_t*)(m_dg->get_data() + m_offset);
        m_offset += 2;
        return swap_le(r);
    }

    // read_int32 reads 4 bytes from the datagram,
    // returning a signed 32-bit integer in native endianness.
    int32_t read_int32()
    {
        check_read_length(4);
        int32_t r = *(int32_t*)(m_dg->get_data() + m_offset);
        m_offset += 4;
        return swap_le(r);
    }

    // read_int64 reads 8 bytes from the datagram,
    // returning a signed 64-bit integer in native endianness.
    int64_t read_int64()
    {
        check_read_length(8);
        int64_t r = *(int64_t*)(m_dg->get_data() + m_offset);
        m_offset += 8;
        return swap_le(r);
    }

    // read_uint8 reads a byte from the datagram,
    // returning an unsigned 8-bit integer.
    uint8_t read_uint8()
    {
        check_read_length(1);
        uint8_t r = *(uint8_t*)(m_dg->get_data() + m_offset);
        m_offset += 1;
        return r;
    }

    // read_uint16 reads 2 bytes from the datagram,
    // returning an unsigned 16-bit integer in native endianness.
    uint16_t read_uint16()
    {
        check_read_length(2);
        uint16_t r = *(uint16_t*)(m_dg->get_data() + m_offset);
        m_offset += 2;
        return swap_le(r);
    }

    // read_uint32 reads 4 bytes from the datagram,
    // returning an unsigned 32-bit integer in native endianness.
    uint32_t read_uint32()
    {
        check_read_length(4);
        uint32_t r = *(uint32_t*)(m_dg->get_data() + m_offset);
        m_offset += 4;
        return swap_le(r);
    }

    // read_uint64 reads 8 bytes from the datagram,
    // returning an unsigned 64-bit integer in native endianness.
    uint64_t read_uint64()
    {
        check_read_length(8);
        uint64_t r = *(uint64_t*)(m_dg->get_data() + m_offset);
        m_offset += 8;
        return swap_le(r);
    }

    // read_size reads a dgsize_t from the datagram.
    dgsize_t read_size()
    {
        check_read_length(sizeof(dgsize_t));
        dgsize_t r = *(dgsize_t*)(m_dg->get_data() + m_offset);
        m_offset += sizeof(dgsize_t);
        return swap_le(r);
    }

    // read_channel reads a channel_t from the datagram.
    channel_t read_channel()
    {
        check_read_length(sizeof(channel_t));
        channel_t r = *(channel_t*)(m_dg->get_data() + m_offset);
        m_offset += sizeof(channel_t);
        return swap_le(r);
    }

    // read_doid reads a doid_t from the datagram.
    doid_t read_doid()
    {
        check_read_length(sizeof(doid_t));
        doid_t r = *(doid_t*)(m_dg->get_data() + m_offset);
        m_offset += sizeof(doid_t);
        return swap_le(r);
    }

    // read_zone reads a zone_t from the datagram.
    zone_t read_zone()
    {
        check_read_length(sizeof(zone_t));
        zone_t r = *(zone_t*)(m_dg->get_data() + m_offset);
        m_offset += sizeof(zone_t);
        return swap_le(r);
    }

    // read_float32 reads 4 bytes from the datagram,
    // returning a 32-bit float in native endianness.
    float read_float32()
    {
        check_read_length(4);
        float r = *(float*)(m_dg->get_data() + m_offset);
        m_offset += 4;
        return swap_le(r);
    }

    // read_float64 reads 8 bytes from the datagram,
    // returning a 64-bit float (double) in native endianness.
    double read_float64()
    {
        check_read_length(8);
        double r = *(double*)(m_dg->get_data() + m_offset);
        m_offset += 8;
        return swap_le(r);
    }

    // read_string reads a string from the datagram in the format
    //     {dgsize_t length; char[length] characters} and returns the character data.
    std::string read_string()
    {
        dgsize_t length = read_size();
        check_read_length(length);
        std::string str((char*)(m_dg->get_data() + m_offset), length);
        m_offset += length;
        return str;
    }

    // read_blob reads a blob from the datagram in the format
    //     {dgsize_t length; uint8[length] binary} and returns the binary part.
    std::vector<uint8_t> read_blob()
    {
        dgsize_t length = read_size();
        return read_data(length);
    }

    // read_datagram reads a blob from the datagram and returns it as another datagram.
    DatagramPtr read_datagram()
    {
        dgsize_t length = read_size();
        return Datagram::create(m_dg->get_data() + m_offset, length);
    }

    // read_data returns the next <length> bytes in the datagram.
    std::vector<uint8_t> read_data(dgsize_t length)
    {
        check_read_length(length);
        std::vector<uint8_t> data(m_dg->get_data() + m_offset, m_dg->get_data() + m_offset + length);
        m_offset += length;
        return data;
    }

    // read_remainder returns a vector containing the rest of the bytes in the datagram.
    std::vector<uint8_t> read_remainder()
    {
        return read_data(m_dg->size() - m_offset);
    }

    // unpack_field accepts a Field of a distributed class
    //     and returns the packed value for the field.
    std::vector<uint8_t> unpack_field(const dclass::Field* field)
    {
        std::vector<uint8_t> buffer;
        unpack_field(field, buffer);
        return buffer;
    }

    // unpack_field can also be called to read into an existing buffer.
    void unpack_field(const dclass::Field* field, std::vector<uint8_t> &buffer)
    {
        unpack_dtype(field->get_type(), buffer);
    }

    // unpack_dtype accepts a DistributedType and copies the data for the value into a buffer.
    void unpack_dtype(const dclass::DistributedType* dtype, std::vector<uint8_t> &buffer)
    {
        using namespace dclass;
        if(dtype->has_fixed_size()) {
            // If field is a fixed-sized type like uint, int, float, etc
            // Also any other type lucky enough to be fixed size will be computed faster
            std::vector<uint8_t> data = read_data(dtype->get_size());
            buffer.insert(buffer.end(), data.begin(), data.end());
            return;
        }

        // For the unlucky types, we have to figure out their size manually
        switch(dtype->get_type()) {
        case T_VARSTRING:
        case T_VARBLOB:
        case T_VARARRAY: {
            dgsize_t len = read_size();
            dgsize_t net_len = swap_le(len);
            buffer.insert(buffer.end(), (uint8_t*)&net_len, (uint8_t*)&net_len + sizeof(dgsize_t));

            std::vector<uint8_t> blob = read_data(len);
            buffer.insert(buffer.end(), blob.begin(), blob.end());
            break;
        }
        case T_STRUCT: {
            const Struct* dstruct = dtype->as_struct();
            size_t num_fields = dstruct->get_num_fields();
            for(unsigned int i = 0; i < num_fields; ++i) {
                unpack_dtype(dstruct->get_field(i)->get_type(), buffer);
            }
            break;
        }
        case T_METHOD: {
            const Method* dmethod = dtype->as_method();
            size_t num_params = dmethod->get_num_parameters();
            for(unsigned int i = 0; i < num_params; ++i) {
                unpack_dtype(dmethod->get_parameter(i)->get_type(), buffer);
            }
            break;
        }
        default: {
            // This case should be impossible, but a default is required by compilers
            break;
        }
        }
    }

    // skip_field can be used to seek past the packed field data for a Field.
    //     Throws DatagramIteratorEOF if it skips past the end of the datagram.
    void skip_field(const dclass::Field* field)
    {
        skip_dtype(field->get_type());
    }

    // skip_dtype can be used to seek past the packed data for a DistributedType.
    //     Throws DatagramIteratorEOF if it skips past the end of the datagram.
    void skip_dtype(const dclass::DistributedType *dtype)
    {
        using namespace dclass;
        if(dtype->has_fixed_size()) {
            dgsize_t length = dtype->get_size();
            check_read_length(length);
            m_offset += length;
            return;
        }

        switch(dtype->get_type()) {
        case T_VARSTRING:
        case T_VARBLOB:
        case T_VARARRAY: {
            dgsize_t length = read_size();
            check_read_length(length);
            m_offset += length;
            break;
        }
        case T_STRUCT: {
            const Struct* dstruct = dtype->as_struct();
            size_t num_fields = dstruct->get_num_fields();
            for(unsigned int i = 0; i < num_fields; ++i) {
                skip_dtype(dstruct->get_field(i)->get_type());
            }
            break;
        }
        case T_METHOD: {
            const Method* dmethod = dtype->as_method();
            size_t num_params = dmethod->get_num_parameters();
            for(unsigned int i = 0; i < num_params; ++i) {
                skip_dtype(dmethod->get_parameter(i)->get_type());
            }
            break;
        }
        default: {
            // This case should be impossible, but a default is required by compilers
            break;
        }
        }
    }

    // get_recipient_count returns the datagram's recipient count. Does not advance the offset.
    // Should be used when the current offset needs to be saved and/or if the next field in the
    // datagram is not the recipient_count. If stepping through a fresh datagram, use read_uint8.
    uint8_t get_recipient_count() const
    {
        if(m_dg->size() > 0) {
            return *(uint8_t*)(m_dg->get_data());
        } else {
            throw DatagramIteratorEOF("Cannot read header from empty datagram.");
        }
    }

    // get_sender returns the datagram's sender. Does not advance the offset.
    // Should be used when the current offset needs to be saved and/or if the next field in the
    //     datagram is not the sender. If stepping through a fresh datagram, use read_channel.
    channel_t get_sender()
    {
        dgsize_t offset = m_offset; // save offset

        m_offset = 1 + get_recipient_count() * sizeof(channel_t); // seek sender
        channel_t sender = read_channel(); // read sender

        m_offset = offset; // restore offset
        return sender;
    }

    // get_msg_type returns the datagram's message type. Does not advance the offset.
    // Should be used when the current offset needs to be saved and/or if the next field in the
    //     datagram is not the msg_type. If stepping through a fresh datagram, use read_uint16.
    uint16_t get_msg_type()
    {
        dgsize_t offset = m_offset; // save offset

        m_offset = 1 + get_recipient_count() * sizeof(channel_t) + sizeof(channel_t); // seek message type
        uint16_t msg_type = read_uint16(); // read message type

        m_offset = offset; // restore offset
        return msg_type;
    }

    // tell returns the current message offset in std::vector<uint8_t>
    dgsize_t tell() const
    {
        return m_offset;
    }

    // get_remaining returns the number of unread bytes left
    dgsize_t get_remaining() const
    {
        return m_dg->size() - m_offset;
    }

    // seek sets the current message offset in std::vector<uint8_t>
    void seek(dgsize_t to)
    {
        m_offset = to;
    }

    // seek_payload seeks to immediately after the list of receivers
    //     (typically, [channel_t sender, uint16_t msgtype, ...])
    void seek_payload()
    {
        m_offset = 0; // Seek to start
        m_offset = 1 + get_recipient_count() * sizeof(channel_t);
    }

    // skip increments the current message offset by a length.
    //     Throws DatagramIteratorEOF if it skips past the end of the datagram.
    void skip(dgsize_t length)
    {
        check_read_length(length);
        m_offset += length;
    }
};


text:
rm -f x.json
for i in settings bhyve_dskcontroller bhyvenic pcibus bhyvedsk; do
	./sql2json.py --dbfile /home/oginzburg/oginzburg/vm/jenkinslin1/local.sqlite --sqlquery="SELECT * FROM ${i}" | python3.6 -mjson.tool >> x.json
done


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0038_auto_20170406_1557'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='hdxexportregion',
            name='export_formats',
        ),
        migrations.RemoveField(
            model_name='hdxexportregion',
            name='feature_selection',
        ),
        migrations.RemoveField(
            model_name='hdxexportregion',
            name='last_run',
        ),
        migrations.RemoveField(
            model_name='hdxexportregion',
            name='name',
        ),
        migrations.RemoveField(
            model_name='hdxexportregion',
            name='the_geom',
        ),
        migrations.AddField(
            model_name='hdxexportregion',
            name='job',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='jobs.Job'),
        ),
        migrations.AddField(
            model_name='job',
            name='feature_selection',
            field=models.TextField(blank=True),
        ),
    ]


text:
var Promise         = require('bluebird'),
    config          = require('../config'),
    image;

image = function (options) {
    var absolute = options && options.hash.absolute;
    if (this.image) {
        return Promise.resolve(config.urlFor('image', {image: this.image}, absolute));
    } else {
        return Promise.resolve();
    }
};

module.exports = image;


text:
<?php
namespace Concrete\Core\Application\UserInterface\Sitemap\TreeCollection;

use Concrete\Core\Application\UserInterface\Sitemap\TreeCollection\Entry\EntryInterface;

class StandardTreeCollection extends TreeCollection
{

    public function displayMenu()
    {
        $entries = $this->getEntries();
        return count($entries) > 1;
    }

}


text:
'use strict';

var buster = require('buster');
var fs = require('fs');
var parser = require('../lib/bitbucketParser');
var util = require('../lib/util');

// Make some functions global for BDD style
buster.spec.expose();
var expect = buster.expect;
var readFile = function (file, callback) {
    return fs.readFile(file, { encoding: 'utf8' }, callback);
};

describe('generateMessage', function () {
    it('should return created message if passed created action', function (done) {
        readFile('test/json/general.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:created');

            expect(out).toBeDefined();

            expect(out.fallback).toMatch('*created*');
            expect(out.fallback).toMatch('https://bitbucket.org/brh55/bitbucket-pullrequest-mock/pull-requests/6');
            expect(out.color).toEqual(util.COLORS.blue);
            expect(out.fields.length).toEqual(2);

            done();
        });
    });

    it('should have reviewers mentions in created message if mentionReviewers switch is true', function (done) {
        readFile('test/json/general.json', function (err, data) {
            data = JSON.parse(data);
            util.FEATURE_SWITCH.mentionReviewers = true;
            var out = parser.generateMessage(data, 'pullrequest:created');

            expect(out).toBeDefined();
            expect(out.fields.length).toEqual(3);

            util.FEATURE_SWITCH.mentionReviewers = false;
            done();
        });
    });

    it('should return updated message if passed updated action', function (done) {
        readFile('test/json/general.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:updated');

            expect(out).toBeDefined();

            expect(out.fallback).toMatch('*updated*');
            expect(out.color).toEqual(util.COLORS.blue);
            expect(out.fields.length).toEqual(2);

            done();
        });
    });

    it('should return approved message if passed approved action', function (done) {
        readFile('test/json/approval.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:approved');

            expect(out).toBeDefined();

            expect(out.fallback).toMatch('*approved*');
            expect(out.fallback).toMatch('Vladamir Jones');
            expect(out.color).toEqual(util.COLORS.green);
            expect(out.fields).not.toBeDefined();

            done();
        });
    });

    it('should return unapproved message if passed unapproved action', function (done) {
        readFile('test/json/approval.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:unapproved');

            expect(out).toBeDefined();

            expect(out.fallback).toMatch('*UNapproved*');
            expect(out.fallback).toMatch('Vladamir Jones');

            expect(out.color).toEqual(util.COLORS.yellow);
            expect(out.fields).not.toBeDefined();

            done();
        });
    });

    it('should return rejected message if passed rejected action', function (done) {
        readFile('test/json/general.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:rejected');

            expect(out).toBeDefined();

            expect(out.fallback).toMatch('*rejected*');
            expect(out.color).toEqual(util.COLORS.red);
            expect(out.fields.length).toEqual(2);

            done();
        });
    });

    it('should return merged message if passed merged action', function (done) {
        readFile('test/json/general.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:fulfilled');

            expect(out).toBeDefined();
            expect(out.fallback).toMatch('*merged*');
            expect(out.color).toEqual(util.COLORS.green);
            expect(out.fields.length).toEqual(2);

            done();
        });
    });

    it('should return comment created message if passed comment_created action', function (done) {
        readFile('test/json/comment.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:comment_created');

            expect(out).toBeDefined();
            expect(out.fallback).toMatch('comment');
            expect(out.fallback).toMatch('*posted*');
            expect(out.fallback).toMatch('Vladamir Jones');
            expect(out.fallback).toMatch('https://bitbucket.org/brh55/bitbucket-pullrequest-mock/pull-requests/6/_/diff#comment-13165480');

            expect(out.color).toEqual(util.COLORS.yellow);
            expect(out.fields.length).toEqual(1);

            done();
        });
    });

    it('should return comment deleted message if passed comment_deleted action', function (done) {
        readFile('test/json/comment.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:comment_deleted');

            expect(out).toBeDefined();
            expect(out.fallback).toMatch('comment');
            expect(out.fallback).toMatch('*deleted*');
            expect(out.fallback).toMatch('Vladamir Jones');
            expect(out.fallback).toMatch('https://bitbucket.org/brh55/bitbucket-pullrequest-mock/pull-requests/6/_/diff#comment-13165480');

            expect(out.color).toEqual(util.COLORS.yellow);
            expect(out.fields.length).toEqual(1);

            done();
        });
    });

    it('should return comment updated message if passed comment_updated action', function (done) {
        readFile('test/json/comment.json', function (err, data) {
            data = JSON.parse(data);
            var out = parser.generateMessage(data, 'pullrequest:comment_updated');

            expect(out).toBeDefined();
            expect(out.fallback).toMatch('comment');
            expect(out.fallback).toMatch('*updated*');
            expect(out.fallback).toMatch('Vladamir Jones');
            expect(out.fallback).toMatch('https://bitbucket.org/brh55/bitbucket-pullrequest-mock/pull-requests/6/_/diff#comment-13165480');

            expect(out.color).toEqual(util.COLORS.yellow);
            expect(out.fields.length).toEqual(1);

            done();
        });
    });

    it('should return undefined if passed unknown pull request action', function () {
        this.stub(console, 'log');
        var out = parser.generateMessage({'unknown': 'dunno'});
        expect(out).not.toBeDefined();
    });

    it('should return undefined if a non pullrequest event is submitted', function () {
        this.stub(console, 'log');
        var out = parser.generateMessage({'unknown': 'dunno'}, 'repo:fork');
        expect(out).not.toBeDefined();
    });
});


text:
/**
 * Node.js SDK for Ma3Route REST API
 * @see https://bitbucket.org/ma3route_team/ma3route-api-documentation/wiki/Home
 */

"use strict";

// Exporting the modules for each  API object
exports = module.exports = {
    Client: require("./lib/client"),
    Poller: require("./lib/poller"),
    auth: require("./lib/auth"),
    activations: require("./lib/activations"),
    bannerAdverts: require("./lib/bannerAdverts"),
    campaigns: require("./lib/campaigns"),
    drivingReports: require("./lib/drivingReports"),
    externalStream: require("./lib/externalStream"),
    images: require("./lib/images"),
    listedAdverts: require("./lib/listedAdverts"),
    misc: require("./lib/misc"),
    news: require("./lib/news"),
    places: require("./lib/places"),
    sse: require("./lib/sse"),
    trafficUpdates: require("./lib/trafficUpdates"),
    users: require("./lib/users"),
    utils: require("./lib/utils"),
    errors: require("common-errors"),
    generate: require("./lib/generate"),
};

/**
 * Settings for the SDK. Defaults can be found in the config.json file in root of repo.
 * This is to be passed to utils.setup().
 * @typedef  {Object} SETTINGS
 * @property {String}  baseurl - API base url
 * @property {Boolean} enforce_params_filter - whether to pick parameters before sending requests
 * @property {Object}  request - configures requests fired by SDK
 * @property {Boolean} request.strictSSL - whether to enable strict ssl
 * @property {Boolean} request.json - whether to return responses in JSON format
 * @see https://github.com/Ma3Route/node-sdk/blob/master/config.json
 */

/**
 * A callback passed a collection of items, such as traffic updates.
 * @callback collectionCallback
 * @param {Error} error - error object
 * @param {Array} items - array of items
 * @param {Object} meta - meta-data concerning the items
 * @param {Object} response - actual response object
 */

/**
 * A callback passed a success indicator
 * @callback successCallback
 * @param {Error} error - error object
 * @param {Object} indicator - status of the operation
 * @param {Boolean} indicator.success - whether the operation succeeded
 * @param {Boolean} indicator.message - message from the API
 * @param {Object} [indicator.object] - affected object
 * @param {Object} response - actual response object
 */

/**
 * A callback passed an error on failure, or nothing otherwise.
 * @callback emptySuccessCallback
 * @param {Error} error - error object
 */

/**
 * A callack passed a single item, such as a single traffic update.
 * @callback itemCallback
 * @param {Error} error -error object
 * @param {Object} item - the single item
 * @param {Object} meta - meta-data concerning the item
 * @param {Object} response - actual response object
 */

/**
 * String representing an endpoint. This is solely used internally by the SDK.
 * @typedef {String} Endpoint
 */

/**
 * Sends a DELETE request to delete a single item.
 * @typedef {Function} itemsDeleteOneRequest
 * @param {Number|Object} identifier - ID of the item
 * @param {Object} [params] - parameters
 * @param {emptySuccessCallback} callback
 */

/**
 * Sends a GET request to fetch an array of items.
 * @typedef {Function} itemsGetRequest
 * @param {Object} [params] - parameters
 * @param {collectionCallback} callback
 */

/**
 * Sends a GET request, to fetch a single item.
 * @typedef {Function} itemsGetOneRequest
 * @param {Number|Object} identifier - ID of the item
 * @param {Object} [params] - parameters
 * @param {itemCallback} callback
 */

/**
 * Sends a POST request, usually for creating and updating entities.
 * @typedef {Function} itemsPostOneRequest
 * @param {Object} body - parameters
 * @param {successCallback} callback
 */

/**
 * Sends a PUT request, usually for editing entities.
 * @typedef {Function} itemsPutOneRequest
 * @param {Object} body
 * @param {successCallback} callback
 */

/**
 * Creates and returns a SSE Client.
 * @typedef {Function} SSEClientFactory
 * @param {Object} initDict - initialization options
 * @return {EventSource}
 */


text:
using System;
using Xamarin.CommunityToolkit.Helpers;
using Xamarin.Forms;

namespace Xamarin.CommunityToolkit.Effects
{
	/// <summary>
	/// An effect to subscribe to the View's lifecycle events.
	/// </summary>
	public class LifecycleEffect : RoutingEffect
	{
		readonly WeakEventManager eventManager = new WeakEventManager();

		/// <summary>
		/// Event that is triggered when the <see cref="View" /> is loaded and is ready for use.
		/// </summary>
		public event EventHandler Loaded
		{
			add => eventManager.AddEventHandler(value);
			remove => eventManager.RemoveEventHandler(value);
		}

		/// <summary>
		/// Event that is triggered when the <see cref="View" /> is unloaded and isn't ready for use.
		/// </summary>
		public event EventHandler Unloaded
		{
			add => eventManager.AddEventHandler(value);
			remove => eventManager.RemoveEventHandler(value);
		}

		/// <summary>
		/// Constructor for the <see cref="LifecycleEffect" />
		/// </summary>
		public LifecycleEffect()
			: base(EffectIds.LifeCycleEffect)
		{
#if __ANDROID__
			if (System.DateTime.Now.Ticks < 0)
				_ = new Xamarin.CommunityToolkit.Android.Effects.LifeCycleEffectRouter();
#elif __IOS__
			if (System.DateTime.Now.Ticks < 0)
				_ = new Xamarin.CommunityToolkit.iOS.Effects.LifeCycleEffectRouter();
#elif UWP
			if (System.DateTime.Now.Ticks < 0)
				_ = new Xamarin.CommunityToolkit.UWP.Effects.LifeCycleEffectRouter();
#endif
		}

		internal void RaiseLoadedEvent(Element element) => eventManager.RaiseEvent(element, EventArgs.Empty, nameof(Loaded));

		internal void RaiseUnloadedEvent(Element element) => eventManager.RaiseEvent(element, EventArgs.Empty, nameof(Unloaded));
	}
}


text:
package rewriting

import java.io.DataInputStream
import java.nio.{ByteBuffer, ByteOrder}

import ir._
import ir.ast._
import lift.arithmetic.SizeVar
import opencl.executor.{DeviceCapabilityException, Execute, TestWithExecutor}
import opencl.ir._
import opencl.ir.pattern._
import org.junit.Assert._
import org.junit.{Assume, Test}
import rewriting.macrorules.{MacroRules, ReuseRules}
import rewriting.rules._

object TestRewriteMriQ extends TestWithExecutor

class TestRewriteMriQ {

  private def bytesToFloats(bytes: Array[Byte]) = {
    val byteBuffer = ByteBuffer.wrap(bytes)
    val floatBuffer = byteBuffer.asFloatBuffer()
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN)

    val floatArray = Array.ofDim[Float](floatBuffer.capacity())

    for (i <- floatArray.indices) {
      floatArray(i) = byteBuffer.getFloat(i * 4)
    }

    floatArray
  }

  private def floatArrayFromResource(name: String): Array[Float] = {
    val inputStream = this.getClass.getClassLoader.getResourceAsStream(name)
    val availableBytes = inputStream.available()
    val byteArray = Array.ofDim[Byte](availableBytes)

    val dataInputStream = new DataInputStream(inputStream)
    dataInputStream.readFully(byteArray)
    dataInputStream.close()

    bytesToFloats(byteArray)
  }

  private val prefix = "mriq/small/"

  private val x = floatArrayFromResource(prefix + "xVals.bin")
  private val y = floatArrayFromResource(prefix + "yVals.bin")
  private val z = floatArrayFromResource(prefix + "zVals.bin")
  private val k = floatArrayFromResource(prefix + "kVals.bin").grouped(4).map(x => (x(0), x(1), x(2), x(3))).toArray

  private val Qr = floatArrayFromResource(prefix + "qrVals.bin")
  private val Qi = floatArrayFromResource(prefix + "qiVals.bin")

  private val xNum = x.length
  private val kNum = k.length

  private val gold = (Qr, Qi).zipped.flatMap((a, b) => Seq(a,b))

  private val qFun = UserFun("computeQ",
    Array("sX", "sY", "sZ", "Kx", "Ky", "Kz", "PhiMag", "acc"),
    """{
      |    #define PIx2 6.2831853071795864769252867665590058f
      |    float expArg = PIx2 * (Kx * sX + Ky * sY + Kz * sZ);
      |    acc._0 = acc._0 + PhiMag * cos(expArg);
      |    acc._1 = acc._1 + PhiMag * sin(expArg);
      |
      |    return acc;
      |}""".
      stripMargin,
    Seq(Float, Float, Float, Float, Float, Float, Float, TupleType
    (Float, Float)),
    TupleType(Float, Float))

  private val mapFun = UserFun("mapFun",
    Array("sX", "sY", "sZ", "Kx", "Ky", "Kz", "PhiMag"),
    """{
      |    #define PIx2 6.2831853071795864769252867665590058f
      |    float expArg = PIx2 * (Kx * sX + Ky * sY + Kz * sZ);
      |    Tuple2_float_float bla = { PhiMag * cos(expArg), PhiMag * sin(expArg) };
      |    return  bla;
      |}""".stripMargin,
    Seq(Float, Float, Float, Float, Float, Float, Float), TupleType(Float, Float))

  private val reduceFun = UserFun("reduceFun",
    Array("x", "y"),
    """{
          | x._0 += y._0;
          | x._1 += y._1;
          | return x;
        }""".stripMargin,
    Seq(TupleType(Float, Float), TupleType(Float, Float)), TupleType(Float, Float))

  private val xSize = SizeVar("X")
  private val kSize = SizeVar("K")

  private val f = fun(
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(TupleType(Float, Float, Float, Float), kSize),
      (x, y, z, kValues) =>
        Map(\(t =>
          Reduce(reduceFun, Value("{ 0.0f, 0.0f}", TupleType(Float, Float))) o
            Map(\(k => mapFun(t._0, t._1, t._2, k._0, k._1, k._2, k._3))) $ kValues
        )) $ Zip(x, y, z)
    )

  private val mappings = EnabledMappings(
    global0 = false, global01 = false, global10 = false,
    global012 = false, global210 = false,
    group0 = true, group01 = false, group10 = false)

  @Test
  def computeQ(): Unit = {

    // TODO: Qr & Qi are outputs initialised to 0.0f
    // TODO: Whole kernel split into 3 invokations??
    val f = fun(
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(TupleType(Float, Float, Float, Float), kSize),
      (x, y, z, Qr, Qi, kvalues) =>
        Map(\(t =>
          ReduceSeq(\((acc, p) =>
            qFun(t._0, t._1, t._2, p._0, p._1, p._2, p._3, acc)
          ), Tuple(t._3, t._4)) $ kvalues
        )) $ Zip(x, y, z, Qr, Qi)
    )

    val f0 = Rewrite.applyRuleAtId(f, 0, CopyRules.addIdForMapParam)
    val f1 = Rewrite.applyRuleAtId(f0, 8, CopyRules.implementOneLevelOfId)
    val f2 = Rewrite.applyRuleAtId(f1, 21, CopyRules.implementIdAsDeepCopy)
    val f3 = Rewrite.applyRuleAtId(f2, 18, CopyRules.implementIdAsDeepCopy)
    val f4 = Rewrite.applyRuleAtId(f3, 15, CopyRules.implementIdAsDeepCopy)
    val f5 = Rewrite.applyRuleAtId(f4, 12, SimplificationRules.dropId)
    val f6 = Rewrite.applyRuleAtId(f5, 9, SimplificationRules.dropId)

    val f7 = Rewrite.applyRuleAtId(f6, 24, CopyRules.tupleToStruct)
    val f8 = Lower.lowerNextLevelWithRule(f7, OpenCLRules.mapGlb)
    val f9 = Rewrite.applyRuleAtId(f8, 22, CopyRules.addIdAfterReduce)
    val f10 = Rewrite.applyRuleAtId(f9, 22, OpenCLRules.globalMemory)
    val f11 = Rewrite.applyRuleAtId(f10, 49, CopyRules.implementIdAsDeepCopy)
    val f12 = Rewrite.applyRuleAtId(f11, 25, OpenCLRules.privateMemory)
    val f13 = Rewrite.applyRuleAtId(f12, 19, OpenCLRules.privateMemory)
    val f14 = Rewrite.applyRuleAtId(f13, 16, OpenCLRules.privateMemory)
    val f15 = Rewrite.applyRuleAtId(f14, 13, OpenCLRules.privateMemory)

    val (output, _) =
      Execute()[Array[Float]](f15, x, y, z, Array.fill(xNum)(0.0f), Array.fill(xNum)(0.0f), k)

    assertArrayEquals(gold, output, 0.001f)
  }

  @Test
  def mriqIntroduceReuse(): Unit = {
    val f0 = Rewrite.applyRuleAtId(f, 0, Rules.splitJoin(64))

    val f1 = Rewrite.applyRuleAtId(f0, 7, ReuseRules.introduceReuseFromMap(64))
    val f2 = Rewrite.applyRuleAtId(f1, 10, ReuseRules.introduceReuseFromMap(64))

    val lowered = Lower.mapCombinations(f2, mappings).head

    val l0 = Rewrite.applyRuleUntilCannot(lowered, MacroRules.userFunCompositionToPrivate)
    val l1 = Rewrite.applyRuleAtId(l0, 9, CopyRules.addIdForCurrentValueInReduce)
    val l2 = Rewrite.applyRuleAtId(l1, 17, CopyRules.implementIdAsDeepCopy)
    val l3 = Rewrite.applyRuleAtId(l2, 17, OpenCLRules.localMemory)
    val l4 = Lower.lowerNextLevelWithRule(l3, OpenCLRules.mapLcl)

    val (output, _) =
      Execute()[Array[Float]](l4, x, y, z, k)

    assertArrayEquals(gold, output, 0.001f)
  }

  @Test
  def mriqIntroduceReuseFromMapping(): Unit = {
    val f0 = Rewrite.applyRuleAtId(f, 0, Rules.splitJoin(64))
    val f1 = Rewrite.applyRuleAtId(f0, 7, ReuseRules.introduceReuseFromMap(64))
    val f2 = Rewrite.applyRuleAtId(f1, 10, ReuseRules.introduceReuseFromMap(64))

    val lowered = Lower.mapCombinations(f2, mappings).head

    val l0 = Rewrite.applyRuleUntilCannot(lowered, MacroRules.userFunCompositionToPrivate)
    val l1 = Rewrite.applyRuleAtId(l0, 9, CopyRules.addIdForCurrentValueInReduce)
    val l2 = Rewrite.applyRuleAtId(l1, 17, OpenCLRules.localMemory)
    val l3 = Rewrite.applyRuleAtId(l2, 19, CopyRules.implementIdAsDeepCopy)
    val l4 = Lower.lowerNextLevelWithRule(l3, OpenCLRules.mapLcl)

    val (output, _) =
      Execute()[Array[Float]](l4, x, y, z, k)

    assertArrayEquals(gold, output, 0.001f)
  }

  @Test
  def partialReduceWithReorder(): Unit = {

    val f0 = Rewrite.applyRuleAtId(f, 5, MacroRules.partialReduceWithReorder(128))

    val lowered = Lower.mapCombinations(f0, mappings).head

    val l0 = Rewrite.applyRuleAtId(lowered, 12, CopyRules.addIdAfterReduce)
    val l1 = Rewrite.applyRuleAtId(l0, 6, CopyRules.addIdAfterReduce)
    val l2 = Rewrite.applyRuleAtId(l1, 42, CopyRules.implementIdAsDeepCopy)
    val l3 = Rewrite.applyRuleAtId(l2, 42, OpenCLRules.localMemory)
    val l4 = Rewrite.applyRuleAtId(l3, 35, CopyRules.implementIdAsDeepCopy)
    val l5 = Rewrite.applyRuleAtId(l4, 35, OpenCLRules.localMemory)
    val l6 = Rewrite.applyRuleUntilCannot(l5, MacroRules.userFunCompositionToPrivate)

    val (output, _) =
      Execute()[Array[Float]](l6, x, y, z, k)

    assertArrayEquals(gold, output, 0.01f)
  }

  @Test
  def partialReduceWithReorderNoRace(): Unit = {

    val f0 = Rewrite.applyRuleAtId(f, 5, MacroRules.partialReduceWithReorder(128))

    val f1 = Lower.pushReduceDeeper(f0)
    val lowered = Lower.mapCombinations(f1, mappings).head

    val l0 = Rewrite.applyRuleAtId(lowered, 13, CopyRules.addIdAfterReduce)
    val l1 = Rewrite.applyRuleAtId(l0, 35, OpenCLRules.localMemory)
    val l2 = Rewrite.applyRuleAtId(l1, 37, CopyRules.implementIdAsDeepCopy)
    val l3 = Rewrite.applyRuleUntilCannot(l2, MacroRules.userFunCompositionToPrivate)

    val (output, _) =
      Execute()[Array[Float]](l3, x, y, z, k)

    assertArrayEquals(gold, output, 0.01f)
  }

  @Test
  def mriQ2(): Unit = {
    val computeQ = fun(
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(Float, xSize),
      ArrayType(TupleType(Float, Float, Float, Float), kSize),
      (x, y, z, kValues) =>
        MapGlb(\(t =>
          toGlobal(MapSeq(idFF))  o
            ReduceSeq(reduceFun, Value("{ 0.0f, 0.0f}", TupleType(Float, Float))) o
            MapSeq(\(k => mapFun(t._0, t._1, t._2, k._0, k._1, k._2, k._3))) $ kValues
        )) $ Zip(x, y, z)
    )

    try {
      val (output, _) =
        Execute()[Array[Float]](computeQ, x, y, z, k)

      assertArrayEquals(gold, output, 0.001f)
    } catch {
      case t: DeviceCapabilityException =>
        Assume.assumeNoException(t)
    }
  }
}


text:
package com.roncoo.jui.common.dao.impl;

import com.roncoo.jui.common.dao.WebSiteDao;
import com.roncoo.jui.common.entity.WebSite;
import com.roncoo.jui.common.entity.WebSiteExample;
import com.roncoo.jui.common.mapper.WebSiteMapper;
import com.roncoo.jui.common.util.PageUtil;
import com.roncoo.jui.common.util.jui.Page;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class WebSiteDaoImpl implements WebSiteDao {
    @Autowired
    private WebSiteMapper webSiteMapper;

    public int save(WebSite record) {
        return this.webSiteMapper.insertSelective(record);
    }

    public int deleteById(Long id) {
        return this.webSiteMapper.deleteByPrimaryKey(id);
    }

    public int updateById(WebSite record) {
        return this.webSiteMapper.updateByPrimaryKeySelective(record);
    }

    public List<WebSite> listByExample(WebSiteExample example) {
        return this.webSiteMapper.selectByExample(example);
    }

    public WebSite getById(Long id) {
        return this.webSiteMapper.selectByPrimaryKey(id);
    }

    public Page<WebSite> listForPage(int pageCurrent, int pageSize, WebSiteExample example) {
        int count = this.webSiteMapper.countByExample(example);
        pageSize = PageUtil.checkPageSize(pageSize);
        pageCurrent = PageUtil.checkPageCurrent(count, pageSize, pageCurrent);
        int totalPage = PageUtil.countTotalPage(count, pageSize);
        example.setLimitStart(PageUtil.countOffset(pageCurrent, pageSize));
        example.setPageSize(pageSize);
        return new Page<WebSite>(count, totalPage, pageCurrent, pageSize, this.webSiteMapper.selectByExample(example));
    }
}


text:
@interface PNHereNowResponseParser : PNResponseParser

@end


text:
/**
 * Module dependencies.
 */
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

var session = require("express-session");
var store = new session.MemoryStore();

var httpServer = require('http').Server(app);

var WebSocketServer = require("websocket").server;
var webSocketServer = new WebSocketServer({
  httpServer:httpServer,
  autoAcceptConnections:false
});

// Dies sollte ein zufaellig generierter Schluessel sein.
var signKey = "RHDwSKMa&vcxnkj";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded( { extended : false } ));
app.use(cookieParser(signKey));
app.use(express.static(path.join(__dirname, 'public')));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(session({store:store}));

webSocketServer.on('request', function(request) {
  var sid = "";
  for (var i = 0; i < request.cookies.length; i++) {
    if(request.cookies[i].name === "connect.sid") {
      sid = request.cookies[i].value;
    }
  };

  var sessionID = cookieParser.signedCookie(sid,signKey);

  store.get(sessionID,function(err,session) {
    if(!session || !session.username) {
      request.reject();
      return;
    }
    else{
      request.accept();
    }
  });
});

webSocketServer.on("connect",function(socket){
  socket.on("message",function(message){
    if(message.type === 'utf8'){
      socket.send(message.utf8Data);
    }
  });

});

function requiresLogin(req,res,next){
  if(!req.session.username){
    req.session.path = req.url;
    res.redirect('/login');
  }
  else{
    next();
  }
}

app.get('/login', function (req,res){
  res.render('login',{title:'Login'});
});

app.post('/login',function(req,res){
  if(req.body.username=="admin"&&req.body.password=="123"){
    var path = req.session.path;
    req.session.regenerate(function(err){
        var hour = 60*60*1000;
        req.session.username = req.body.username;
        req.session.cookie.expires = new Date(Date.now()+hour);
        if(path){
        res.redirect(path);

        }
        else{
          res.redirect("/");
        }
     });
  }
  else{
   res.redirect('back');
  }
});

app.get('/',requiresLogin ,function (req,res){
  res.render('index',{title:'Home'});
});

app.get("/logout",function(req,res){
  req.session.destroy();
  res.redirect("/login");
});

httpServer.listen(3000, function(){
  console.log("Express-Server laeuft auf dem Port 3000");
});


text:
package c88_PlaneGame;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyFrame extends Frame{

	/**
	 * loading
	 */
	public void launchFrame() {
		setSize(Constant.GAME_WIDTH,Constant.GAME_HEIGHT);
		setLocation(100,100);
		setVisible(true);

		new PaintThread().start();//Æô¶¯ÖØ»æÏß³Ì
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);
			}

		});

	}

	/**
	 * ¶¨ÒåÒ»¸öÖØ»æÏ̵߳ÄÄÚ²¿Àà
	 * @author Administrator
	 *
	 */
	class PaintThread extends Thread{
		public void run() {
			while(true){
				repaint();
				try {
					Thread.sleep(40);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}


text:
package org.grails.web.servlet;

import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;

/**
 * Defines the methods and objects available during a Grails request context.
 *
 * @author Graeme Rocher
 * @since 0.6
 */
public interface GrailsRequestContext {

    /**
     * The request object.
     * @return The request object
     */
    HttpServletRequest getRequest();

    /**
     * The response object.
     * @return The response object
     */
    HttpServletResponse getResponse();

    /**
     * The session object.
     * @return The session object
     */
    HttpSession getSession();

    /**
     * The servletContext object.
     * @return The servletContext Object
     */
    ServletContext getServletContext();

    /**
     * The params object.
     * @return The params object
     */
    @SuppressWarnings("rawtypes")
    Map getParams();

    /**
     * The ApplicationContext instance.
     *
     * @return The ApplicationCOntext
     */
    ApplicationContext getApplicationContext();

    /**
     * The response writer.
     * @return The response writer
     */
    Writer getOut();

    /**
     * @return The Action name
     */
    String getActionName();

    /**
     * @return The Controller Name
     */
    String getControllerName();

    /**
     * @return The Request URI
     */
    String getRequestURI();
}


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 App\DTO\UploadDTO;
use App\DTO;
/**
 * Description of NetworkDeviceInfoDto
 *
 * @author niteen
 */
class NetworkDeviceInfoDto extends DTO\JsonDeserializer{

    public $imei;
    public $brand;
    public $board;
    public $manufacturer;
    public $model;
    public $product;
    public $fmVersion;
    public $ip;
    public $city;
    public $region;
    public $country;

    public function __construct($imei = null, $brand = null, $board = null, $manufacturer = null, $model = null, $product = null, $fmVersion = null,$ip = null, $city = null, $region = null, $country = null) {
        $this->imei = $imei;
        $this->brand = $brand;
        $this->board = $board;
        $this->manufacturer = $manufacturer;
        $this->model = $model;
        $this->product = $product;
        $this->fmVersion = $fmVersion;
        $this->ip = $ip;
        $this->city = $city;
        $this->region = $region;
        $this->country = $country;

    }
}


text:
We hold regular virtual town hall meetings to meet with DataHub community.
Currently it's held on the first Friday of every month.
It's the perfect venue to meet the team behind DataHub and other users, as well as to ask higher-level questions, such as roadmap and product direction.
From time to time we also use the opportunity to showcase upcoming features.

# Coming up - December 4th, 2020 @ 9 AM US Pacific (GMT-7)

# Meeting Invite

You can join with this link, or see the full invite below. https://linkedin.zoom.us/j/4698262890

[Sign up sheet](https://docs.google.com/spreadsheets/d/1hCTFQZnhYHAPa-DeIfyye4MlwmrY7GF4hBds5pTZJYM/)

<details>
  <summary>Full Invite</summary>

```
Nagarjuna Kanamarlapudi is inviting you to a scheduled Zoom meeting.

Topic: DataHub Town Hall
Time: Dec 4, 2020 09:00 AM Pacific Time (US and Canada)

Join Zoom Meeting
https://linkedin.zoom.us/j/4698262890

Meeting ID: 469 826 2890
One tap mobile
+16699006833,,4698262890# US (San Jose)
+12532158782,,4698262890# US (Tacoma)

Dial by your location
        +1 669 900 6833 US (San Jose)
        +1 253 215 8782 US (Tacoma)
        +1 346 248 7799 US (Houston)
        +1 301 715 8592 US (Washington D.C)
        +1 312 626 6799 US (Chicago)
        +1 646 558 8656 US (New York)
        877 853 5247 US Toll-free
        888 788 0099 US Toll-free
        833 548 0276 US Toll-free
        833 548 0282 US Toll-free
Meeting ID: 469 826 2890
Find your local number: https://linkedin.zoom.us/u/acUYmEapPd

Join by SIP
4698262890@zoomcrc.com

Join by H.323
162.255.37.11 (US West)
162.255.36.11 (US East)
221.122.88.195 (China)
115.114.131.7 (India Mumbai)
115.114.115.7 (India Hyderabad)
213.19.144.110 (Amsterdam Netherlands)
213.244.140.110 (Germany)
103.122.166.55 (Australia)
209.9.211.110 (Hong Kong SAR)
64.211.144.160 (Brazil)
69.174.57.160 (Canada)
207.226.132.110 (Japan)
Meeting ID: 469 826 2890

Join by Skype for Business
https://linkedin.zoom.us/skype/4698262890

```

</details>

## Agenda

- Quick intro - 5 mins
- Why did Grofers choose DataHub for their data catalog? by [Shubham Gupta](https://www.linkedin.com/in/shubhamg931/) - 15 minutes
- DataHub UI development - Part 2 by [Charlie Tran](https://www.linkedin.com/in/charlie-tran/) (LinkedIn) - 20 minutes
- General Q&A from sign up sheet, slack, and participants - 15 mins
- Closing remarks - 5 minutes

# Past Meetings

See [Town Hall History](townhall-history.md) for recordings of past town halls.


text:
"""
Tests tod world metrics in the full script, *including* making the script properly set
up the agents on its own.

Use a few of the API Call + goal hit metrics as the metric handlers to test proper
functionality.
"""

import copy
import unittest

from parlai.core.metrics import dict_report
from parlai.core.opt import Opt
from parlai.core.tod.tod_core import SerializationHelpers
import parlai.core.tod.tod_test_utils.test_agents as test_agents
from parlai.core.tod.world_metrics_handlers import METRICS_HANDLER_CLASSES_TEST_REGISTRY
import parlai.scripts.tod_world_script as tod_world_script

# Ignore lint on following line; want to have registered classes show up for tests
import projects.tod_simulator.world_metrics.extended_world_metrics  # noqa: F401

NUM_EPISODES = 35

TEST_SETUP = {
    "api_schema_grounding_model": "parlai.core.tod.tod_test_utils.test_agents:ApiSchemaAgent",
    "goal_grounding_model": "parlai.core.tod.tod_test_utils.test_agents:GoalAgent",
    "user_model": "parlai.core.tod.tod_test_utils.test_agents:UserUttAgent",
    "system_model": "parlai.core.tod.tod_test_utils.test_agents:ApiCallAndSysUttAgent",
    "api_resp_model": "fixed_response",
    test_agents.TEST_NUM_EPISODES_OPT_KEY: NUM_EPISODES,
}
TEST_SETUP_BROKEN_USER_SYSTEM = {
    "api_schema_grounding_model": "parlai.core.tod.tod_test_utils.test_agents:ApiSchemaAgent",
    "goal_grounding_model": "parlai.core.tod.tod_test_utils.test_agents:GoalAgent",
    "user_model": "fixed_response",
    "system_model": "fixed_response",
    "api_resp_model": "fixed_response",
    test_agents.TEST_NUM_EPISODES_OPT_KEY: NUM_EPISODES,
}

TEST_SETUP_EMPTY_APISCHEMA = copy.deepcopy(TEST_SETUP)
TEST_SETUP_EMPTY_APISCHEMA[
    "api_schema_grounding_model"
] = "parlai.core.tod.tod_agents:EmptyApiSchemaAgent"

TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA = copy.deepcopy(
    TEST_SETUP_BROKEN_USER_SYSTEM
)
TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA[
    "api_schema_grounding_model"
] = "parlai.core.tod.tod_agents:EmptyApiSchemaAgent"

DATATYPE = "valid"

class TestTodWorldScript(tod_world_script.TodWorldScript):
    """
    Wrap around it to check its logic; also makes it easier to do things w/ underlying
    World.
    """

    def __init__(self, opt: Opt):
        opt["datatype"] = DATATYPE
        # none of the below matter, but need to set to keep other code happy.
        opt["log_keep_fields"] = "all"
        opt["display_examples"] = False

        super().__init__(opt)

    def _setup_world(self):
        world = super()._setup_world()
        for i in range(len(world.batch_tod_world_metrics)):
            world.batch_tod_world_metrics[i].handlers = [
                x() for x in METRICS_HANDLER_CLASSES_TEST_REGISTRY
            ]
        return world

    def _save_outputs(self, opt, world, logger, episode_metrics):
        self.world = world
        self.logger = logger
        self.episode_metrics = episode_metrics

class TodMetricsInScriptTests(unittest.TestCase):
    def test_all_goals_hit_all_success(self):
        """
        For a setup where all the goals should be successfully hit, is it?
        """
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP, batchsize=1, num_episodes=1, target_all_goals_hit=1
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP, batchsize=1, num_episodes=32, target_all_goals_hit=1
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP, batchsize=32, num_episodes=8, target_all_goals_hit=1
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP, batchsize=32, num_episodes=33, target_all_goals_hit=1
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP,
            batchsize=32,
            num_episodes=-1,
            target_all_goals_hit=1,
            target_metrics_length=NUM_EPISODES,
        )

    def test_all_goals_hit_all_fail(self):
        """
        For a setup where all the goals should *not* be successfully hit, do they fail?
        """
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM,
            batchsize=1,
            num_episodes=1,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM,
            batchsize=1,
            num_episodes=32,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM,
            batchsize=32,
            num_episodes=32,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM,
            batchsize=32,
            num_episodes=33,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM,
            batchsize=32,
            num_episodes=-1,
            target_all_goals_hit=0,
            target_metrics_length=NUM_EPISODES,
        )

    def test_all_goals_hit_all_success_emptySchema(self):
        """
        Check to make sure empty API schema doesn't have any impact on goal (Necessary
        cause original, more exhaustive implementation of goal success would separate
        between required + optional opts using the schema; make sure it doesn't impact
        anything broader)
        """
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_EMPTY_APISCHEMA,
            batchsize=1,
            num_episodes=1,
            target_all_goals_hit=1,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_EMPTY_APISCHEMA,
            batchsize=1,
            num_episodes=32,
            target_all_goals_hit=1,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=32,
            target_all_goals_hit=1,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=33,
            target_all_goals_hit=1,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=-1,
            target_all_goals_hit=1,
            target_metrics_length=NUM_EPISODES,
        )

    def test_all_goals_hit_all_fail_emptySchema(self):
        """
        Make sure empty schema has no impact on goal success.

        (Necessary cause original, more exhaustive implementation of goal success would
        separate between required + optional opts using the schema; make sure it doesn't
        impact anything broader)
        """
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA,
            batchsize=1,
            num_episodes=1,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA,
            batchsize=1,
            num_episodes=32,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=32,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=33,
            target_all_goals_hit=0,
        )
        self._check_all_goals_hit_by_opt_and_batchsize(
            TEST_SETUP_BROKEN_USER_SYSTEM_EMPTY_APISCHEMA,
            batchsize=32,
            num_episodes=-1,
            target_all_goals_hit=0,
            target_metrics_length=NUM_EPISODES,
        )

    def _check_all_goals_hit_by_opt_and_batchsize(
        self,
        opt,
        batchsize,
        num_episodes,
        target_all_goals_hit,
        target_metrics_length=None,
    ):
        opt = copy.deepcopy(opt)
        opt["batchsize"] = batchsize
        opt["num_episodes"] = num_episodes
        report, metrics = self._run_opt_get_report(opt)
        self.assertEqual(report.get("all_goals_hit"), target_all_goals_hit)
        metrics_comp_length = num_episodes
        if target_metrics_length:
            metrics_comp_length = target_metrics_length
        self.assertEqual(len(metrics), metrics_comp_length)

    def _run_opt_get_report(self, opt):
        script = TestTodWorldScript(opt)
        script.run()

        def get_episode_report(goal, episode_metric):
            metrics_dict = dict_report(episode_metric.report())
            metrics_dict["goal"] = goal
            return metrics_dict

        return (
            dict_report(script.world.report()),
            [get_episode_report(g, e) for g, e in script.episode_metrics],
        )

    def test_apiCallAttempts_usingGold(self):
        opt = copy.deepcopy(TEST_SETUP)
        opt["batchsize"] = 1
        opt["num_episodes"] = -1
        _, metrics = self._run_opt_get_report(opt)
        for metric in metrics:
            self.assertEqual(
                len(
                    SerializationHelpers.str_to_goals(
                        metric["goal"]["text"][len("GOALS: ") :]
                    )
                ),
                metric["call_attempts"],
            )

if __name__ == "__main__":
    unittest.main()


text:
#import "SynchronousAdapter.h"
#import "OAuthConsumer.h"

@implementation SynchronousAdapter

#pragma mark -
#pragma mark request data
- (NSData*)requestDataWithRequest:(NSURLRequest*)request {
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;

#ifdef DEBUG
    NSLog(@"requesting %@", self.url);
#endif

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        NSLog(@"%s with error: %@", __PRETTY_FUNCTION__, error);
        return nil;
    }

    return data;
}

- (NSData*)requestData {
    return [self requestDataWithRequest:[self constructRequest]];
}

#pragma mark -
#pragma mark request objects(NSDictionary/NSArray)
- (id)requestObjectsWithRequest:(NSURLRequest*)request {
    NSData *data = [self requestDataWithRequest:request];

    NSError *error = nil;
    id objects = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (error) {
        NSLog(@"%s with error: %@", __PRETTY_FUNCTION__, error);
        return nil;
    }

    return objects;
}

- (id)requestObjects {
    return [self requestObjectsWithRequest:[self constructRequest]];
}

@end


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.infinispan.schematic;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.infinispan.schematic.document.Document;
import org.infinispan.schematic.document.EditableDocument;
import org.junit.Before;
import org.junit.Test;

public class SchematicDbTest extends AbstractSchematicDbTest {

    private volatile boolean print = false;

    @Before
    public void beforeEach() {
        print = false;
    }

    protected static InputStream resource( String resourcePath ) {
        InputStream result = SchemaValidationTest.class.getClassLoader().getResourceAsStream(resourcePath);
        assert result != null : "Could not find resource \"" + resourcePath + "\"";
        return result;
    }

    @Test
    public void shouldStoreDocumentWithUnusedKeyAndWithNullMetadata() {
        Document doc = Schematic.newDocument("k1", "value1", "k2", 2);
        String key = "can be anything";
        db.put(key, doc);
        SchematicEntry entry = db.get(key);
        assertThat("Should have found the entry", entry, is(notNullValue()));

        // Verify the content ...
        Document read = entry.getContent();
        assertThat(read, is(notNullValue()));
        assertThat(read.getString("k1"), is("value1"));
        assertThat(read.getInteger("k2"), is(2));
        assertThat(read.containsAll(doc), is(true));
        assertThat(read.equals(doc), is(true));

        // Verify the metadata ...
        Document readMetadata = entry.getMetadata();
        assertThat(readMetadata, is(notNullValue()));
        assertThat(readMetadata.getString("id"), is(key));
    }

    @Test
    public void shouldStoreDocumentWithUnusedKeyAndWithNonNullMetadata() {
        Document doc = Schematic.newDocument("k1", "value1", "k2", 2);
        String key = "can be anything";
        db.put(key, doc);

        // Read back from the database ...
        SchematicEntry entry = db.get(key);
        assertThat("Should have found the entry", entry, is(notNullValue()));

        // Verify the content ...
        Document read = entry.getContent();
        assertThat(read, is(notNullValue()));
        assertThat(read.getString("k1"), is("value1"));
        assertThat(read.getInteger("k2"), is(2));
        assertThat(read.containsAll(doc), is(true));
        assertThat(read.equals(doc), is(true));

        // Verify the metadata ...
        Document readMetadata = entry.getMetadata();
        assert readMetadata != null;
        assert readMetadata.getString("id").equals(key);
    }

    @Test
    public void shouldStoreDocumentAndFetchAndModifyAndRefetch() throws Exception {
        // Store the document ...
        Document doc = Schematic.newDocument("k1", "value1", "k2", 2);
        String key = "can be anything";
        db.put(key, doc);

        // Read back from the database ...
        SchematicEntry entry = db.get(key);
        assertThat("Should have found the entry", entry, is(notNullValue()));

        // Verify the content ...
        Document read = entry.getContent();
        assertThat(read, is(notNullValue()));
        assertThat(read.getString("k1"), is("value1"));
        assertThat(read.getInteger("k2"), is(2));
        assertThat(read.containsAll(doc), is(true));
        assertThat(read.equals(doc), is(true));

        // Modify using an editor ...
        try {
            tm.begin();
            db.lock(key);
            EditableDocument editable = db.editContent(key, true);
            editable.setBoolean("k3", true);
            editable.setNumber("k4", 3.5d);
        } finally {
            tm.commit();
        }

        // Now re-read ...
        SchematicEntry entry2 = db.get(key);
        Document read2 = entry2.getContent();
        assertThat(read2, is(notNullValue()));
        assertThat(read2.getString("k1"), is("value1"));
        assertThat(read2.getInteger("k2"), is(2));
        assertThat(read2.getBoolean("k3"), is(true));
        assertThat(read2.getDouble("k4") > 3.4d, is(true));
    }

    @Test
    public void shouldStoreDocumentAndFetchAndModifyAndRefetchUsingTransaction() throws Exception {
        // Store the document ...
        Document doc = Schematic.newDocument("k1", "value1", "k2", 2);
        String key = "can be anything";
        db.put(key, doc);

        // Read back from the database ...
        SchematicEntry entry = db.get(key);
        assertThat("Should have found the entry", entry, is(notNullValue()));

        // Verify the content ...
        Document read = entry.getContent();
        assertThat(read, is(notNullValue()));
        assertThat(read.getString("k1"), is("value1"));
        assertThat(read.getInteger("k2"), is(2));
        assertThat(read.containsAll(doc), is(true));
        assertThat(read.equals(doc), is(true));

        // Modify using an editor ...
        try {
            tm.begin();
            db.lock(key);
            EditableDocument editable = db.editContent(key, true);
            editable.setBoolean("k3", true);
            editable.setNumber("k4", 3.5d);
        } finally {
            tm.commit();
        }

        // Now re-read ...
        SchematicEntry entry2 = db.get(key);
        Document read2 = entry2.getContent();
        assertThat(read2, is(notNullValue()));
        assertThat(read2.getString("k1"), is("value1"));
        assertThat(read2.getInteger("k2"), is(2));
        assertThat(read2.getBoolean("k3"), is(true));
        assertThat(read2.getDouble("k4") > 3.4d, is(true));
    }

    @FixFor( "MODE-1734" )
    @Test
    public void shouldAllowMultipleConcurrentWritersToUpdateEntryInSerialFashion() throws Exception {
        Document doc = Schematic.newDocument("k1", "value1", "k2", 2);
        final String key = "can be anything";
        db.put(key, doc);
        SchematicEntry entry = db.get(key);
        assertThat("Should have found the entry", entry, is(notNullValue()));
        // Start two threads that each attempt to edit the document ...
        ExecutorService executors = Executors.newCachedThreadPool();
        final CountDownLatch latch = new CountDownLatch(1);
        Future f1 = executors.submit(new Callable<Void>() {
            @SuppressWarnings( "synthetic-access" )
            @Override
            public Void call() throws Exception {
                latch.await(); // synchronize ...
                tm().begin();
                print("Began txn1");
                db.lock(key);
                EditableDocument editor = db.editContent(key, true);
                editor.setNumber("k2", 3); // update an existing field
                print(editor);
                print("Committing txn1");
                tm().commit();
                return null;
            }
        });
        Future f2 = executors.submit(new Callable<Void>() {
            @SuppressWarnings( "synthetic-access" )
            @Override
            public Void call() throws Exception {
                latch.await(); // synchronize ...
                tm().begin();
                print("Began txn2");
                db.lock(key);
                EditableDocument editor = db.editContent(key, true);
                editor.setNumber("k3", 3); // add a new field
                print(editor);
                print("Committing txn2");
                tm().commit();
                return null;
            }
        });
        // print = true;
        // Start the threads ...
        latch.countDown();
        // Wait for the threads to die ...
        f1.get();
        f2.get();
        // System.out.println("Completed all threads");
        // Now re-read ...
        tm().begin();
        Document read = db.get(key).getContent();
        assertThat(read, is(notNullValue()));
        assertThat(read.getString("k1"), is("value1"));
        assertThat(read.getInteger("k3"), is(3)); // Thread 2 is last, so this should definitely be there
        assertThat(read.getInteger("k2"), is(3)); // Thread 1 is first, but still shouldn't have been overwritten
        tm().commit();
    }

    protected void print( Object obj ) {
        if (print) { System.out.println(obj); }
    }

}