text:
<?php
/**
 * This file belongs to the AnoynmFramework
 *
 * @author vahitserifsaglam <vahit.serif119@gmail.com>
 * @see http://gemframework.com
 *
 * Thanks for using
 */

namespace Anonym\Support;

use Anonym\Application\ServiceProvider;
use Anonym\Facades\ErrorBag;
use Anonym\Facades\View;

/**
 * Class ErrorbagServiceProvider
 * @package Anonym\Support
 */
class ErrorbagServiceProvider extends ServiceProvider
{

    /**
     *  register error composer
     */
    public function register(){
        View::composer('*', ErrorBag::getErrors());
    }

}

redpajama_set_name: RedPajamaGithub


text:
import os.path as osp
import tempfile
import unittest.mock as mock
from collections import OrderedDict
from unittest.mock import MagicMock, patch

import pytest
import torch
import torch.nn as nn
from mmcv.runner import EpochBasedRunner, build_optimizer
from mmcv.utils import get_logger
from torch.utils.data import DataLoader, Dataset

from mmdet.core import DistEvalHook, EvalHook

class ExampleDataset(Dataset):

    def __init__(self):
        self.index = 0
        self.eval_result = [0.1, 0.4, 0.3, 0.7, 0.2, 0.05, 0.4, 0.6]

    def __getitem__(self, idx):
        results = dict(imgs=torch.tensor([1]))
        return results

    def __len__(self):
        return 1

    @mock.create_autospec
    def evaluate(self, results, logger=None):
        pass

class EvalDataset(ExampleDataset):

    def evaluate(self, results, logger=None):
        mean_ap = self.eval_result[self.index]
        output = OrderedDict(mAP=mean_ap, index=self.index, score=mean_ap)
        self.index += 1
        return output

class ExampleModel(nn.Module):

    def __init__(self):
        super().__init__()
        self.conv = nn.Linear(1, 1)
        self.test_cfg = None

    def forward(self, imgs, rescale=False, return_loss=False):
        return imgs

    def train_step(self, data_batch, optimizer, **kwargs):
        outputs = {
            'loss': 0.5,
            'log_vars': {
                'accuracy': 0.98
            },
            'num_samples': 1
        }
        return outputs

@pytest.mark.skipif(
    not torch.cuda.is_available(), reason='requires CUDA support')
@patch('mmdet.apis.single_gpu_test', MagicMock)
@patch('mmdet.apis.multi_gpu_test', MagicMock)
@pytest.mark.parametrize('EvalHookCls', (EvalHook, DistEvalHook))
def test_eval_hook(EvalHookCls):
    with pytest.raises(TypeError):
        # dataloader must be a pytorch DataLoader
        test_dataset = ExampleDataset()
        data_loader = [
            DataLoader(
                test_dataset,
                batch_size=1,
                sampler=None,
                num_worker=0,
                shuffle=False)
        ]
        EvalHookCls(data_loader)

    with pytest.raises(KeyError):
        # rule must be in keys of rule_map
        test_dataset = ExampleDataset()
        data_loader = DataLoader(
            test_dataset,
            batch_size=1,
            sampler=None,
            num_workers=0,
            shuffle=False)
        EvalHookCls(data_loader, save_best='auto', rule='unsupport')

    with pytest.raises(ValueError):
        # key_indicator must be valid when rule_map is None
        test_dataset = ExampleDataset()
        data_loader = DataLoader(
            test_dataset,
            batch_size=1,
            sampler=None,
            num_workers=0,
            shuffle=False)
        EvalHookCls(data_loader, save_best='unsupport')

    optimizer_cfg = dict(
        type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)

    test_dataset = ExampleDataset()
    loader = DataLoader(test_dataset, batch_size=1)
    model = ExampleModel()
    optimizer = build_optimizer(model, optimizer_cfg)

    data_loader = DataLoader(test_dataset, batch_size=1)
    eval_hook = EvalHookCls(data_loader, save_best=None)
    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 1)
        assert runner.meta is None or 'best_score' not in runner.meta[
            'hook_msgs']
        assert runner.meta is None or 'best_ckpt' not in runner.meta[
            'hook_msgs']

    # when `save_best` is set to 'auto', first metric will be used.
    loader = DataLoader(EvalDataset(), batch_size=1)
    model = ExampleModel()
    data_loader = DataLoader(EvalDataset(), batch_size=1)
    eval_hook = EvalHookCls(data_loader, interval=1, save_best='auto')

    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 8)

        real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.7

    loader = DataLoader(EvalDataset(), batch_size=1)
    model = ExampleModel()
    data_loader = DataLoader(EvalDataset(), batch_size=1)
    eval_hook = EvalHookCls(data_loader, interval=1, save_best='mAP')

    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 8)

        real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.7

    data_loader = DataLoader(EvalDataset(), batch_size=1)
    eval_hook = EvalHookCls(
        data_loader, interval=1, save_best='score', rule='greater')
    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 8)

        real_path = osp.join(tmpdir, 'best_score_epoch_4.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.7

    data_loader = DataLoader(EvalDataset(), batch_size=1)
    eval_hook = EvalHookCls(data_loader, save_best='mAP', rule='less')
    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 8)

        real_path = osp.join(tmpdir, 'best_mAP_epoch_6.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.05

    data_loader = DataLoader(EvalDataset(), batch_size=1)
    eval_hook = EvalHookCls(data_loader, save_best='mAP')
    with tempfile.TemporaryDirectory() as tmpdir:
        logger = get_logger('test_eval')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.run([loader], [('train', 1)], 2)

        real_path = osp.join(tmpdir, 'best_mAP_epoch_2.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.4

        resume_from = osp.join(tmpdir, 'latest.pth')
        loader = DataLoader(ExampleDataset(), batch_size=1)
        eval_hook = EvalHookCls(data_loader, save_best='mAP')
        runner = EpochBasedRunner(
            model=model,
            batch_processor=None,
            optimizer=optimizer,
            work_dir=tmpdir,
            logger=logger)
        runner.register_checkpoint_hook(dict(interval=1))
        runner.register_hook(eval_hook)
        runner.resume(resume_from)
        runner.run([loader], [('train', 1)], 8)

        real_path = osp.join(tmpdir, 'best_mAP_epoch_4.pth')

        assert runner.meta['hook_msgs']['best_ckpt'] == osp.realpath(real_path)
        assert runner.meta['hook_msgs']['best_score'] == 0.7


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(1);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	/***Inverted Index Application to index, sort and search words in a string***/

	const indexApp = angular.module('invertedIndex', []);

	indexApp.controller('rootAppController', ['$scope', ($scope) => {

	  const InvertedIndex = __webpack_require__(2);
	  const invertedIndex = new InvertedIndex();

	  // Define a template Document for the Inverted Index Landing Page
	  $scope.columns = [];
	  $scope.terms = [];
	  $scope.allContent = {};
	  $scope.storyTitle = [];
	  $scope.storyContent = [];
	  $scope.storyIndex = 0;
	  $scope.bookNames = [];
	  $scope.books = {};
	  $scope.fileSelected = true;

	  /**
	   * Method to create index.
	   * @Param {string}
	   * @returns {}
	   */

	  $scope.uploadFile = (url) => {

	    const uploadedFile = document.getElementById('filePath').files[0];

	    if ((!uploadedFile) && ($.trim(url) === '')) {
	      $scope.selectEmptyMsg = true;
	      return false;
	    }

	    $scope.selectEmptyMsg = false;
	    if (!uploadedFile && ($.trim(url) !== '')) {
	      const httpRequest = new XMLHttpRequest();

	      // Make a promise to send the http get request
	      const promise = new Promise((resolve, reject) => {

	        // Make sure the request object was created for modern browsers
	        if (httpRequest) {
	          httpRequest.onreadystatechange = alertContents;
	          httpRequest.open('GET', url);
	          httpRequest.send();
	        } else {
	          reject('Browser Not Supported');
	        }

	        // function to handle the promise
	        function alertContents() {
	          if (httpRequest.readyState === XMLHttpRequest.DONE) {
	            if (httpRequest.status === 200) {
	              resolve(JSON.parse(httpRequest.responseText));
	            } else {
	              reject('There was an error resolving url');
	            }
	          }
	        }
	      });

	      promise.then((response) => {
	        resolveData(response, url);
	      })
	        .catch((err) => {
	          showErr(err);
	        });
	    } else {
	      // Ensure a valid file is selected and is has a '.json' extension
	      const fileExt = uploadedFile.name
	        .substring(uploadedFile.name.length - 5, uploadedFile.name.length);

	      if ((fileExt !== '.json') && (fileExt !== '.JSON') && ($.trim(url) === '')) {
	        showErr('Please select a valid json file');
	        return false;
	      }
	      const reader = new FileReader();
	      reader.readAsText(uploadedFile);

	      const promise = new Promise((resolve, reject) => {
	        reader.onload = ((e) => {
	          if (e.target.result) {
	            try {
	              if (JSON.parse(e.target.result)) {
	                resolve(JSON.parse(e.target.result));
	              }
	            } catch (e) {
	              reject('Invalid JSON file');
	            }
	          } else {
	            reject('Invalid File Selected');
	          }
	        });
	      });

	      promise.then((response) => {
	        resolveData(response, uploadedFile.name);
	      })
	        .catch((err) => {
	          showErr(err);
	        });
	    }
	  };

	  /**
	   * function to display error for 8 seconds
	   * @param {string} error message
	   */

	  showErr = (errMsg) => {
	    setTimeout(() => {
	      $scope.errExist = false;
	      $scope.errMsg = '';
	      $scope.$apply();
	    }, 5000);
	    $scope.errMsg = errMsg;
	    $scope.errExist = true;
	    $scope.$apply();
	    return false;
	  };

	  /**
	   *  Method to resolve response from the Inverted index function
	   *  @param {object}
	   *  @returns {}
	   */
	  resolveData = (responseData, responseDataName) => {
	    document.getElementById('uploadJsonForm').reset();
	    if (Object.keys(responseData).length <= 0) {
	      showErr('error! cannot upload empty file');
	      return false;
	    }
	    if (!Array.isArray(responseData)) {
	      if (Object.keys(responseData).length !== 2) {
	        showErr('error! file must have only title and content keys');
	        return false;
	      }
	    } else {
	      const bookLength = responseData.length;
	      for (let i = 0; i < bookLength; i++) {
	        if (Object.keys(responseData[i]).length !== 2) {
	          showErr('error! each file must have only title and content keys');
	          return false;
	        }
	      }
	    }
	    $scope.books[responseDataName] = responseData;
	    $scope.bookNames = Object.keys($scope.books);
	    $scope.numberOfTitles = responseData.length;
	    $scope.validBook = true;
	    $scope.$apply();
	  };

	  $scope.setBook = (name) => {
	    $('.list-group-item').not(':first').css('background-color', 'white');
	    document.getElementById(name).style.backgroundColor = 'lightgray';
	    $scope.fileToRead = name;
	  };

	  $scope.createIndex = () => {
	    if (!$scope.fileToRead) {
	      $scope.fileSelected = false;
	      return false;
	    }
	    $scope.fileSelected = true;
	    const filename = $scope.fileToRead;
	    const thisBook = $scope.books[filename];
	    const bookIndex = invertedIndex.createIndex(thisBook);

	    if (!bookIndex) {
	      // Delete the object from the books object.
	      delete $scope.books[filename];
	      $scope.bookNames.splice($scope.bookNames.indexOf(filename), 1);
	      showErr('Error! ensure your json file has a title key and a content key');
	      return false;
	    }

	    $scope.storyTitle = invertedIndex.getStory().titles;
	    $scope.storyContent = invertedIndex.getStory().stories;
	    $scope.getIndex();
	  };

	  /**
	   * Method to get the index of the object
	   * @param {object}
	   * @returns {}
	   */
	  $scope.getIndex = () => {
	    const wordsIndex = invertedIndex.getIndex();
	    if (!wordsIndex) {
	      showErr('Error! no file uploaded!');
	      return false;
	    }
	    $scope.allContent = InvertedIndex.mergeObjects($scope.allContent, wordsIndex);
	    $scope.terms = Object.keys(wordsIndex);
	    $scope.storeTerms = $scope.terms;
	    for (let term of $scope.terms) {
	      $scope.columns = $scope.columns.concat(wordsIndex[term]);
	    }
	    $scope.columns = InvertedIndex.generateUniqueArray($scope.columns);
	    $scope.storeColumns = $scope.columns;
	  };

	  /**
	   * Method to change the story being displayed when user clicks next button
	   * @params {}
	   * @returns {}
	   */

	  $scope.changeStory = (currentStoryIndex) => {
	    $scope.storyIndex = currentStoryIndex;
	  };

	  $scope.nextPrev = function(value) {
	    if (value === 'next') {
	      if ($scope.storyIndex === $scope.storyTitle.length - 1) {
	        return false;
	      }
	      $scope.storyIndex++;
	    } else {
	      if ($scope.storyIndex === 0) {
	        return false;
	      }
	      $scope.storyIndex--;
	    }
	  };

	  /**
	   * Method to compare the selected word in the array of words and check the
	   * story title column where it belongs
	   * @param {string} {integer}
	   * @returns {}
	   */
	  $scope.checkThis = (word, columnIndex) => {
	    $scope.count = 0;
	    try {
	      if ($scope.allContent[word].indexOf(columnIndex) !== -1) {
	        $scope.count += 1;
	      }
	    } catch (e) {
	      // Fail silently
	    }
	  };

	  /**
	   * Method to search for a given keyword
	   * @param {string : number}
	   * @returns {}
	   */
	  $scope.searchWord = (keyword, criteria) => {
	    $scope.searchState = false;
	    if (Object.keys($scope.allContent).length === 0) {
	      return false;
	    }

	    let searchTerm = keyword.toLowerCase();

	    $scope.terms = InvertedIndex.generateUniqueArray(searchTerm.split(' '));

	    let i = searchTerm.split(' ').length; //get the length of the search field and set the searchterm to the last item.
	    searchTerm = searchTerm.split(' ')[i - 1];

	    const searchQuery = invertedIndex.searchIndex(searchTerm, criteria);
	    if (searchQuery) {
	      $scope.status = 'Found';
	      $scope.searchState = true;
	    } else {
	      $scope.status = 'Not Found';
	    }

	    $scope.exists = false;
	    if ($.trim(keyword) === '') {
	      $scope.status = '';
	      $scope.terms = $scope.storeTerms;
	    }
	  };

	  /**
	   * Checks the searchKeyword and re-adjust column displayed
	   * @param {string}
	   * @returns {}
	   */
	  $scope.changeCriteria = (searchKeyword) => (
	  (searchKeyword) === null ? ($scope.columns = $scope.storeColumns) :
	    `${$scope.columns = []} ${$scope.columns.push(searchKeyword)}`);

	}]);

/***/ },
/* 2 */
/***/ function(module, exports) {

	/** *Inverted Index Application to index, sort and search words in a string***/
	/**
	 * InvertedIndex Class.
	 */
	class InvertedIndex {

	  /**
	   *  @constructor
	   */
	  constructor() {
	    this.stories = [];
	    this.titles = [];
	    this.indexes = {};
	    this.searchResult = {};
	    this.bookIndex = {};
	  }

	  /**
	    * Creates an Index of the file at the path specified
	    * @param {string} book
	    * @returns {boolean} true if index is created and false otherwise
	    */
	  createIndex(book) {
	    // Check if the data is a single json object(one content) and resolve
	    if (!Array.isArray(book)) {
	      const bookTitle = book[Object.keys(book)[0]],
	        bookContent = book[Object.keys(book)[1]];
	      this.bookIndex = this.generateObject(bookTitle, bookContent);
	    } else {
	      const dataLength = book.length;
	      for (let i = 0; i < dataLength; i += 1) {
	        const bookTitle = book[i][Object.keys(book[i])[0]],
	          bookContent = book[i][Object.keys(book[i])[1]];
	        this.bookIndex = this.generateObject(bookTitle, bookContent);
	      }
	    }
	    if (!this.bookIndex) {
	      this.bookIndex = {};
	      return false;
	    }
	    this.indexes = InvertedIndex.mergeObjects(this.indexes, this.bookIndex);
	    return true;
	  }

	  /**
	   * Method to generate an object for each text in the specified array arguments.
	   * @param {array} bookTitle
	   * @param {array} bookContent
	   * @returns {object} indexed words object.
	   */
	  generateObject(bookTitle, bookContent) {
	    if (bookTitle.trim().length === 0 || bookContent.trim().length === 0) {
	      return false;
	    }

	    let wordsInText = `${bookTitle} ${bookContent}`;
	    wordsInText = InvertedIndex.generateUniqueArray(InvertedIndex.filter(wordsInText));
	    if (!wordsInText) {
	      return false;
	    }

	    this.titles.push(bookTitle);
	    this.stories.push(bookContent);
	    wordsInText.forEach((word) => {
	      if (this.bookIndex[word]) {
	        this.bookIndex[word] = this.bookIndex[word].concat([bookTitle]);
	      } else {
	        this.bookIndex[word] = [bookTitle];
	      }
	    });

	    return this.bookIndex;
	  }

	  /**
	    * Method to filter out special characters and create a string out of the words specified
	    * @param {string} words
	    * @returns {array} filtered array
	    */
	  static filter(words) {
	    if ((typeof words) !== 'string') {
	      return false;
	    }

	    const filtered = words.replace(/[.,\/#!$£%\^&\*;:'{}=\-_`~()]/g, '')
	      .toLowerCase();

	    if (filtered.trim().length > 0) {
	      return filtered.split(' ');
	    }
	  }

	  /**
	  * Method to merge two objects.
	  * @param {object} input1 destination object to be merged into
	  * @param {object} input2 source object to merge into input1.
	  * @returns {object} merged object containing the two object arguments.
	  */
	  static mergeObjects(input1, input2) {
	    if ((typeof input1 !== 'object') || (typeof input2 !== 'object')) {
	      return false;
	    }
	    const makeUnique = InvertedIndex.generateUniqueArray;
	    Object.keys(input2).forEach((key) => {
	      if (input1[key]) {
	        input1[key] = makeUnique(input1[key].concat(input2[key]));
	      } else {
	        input1[key] = input2[key];
	      }
	    });
	    return input1;
	  }

	  /**
	    * Method to generate unique array items from the array specified.
	    * @param {array} item an array item.
	    * @returns {array} array of unique words
	    */
	  static generateUniqueArray(item) {
	    if (!Array.isArray(item)) {
	      return false;
	    }
	    const uniqueArray = [];
	    item.forEach((value) => {
	      const index = uniqueArray.indexOf(value);
	      if (index === -1) {
	        uniqueArray.push(value);
	      }
	    });
	    return uniqueArray;
	  }

	  /**
	    * getStory method to return an array of titles and corresponding stories
	    * @returns {object} object containing the titles and stories of the book
	    */
	  getStory() {
	    return {
	      titles: InvertedIndex.generateUniqueArray(this.titles),
	      stories: this.stories,
	    };
	  }

	  /**
	   * getIndex Method to get the index of an element
	   * @returns {object} object of the indexes created for the book file.
	   */
	  getIndex() {
	    // Check if an index has been created
	    if (!Object.keys(this.indexes)[0]) {
	      return false;
	    }

	    return this.indexes;
	  }

	  /**
	   * searchIndex method to search for index
	   * @param {string} term term to be searched for.
	   * @param {string} criteria a particular title to search in.
	   * @returns {object} object containing the term and array of index of titles where it appears.
	   */
	  searchIndex(term, criteria = null) {
	    const docPosition = [];
	    this.searchResult = {};
	    if (this.indexes[term]) {
	      if ((criteria === null) || (criteria === undefined)) {
	        this.indexes[term].forEach((title) => {
	          docPosition.push(this.titles.indexOf(title));
	        });
	        this.searchResult[term] = docPosition;
	        return this.searchResult;
	      } else if (this.indexes[term].indexOf(criteria) !== -1) {
	        docPosition.push(this.indexes[term].indexOf(criteria));
	        this.searchResult[term] = docPosition;
	        return this.searchResult;
	      }
	    } else {
	      return false;
	    }
	  }
	}
	module.exports = InvertedIndex;

/***/ }
/******/ ]);


text:
#include "tensorflow/tools/graph_transforms/fold_constants_lib.h"

#include "tensorflow/core/common_runtime/constant_folding.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"

namespace tensorflow {
namespace graph_transforms {

// Clears the device field of all ops in the graph.
Status InsertLogging(const GraphDef& input_graph_def,
                     const TransformFuncContext& context,
                     GraphDef* output_graph_def) {
  std::unordered_set<string> ops;
  bool has_ops;
  if (context.params.count("op")) {
    has_ops = true;
    for (const string& op : context.params.at("op")) {
      ops.insert(op);
    }
  } else {
    has_ops = false;
  }

  std::unordered_set<string> prefixes;
  bool has_prefixes;
  if (context.params.count("prefix")) {
    has_prefixes = true;
    for (const string& prefix : context.params.at("prefix")) {
      prefixes.insert(prefix);
    }
  } else {
    has_prefixes = false;
  }

  string message;
  TF_RETURN_IF_ERROR(context.GetOneStringParameter("message", "", &message));

  bool show_name;
  TF_RETURN_IF_ERROR(
      context.GetOneBoolParameter("show_name", false, &show_name));

  bool show_op;
  TF_RETURN_IF_ERROR(context.GetOneBoolParameter("show_op", false, &show_op));

  int32 first_n;
  TF_RETURN_IF_ERROR(context.GetOneInt32Parameter("first_n", -1, &first_n));

  int32 summarize;
  TF_RETURN_IF_ERROR(
      context.GetOneInt32Parameter("summarize", 1024, &summarize));

  std::unordered_map<string, std::set<int>> node_outputs;
  for (const NodeDef& node : input_graph_def.node()) {
    for (const string& input : node.input()) {
      const string canonical_input = CanonicalInputName(input);
      string prefix;
      string name;
      string suffix;
      NodeNamePartsFromInput(canonical_input, &prefix, &name, &suffix);
      const string output_index_string = suffix.substr(1, suffix.size() - 1);
      int32 output_index;
      if (!strings::safe_strto32(output_index_string, &output_index)) {
        return errors::InvalidArgument("Couldn't understand output number in ",
                                       input);
      }
      node_outputs[name].insert(output_index);
    }
  }

  std::map<string, string> inputs_to_rename;
  std::unordered_set<string> ignore_when_renaming;
  GraphDef logged_graph_def;
  for (const NodeDef& node : input_graph_def.node()) {
    NodeDef* new_node = logged_graph_def.mutable_node()->Add();
    new_node->CopyFrom(node);
    if (node_outputs[node.name()].empty()) {
      // There were no outputs found to this node, so skip it.
      continue;
    }
    const bool op_matches = (ops.count(node.op()) > 0);
    bool prefix_matches = false;
    for (const string& prefix : prefixes) {
      if (StringPiece(node.name()).starts_with(prefix)) {
        prefix_matches = true;
      }
    }
    // If we're not looking for ops, or we found the right op, and if we're not
    // looking for prefixes or we found the right prefix, then add logging here.
    if ((!has_ops || op_matches) && (!has_prefixes || prefix_matches)) {
      const string name_suffix = "__print__";
      DataTypeVector input_types;
      DataTypeVector output_types;
      TF_RETURN_IF_ERROR(GetInOutTypes(node, &input_types, &output_types));
      NodeDef* print_node = logged_graph_def.mutable_node()->Add();
      print_node->set_op("Print");
      print_node->set_name(strings::StrCat(node.name(), name_suffix));
      string node_message;
      if (show_op) {
        node_message += ";" + node.op() + ";";
      }
      if (show_name) {
        node_message += ";" + print_node->name() + ";";
      }
      node_message += message;
      SetNodeAttr("message", node_message, print_node);
      SetNodeAttr("first_n", first_n, print_node);
      SetNodeAttr("summarize", summarize, print_node);
      print_node->add_input(node.name() + ":0");
      SetNodeAttr("T", output_types[0], print_node);
      for (int output_index : node_outputs[node.name()]) {
        print_node->add_input(strings::StrCat(node.name(), ":", output_index));
      }
      SetNodeAttr("U", output_types, print_node);
      ignore_when_renaming.insert(print_node->name());
      // Rewrite the graph so all references to the first input of the original
      // op now pull from the print op instead, so it's executed.
      inputs_to_rename[node.name() + ":0"] =
          strings::StrCat(node.name(), name_suffix, ":0");
    }
  }

  output_graph_def->Clear();
  RenameNodeInputs(logged_graph_def, inputs_to_rename, ignore_when_renaming,
                   output_graph_def);

  return Status::OK();
}

REGISTER_GRAPH_TRANSFORM("insert_logging", InsertLogging);

}  // namespace graph_transforms
}  // namespace tensorflow


text:
<!--
Copyright 2016 Goldman Sachs.
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.
-->
<FlatFileParserConfig
        delimiter="	"
        inflatedObject="com.gs.fw.para.domain.guyocedep.implementation.PonuzeyuYotuqociqajaYofEvazeXaja"
        columns="42"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../xsd/parserconfig.xsd">
	<Header required="false"/>
	<Trailer required="false"/>

    <Mapping attribute="fufIraVaz"                      position="2"     trim="true" nullable="true"/>
    <Mapping attribute="mudegIdof"                      position="6"     trim="true" nullable="true"/>
    <Mapping attribute="lomoh"                          position="7"     trim="true" nullable="true"/>
    <Mapping attribute="qiKelAmut"                      position="14"    format="kufuXEri" trim="true" nullable="true"/>
    <Mapping attribute="bumewaSira"                     position="15"    format="kufuXEri" trim="true" nullable="true"/>
    <Mapping attribute="wutirijIwom"                    position="16"    format="kufuXEri" trim="true" nullable="true"/>
    <Mapping attribute="capirizIdefufiy"                position="18"    trim="true" nullable="true"/>
    <Mapping attribute="bumitom"                        position="19"    trim="true" nullable="true"/>
    <Mapping attribute="nihurePimopoxo"                 position="25"    format="kufuXEri" trim="true" nullable="true"/>

    <FixedValue attribute="source" value="XEZE"/>
    <FixedValue attribute="zupuhAliKafu" value="T"/>
</FlatFileParserConfig>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Foodroach - free food</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

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

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                     Food Roach

                        About

                        Download

                        Contact

In a hurry? Need food now?

FoodRoach crawls through the web to find you
free food!!

About FoodRoach

Android Demo

Download FoodRoach

You can download FoodRoach for free on the Play Store for Android.

                    Download

Technology behind FoodRoach

Contact FoodRoach

Feel free to email us to thank us for the great service we provide you!!

thankyou@foodroach.com

                         Twitter

                         Github

                         Google+

Copyright © Foodroach 2015


text:
import React from 'react';
import Link from 'gatsby-link';

import BlogCard from '../components/cards/blog-card';
import ProjectCard from '../components/cards/project-card';
import * as constants from '../util/constants';

const IndexPage = ({data}) => {
  const pages = data.allMarkdownRemark.edges.map((d) => {
    const id = d.node.id;
    const front = d.node.frontmatter;
    const excerpt = d.node.excerpt;
    switch(front.post_type) {
      case constants.BLOG_TYPE:
        return <BlogCard key={id} frontmatter={front} excerpt={excerpt} />
      case constants.PROJECT_TYPE:
        return <ProjectCard key={id} frontmatter={front} excerpt={excerpt} />
      default:
        return
NO CARD

    }
  });
  return (

Home

Hi There!

Welcome to my website: GhostsAndGlass.com. Here I have all of my current coding projects,
          thoughts, reviews, and rants. I love to code, read, and write, and this site is a tribute
          to all of that. Feel free to contact me via email or
          connect with me on social media.

      {pages}

  );
}

export default IndexPage;

export const postQuery = graphql`
query IndexQurey {
  allMarkdownRemark(
    sort: { fields: [frontmatter___post_date], order: DESC },
    filter: { frontmatter: { published: { eq: true } } }
  ) {
    edges {
      node {
        id
        excerpt(pruneLength: 250)
        frontmatter {
          title
          subtitle
          path
          post_type
          post_date
          published
          subject_url
          category
          folder
          tags
        }
      }
    }
  }
}`


text:
package org.torpedoquery.jpa.internal.conditions;

import org.torpedoquery.jpa.internal.Selector;
public class NotEqualPolymorphicCondition<T> extends PolymorphicCondition<T> {

	/**
	 *
Constructor for NotEqualPolymorphicCondition.

	 *
	 * @param selector a {@link org.torpedoquery.jpa.internal.Selector} object.
	 * @param condition a {@link java.lang.Class} object.
	 */
	public NotEqualPolymorphicCondition(Selector selector,
			Class<? extends T> condition) {
		super(selector, condition);
	}

	/** {@inheritDoc} */
	@Override
	protected String getComparator() {
		return NotEqualCondition.NOT_EQUAL;
	}

}


text:
XML_Util tests for Bug #5392 "encoding of ISO-8859-1 is the only supported encoding"
--CREDITS--
Chuck Burgess <ashnazg@php.net>
# created for v1.2.0a1 2008-05-04
--FILE--
<?php
require_once 'XML' . DIRECTORY_SEPARATOR . 'Util.php';
echo '=====XML_Util tests for Bug #5392 "encoding of ISO-8859-1 is the only supported encoding"=====' . PHP_EOL . PHP_EOL;

echo "TEST:  test case provided in bug report" . PHP_EOL;
$data = 'This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê';

$replaced = XML_Util::replaceEntities($data, XML_UTIL_ENTITIES_HTML, 'UTF-8');

$reversed = XML_Util::reverseEntities($replaced, XML_UTIL_ENTITIES_HTML, 'UTF-8');

echo $replaced . PHP_EOL;
echo $reversed . PHP_EOL;

?>
--EXPECT--
=====XML_Util tests for Bug #5392 "encoding of ISO-8859-1 is the only supported encoding"=====

TEST:  test case provided in bug report
This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê
This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê


text:
package com.jsteamkit.internals.steamlanguageinternal;

import com.jsteamkit.internals.steamlanguage.EMsg;
import com.jsteamkit.internals.stream.BinaryReader;
import com.jsteamkit.internals.stream.BinaryWriter;

import java.io.IOException;

public class MsgHeader extends SerializableMsg {

    public EMsg msg = EMsg.Invalid;

    public long targetJobId = 0xFFFFFFFFFFFFFFFFL;
    public long sourceJobId = 0xFFFFFFFFFFFFFFFFL;

    @Override
    public void encode(BinaryWriter writer) throws IOException {
        writer.write(msg.getCode());
        writer.write(targetJobId);
        writer.write(sourceJobId);
    }

    @Override
    public void decode(BinaryReader reader) throws IOException {
        msg = EMsg.get(reader.readInt());
        targetJobId = reader.readLong();
        sourceJobId = reader.readLong();
    }
}


text:
/**
 * @fileoverview Audit a page to see if it's using document.write()
 */

'use strict';

const ViolationAudit = require('../violation-audit');

class NoDocWriteAudit extends ViolationAudit {
  /**
   * @return {LH.Audit.Meta}
   */
  static get meta() {
    return {
      id: 'no-document-write',
      title: 'Avoids `document.write()`',
      failureTitle: 'Uses `document.write()`',
      description: 'For users on slow connections, external scripts dynamically injected via ' +
          '`document.write()` can delay page load by tens of seconds. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/document-write).',
      requiredArtifacts: ['ChromeConsoleMessages'],
    };
  }

  /**
   * @param {LH.Artifacts} artifacts
   * @return {LH.Audit.Product}
   */
  static audit(artifacts) {
    const results = ViolationAudit.getViolationResults(artifacts, /document\.write/);

    const headings = [
      {key: 'url', itemType: 'url', text: 'URL'},
      {key: 'label', itemType: 'text', text: 'Location'},
    ];
    // TODO(bckenny): see TODO in geolocation-on-start
    const details = ViolationAudit.makeTableDetails(headings, results);

    return {
      rawValue: results.length === 0,
      extendedInfo: {
        value: results,
      },
      details,
    };
  }
}

module.exports = NoDocWriteAudit;


text:
module.exports = function(RED) {
    "use strict";
    var spawn = require('child_process').spawn;
    var exec = require('child_process').exec;
    var isUtf8 = require('is-utf8');

    function ExecNode(n) {
        RED.nodes.createNode(this,n);
        this.cmd = (n.command || "").trim();
        if (n.addpay === undefined) { n.addpay = true; }
        this.addpay = n.addpay;
        this.append = (n.append || "").trim();
        this.useSpawn = n.useSpawn;

        var node = this;
        this.on("input", function(msg) {
            node.status({fill:"blue",shape:"dot"});
            if (this.useSpawn === true) {
                // make the extra args into an array
                // then prepend with the msg.payload
                if (typeof(msg.payload !== "string")) { msg.payload = (msg.payload || "").toString(); }
                var arg = [];
                if (node.append.length > 0) { arg = node.append.split(","); }
                if ((node.addpay === true) && (msg.payload.trim() !== "")) { arg.unshift(msg.payload); }
                if (RED.settings.verbose) { node.log(node.cmd+" ["+arg+"]"); }
                if (node.cmd.indexOf(" ") == -1) {
                    var ex = spawn(node.cmd,arg);
                    ex.stdout.on('data', function (data) {
                        //console.log('[exec] stdout: ' + data);
                        if (isUtf8(data)) { msg.payload = data.toString(); }
                        else { msg.payload = data; }
                        node.send([msg,null,null]);
                    });
                    ex.stderr.on('data', function (data) {
                        //console.log('[exec] stderr: ' + data);
                        if (isUtf8(data)) { msg.payload = data.toString(); }
                        else { msg.payload = new Buffer(data); }
                        node.send([null,msg,null]);
                    });
                    ex.on('close', function (code) {
                        //console.log('[exec] result: ' + code);
                        msg.payload = code;
                        node.status({});
                        node.send([null,null,msg]);
                    });
                    ex.on('error', function (code) {
                        node.error(code,msg);
                    });
                }
                else { node.error("Spawn command must be just the command - no spaces or extra parameters"); }
            }
            else {
                var cl = node.cmd;
                if ((node.addpay === true) && ((msg.payload || "").trim() !== "")) { cl += " "+msg.payload; }
                if (node.append.trim() !== "") { cl += " "+node.append; }
                if (RED.settings.verbose) { node.log(cl); }
                var child = exec(cl, {encoding: 'binary', maxBuffer:10000000}, function (error, stdout, stderr) {
                    msg.payload = new Buffer(stdout,"binary");
                    try {
                        if (isUtf8(msg.payload)) { msg.payload = msg.payload.toString(); }
                    } catch(e) {
                        node.log("Bad STDOUT");
                    }
                    var msg2 = {payload:stderr};
                    var msg3 = null;
                    //console.log('[exec] stdout: ' + stdout);
                    //console.log('[exec] stderr: ' + stderr);
                    if (error !== null) {
                        msg3 = {payload:error};
                        //console.log('[exec] error: ' + error);
                    }
                    node.status({});
                    node.send([msg,msg2,msg3]);
                });
            }
        });
    }
    RED.nodes.registerType("exec",ExecNode);
}


text:
<dom-module id="te-columndialog">
	<template>

		<paper-dialog xith-backdrop id="dialogId">

					<iron-icon class="error-big" icon="vaadin-icons:grid-h"></iron-icon>
					[[tr('te.new_column')]]

				<simpl-form id="formId" namespace="global" on-xaction="onTap" data="[[data]]" form-name="teNewColumn.form"></simpl-form>

				<paper-button raised dialog on-tap="onTap">
					<iron-icon icon="check"></iron-icon>Ok</paper-button>
				<paper-button raised dialog on-tap="close">
					<iron-icon icon="cancel"></iron-icon>[[tr('button.cancel')]]</paper-button>

		</paper-dialog>
	</template>

</dom-module>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Yen, Cahiers de La Maboké 9(1): 29 (1971)

#### Original name
Cercospora anthocleistae J.M. Yen & Gilles

### Remarks
null


text:
import datetime

import elasticsearch_dsl.filter as es_filter
from elasticsearch_dsl import aggs, query, SF
from rest_framework.filters import BaseFilterBackend

from mkt.games.constants import GAME_CATEGORIES

class DailyGamesFilter(BaseFilterBackend):
    """
    Randomly chooses 4 games, one from each featured game category, based off
    of the current date such that the games are shuffled daily.

    The query:
        - Selects only games that match the featured game category tags.
        - Scores randomly using random_score using date as seed.
        - Buckets by tag, using Top Hits with size=1 to select only one game
          from each category.
        - elastic.co/guide/en/elasticsearch/guide/current/top-hits.html
    """
    def filter_queryset(self, request, queryset, view):
        daily_seed = int(datetime.datetime.now().strftime('%Y%m%d'))

        # For each game category, create a query that matches the tag, orders
        # randomly based on the day.
        generate_game_category_query = (lambda cat: query.Q(
            'function_score',
            # Consistently random based on the day.
            functions=[SF('random_score', seed=daily_seed)],
            filter=es_filter.Bool(must=[es_filter.Term(tags=cat)]),
        ))

        # Map over the game categories to create a function score query for one
        # and dump it into a Bool should.
        game_query = query.Bool(should=map(generate_game_category_query,
                                           GAME_CATEGORIES))

        # Run a size=1 TopHits aggregation to only select one game from each
        # tag. Results will have to be pulled out of S.execute().aggregations
        # rather than S.execute().hits.
        top_hits = aggs.TopHits(size=1)
        a = aggs.A('terms', field='tags', aggs={'first_game': top_hits})

        queryset = queryset.query(game_query)
        queryset.aggs.bucket('top_hits', a)  # Not chainable.
        return queryset


text:
package computician.janusclientapi;

import org.json.JSONObject;

/**
 * Created by ben.trent on 6/25/2015.
 */
interface IJanusSessionCreationCallbacks extends IJanusCallbacks {
    void onSessionCreationSuccess(JSONObject obj);
}


text:
"""Utils for the io library.
* CountingSource: Subclass of iobase.BoundedSource. Used
on transforms.ptransform_test.test_read_metrics.
"""

# pytype: skip-file

from __future__ import absolute_import

from builtins import range

from apache_beam.io import iobase
from apache_beam.io.range_trackers import OffsetRangeTracker
from apache_beam.metrics import Metrics

class CountingSource(iobase.BoundedSource):
  def __init__(self, count):
    self.records_read = Metrics.counter(self.__class__, 'recordsRead')
    self._count = count

  def estimate_size(self):
    return self._count

  def get_range_tracker(self, start_position, stop_position):
    if start_position is None:
      start_position = 0
    if stop_position is None:
      stop_position = self._count

    return OffsetRangeTracker(start_position, stop_position)

  def read(self, range_tracker):
    for i in range(range_tracker.start_position(),
                   range_tracker.stop_position()):
      if not range_tracker.try_claim(i):
        return
      self.records_read.inc()
      yield i

  def split(self, desired_bundle_size, start_position=None, stop_position=None):
    if start_position is None:
      start_position = 0
    if stop_position is None:
      stop_position = self._count

    bundle_start = start_position
    while bundle_start < stop_position:
      bundle_stop = min(stop_position, bundle_start + desired_bundle_size)
      yield iobase.SourceBundle(
          weight=(bundle_stop - bundle_start),
          source=self,
          start_position=bundle_start,
          stop_position=bundle_stop)
      bundle_start = bundle_stop


text:
<?php

namespace spec\Slick\Http\Server\Middleware;

use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slick\Http\Message\Response;
use Slick\Http\Server\Exception\UnexpectedValueException;
use Slick\Http\Server\Middleware\CallableMiddleware;
use PhpSpec\ObjectBehavior;

/**
 * CallableMiddlewareSpec specs
 *
 * @package spec\Slick\Http\Server\Middleware
 */
class CallableMiddlewareSpec extends ObjectBehavior
{
    private $callable;

    function let()
    {
        $this->callable = function () {return new Response(200);};
        $this->beConstructedWith($this->callable);
    }

    function its_a_middleware()
    {
        $this->shouldBeAnInstanceOf(MiddlewareInterface::class);
    }

    function it_is_initializable_with_a_callable()
    {
        $this->shouldHaveType(CallableMiddleware::class);
    }

    function it_throws_an_exception_if_it_cannot_create_a_response_from_return(
        ServerRequestInterface $request,
        RequestHandlerInterface $requestHandler
    )
    {
        $this->beConstructedWith(function (){return (object)[];});
        $this->shouldThrow(UnexpectedValueException::class)
            ->during('process', [$request, $requestHandler]);
    }
}


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'prawn'
require 'prawn/format'

JAPANESE = "#{Prawn::BASEDIR}/data/fonts/gkai00mp.ttf"

Prawn::Document.generate "basic-formatting.pdf" do
  text "Thanks to the Prawn-Format library, Prawn now supports inline formatting. What this means in practical terms is that you can embed XML tags in your text calls, turning bits like <b>bold</b> into bold."

  move_text_position font_size

  text "Most common HTML tags are supported, including <i>, <b>, <u>, <code>, <sub> and <sup>. (For the full list, refer to Prawn::Format::DEFAULT_TAGS in prawn/format.rb.)"

  move_text_position font_size

  bounding_box [bounds.left + 72, y - bounds.absolute_bottom], :width => bounds.width - 144 do
    text "Finally, and as demonstrated by this very paragraph, Prawn-Format also supports full-justification of text. All you need to do is set :align => :justify in your text options, and the rest is taken care of. No more ragged right! Enter a new era of professional-looking documents.", :align => :justify
  end

  start_new_page

  text "Prawn is a PDF generation library for Ruby. Its emphasis is on speed, but also provides a very easy-to-use API, and boasts such advanced features as True-Type font embedding, font subsetting, image support, and many text layout functions."

  move_text_position font_size

  text "Return to top of document"

  start_new_page

  text "Ruby is a programming language with an emphasis on programmer happiness. It was developed by Yukihiro Matsumoto (まつもとゆきひろ, a.k.a. Matz)."

  move_text_position font_size

  text "Return to top of document"
end