text:
function im = load_image(fname)
%
% Load in the selected image, special handling if it comes from a known
% dataset of linear natural scene images (Van Hateren or McGill)
%
% INPUT:
%
%       fname:  name of file to load
%
% OUTPUT
%
%       im:     matrix with light intensity values
%
% Emily Cooper, 2015

if any(strfind(fname,'.iml'))               % Van Hateren Dataset IML images from Bethge lab website (http://bethgelab.org/datasets/vanhateren/)

    f   = fopen(fname, 'rb', 'ieee-be');	% open image file
    w  	= 1536; h = 1024;                   % set width and height
    im 	= fread(f, [w, h], 'uint16');       % read in contents
    im  = flipud(double(im)');              % flip dimensions

elseif any(strfind(lower(fname),'mcg'))     % McGill Calibrated Colour Image Database (http://tabby.vision.mcgill.ca)

    im      = rgb2linear(fname);                          % load linear image, this is a calibration function provided with the McGill iamges
    im      = im(:,:,1).*0.2989 + ...                     % convert RGB image to relative luminance
        im(:,:,2).*0.5870 + im(:,:,3).*0.1140;

else                                        % just try to load in image file

    % if it's a mat file, try to load it and look for a single matrix to use as the image
    if any(strfind(fname,'.mat'))

        data    = load(fname);      % load the mat file
        fields  = fieldnames(data); % get the names of loaded variables

        % you should have loaded just one variable, the 2D or 3D image matrix
        if length(fields) == 1 && ndims(data.(fields{1})) > 1
            im = data.(fields{1});  % if so, assign it to the im variable
        else
            error('If loading a mat file, by default the file must contain a single variable with the image matrix (2D or 3D)');
        end

    else                                                % otherwise, try to load it as an image

        try
            im = flipdim(double(imread(fname))./255,1);
        catch
            error('Unhandled file type, add this type to load_image.m');
        end

    end

    if size(im,3) > 1
        im = im(:,:,1).*0.2989 + ...                % convert RGB image to relative luminance if this is a color iamge
            im(:,:,2).*0.5870 + im(:,:,3).*0.1140;
    end

    display('Assuming this image has values that are linear with world light intensity');

end


text:
package org.camunda.bpm.engine.impl.history.handler;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;

public class CallActivityStartHandler implements ExecutionListener {

  public void notify(DelegateExecution execution) throws Exception {

  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.rv.parser

import org.scalatest.FlatSpec

class TrigrammeSpec extends FlatSpec {

  it should "contain 9 elements in list" in {
    assert(9 == (Trigramme.perThree("hello world").size))
  }

  it should "contain 1 elements in list" in {
    assert(1 == (Trigramme.perThree("HEL").size))
  }

  it should "contain 9 elements in list after decoupe" in {
    val res = Trigramme.decoupe("hello world", 3)
    assert(9 == (res.size))
    assert(res.contains("HEL"))
    assert(res.contains("ELL"))
    assert(res.contains("LLO"))
    assert(res.contains("LO "))
    assert(res.contains("O W"))
    assert(res.contains(" WO"))
    assert(res.contains("RLD"))
  }

  it should "contain the same elements : methods decoupe and perThree" in {
    val line = "hello world"
    val resDecoupe = Trigramme.decoupe(line, 3)
    val resTri = Trigramme.perThree(line)
    assert(resDecoupe.equals(resTri))

  }
}


text:
'use strict';

const assert = require('assert');
const mm = require('egg-mock');
const request = require('supertest');
const sleep = require('mz-modules/sleep');
const fs = require('fs');
const path = require('path');
const Application = require('../../lib/application');
const utils = require('../utils');

describe('test/lib/application.test.js', () => {
  let app;

  afterEach(mm.restore);

  describe('create application', () => {
    it('should throw options.baseDir required', () => {
      assert.throws(() => {
        new Application({
          baseDir: 1,
        });
      }, /options.baseDir required, and must be a string/);
    });

    it('should throw options.baseDir not exist', () => {
      assert.throws(() => {
        new Application({
          baseDir: 'not-exist',
        });
      }, /Directory not-exist not exists/);
    });

    it('should throw options.baseDir is not a directory', () => {
      assert.throws(() => {
        new Application({
          baseDir: __filename,
        });
      }, /is not a directory/);
    });
  });

  describe('app start timeout', function() {
    afterEach(() => app.close());
    it('should emit `startTimeout` event', function(done) {
      app = utils.app('apps/app-start-timeout');
      app.once('startTimeout', done);
    });
  });

  describe('app.keys', () => {
    it('should throw when config.keys missing on non-local and non-unittest env', function* () {
      mm.env('test');
      app = utils.app('apps/keys-missing');
      yield app.ready();
      mm(app.config, 'keys', null);

      try {
        app.keys;
        throw new Error('should not run this');
      } catch (err) {
        assert(err.message === 'Please set config.keys first');
      }

      // make sure app close
      yield app.close();
    });

    it('should throw when config.keys missing on unittest env', function* () {
      mm.env('unittest');
      app = utils.app('apps/keys-missing');
      yield app.ready();
      mm(app.config, 'keys', null);

      try {
        app.keys;
        throw new Error('should not run this');
      } catch (err) {
        assert(err.message === 'Please set config.keys first');
      }

      // make sure app close
      yield app.close();
    });

    it('should throw when config.keys missing on local env', function* () {
      mm.env('local');
      app = utils.app('apps/keys-missing');
      yield app.ready();
      mm(app.config, 'keys', null);

      try {
        app.keys;
        throw new Error('should not run this');
      } catch (err) {
        assert(err.message === 'Please set config.keys first');
      }

      // make sure app close
      yield app.close();
    });

    it('should use exists keys', function* () {
      mm.env('unittest');
      app = utils.app('apps/keys-exists');
      yield app.ready();

      assert(app.keys);
      assert(app.keys);
      assert(app.config.keys === 'my keys');

      yield app.close();
    });
  });

  describe('handle uncaughtException', () => {
    let app;
    before(() => {
      app = utils.cluster('apps/app-throw');
      return app.ready();
    });
    after(() => app.close());

    it('should handle uncaughtException and log it', function* () {
      yield request(app.callback())
        .get('/throw')
        .expect('foo')
        .expect(200);

      yield sleep(1100);
      const logfile = path.join(utils.getFilepath('apps/app-throw'), 'logs/app-throw/common-error.log');
      const body = fs.readFileSync(logfile, 'utf8');
      assert(body.includes('ReferenceError: a is not defined (uncaughtException throw'));
    });
  });

  describe('warn confused configurations', () => {
    it('should warn if confused configurations exist', function* () {
      const app = utils.app('apps/confused-configuration');
      yield app.ready();
      const logs = fs.readFileSync(utils.getFilepath('apps/confused-configuration/logs/confused-configuration/confused-configuration-web.log'), 'utf8');
      assert(logs.match(/Unexpected config key `bodyparser` exists, Please use `bodyParser` instead\./));
      assert(logs.match(/Unexpected config key `notFound` exists, Please use `notfound` instead\./));
      assert(logs.match(/Unexpected config key `sitefile` exists, Please use `siteFile` instead\./));
      assert(logs.match(/Unexpected config key `middlewares` exists, Please use `middleware` instead\./));
      assert(logs.match(/Unexpected config key `httpClient` exists, Please use `httpclient` instead\./));
    });
  });

  describe('test on apps/demo', () => {
    let app;
    before(() => {
      app = utils.app('apps/demo');
      return app.ready();
    });
    after(() => app.close());

    describe('application.deprecate', () => {
      it('should get deprecate with namespace egg', function* () {
        const deprecate = app.deprecate;
        assert(deprecate._namespace === 'egg');
        assert(deprecate === app.deprecate);
      });
    });

    describe('curl()', () => {
      it('should curl success', function* () {
        const localServer = yield utils.startLocalServer();
        const res = yield app.curl(`${localServer}/foo/app`);
        assert(res.status === 200);
      });
    });

    describe('env', () => {
      it('should return app.config.env', function* () {
        assert(app.env === app.config.env);
      });
    });

    describe('proxy', () => {
      it('should delegate app.config.proxy', function* () {
        assert(app.proxy === app.config.proxy);
      });
    });

    describe('inspect && toJSON', () => {
      it('should override koa method', function() {
        const inspectResult = app.inspect();
        const jsonResult = app.toJSON();
        assert.deepEqual(inspectResult, jsonResult);
        assert(inspectResult.env === app.config.env);
      });
    });

    describe('class style controller', () => {
      it('should work with class style controller', () => {
        return request(app.callback())
          .get('/class-controller')
          .expect('this is bar!')
          .expect(200);
      });
    });
  });
});


text:
import datetime

from . import Framework

class GitCommit(Framework.TestCase):
    def setUp(self):
        Framework.TestCase.setUp(self)
        self.commit = self.g.get_user().get_repo("PyGithub").get_git_commit("4303c5b90e2216d927155e9609436ccb8984c495")

    def testAttributes(self):
        self.assertEqual(self.commit.author.name, "Vincent Jacques")
        self.assertEqual(self.commit.author.email, "vincent@vincent-jacques.net")
        self.assertEqual(self.commit.author.date, datetime.datetime(2012, 4, 17, 17, 55, 16))
        self.assertEqual(self.commit.committer.name, "Vincent Jacques")
        self.assertEqual(self.commit.committer.email, "vincent@vincent-jacques.net")
        self.assertEqual(self.commit.committer.date, datetime.datetime(2012, 4, 17, 17, 55, 16))
        self.assertEqual(self.commit.message, "Merge branch 'develop'\n")
        self.assertEqual(len(self.commit.parents), 2)
        self.assertEqual(self.commit.parents[0].sha, "936f4a97f1a86392637ec002bbf89ff036a5062d")
        self.assertEqual(self.commit.parents[1].sha, "2a7e80e6421c5d4d201d60619068dea6bae612cb")
        self.assertEqual(self.commit.sha, "4303c5b90e2216d927155e9609436ccb8984c495")
        self.assertEqual(self.commit.tree.sha, "f492784d8ca837779650d1fb406a1a3587a764ad")
        self.assertEqual(self.commit.url, "https://api.github.com/repos/jacquev6/PyGithub/git/commits/4303c5b90e2216d927155e9609436ccb8984c495")


text:
from unittest import TestCase
from Weltall.weltall import Weltall
from Model.solarSysModel import SolarSunModel
from Objekte.planet import Planet
from OpenGL.GLUT import *

__author__ = 'floriandienesch'

class TestWeltall(TestCase):

    def setUp(self):
        glutInit(sys.argv)
        glutCreateWindow("Solarsystem v0.9")

        self.weltall = Weltall
        self.planet = Planet()
        self.model = SolarSunModel()

    def tearDown(self):
        self.weltall = None
        self.planet = None
        self.model = None

    def test_reSizeGLScene(self):
        self.assertEqual(self.weltall.reSizeGLScene("d", 200, 200), None)


text:
angular.module('starter', ['ionic', 'starter.services', 'starter.controllers'])

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

    // setup an abstract state for the tabs directive
    .state('tab', {
      url: '/tab',
      abstract: true,
      templateUrl: 'templates/tabs.html'
    })

    // the pet tab has its own child nav-view and history
    .state('tab.swim-index', {
      url: '/swims',
      views: {
        'swims-tab': {
          templateUrl: 'templates/pet-index.html',
          controller: 'SwimIndexCtrl'
        }
      }
    })

    .state('tab.swim-detail', {
      url: '/swim/:swimId',
      views: {
        'swims-tab': {
          templateUrl: 'templates/pet-detail.html',
          controller: 'SwimDetailCtrl'
        }
      }
    })

    .state('tab.addswim', {
      url: '/addswim',
      views: {
        'adopt-tab': {
          templateUrl: 'templates/addswim.html',
          controller: 'AddSwimCtrl'
        }
      }
    })

    .state('tab.about', {
      url: '/about',
      views: {
        'about-tab': {
          templateUrl: 'templates/about.html'
        }
      }
    });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/swims');

});


text:
import unittest

from typing import List, Dict, Union, Optional
from kfp.deprecated.components.modelbase import ModelBase

class TestModel1(ModelBase):
    _serialized_names = {
        'prop_1': 'prop1',
        'prop_2': 'prop 2',
        'prop_3': '@@',
    }

    def __init__(
        self,
        prop_0: str,
        prop_1: Optional[str] = None,
        prop_2: Union[int, str, bool] = '',
        prop_3: 'TestModel1' = None,
        prop_4: Optional[Dict[str, 'TestModel1']] = None,
        prop_5: Optional[Union['TestModel1', List['TestModel1'],
                               Dict[str, 'TestModel1']]] = None,
        prop_6: Optional[Union[str, List, Dict]] = None,
    ):
        #print(locals())
        super().__init__(locals())

class StructureModelBaseTestCase(unittest.TestCase):

    def test_handle_type_check_for_simple_builtin(self):
        self.assertEqual(TestModel1(prop_0='value 0').prop_0, 'value 0')

        with self.assertRaises(TypeError):
            TestModel1(prop_0=1)

        with self.assertRaises(TypeError):
            TestModel1(prop_0=None)

        with self.assertRaises(TypeError):
            TestModel1(prop_0=TestModel1(prop_0='value 0'))

    def test_handle_type_check_for_optional_builtin(self):
        self.assertEqual(
            TestModel1(prop_0='', prop_1='value 1').prop_1, 'value 1')
        self.assertEqual(TestModel1(prop_0='', prop_1=None).prop_1, None)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_1=1)

        with self.assertRaises(TypeError):
            TestModel1(
                prop_0='', prop_1=TestModel1(prop_0='', prop_1='value 1'))

    def test_handle_type_check_for_union_builtin(self):
        self.assertEqual(
            TestModel1(prop_0='', prop_2='value 2').prop_2, 'value 2')
        self.assertEqual(TestModel1(prop_0='', prop_2=22).prop_2, 22)
        self.assertEqual(TestModel1(prop_0='', prop_2=True).prop_2, True)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_2=None)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_2=22.22)

        with self.assertRaises(TypeError):
            TestModel1(
                prop_0='', prop_2=TestModel1(prop_0='', prop_2='value 2'))

    def test_handle_type_check_for_class(self):
        val3 = TestModel1(prop_0='value 0')
        self.assertEqual(TestModel1(prop_0='', prop_3=val3).prop_3, val3)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_3=1)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_3='value 3')

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_3=[val3])

    def test_handle_type_check_for_dict_class(self):
        val4 = TestModel1(prop_0='value 0')
        self.assertEqual(
            TestModel1(prop_0='', prop_4={
                'key 4': val4
            }).prop_4['key 4'], val4)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_4=1)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_4='value 4')

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_4=[val4])

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_4={42: val4})

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_4={'key 4': [val4]})

    def test_handle_type_check_for_union_dict_class(self):
        val5 = TestModel1(prop_0='value 0')
        self.assertEqual(TestModel1(prop_0='', prop_5=val5).prop_5, val5)
        self.assertEqual(TestModel1(prop_0='', prop_5=[val5]).prop_5[0], val5)
        self.assertEqual(
            TestModel1(prop_0='', prop_5={
                'key 5': val5
            }).prop_5['key 5'], val5)
        self.assertEqual(TestModel1(prop_0='', prop_5=None).prop_5, None)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_5=1)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_5='value 5')

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_5={'key 5': 'value 5'})

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_5={42: val5})

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_5={'key 5': [val5]})

    def test_handle_type_check_for_open_generic_classes(self):
        val6 = TestModel1(prop_0='value 0')
        self.assertEqual(TestModel1(prop_0='', prop_6='val6').prop_6, 'val6')
        self.assertEqual(TestModel1(prop_0='', prop_6=[val6]).prop_6[0], val6)
        self.assertEqual(
            TestModel1(prop_0='', prop_6={
                'key 6': val6
            }).prop_6['key 6'], val6)
        self.assertEqual(TestModel1(prop_0='', prop_6=None).prop_6, None)

        with self.assertRaises(TypeError):
            TestModel1(prop_0='', prop_6=1)

    def test_handle_from_to_dict_for_simple_builtin(self):
        struct0 = {'prop_0': 'value 0'}
        obj0 = TestModel1.from_dict(struct0)
        self.assertEqual(obj0.prop_0, 'value 0')
        self.assertDictEqual(obj0.to_dict(), struct0)

        with self.assertRaises(AttributeError):  #TypeError:
            TestModel1.from_dict(None)

        with self.assertRaises(AttributeError):  #TypeError:
            TestModel1.from_dict('')

        with self.assertRaises(TypeError):
            TestModel1.from_dict({})

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop0': 'value 0'})

    def test_handle_from_to_dict_for_optional_builtin(self):
        struct11 = {'prop_0': '', 'prop1': 'value 1'}
        obj11 = TestModel1.from_dict(struct11)
        self.assertEqual(obj11.prop_1, struct11['prop1'])
        self.assertDictEqual(obj11.to_dict(), struct11)

        struct12 = {'prop_0': '', 'prop1': None}
        obj12 = TestModel1.from_dict(struct12)
        self.assertEqual(obj12.prop_1, None)
        self.assertDictEqual(obj12.to_dict(), {'prop_0': ''})

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop 1': ''})

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop1': 1})

    def test_handle_from_to_dict_for_union_builtin(self):
        struct21 = {'prop_0': '', 'prop 2': 'value 2'}
        obj21 = TestModel1.from_dict(struct21)
        self.assertEqual(obj21.prop_2, struct21['prop 2'])
        self.assertDictEqual(obj21.to_dict(), struct21)

        struct22 = {'prop_0': '', 'prop 2': 22}
        obj22 = TestModel1.from_dict(struct22)
        self.assertEqual(obj22.prop_2, struct22['prop 2'])
        self.assertDictEqual(obj22.to_dict(), struct22)

        struct23 = {'prop_0': '', 'prop 2': True}
        obj23 = TestModel1.from_dict(struct23)
        self.assertEqual(obj23.prop_2, struct23['prop 2'])
        self.assertDictEqual(obj23.to_dict(), struct23)

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': 'ZZZ', 'prop 2': None})

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop 2': 22.22})

    def test_handle_from_to_dict_for_class(self):
        val3 = TestModel1(prop_0='value 0')

        struct31 = {
            'prop_0': '',
            '@@': val3.to_dict()
        }  #{'prop_0': '', '@@': TestModel1(prop_0='value 0')} is also valid for from_dict, but this cannot happen when parsing for real
        obj31 = TestModel1.from_dict(struct31)
        self.assertEqual(obj31.prop_3, val3)
        self.assertDictEqual(obj31.to_dict(), struct31)

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', '@@': 'value 3'})

    def test_handle_from_to_dict_for_dict_class(self):
        val4 = TestModel1(prop_0='value 0')

        struct41 = {'prop_0': '', 'prop_4': {'val 4': val4.to_dict()}}
        obj41 = TestModel1.from_dict(struct41)
        self.assertEqual(obj41.prop_4['val 4'], val4)
        self.assertDictEqual(obj41.to_dict(), struct41)

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop_4': {44: val4.to_dict()}})

    def test_handle_from_to_dict_for_union_dict_class(self):
        val5 = TestModel1(prop_0='value 0')

        struct51 = {'prop_0': '', 'prop_5': val5.to_dict()}
        obj51 = TestModel1.from_dict(struct51)
        self.assertEqual(obj51.prop_5, val5)
        self.assertDictEqual(obj51.to_dict(), struct51)

        struct52 = {'prop_0': '', 'prop_5': [val5.to_dict()]}
        obj52 = TestModel1.from_dict(struct52)
        self.assertListEqual(obj52.prop_5, [val5])
        self.assertDictEqual(obj52.to_dict(), struct52)

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop_5': {44: val5.to_dict()}})

        with self.assertRaises(TypeError):
            TestModel1.from_dict({
                'prop_0': '',
                'prop_5': [val5.to_dict(), None]
            })

    def test_handle_from_to_dict_for_open_generic_class(self):
        value61 = "value 6 1"
        struct61 = {'prop_0': '', 'prop_6': value61}
        obj61 = TestModel1.from_dict(struct61)
        self.assertEqual(obj61.prop_6, value61)
        self.assertEqual(obj61.to_dict(), struct61)

        value62 = ["value 6 2"]
        struct62 = {'prop_0': '', 'prop_6': value62}
        obj62 = TestModel1.from_dict(struct62)
        self.assertEqual(obj62.prop_6, value62)
        self.assertEqual(obj62.to_dict(), struct62)

        value63 = {"key 6 3": "value 6 3"}
        struct63 = {'prop_0': '', 'prop_6': value63}
        obj63 = TestModel1.from_dict(struct63)
        self.assertEqual(obj63.prop_6, value63)
        self.assertEqual(obj63.to_dict(), struct63)

        with self.assertRaises(TypeError):
            TestModel1.from_dict({'prop_0': '', 'prop_6': 64})

    def test_handle_comparisons(self):

        class A(ModelBase):

            def __init__(self, a, b):
                super().__init__(locals())

        self.assertEqual(A(1, 2), A(1, 2))
        self.assertNotEqual(A(1, 2), A(1, 3))

        class B(ModelBase):

            def __init__(self, a, b):
                super().__init__(locals())

        self.assertNotEqual(A(1, 2), B(1, 2))

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


text:
package com.flowci.util;

import com.google.common.hash.Hashing;

/**
 * @author yang
 */
public abstract class HashingHelper {

    public static String md5(String value) {
        return Hashing.md5().hashBytes(value.getBytes()).toString();
    }
}


text:
package com.tepidpond.tum.PlateTectonics;

import java.util.Vector;

public class PlateArea {
	private Vector<Integer> border = new Vector(2048);
	private int mapSize;
	public int x0, y0, x1, y1;
	public int rgt() { return x1; }
	public int lft() { return x0; }
	public int btm() { return y1; }
	public int top() { return y0; }
	public int wdt() { return x1 - x0; }
	public int hgt() { return y1 - y0; }
	public PlateArea(int mapTile, int mapSize) {
		this.mapSize = mapSize;
		this.x0 = Util.getX(mapTile, mapSize);
		this.x1 = Util.getX(mapTile, mapSize);
		this.y0 = Util.getY(mapTile, mapSize);
		this.y1 = Util.getY(mapTile, mapSize);
		border.addElement(mapTile);
	}
	public int getBorder(int index) {
		return border.get(index);
	}
	public void setBorder(int index, int mapTile) {
		if (index == borderSize()) {
			pushBorder(mapTile);
			updateBoundsToInclude(mapTile, mapSize);
		} else {
			border.setElementAt(mapTile, index);
		}
	}
	public int lastBorder() {
		return border.get(border.size() - 1);
	}
	public int popBorder() {
		int mapTile = border.lastElement();
		border.removeElementAt(border.size() - 1);
		return mapTile;
	}
	public void pushBorder(int mapTile) {
		border.addElement(mapTile);
		updateBoundsToInclude(mapTile, mapSize);
	}
	public int borderSize() {
		return border.size();
	}
	private void updateBoundsToInclude(int mapTile, int mapSize) {
		int x = Util.getX(mapTile, mapSize);
		int y = Util.getY(mapTile, mapSize);

		if (y > y1) y1 = y;
		if (y < y0) y0 = y;
		if (x > x1) x1 = x;
		if (x < x0) x0 = x;
	}
}


text:
package org.apache.flink.runtime.webmonitor.history;

import org.apache.flink.runtime.history.FsJobArchivist;
import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.util.RestMapperUtils;
import org.apache.flink.util.Preconditions;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Objects;

/**
 * A simple container for a handler's JSON response and the REST URLs for which the response would've been returned.
 *
 * <p>These are created by {@link JsonArchivist}s, and used by the {@link FsJobArchivist} to create a directory structure
 * resembling the REST API.
 */
public class ArchivedJson {

	private static final ObjectMapper MAPPER = RestMapperUtils.getStrictObjectMapper();

	private final String path;
	private final String json;

	public ArchivedJson(String path, String json) {
		this.path = Preconditions.checkNotNull(path);
		this.json = Preconditions.checkNotNull(json);
	}

	public ArchivedJson(String path, ResponseBody json) throws IOException {
		this.path = Preconditions.checkNotNull(path);
		StringWriter sw = new StringWriter();
		MAPPER.writeValue(sw, Preconditions.checkNotNull(json));
		this.json = sw.toString();
	}

	public String getPath() {
		return path;
	}

	public String getJson() {
		return json;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof ArchivedJson) {
			ArchivedJson other = (ArchivedJson) obj;
			return this.path.equals(other.path) && this.json.equals(other.json);
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return Objects.hash(path, json);
	}

	@Override
	public String toString() {
		return path + ":" + json;
	}
}


text:
@interface urlrunnerAppDelegate : NSObject <NSApplicationDelegate> {

}

@end


text:
  <?php if (!$pager->getNbResults()): ?>

<?php echo __('No result', array(), 'sf_admin') ?>

  <?php else: ?>

          <?php include_partial('category/list_th_tabular', array('sort' => $sort)) ?>
          <?php echo __('Actions', array(), 'sf_admin') ?>

            <?php if ($pager->haveToPaginate()): ?>
              <?php include_partial('category/pagination', array('pager' => $pager)) ?>
            <?php endif; ?>

            <?php echo format_number_choice('[0] no result|[1] 1 result|(1,+Inf] %1% results', array('%1%' => $pager->getNbResults()), $pager->getNbResults(), 'sf_admin') ?>
            <?php if ($pager->haveToPaginate()): ?>
              <?php echo __('(page %%page%%/%%nb_pages%%)', array('%%page%%' => $pager->getPage(), '%%nb_pages%%' => $pager->getLastPage()), 'sf_admin') ?>
            <?php endif; ?>

        <?php foreach ($pager->getResults() as $i => $JobeetCategory): $odd = fmod(++$i, 2) ? 'odd' : 'even' ?>
          <tr class="sf_admin_row <?php echo $odd ?>">
            <?php include_partial('category/list_td_tabular', array('JobeetCategory' => $JobeetCategory)) ?>
            <?php include_partial('category/list_td_actions', array('JobeetCategory' => $JobeetCategory, 'helper' => $helper)) ?>

        <?php endforeach; ?>

  <?php endif; ?>


text:
/**
 * App site application.
 */
qx.Class.define("${rootArtifactId}.Application", {
    extend: ncms.Application,

    members: {

        main: function () {
            this.base(arguments);
        },

        createActions: function () {
            return new ${rootArtifactId}.Actions();
        }
    }
});


text:
package org.traccar.protocol;

import java.net.SocketAddress;
import java.util.regex.Pattern;

import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.Protocol;
import org.traccar.helper.Parser;
import org.traccar.helper.Parser.CoordinateFormat;
import org.traccar.helper.PatternBuilder;
import org.traccar.model.Position;

public class IdplProtocolDecoder extends BaseProtocolDecoder {

    public IdplProtocolDecoder(Protocol protocol) {
        super(protocol);
    }

    private static final Pattern PATTERN = new PatternBuilder()
            .text("*ID")                         // start of frame
            .number("(d+),")                     // command code
            .number("(d+),")                     // imei
            .number("(dd)(dd)(dd),")             // current date (ddmmyy)
            .number("(dd)(dd)(dd),")             // current time (hhmmss)
            .expression("([A|V]),")              // gps fix
            .number("(dd)(dd).?(d+),([NS]),")    // latitude
            .number("(ddd)(dd).?(d+),([EW]),")   // longitude
            .number("(d{1,3}.dd),")              // speed
            .number("(d{1,3}.dd),")              // course
            .number("(d{1,2}),")                 // sats
            .number("(d{1,3}),")                 // gsm signal strength
            .expression("([A|N|S]),")            // vehicle status
            .expression("([0|1]),")              // main power status
            .number("(d.dd),")                   // internal battery voltage
            .expression("([0|1]),")              // sos alert
            .expression("([0|1]),")              // body tamper
            .expression("([0|1])([0|1]),")       // ac status + ign status
            .expression("([0|1|2]),")            // output1 status
            .number("(d{1,3}),")                 // adc1
            .number("(d{1,3}),")                 // adc2
            .expression("([0-9A-Z]{3}),")        // software version
            .expression("([L|R]),")              // message type
            .number("(x{4})#")                   // crc
            .compile();

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        Parser parser = new Parser(PATTERN, (String) msg);
        if (!parser.matches()) {
            return null;
        }

        Position position = new Position(getProtocolName());

        position.set(Position.KEY_TYPE, parser.nextInt(0));

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
        if (deviceSession == null) {
            return null;
        }
        position.setDeviceId(deviceSession.getDeviceId());

        position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

        position.setValid(parser.next().equals("A"));
        position.setLatitude(parser.nextCoordinate(CoordinateFormat.DEG_MIN_MIN_HEM));
        position.setLongitude(parser.nextCoordinate(CoordinateFormat.DEG_MIN_MIN_HEM));
        position.setSpeed(parser.nextDouble(0));
        position.setCourse(parser.nextDouble(0));

        position.set(Position.KEY_SATELLITES, parser.nextInt(0));
        position.set(Position.KEY_RSSI, parser.nextInt(0));
        position.set("vehicleStatus", parser.next());
        position.set(Position.KEY_POWER, parser.nextInt(0));
        position.set(Position.KEY_BATTERY, parser.nextDouble(0));
        if (parser.nextInt(0) == 1) {
            position.set(Position.KEY_ALARM, Position.ALARM_SOS);
        }
        parser.nextInt(0); // body tamper
        position.set("acStatus", parser.nextInt(0));
        position.set(Position.KEY_IGNITION, parser.nextInt(0) == 1);
        position.set(Position.KEY_OUTPUT, parser.nextInt(0));
        position.set(Position.PREFIX_ADC + 1, parser.nextInt(0));
        position.set(Position.PREFIX_ADC + 2, parser.nextInt(0));
        position.set(Position.KEY_VERSION_FW, parser.next());
        position.set(Position.KEY_ARCHIVE, parser.next().equals("R"));

        parser.next(); // checksum

        return position;
    }

}


text:
LEVEL = ../../../..

PROG     = uuencode
LDFLAGS  =
RUN_OPTIONS = $(PROJ_SRC_DIR)/input.txt
include $(LEVEL)/MultiSource/Makefile.multisrc


text:
/*
 * Script to run Adyen notification related jobs
 */

/* API Includes */
// eslint-disable-next-line no-unused-vars
const Order = require('dw/order/Order');
const OrderMgr = require('dw/order/OrderMgr');
// eslint-disable-next-line no-unused-vars
const Resource = require('dw/web/Resource');
// eslint-disable-next-line no-unused-vars
const Status = require('dw/system/Status');
const Transaction = require('dw/system/Transaction');
const CustomObjectMgr = require('dw/object/CustomObjectMgr');
const logger = require('dw/system/Logger').getLogger('Adyen', 'adyen');

function execute(pdict) {
  processNotifications(pdict);
  clearNotifications(pdict);
  return PIPELET_NEXT;
}

/**
 * ProcessNotifications - search for custom objects that need to be processed and handle them to place or fail order
 */
function processNotifications(/* pdict */) {
  const objectsHandler = require('*/cartridge/scripts/handleCustomObject');
  const searchQuery = CustomObjectMgr.queryCustomObjects(
    'adyenNotification',
    "custom.updateStatus = 'PROCESS'",
    null,
  );
  logger.info('Process notifications start with count {0}', searchQuery.count);

  let customObj; let handlerResult; let
    order;
  while (searchQuery.hasNext()) {
    customObj = searchQuery.next();
    Transaction.wrap(function () { // eslint-disable-line no-loop-func
      handlerResult = objectsHandler.handle(customObj);
    });

    /*
			Sometimes order cannot be found in DWRE DB even if it exists there,
			in that case we shouldn't reply to Adyen that all was ok in order to get a new notification
		*/

    order = handlerResult.Order;
    if (!handlerResult.status || handlerResult.status === PIPELET_ERROR) {
      // Only CREATED orders can be failed
      if (
        order === null
        || order.status !== dw.order.Order.ORDER_STATUS_CREATED
        || handlerResult.RefusedHpp
      ) {
        continue;
      }
      // Refused payments which are made with using Adyen payment method are handled when user is redirected back from Adyen HPP.
      // Here we shouldn't fail an order and send a notification
      Transaction.wrap(function () { // eslint-disable-line no-loop-func
        OrderMgr.failOrder(order, true);
      });
      continue;
    }

    if (handlerResult.SkipOrder || handlerResult.Pending) {
      continue;
    }

    // Submitting an order -> update status and send all required email
    if (handlerResult.SubmitOrder) {
      const placeOrderResult = submitOrder(order);
      if (!placeOrderResult.order_created || placeOrderResult.error) {
        logger.error(
          'Failed to place an order: {0}, during notification process.',
          order.orderNo,
        );
      }
    }
  }
  logger.info(
    'Process notifications finished with count {0}',
    searchQuery.count,
  );
  searchQuery.close();

  return PIPELET_NEXT;
}

/**
 * cleanNotifications
 */
function clearNotifications(/* pdict */) {
  const deleteCustomObjects = require('*/cartridge/scripts/deleteCustomObjects');
  const searchQuery = CustomObjectMgr.queryCustomObjects(
    'adyenNotification',
    "custom.processedStatus = 'SUCCESS'",
    null,
  );
  logger.info(
    'Removing Processed Custom Objects start with count {0}',
    searchQuery.count,
  );

  let customObj;
  while (searchQuery.hasNext()) {
    customObj = searchQuery.next();
    Transaction.wrap(function () { // eslint-disable-line no-loop-func
      deleteCustomObjects.remove(customObj);
    });
  }
  logger.info(
    'Removing Processed Custom Objects finished with count {0}',
    searchQuery.count,
  );
  searchQuery.close();

  return PIPELET_NEXT;
}

/**
 * Submits an order, original function located in OrderModel, but we need to manage triggering of email
 * @param order {dw.order.Order} The order object to be submitted.
 * @transactional
 * @return {Object} object If order cannot be placed, object.error is set to true. Ortherwise, object.order_created is true, and object.Order is set to the order.
 */
function submitOrder(order) {
  const adyenService = require('*/cartridge/scripts/adyenService');
  adyenService.submit(order);

  return {
    Order: order,
    order_created: true,
  };
}

module.exports = {
  execute: execute,
  processNotifications: processNotifications,
  clearNotifications: clearNotifications,
};


text:
package servicefabric

import original "github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2017-07-01-preview/servicefabric"

type ApplicationClient = original.ApplicationClient
type ClustersClient = original.ClustersClient
type ServiceClient = original.ServiceClient
type OperationsClient = original.OperationsClient
type VersionClient = original.VersionClient
type ApplicationTypeClient = original.ApplicationTypeClient

const (
	DefaultBaseURI = original.DefaultBaseURI
)

type BaseClient = original.BaseClient
type ClusterVersionsClient = original.ClusterVersionsClient
type ClusterState = original.ClusterState

const (
	AutoScale                 ClusterState = original.AutoScale
	BaselineUpgrade           ClusterState = original.BaselineUpgrade
	Deploying                 ClusterState = original.Deploying
	EnforcingClusterVersion   ClusterState = original.EnforcingClusterVersion
	Ready                     ClusterState = original.Ready
	UpdatingInfrastructure    ClusterState = original.UpdatingInfrastructure
	UpdatingUserCertificate   ClusterState = original.UpdatingUserCertificate
	UpdatingUserConfiguration ClusterState = original.UpdatingUserConfiguration
	UpgradeServiceUnreachable ClusterState = original.UpgradeServiceUnreachable
	WaitingForNodes           ClusterState = original.WaitingForNodes
)

type DefaultMoveCost = original.DefaultMoveCost

const (
	High   DefaultMoveCost = original.High
	Low    DefaultMoveCost = original.Low
	Medium DefaultMoveCost = original.Medium
	Zero   DefaultMoveCost = original.Zero
)

type DurabilityLevel = original.DurabilityLevel

const (
	Bronze DurabilityLevel = original.Bronze
	Gold   DurabilityLevel = original.Gold
	Silver DurabilityLevel = original.Silver
)

type Environment = original.Environment

const (
	Linux   Environment = original.Linux
	Windows Environment = original.Windows
)

type PartitionScheme = original.PartitionScheme

const (
	PartitionSchemeNamed                      PartitionScheme = original.PartitionSchemeNamed
	PartitionSchemePartitionSchemeDescription PartitionScheme = original.PartitionSchemePartitionSchemeDescription
	PartitionSchemeSingleton                  PartitionScheme = original.PartitionSchemeSingleton
	PartitionSchemeUniformInt64Range          PartitionScheme = original.PartitionSchemeUniformInt64Range
)

type ProvisioningState = original.ProvisioningState

const (
	Canceled  ProvisioningState = original.Canceled
	Failed    ProvisioningState = original.Failed
	Succeeded ProvisioningState = original.Succeeded
	Updating  ProvisioningState = original.Updating
)

type ReliabilityLevel = original.ReliabilityLevel

const (
	ReliabilityLevelBronze   ReliabilityLevel = original.ReliabilityLevelBronze
	ReliabilityLevelGold     ReliabilityLevel = original.ReliabilityLevelGold
	ReliabilityLevelNone     ReliabilityLevel = original.ReliabilityLevelNone
	ReliabilityLevelPlatinum ReliabilityLevel = original.ReliabilityLevelPlatinum
	ReliabilityLevelSilver   ReliabilityLevel = original.ReliabilityLevelSilver
)

type ReliabilityLevel1 = original.ReliabilityLevel1

const (
	ReliabilityLevel1Bronze ReliabilityLevel1 = original.ReliabilityLevel1Bronze
	ReliabilityLevel1Gold   ReliabilityLevel1 = original.ReliabilityLevel1Gold
	ReliabilityLevel1Silver ReliabilityLevel1 = original.ReliabilityLevel1Silver
)

type Scheme = original.Scheme

const (
	Affinity           Scheme = original.Affinity
	AlignedAffinity    Scheme = original.AlignedAffinity
	Invalid            Scheme = original.Invalid
	NonAlignedAffinity Scheme = original.NonAlignedAffinity
)

type ServiceKind = original.ServiceKind

const (
	ServiceKindServiceProperties ServiceKind = original.ServiceKindServiceProperties
	ServiceKindStateful          ServiceKind = original.ServiceKindStateful
	ServiceKindStateless         ServiceKind = original.ServiceKindStateless
)

type ServiceKindBasicServiceUpdateProperties = original.ServiceKindBasicServiceUpdateProperties

const (
	ServiceKindBasicServiceUpdatePropertiesServiceKindServiceUpdateProperties ServiceKindBasicServiceUpdateProperties = original.ServiceKindBasicServiceUpdatePropertiesServiceKindServiceUpdateProperties
	ServiceKindBasicServiceUpdatePropertiesServiceKindStateful                ServiceKindBasicServiceUpdateProperties = original.ServiceKindBasicServiceUpdatePropertiesServiceKindStateful
	ServiceKindBasicServiceUpdatePropertiesServiceKindStateless               ServiceKindBasicServiceUpdateProperties = original.ServiceKindBasicServiceUpdatePropertiesServiceKindStateless
)

type Type = original.Type

const (
	TypeServicePlacementPolicyDescription Type = original.TypeServicePlacementPolicyDescription
)

type UpgradeMode = original.UpgradeMode

const (
	Automatic UpgradeMode = original.Automatic
	Manual    UpgradeMode = original.Manual
)

type UpgradeMode1 = original.UpgradeMode1

const (
	UpgradeMode1Automatic UpgradeMode1 = original.UpgradeMode1Automatic
	UpgradeMode1Manual    UpgradeMode1 = original.UpgradeMode1Manual
)

type Weight = original.Weight

const (
	WeightHigh   Weight = original.WeightHigh
	WeightLow    Weight = original.WeightLow
	WeightMedium Weight = original.WeightMedium
	WeightZero   Weight = original.WeightZero
)

type X509StoreName = original.X509StoreName

const (
	AddressBook          X509StoreName = original.AddressBook
	AuthRoot             X509StoreName = original.AuthRoot
	CertificateAuthority X509StoreName = original.CertificateAuthority
	Disallowed           X509StoreName = original.Disallowed
	My                   X509StoreName = original.My
	Root                 X509StoreName = original.Root
	TrustedPeople        X509StoreName = original.TrustedPeople
	TrustedPublisher     X509StoreName = original.TrustedPublisher
)

type ApplicationDeleteFuture = original.ApplicationDeleteFuture
type ApplicationHealthPolicy = original.ApplicationHealthPolicy
type ApplicationMetricDescription = original.ApplicationMetricDescription
type ApplicationParameter = original.ApplicationParameter
type ApplicationPatchFuture = original.ApplicationPatchFuture
type ApplicationProperties = original.ApplicationProperties
type ApplicationPutFuture = original.ApplicationPutFuture
type ApplicationResource = original.ApplicationResource
type ApplicationResourceList = original.ApplicationResourceList
type ApplicationResourceUpdate = original.ApplicationResourceUpdate
type ApplicationTypeDeleteFuture = original.ApplicationTypeDeleteFuture
type ApplicationTypeProperties = original.ApplicationTypeProperties
type ApplicationTypeResource = original.ApplicationTypeResource
type ApplicationTypeResourceList = original.ApplicationTypeResourceList
type ApplicationUpdateProperties = original.ApplicationUpdateProperties
type ApplicationUpgradePolicy = original.ApplicationUpgradePolicy
type AvailableOperationDisplay = original.AvailableOperationDisplay
type AzureActiveDirectory = original.AzureActiveDirectory
type CertificateDescription = original.CertificateDescription
type ClientCertificateCommonName = original.ClientCertificateCommonName
type ClientCertificateThumbprint = original.ClientCertificateThumbprint
type Cluster = original.Cluster
type ClusterCodeVersionsListResult = original.ClusterCodeVersionsListResult
type ClusterCodeVersionsResult = original.ClusterCodeVersionsResult
type ClusterHealthPolicy = original.ClusterHealthPolicy
type ClusterListResult = original.ClusterListResult
type ClusterProperties = original.ClusterProperties
type ClusterPropertiesUpdateParameters = original.ClusterPropertiesUpdateParameters
type ClustersCreateFuture = original.ClustersCreateFuture
type ClustersUpdateFuture = original.ClustersUpdateFuture
type ClusterUpdateParameters = original.ClusterUpdateParameters
type ClusterUpgradeDeltaHealthPolicy = original.ClusterUpgradeDeltaHealthPolicy
type ClusterUpgradePolicy = original.ClusterUpgradePolicy
type ClusterVersionDetails = original.ClusterVersionDetails
type DiagnosticsStorageAccountConfig = original.DiagnosticsStorageAccountConfig
type EndpointRangeDescription = original.EndpointRangeDescription
type ErrorModel = original.ErrorModel
type NamedPartitionSchemeDescription = original.NamedPartitionSchemeDescription
type NodeTypeDescription = original.NodeTypeDescription
type OperationListResult = original.OperationListResult
type OperationListResultIterator = original.OperationListResultIterator
type OperationListResultPage = original.OperationListResultPage
type OperationResult = original.OperationResult
type BasicPartitionSchemeDescription = original.BasicPartitionSchemeDescription
type PartitionSchemeDescription = original.PartitionSchemeDescription
type ProxyResource = original.ProxyResource
type Resource = original.Resource
type RollingUpgradeMonitoringPolicy = original.RollingUpgradeMonitoringPolicy
type ServiceCorrelationDescription = original.ServiceCorrelationDescription
type ServiceDeleteFuture = original.ServiceDeleteFuture
type ServiceLoadMetricDescription = original.ServiceLoadMetricDescription
type ServicePatchFuture = original.ServicePatchFuture
type BasicServicePlacementPolicyDescription = original.BasicServicePlacementPolicyDescription
type ServicePlacementPolicyDescription = original.ServicePlacementPolicyDescription
type BasicServiceProperties = original.BasicServiceProperties
type ServiceProperties = original.ServiceProperties
type ServicePropertiesBase = original.ServicePropertiesBase
type ServicePutFuture = original.ServicePutFuture
type ServiceResource = original.ServiceResource
type ServiceResourceList = original.ServiceResourceList
type ServiceResourceUpdate = original.ServiceResourceUpdate
type ServiceTypeDeltaHealthPolicy = original.ServiceTypeDeltaHealthPolicy
type ServiceTypeHealthPolicy = original.ServiceTypeHealthPolicy
type ServiceTypeHealthPolicyMapItem = original.ServiceTypeHealthPolicyMapItem
type BasicServiceUpdateProperties = original.BasicServiceUpdateProperties
type ServiceUpdateProperties = original.ServiceUpdateProperties
type SettingsParameterDescription = original.SettingsParameterDescription
type SettingsSectionDescription = original.SettingsSectionDescription
type SingletonPartitionSchemeDescription = original.SingletonPartitionSchemeDescription
type StatefulServiceProperties = original.StatefulServiceProperties
type StatefulServiceUpdateProperties = original.StatefulServiceUpdateProperties
type StatelessServiceProperties = original.StatelessServiceProperties
type StatelessServiceUpdateProperties = original.StatelessServiceUpdateProperties
type UniformInt64RangePartitionSchemeDescription = original.UniformInt64RangePartitionSchemeDescription
type VersionDeleteFuture = original.VersionDeleteFuture
type VersionProperties = original.VersionProperties
type VersionPutFuture = original.VersionPutFuture
type VersionResource = original.VersionResource
type VersionResourceList = original.VersionResourceList

func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}
func NewVersionClient() VersionClient {
	return original.NewVersionClient()
}
func NewVersionClientWithBaseURI(baseURI string) VersionClient {
	return original.NewVersionClientWithBaseURI(baseURI)
}
func NewApplicationTypeClient() ApplicationTypeClient {
	return original.NewApplicationTypeClient()
}
func NewApplicationTypeClientWithBaseURI(baseURI string) ApplicationTypeClient {
	return original.NewApplicationTypeClientWithBaseURI(baseURI)
}
func New() BaseClient {
	return original.New()
}
func NewWithBaseURI(baseURI string) BaseClient {
	return original.NewWithBaseURI(baseURI)
}
func NewClusterVersionsClient() ClusterVersionsClient {
	return original.NewClusterVersionsClient()
}
func NewClusterVersionsClientWithBaseURI(baseURI string) ClusterVersionsClient {
	return original.NewClusterVersionsClientWithBaseURI(baseURI)
}
func NewOperationsClient() OperationsClient {
	return original.NewOperationsClient()
}
func NewOperationsClientWithBaseURI(baseURI string) OperationsClient {
	return original.NewOperationsClientWithBaseURI(baseURI)
}
func NewApplicationClient() ApplicationClient {
	return original.NewApplicationClient()
}
func NewApplicationClientWithBaseURI(baseURI string) ApplicationClient {
	return original.NewApplicationClientWithBaseURI(baseURI)
}
func NewClustersClient() ClustersClient {
	return original.NewClustersClient()
}
func NewClustersClientWithBaseURI(baseURI string) ClustersClient {
	return original.NewClustersClientWithBaseURI(baseURI)
}
func NewServiceClient() ServiceClient {
	return original.NewServiceClient()
}
func NewServiceClientWithBaseURI(baseURI string) ServiceClient {
	return original.NewServiceClientWithBaseURI(baseURI)
}


text:
if<caret> :
    doSomething()
elif
    pass
elif :
    pass
elif a
    pass
else


text:
#include <cinttypes>
#include <cstdlib>

#include "el/animation_manager.h"
#include "xenia/base/string_buffer.h"
#include "xenia/base/string_util.h"
#include "xenia/cpu/x64_context.h"
#include "xenia/debug/ui/views/cpu/register_list_control.h"

namespace xe {
namespace debug {
namespace ui {
namespace views {
namespace cpu {

using xe::cpu::frontend::PPCRegister;
using xe::cpu::X64Register;

enum class RegisterType {
  kControl,
  kInteger,
  kFloat,
  kVector,
};

class RegisterItem : public el::GenericStringItem {
 public:
  const char* name() { return name_.c_str(); }

  virtual void set_thread(model::Thread* thread) { thread_ = thread; }

 protected:
  RegisterItem(RegisterSet set, RegisterType type, int ordinal)
      : GenericStringItem(""), set_(set), type_(type), ordinal_(ordinal) {
    tag.set_integer(ordinal);
  }

  RegisterSet set_;
  RegisterType type_;
  int ordinal_;
  model::Thread* thread_ = nullptr;
  std::string name_;
};

class GuestRegisterItem : public RegisterItem {
 public:
  GuestRegisterItem(RegisterSet set, RegisterType type, PPCRegister reg)
      : RegisterItem(set, type, static_cast<int>(reg)), reg_(reg) {
    name_ = xe::cpu::frontend::PPCContext::GetRegisterName(reg_);
  }

  void set_thread(model::Thread* thread) override {
    RegisterItem::set_thread(thread);
    if (thread_) {
      str = thread_->guest_context()->GetStringFromValue(reg_);
    } else {
      str = "unknown";
    }
  }

 private:
  PPCRegister reg_;
};

class HostRegisterItem : public RegisterItem {
 public:
  HostRegisterItem(RegisterSet set, RegisterType type, X64Register reg)
      : RegisterItem(set, type, static_cast<int>(reg)), reg_(reg) {
    name_ = xe::cpu::X64Context::GetRegisterName(reg_);
  }

  void set_thread(model::Thread* thread) override {
    RegisterItem::set_thread(thread);
    if (thread_) {
      str = thread_->host_context()->GetStringFromValue(reg_);
    } else {
      str = "unknown";
    }
  }

 private:
  X64Register reg_;
};

class RegisterItemElement : public el::LayoutBox {
 public:
  RegisterItemElement(RegisterItem* item, RegisterItemSource* source,
                      el::ListItemObserver* source_viewer, size_t index)
      : item_(item),
        source_(source),
        source_viewer_(source_viewer),
        index_(index) {
    set_background_skin(TBIDC("ListItem"));
    set_axis(el::Axis::kY);
    set_gravity(el::Gravity::kAll);
    set_layout_position(el::LayoutPosition::kLeftTop);
    set_layout_distribution(el::LayoutDistribution::kAvailable);
    set_layout_distribution_position(el::LayoutDistributionPosition::kLeftTop);
    set_layout_size(el::LayoutSize::kAvailable);
    set_paint_overflow_fadeout(false);

    using namespace el::dsl;  // NOLINT(build/namespaces)
    el::AnimationBlocker animation_blocker;

    auto node = LayoutBoxNode()
                    .axis(Axis::kX)
                    .gravity(Gravity::kLeft)
                    .distribution(LayoutDistribution::kAvailable)
                    .child(LabelNode(item_->name())
                               .ignore_input(true)
                               .width(45_px)
                               .gravity(Gravity::kLeft))
                    .child(TextBoxNode(item_->str.c_str())
                               .gravity(Gravity::kLeftRight));
    content_root()->LoadNodeTree(node);
  }

  bool OnEvent(const el::Event& ev) override {
    return el::LayoutBox::OnEvent(ev);
  }

 private:
  RegisterItem* item_ = nullptr;
  RegisterItemSource* source_ = nullptr;
  el::ListItemObserver* source_viewer_ = nullptr;
  size_t index_ = 0;
};

class RegisterItemSource : public el::ListItemSourceList<RegisterItem> {
 public:
  el::Element* CreateItemElement(size_t index,
                                 el::ListItemObserver* viewer) override {
    return new RegisterItemElement(at(index), this, viewer, index);
  }
};

void DefineRegisterItem(RegisterItemSource* item_source, RegisterSet set,
                        RegisterType type, PPCRegister reg) {
  auto item = std::make_unique<GuestRegisterItem>(set, type, reg);
  item->tag.set_integer(static_cast<int>(reg));
  item_source->push_back(std::move(item));
}
void DefineRegisterItem(RegisterItemSource* item_source, RegisterSet set,
                        RegisterType type, X64Register reg) {
  auto item = std::make_unique<HostRegisterItem>(set, type, reg);
  item->tag.set_integer(static_cast<int>(reg));
  item_source->push_back(std::move(item));
}

RegisterListControl::RegisterListControl(RegisterSet set)
    : set_(set), item_source_(new RegisterItemSource()) {
  switch (set_) {
    case RegisterSet::kGeneral: {
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         PPCRegister::kLR);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         PPCRegister::kCTR);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kControl,
                         PPCRegister::kXER);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kControl,
                         PPCRegister::kCR);
      for (size_t i = 0; i < 32; ++i) {
        DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                           static_cast<PPCRegister>(
                               static_cast<size_t>(PPCRegister::kR0) + i));
      }
    } break;
    case RegisterSet::kFloat: {
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kControl,
                         PPCRegister::kFPSCR);
      for (size_t i = 0; i < 32; ++i) {
        DefineRegisterItem(item_source_.get(), set_, RegisterType::kFloat,
                           static_cast<PPCRegister>(
                               static_cast<size_t>(PPCRegister::kFR0) + i));
      }
    } break;
    case RegisterSet::kVector: {
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kControl,
                         PPCRegister::kVSCR);
      for (size_t i = 0; i < 128; ++i) {
        DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                           static_cast<PPCRegister>(
                               static_cast<size_t>(PPCRegister::kVR0) + i));
      }
    } break;
    case RegisterSet::kHost: {
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRip);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kControl,
                         X64Register::kEflags);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRax);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRcx);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRdx);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRbx);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRsp);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRbp);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRsi);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kRdi);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR8);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR9);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR10);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR11);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR12);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR13);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR14);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kInteger,
                         X64Register::kR15);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm0);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm1);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm2);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm3);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm4);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm5);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm6);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm7);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm8);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm9);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm10);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm11);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm12);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm13);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm14);
      DefineRegisterItem(item_source_.get(), set_, RegisterType::kVector,
                         X64Register::kXmm15);
    } break;
  }
}

RegisterListControl::~RegisterListControl() = default;

el::Element* RegisterListControl::BuildUI() {
  using namespace el::dsl;  // NOLINT(build/namespaces)
  el::AnimationBlocker animation_blocker;

  auto node =
      LayoutBoxNode()
          .gravity(Gravity::kAll)
          .distribution(LayoutDistribution::kAvailable)
          .child(ListBoxNode().id("register_listbox").gravity(Gravity::kAll));

  root_element_.set_gravity(Gravity::kAll);
  root_element_.set_layout_distribution(LayoutDistribution::kAvailable);
  root_element_.LoadNodeTree(node);

  auto register_listbox =
      root_element_.GetElementById<el::ListBox>(TBIDC("register_listbox"));
  register_listbox->set_source(item_source_.get());
  register_listbox->scroll_container()->set_scroll_mode(
      el::ScrollMode::kAutoXAutoY);

  handler_ = std::make_unique<el::EventHandler>(&root_element_);

  return &root_element_;
}

void RegisterListControl::Setup(DebugClient* client) {
  client_ = client;

  system()->on_thread_state_updated.AddListener([this](model::Thread* thread) {
    if (thread == thread_) {
      InvalidateRegisters();
    }
  });
}

void RegisterListControl::set_thread(model::Thread* thread) {
  thread_ = thread;
  InvalidateRegisters();
}

void RegisterListControl::InvalidateRegisters() {
  for (size_t i = 0; i < item_source_->size(); ++i) {
    item_source_->at(i)->set_thread(thread_);
  }

  auto register_listbox =
      root_element_.GetElementById<el::ListBox>(TBIDC("register_listbox"));
  register_listbox->InvalidateList();
}

}  // namespace cpu
}  // namespace views
}  // namespace ui
}  // namespace debug
}  // namespace xe


text:
/** See the file "LICENSE" for the full license governing this code. */
/** Top level of the db classes. */
package au.org.ands.vocabs.toolkit.db;


text:
package ca.ualberta.physics.cssdp.util;

import java.io.File;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import ca.ualberta.physics.cssdp.configuration.ApplicationProperties;

import com.google.common.io.Files;

public class TarTest {

	@Test
	public void testTarAndUnTar() throws Exception {

		// tar up the source files
		File dirToTar = new File(ApplicationProperties.class.getResource(".")
				.toURI()).getParentFile().getCanonicalFile();

		File tarFile = FileUtil
				.tar(dirToTar,
						"/home/rpotter/workspaces/cicstart/common/bin/ca/ualberta/physics");

		File untarDir = Files.createTempDir();

		List<File> untaredFiles = FileUtil.unTar(tarFile, untarDir);

		List<File> original = FileUtil.walk(dirToTar);

		Assert.assertEquals(original.size(), untaredFiles.size());

		for (int i = 0; i < original.size(); i++) {
			Assert.assertEquals(original.get(i).getName(), untaredFiles.get(i)
					.getName());
		}

		// cleanup
		tarFile.delete();
		for (File file : untaredFiles) {
			file.delete();
		}
	}

	@Test
	public void testGzipAndUnGzip() throws Exception {

		// tar up the source files
		File dirToTar = new File(ApplicationProperties.class.getResource(".")
				.toURI()).getParentFile().getCanonicalFile();

		File tarFile = FileUtil
				.tar(dirToTar,
						"/home/rpotter/workspaces/cicstart/common/bin/ca/ualberta/physics");

		long tarFileSize = tarFile.length();
		String tarFileName = tarFile.getName();

		File gzippedFile = FileUtil.gzip(tarFile);

		Assert.assertTrue(tarFileSize > gzippedFile.length());
		Assert.assertEquals(tarFile.getAbsolutePath() + ".gz",
				gzippedFile.getAbsolutePath());

		File tempDir = Files.createTempDir();

		File unGzippedFile = FileUtil.unGzip(gzippedFile, tempDir);

		Assert.assertEquals(tarFileSize, unGzippedFile.length());
		Assert.assertEquals(tarFileName, unGzippedFile.getName());

		unGzippedFile.delete();
		tempDir.delete();

	}

}


text:
<?php
/**
 * Parse CSV, group by the first X columns and return CSV
 *
 * See README.md for example.
 *
 * To highlight different groups in Excel:
 *   - Open output CSV in Excel.
 *   - Select all cells.
 *   - Go to Home > Conditional Formatting > New Rule.
 *       + Rule type: Use a formula to determine which cells to format
 *       + Format values where this formula is true (assuming 2 grouping columns):
 *           * If highlighting by combined group: =(INDIRECT(ADDRESS(ROW(), 1)) = "combined:0:0")
 *           * If highlighting by 1st grouping column: =(INDIRECT(ADDRESS(ROW(), 2)) = "group:1:0")
 *           * If highlighting by 2nd grouping column: =(INDIRECT(ADDRESS(ROW(), 3)) = "group:2:0")
 *       + Format: Fill > select a color.
 *       + Click OK.
 *   - Background color for groups will alternate between the selected color and the default white color.
 *
 * If running via commandline and taking in 3 arguments to match the 3 method parameters:
 *   groupCsv($argv[1], $argv[2], $argv[3]);
 *
 * @link  https://github.com/zionsg/standalone-php-scripts/tree/master/groupCsv
 * @param string $inputCsvPath Path to input CSV file
 * @param int $columnsToGroup No. of columns to group. 0="no grouping", 1="group by first column",
 *                            2="group by the first 2 columns", etc.
 * @param string $inputCsvPath Path to output CSV file
 * @return void
 */
function groupCsv($inputCsvPath, $columnsToGroup = 0, $outputCsvPath = 'php://output')
{
    $inputHandle = fopen($inputCsvPath, 'r');
    $outputHandle = fopen($outputCsvPath, 'w');

    $rowIndex = 0;
    $groupIndices = $columnsToGroup ? array_fill(0, $columnsToGroup, 1) : [];
    $prevGroup = [];

    while (($data = fgetcsv($inputHandle)) !== false) {
        // Header row - prepend X columns to row as per columns to group, as well as a combined group
        if (0 === $rowIndex) {
            $headers = [
                'Combined Group: ' . implode(',', array_slice($data, 0, $columnsToGroup))
            ];
            for ($groupCol = 0; $groupCol < $columnsToGroup; $groupCol++) {
                $headers[] = 'Group ' . ($groupCol + 1) . ': ' . $data[$groupCol];
            }
            for ($col = 0; $col < count($data); $col++) {
                $headers[] = $data[$col];
            }

            fputcsv($outputHandle, $headers);
            $rowIndex++;

            continue;
        }

        // Determine groups
        for ($groupCol = 0; $groupCol < $columnsToGroup; $groupCol++) {
            $prev = $prevGroup[$groupCol] ?? null;
            $curr = $data[$groupCol];

            if ($curr !== $prev) {
                $groupIndices[$groupCol] = ($groupIndices[$groupCol] + 1) % 2;
                $prevGroup[$groupCol] = $curr;
            } else {
                // Blank out grouping columns if value is the same as previous row
                $data[$groupCol] = '';
            }
        }

        // Prepend X columns to row as per columns to group
        for ($groupCol = ($columnsToGroup - 1); $groupCol >= 0; $groupCol--) {
            array_unshift($data, 'group:' . ($groupCol + 1) . ':' . $groupIndices[$groupCol]);
        }
        array_unshift($data, 'combined:' . implode(':', $groupIndices));

        fputcsv($outputHandle, $data);
        $rowIndex++;
    }

    fclose($inputHandle);
    fclose($outputHandle);
}


text:
package org.apache.geode.internal.cache.tier.sockets.command;

import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;
import org.apache.geode.test.dunit.rules.CQUnitTestRule;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class CloseCQTest {

  @Rule
  public CQUnitTestRule cqRule = new CQUnitTestRule();

  @Test
  public void needDataReadRegionToClose() throws Exception {
    CloseCQ closeCQ = mock(CloseCQ.class);
    doCallRealMethod().when(closeCQ).cmdExecute(cqRule.message, cqRule.connection,
        cqRule.securityService, 0);

    closeCQ.cmdExecute(cqRule.message, cqRule.connection, cqRule.securityService, 0);

    verify(cqRule.securityService).authorize(Resource.DATA, Operation.READ, "regionName");
  }
}


text:
<?php

namespace Kanboard\Api;

/**
 * Group API controller
 *
 * @package  api
 * @author   Frederic Guillot
 */
class Group extends \Kanboard\Core\Base
{
    public function createGroup($name, $external_id = '')
    {
        return $this->group->create($name, $external_id);
    }

    public function updateGroup($group_id, $name = null, $external_id = null)
    {
        $values = array(
            'id' => $group_id,
            'name' => $name,
            'external_id' => $external_id,
        );

        foreach ($values as $key => $value) {
            if (is_null($value)) {
                unset($values[$key]);
            }
        }

        return $this->group->update($values);
    }

    public function removeGroup($group_id)
    {
        return $this->group->remove($group_id);
    }

    public function getGroup($group_id)
    {
        return $this->group->getById($group_id);
    }

    public function getAllGroups()
    {
        return $this->group->getAll();
    }
}


text:
package proto

import (
	"reflect"
	"testing"
)

func TestProduceResponse(t *testing.T) {
	expected := ProduceResponse{"topic", 0, 1234}
	b, err := Encode(&expected)
	if err != nil {
		t.Fatalf("Encode: %v", err)
	}
	var actual ProduceResponse
	err = Decode(b, &actual)
	if err != nil {
		t.Fatalf("Decode: %v", err)
	}
	if !reflect.DeepEqual(expected, actual) {
		t.Fatalf("expected %+v, got %v", expected, actual)
	}
}


text:
<?php

namespace Storekeeper\InventoryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Pack
 */
class Pack
{
    /**
     * @var integer
     */
    private $id;

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

    /**
     * Convert name object to string
     *
     * @return string
     */
    public function __toString(){
        return (string)$this->id;
    }

    /**
     * @var string
     */
    private $description;

    /**
     * @var boolean
     */
    private $hasPicture;

    /**
     * Set name
     *
     * @param string $name
     * @return Pack
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

    /**
     * Set description
     *
     * @param string $description
     * @return Pack
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

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

    /**
     * Set hasPicture
     *
     * @param boolean $hasPicture
     * @return Pack
     */
    public function setHasPicture($hasPicture)
    {
        $this->hasPicture = $hasPicture;

        return $this;
    }

    /**
     * Get hasPicture
     *
     * @return boolean
     */
    public function getHasPicture()
    {
        return $this->hasPicture;
    }
    /**
     * @var string
     */
    private $barcode;

    /**
     * Set barcode
     *
     * @param string $barcode
     * @return Pack
     */
    public function setBarcode($barcode)
    {
        $this->barcode = $barcode;

        return $this;
    }

    /**
     * Get barcode
     *
     * @return string
     */
    public function getBarcode()
    {
        return $this->barcode;
    }
    /**
     * @var string
     */
    private $name;

}


text:
class MutableMatrix44D;
class IFloatBuffer;
class Color;

class AbstractMesh : public Mesh {
protected:
  const int               _primitive;
  const bool              _owner;
  const Vector3D                _center;
  const MutableMatrix44D* _translationMatrix;
  const IFloatBuffer*           _vertices;
  const Color*            _flatColor;
  const IFloatBuffer*           _colors;
  const float             _colorsIntensity;
  const float             _lineWidth;
  const float             _pointSize;
  const bool              _depthTest;
  const IFloatBuffer*           _normals;

  mutable BoundingVolume* _boundingVolume;
  BoundingVolume* computeBoundingVolume() const;

  AbstractMesh(const int primitive,
               bool owner,
               const Vector3D& center,
               const IFloatBuffer* vertices,
               float lineWidth,
               float pointSize,
               const Color* flatColor,
               const IFloatBuffer* colors,
               const float colorsIntensity,
               bool depthTest,
               const IFloatBuffer* normals);

  virtual void rawRender(const G3MRenderContext* rc) const = 0;
//  virtual void rawRender(const G3MRenderContext* rc, const GLState* parentGLState) const = 0;

  GLState* _glState;

  void createGLState();

  mutable bool _showNormals;
  mutable Mesh* _normalsMesh;
  Mesh* createNormalsMesh() const;

public:
  ~AbstractMesh();

  BoundingVolume* getBoundingVolume() const;

  int getVertexCount() const;

  const Vector3D getVertex(int i) const;

  bool isTransparent(const G3MRenderContext* rc) const;

  void rawRender(const G3MRenderContext* rc,
                 const GLState* parentGLState) const;

  void showNormals(bool v) const {
    _showNormals = v;
  }

};

#endif


text:
Chuck Norris does not write descriptions. Descriptions are invented by Chuck Norris.

# Chuck Norris Sources

- German: http://www.chuck-norris-facts.org/alle_facts?order=title&sort=desc


text:
package org.ovirt.engine.ui.uicommonweb.models.templates;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.DiskImageList;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.IIsObjectInSetup;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicommonweb.validation.RegexValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;

@SuppressWarnings("unused")
public class ImportTemplateModel extends ListWithDetailsModel implements IIsObjectInSetup
{

    private storage_domain_static privateSourceStorage;

    public storage_domain_static getSourceStorage()
    {
        return privateSourceStorage;
    }

    public void setSourceStorage(storage_domain_static value)
    {
        privateSourceStorage = value;
    }

    private storage_pool privateStoragePool;

    public storage_pool getStoragePool()
    {
        return privateStoragePool;
    }

    public void setStoragePool(storage_pool value)
    {
        privateStoragePool = value;
    }

    private ListModel privateDestinationStorage;

    public ListModel getDestinationStorage()
    {
        return privateDestinationStorage;
    }

    private void setDestinationStorage(ListModel value)
    {
        privateDestinationStorage = value;
    }

    private ListModel privateCluster;

    public ListModel getCluster()
    {
        return privateCluster;
    }

    private void setCluster(ListModel value)
    {
        privateCluster = value;
    }

    private String nameAndDescription;
    private TemplateImportDiskListModel templateImportDiskListModel;

    public String getNameAndDescription()
    {
        return nameAndDescription;
    }

    public void setNameAndDescription(String value)
    {
        if (!StringHelper.stringsEqual(nameAndDescription, value))
        {
            nameAndDescription = value;
            OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription")); //$NON-NLS-1$
        }
    }

    private EntityModel privateIsSingleDestStorage;

    public EntityModel getIsSingleDestStorage() {
        return privateIsSingleDestStorage;
    }

    public void setIsSingleDestStorage(EntityModel value) {
        privateIsSingleDestStorage = value;
    }

    private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap;

    public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap()
    {
        return privateDiskStorageMap;
    }

    public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value)
    {
        privateDiskStorageMap = value;
    }

    private HashMap<Guid, VmTemplate> alreadyInSystem;

    private EntityModel cloneAllTemplates;
    private EntityModel cloneAllTemplates_message;
    private EntityModel cloneOnlyDuplicateTemplates;
    private EntityModel cloneTemplatesSuffix;

    public EntityModel getCloneAllTemplates() {
        return cloneAllTemplates;
    }

    public void setCloneAllTemplates(EntityModel cloneAllTemplates) {
        this.cloneAllTemplates = cloneAllTemplates;
    }

    public EntityModel getCloneAllTemplates_message() {
        return cloneAllTemplates_message;
    }

    public void setCloneAllTemplates_message(EntityModel cloneAllTemplates_message) {
        this.cloneAllTemplates_message = cloneAllTemplates_message;
    }

    public EntityModel getCloneOnlyDuplicateTemplates() {
        return cloneOnlyDuplicateTemplates;
    }

    public void setCloneOnlyDuplicateTemplates(EntityModel cloneOnlyDuplicateTemplates) {
        this.cloneOnlyDuplicateTemplates = cloneOnlyDuplicateTemplates;
    }

    public EntityModel getCloneTemplatesSuffix() {
        return cloneTemplatesSuffix;
    }

    public void setCloneTemplatesSuffix(EntityModel cloneTemplatesSuffix) {
        this.cloneTemplatesSuffix = cloneTemplatesSuffix;
    }

    public ImportTemplateModel()
    {
        setDestinationStorage(new ListModel());
        setCluster(new ListModel());
        setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>());
        setIsSingleDestStorage(new EntityModel());
        getIsSingleDestStorage().setEntity(true);

        setCloneAllTemplates(new EntityModel());
        getCloneAllTemplates().setEntity(false);
        getCloneAllTemplates().getEntityChangedEvent().addListener(new IEventListener() {

            @Override
            public void eventRaised(Event ev, Object sender, EventArgs args) {
                if ((Boolean) getCloneAllTemplates().getEntity()) {
                    getCloneTemplatesSuffix().setIsAvailable(true);
                } else if (!(Boolean) getCloneOnlyDuplicateTemplates().getEntity()) {
                    getCloneTemplatesSuffix().setIsAvailable(false);
                }
            }
        });
        setCloneOnlyDuplicateTemplates(new EntityModel());
        getCloneOnlyDuplicateTemplates().setEntity(false);
        getCloneOnlyDuplicateTemplates().setIsAvailable(false);
        setCloneTemplatesSuffix(new EntityModel());
        getCloneTemplatesSuffix().setEntity("_Copy"); //$NON-NLS-1$
        getCloneTemplatesSuffix().setIsAvailable(false);
        setCloneAllTemplates_message(new EntityModel());
    }

    @Override
    protected void InitDetailModels()
    {
        super.InitDetailModels();

        ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
        list.add(new TemplateGeneralModel());
        list.add(new TemplateImportInterfaceListModel());
        this.templateImportDiskListModel = new TemplateImportDiskListModel();
        list.add(templateImportDiskListModel);
        setDetailModels(list);
    }

    public boolean Validate()
    {
        getDestinationStorage().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });

        getCluster().ValidateSelectedItem(new IValidation[] { new NotEmptyValidation() });

        getCloneTemplatesSuffix().setIsValid(true);
        if (getCloneTemplatesSuffix().getIsAvailable()) {
            getCloneTemplatesSuffix().ValidateEntity(new IValidation[] { new NotEmptyValidation() });
            if (!getCloneTemplatesSuffix().getIsValid()) {
                return false;
            }
            List<VmTemplate> list = (List<VmTemplate>) getItems();
            for (VmTemplate template : list) {
                String newTemplateName = template.getname() + getCloneTemplatesSuffix().getEntity();

                String nameExpr;
                String nameMsg;
                nameExpr = "^[0-9a-zA-Z-_]{1," + 49 + "}$"; //$NON-NLS-1$ //$NON-NLS-2$
                nameMsg =
                        ConstantsManager.getInstance()
                                .getMessages()
                                .newNameWithSuffixCannotContainBlankOrSpecialChars(40);
                EntityModel temp = new EntityModel();
                temp.setIsValid(true);
                temp.setEntity(newTemplateName);
                temp.ValidateEntity(
                        new IValidation[] {
                                new NotEmptyValidation(),
                                new RegexValidation(nameExpr, nameMsg)
                        });
                if (!temp.getIsValid()) {
                    getCloneTemplatesSuffix().setInvalidityReasons(temp.getInvalidityReasons());
                    getCloneTemplatesSuffix().setIsValid(false);
                    return false;
                }
            }
        }

        return getDestinationStorage().getIsValid() && getCluster().getIsValid()
                & getCloneTemplatesSuffix().getIsValid();
    }

    @Override
    public void setItems(final Iterable value)
    {
        String vmt_guidKey = "_VMT_ID ="; //$NON-NLS-1$
        String orKey = " or "; //$NON-NLS-1$
        StringBuilder searchPattern = new StringBuilder();
        searchPattern.append("Template: "); //$NON-NLS-1$

        final List<VmTemplate> list = (List<VmTemplate>) value;
        for (int i = 0; i < list.size(); i++) {
            VmTemplate vmTemplate = list.get(i);

            searchPattern.append(vmt_guidKey);
            searchPattern.append(vmTemplate.getId().toString());
            if (i < list.size() - 1) {
                searchPattern.append(orKey);
            }
        }

        Frontend.RunQuery(VdcQueryType.Search,
                new SearchParameters(searchPattern.toString(), SearchType.VmTemplate),
                new AsyncQuery(this, new INewAsyncCallback() {

                    @Override
                    public void OnSuccess(Object model, Object returnValue) {
                        List<VmTemplate> vmtList =
                                (List<VmTemplate>) ((VdcQueryReturnValue) returnValue).getReturnValue();
                        alreadyInSystem = new HashMap<Guid, VmTemplate>();
                        for (VmTemplate vmt : vmtList) {
                            alreadyInSystem.put(vmt.getId(), vmt);
                        }

                        if (alreadyInSystem.size() > 0) {
                            getCloneAllTemplates_message().setEntity(alreadyInSystem.size() + " " //$NON-NLS-1$
                                    + ConstantsManager.getInstance().getConstants().templateAlreadyExistsMsg());
                            if (list.size() == alreadyInSystem.size()) {
                                getCloneAllTemplates().setEntity(true);
                                getCloneTemplatesSuffix().setIsAvailable(true);
                            } else {
                                getCloneOnlyDuplicateTemplates().setIsAvailable(true);
                                getCloneOnlyDuplicateTemplates().setEntity(true);
                                getCloneTemplatesSuffix().setIsAvailable(true);
                            }
                        } else {
                            getCloneAllTemplates_message().setEntity(ConstantsManager.getInstance()
                                    .getConstants()
                                    .templateNoExistsMsg());
                        }

                        setSuperItems(value);
                    }
                }));

    }

    protected void setSuperItems(Iterable value) {
        super.setItems(value);
        List<VmTemplate> list = (List<VmTemplate>) getItems();
        for (VmTemplate vmTemplate : list) {
            getDiskStorageMap().put(vmTemplate.getId(), new HashMap<Guid, Guid>());
        }
        initDiskStorageMap();
    }

    private void initDiskStorageMap() {
        ArrayList<storage_domains> allDestStorages = (ArrayList<storage_domains>) getDestinationStorage().getItems();
        for (Object item : getItems()) {
            VmTemplate vmTemplate = (VmTemplate) item;
            for (DiskImage disk : vmTemplate.getDiskList()) {
                Guid storageId = !allDestStorages.isEmpty() ? allDestStorages.get(0).getId() : new Guid();
                addToDiskStorageMap(vmTemplate.getId(), disk, storageId);
            }
        }
    }

    @Override
    protected void OnSelectedItemChanged()
    {
        super.OnSelectedItemChanged();
    }

    @Override
    protected String getListName() {
        return "ImportTemplateModel"; //$NON-NLS-1$
    }

    public void setExtendedItems(ArrayList<Map.Entry<VmTemplate, DiskImageList>> arrayList) {
        templateImportDiskListModel.setExtendedItems(arrayList);
    }

    public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) {
        VmTemplate item = (VmTemplate) getSelectedItem();
        addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId());
    }

    public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) {
        HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId);
        vmDiskStorageMap.put(disk.getId(), storageId);
    }

    private storage_domains getStorageDomainByName(String storageDomainName) {
        storage_domains storage = null;
        for (Object storageDomain : getDestinationStorage().getItems()) {
            storage = (storage_domains) storageDomain;
            if (storageDomainName.equals(storage.getstorage_name())) {
                break;
            }
        }
        return storage;
    }

    @Override
    public boolean isObjectInSetup(Object vmTemplate) {
        if (alreadyInSystem == null) {
            return false;
        }
        return alreadyInSystem.containsKey(((VmTemplate) vmTemplate).getId());
    }
}


text: gTestsubsuite='Types';


text:
module.exports = function (opts) {
  require('../../index.js')(opts)
}


text:
using System;

namespace StayWell.ServiceDefinitions.Buckets.Objects
{
	[Obsolete]
	public enum ObjectStatus
	{
		None = 0,
		Active = 1,
		Deleted = 2,
		Uploading = 3 // added for image uploading process
	}
}


text:
package upcrm

import "go-common/app/admin/main/up/model/upcrmmodel"

//QueryPlayInfo query db
func (d *Dao) QueryPlayInfo(mid int64, busiType []int) (result []upcrmmodel.UpPlayInfo, err error) {
	err = d.crmdb.Where("mid=? and business_type in (?)", mid, busiType).Find(&result).Error
	return
}

// QueryPlayInfoBatch query db
func (d *Dao) QueryPlayInfoBatch(mid []int64, busiType int) (result []*upcrmmodel.UpPlayInfo, err error) {
	err = d.crmdb.Where("mid in (?) and business_type = ?", mid, busiType).Find(&result).Error
	return
}


text:
/* global AFRAME */
(function(){
  "use strict";

  AFRAME.registerComponent("wvrtd-life-bar", {
    schema: {
      life: { type: "number", default: 10 },
      height: { type: "number", default: 1 },
      radius: { type: "number", default: 0.2 },
      position: { type: "string", default: "0.5 0.5 0" }
    },
    init: function() {
      this.currentLife = this.data.life;

      this.lifeBar = document.createElement("a-cylinder");
      this.lifeBar.id = "lifeBar_" + (Math.floor(Math.random() * 100));
      this.lifeBar.setAttribute("height", this.data.height);
      this.lifeBar.setAttribute("radius", this.data.radius);
      this.lifeBar.setAttribute("material", {color: this.colorMyLife(1)});
      this.lifeBar.setAttribute("position", this.data.position);
      this.el.appendChild(this.lifeBar);

      this.el.addEventListener("hit", this.onHit.bind(this));
    },
    onHit: function(data){
      this.currentLife -= (data.detail ? data.detail.hitPoints : data.hitPoints);
      if(this.currentLife > 0){
        var ratio = this.currentLife / this.data.life;
        this.lifeBar.setAttribute("height", this.data.height * ratio);
        this.lifeBar.setAttribute("material", {color: this.colorMyLife(ratio)});
      }
      else{
        this.lifeBar.setAttribute("visible", false);
        this.el.emit("killed");
      }
    },
    colorMyLife: function(ratio){
      if(ratio > (2/3)){
        return "green";
      }
      else if(ratio > (1/3)){
        return "orange";
      }
      else{
        return "red";
      }
    }
  });

})();


text:
require "spec_helper"

RSpec.describe Graphiti::Delegates::Pagination do
  include_context "pagination_context"
  let(:instance) { described_class.new(proxy) }

  describe "#links?" do
    context "with empty data" do
      before { allow(proxy).to receive(:data).and_return([]) }

      it "returns false" do
        expect(instance.links?).to eq(false)
      end
    end
  end

  describe "#links" do
    subject { instance.links }
    before do
      allow(instance).to receive(:item_count).and_return(current_per_page * total_pages)
    end
    it "generates pagination links" do
      expect(subject).to include(:first, :next, :last, :prev)
    end
    it "generates a link for the first page" do
      expect(subject[:first]).to eq pagination_link(1)
    end
    it "generates a link for the last page" do
      expect(subject[:last]).to eq pagination_link(total_pages)
    end
    it "generates a link for the next page" do
      expect(subject[:next]).to eq pagination_link(next_page)
    end
    it "generates a link for the prev page" do
      expect(subject[:prev]).to eq pagination_link(prev_page)
    end
    context "if on the first page" do
      let(:current_page) { 1 }
      it "does not have a link for prev" do
        expect(subject[:prev]).to be_nil
      end
    end
    context "if on the last page" do
      let(:current_page) { total_pages }
      it "does not have a link for next" do
        expect(subject[:next]).to be_nil
      end
    end
    context "if only 1 page" do
      let(:current_page) { 1 }
      let(:total_pages) { 1 }
      it "does not have a link for next" do
        expect(subject[:next]).to be_nil
      end
      it "does not have a link for prev" do
        expect(subject[:prev]).to be_nil
      end
    end

    context "when no size param is passed" do
      let(:params) { {} }
      it "returns the default size" do
        expect(subject[:first]).to eq(pagination_link(1, size: Graphiti::Scoping::Paginate::DEFAULT_PAGE_SIZE))
      end
    end

    context "with included relationship" do
      let(:params) {
        {include: "bar,bazzes", filter: {"bazzes.deprecated" => "foo"}}
      }

      it "preserves include directive and filters on relationships" do
        query = URI.decode_www_form(URI(subject[:first]).query).to_h
        expect(query["include"]).to include("bar")
        expect(query["include"]).to include("bazzes")
        expect(query["filter[bazzes.deprecated]"]).to eq("foo")
      end
    end

    context "with rails parameters" do
      let(:params) {
        {controller: "foos", action: "index", format: "jsonapi"}
      }

      it "removes them" do
        page_links = subject.values
        expect(page_links).to all(satisfy { |v| v["controller=foos"].nil? })
        expect(page_links).to all(satisfy { |v| v["action=index"].nil? })
        expect(page_links).to all(satisfy { |v| v["format=jsonapi"].nil? })
      end
    end
  end

  def pagination_link(number, size: current_per_page)
    uri = URI(endpoint[:url])
    uri.query = params.merge(page: {number: number, size: size}).to_query
    uri.to_s
  end

  describe "#pagination_link" do
    subject { URI(instance.send(:pagination_link, current_page)) }
    it "retains existing params" do
      expect(subject.query).to eq(params.to_query)
    end
  end

  describe "#last_page" do
    subject { instance.send(:last_page) }
    it "returns 1 page if item_count is 1 and page_size is 1" do
      allow(instance).to receive(:item_count).and_return(1)
      allow(instance).to receive(:page_size).and_return(1)
      expect(subject).to eq 1
    end

    it "returns 2 pages if item_count 3 and page_size is 2" do
      allow(instance).to receive(:item_count).and_return(3)
      allow(instance).to receive(:page_size).and_return(2)
      expect(subject).to eq 2
    end

    context "when item_count is 0" do
      it "returns nil" do
        allow(instance).to receive(:item_count).and_return(0)
        allow(instance).to receive(:page_size).and_return(2)
        expect(subject).to eq nil
      end
    end

    context "when page_size is 0" do
      it "returns nil" do
        allow(instance).to receive(:item_count).and_return(3)
        allow(instance).to receive(:page_size).and_return(0)
        expect(subject).to eq nil
      end
    end
  end

  describe "#item_count" do
    subject { instance.send(:item_count) }
    let(:expected_item_count) { 1 }

    context "without stats param in request" do
      before { allow(proxy).to receive(:stats).and_return({}) }
      before { allow(proxy).to receive(:data).and_return([]) }

      it "returns 0 if resource.stat(:total, :count) is nil" do
        expect(proxy.scope).to receive(:unpaginated_object)
        expect(proxy.resource).to receive(:stat).with(:total, :count).and_return(lambda { |obj, meth| nil })
        expect(subject).to eq 0
      end

      it "returns the value of resource.stat(:total, :count)" do
        expect(proxy.scope).to receive(:unpaginated_object)
        expect(proxy.resource).to receive(:stat).with(:total, :count).and_return(lambda { |obj, meth| expected_item_count })
        expect(subject).to eq expected_item_count
      end
    end

    context "with stats[total]=count in request" do
      let(:params) { super().merge!(stats: {total: "count"}) }
      let(:stats_map) { {total: {count: expected_item_count}} }
      before { allow(proxy).to receive(:stats).and_return(stats_map) }

      it "depends on proxy to get count" do
        expect(instance).to receive(:item_count_from_proxy).and_call_original
        expect(instance).not_to receive(:item_count_from_stats)
        subject
      end

      it "returns the correct value of item count" do
        expect(subject).to eq expected_item_count
      end
    end
  end
end


text:
from dowhy.interpreter import Interpreter

class VisualInterpreter(Interpreter):
    """Base class for interpreters that show plots or visualizations as output.

    """
    def __init__(self, instance, **kwargs):
        super().__init__(instance, **kwargs)

    def show(self, interpret_plot):
        """Display the intepretation.

        :param interpret_plot: Plot object containing the interpretation

        :returns: None

        """
        # TODO: A common way to show all plots
        raise NotImplementedError


text:
package com.intellij.util.xml.highlighting;

import com.intellij.util.xml.DomElement;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.NonNls;

@SuppressWarnings("InspectionDescriptionNotFoundInspection")
public final class MockAnnotatingDomInspection<T extends DomElement> extends BasicDomElementsInspection<T>{
  public MockAnnotatingDomInspection(final Class<? extends T> domClass) {
    super(domClass);
  }

  @Override
  protected void checkDomElement(DomElement element, DomElementAnnotationHolder holder, DomHighlightingHelper helper) {
    for (Class aClass : getDomClasses()) {
      helper.runAnnotators(element, holder, aClass);
    }
  }

  @Override
  public @Nls @NotNull String getGroupDisplayName() {
    throw new UnsupportedOperationException("Method getGroupDisplayName is not yet implemented in " + getClass().getName());
  }

  @Override
  public @NonNls @NotNull String getShortName() {
    throw new UnsupportedOperationException("Method getShortName is not yet implemented in " + getClass().getName());
  }

  public static @NotNull Class<? extends DomElementsInspection<?>> getInspection() {
    Class<?> aClass = MockAnnotatingDomInspection.class;
    //noinspection unchecked
    return (Class<? extends DomElementsInspection<?>>)aClass;
  }
}


text:
export default class StoryType {}

StoryType.TOP_TYPE = 'top'
StoryType.SHOW_TYPE = 'show'
StoryType.ASK_TYPE = 'ask'
StoryType.ALL = [ StoryType.TOP_TYPE, StoryType.SHOW_TYPE, StoryType.ASK_TYPE ]


text:
views:
    sidebar1:
        region: sidebar-right
        template: default/content
        data:
            meta:
                type: content
                route: block/gridsidebar

    byline:
        region: after-main
        template: default/content
        sort: 1
        data:
            meta:
                type: content
                route: block/byline
...

Grid-sidan
==============================================

Denna sida visar vertikalt grid.

Snart kanske den även visar horisontellt grid. Den som lever får se!

Random text (som inte alls är random).

Ickerandom text. Ja!