text:
/* This is a generated file, edit the .stub.php file instead.
 * Stub hash: 0e1e56d853a47168a1f7f0950b674c2de6a91976 */

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_rd_kafka_get_err_descs, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_rd_kafka_err2name, 0, 1, IS_STRING, 1)
	ZEND_ARG_TYPE_INFO(0, err, IS_LONG, 0)
ZEND_END_ARG_INFO()

#define arginfo_rd_kafka_err2str arginfo_rd_kafka_err2name

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_rd_kafka_errno2err, 0, 1, IS_LONG, 0)
	ZEND_ARG_TYPE_INFO(0, errnox, IS_LONG, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_rd_kafka_errno, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_rd_kafka_offset_tail, 0, 1, IS_LONG, 0)
	ZEND_ARG_TYPE_INFO(0, cnt, IS_LONG, 0)
ZEND_END_ARG_INFO()

#define arginfo_rd_kafka_thread_cnt arginfo_rd_kafka_errno

ZEND_FUNCTION(rd_kafka_get_err_descs);
ZEND_FUNCTION(rd_kafka_err2name);
ZEND_FUNCTION(rd_kafka_err2str);
ZEND_FUNCTION(rd_kafka_errno2err);
ZEND_FUNCTION(rd_kafka_errno);
ZEND_FUNCTION(rd_kafka_offset_tail);
ZEND_FUNCTION(rd_kafka_thread_cnt);

static const zend_function_entry ext_functions[] = {
	ZEND_FE(rd_kafka_get_err_descs, arginfo_rd_kafka_get_err_descs)
	ZEND_FE(rd_kafka_err2name, arginfo_rd_kafka_err2name)
	ZEND_FE(rd_kafka_err2str, arginfo_rd_kafka_err2str)
	ZEND_DEP_FE(rd_kafka_errno2err, arginfo_rd_kafka_errno2err)
	ZEND_DEP_FE(rd_kafka_errno, arginfo_rd_kafka_errno)
	ZEND_FE(rd_kafka_offset_tail, arginfo_rd_kafka_offset_tail)
	ZEND_FE(rd_kafka_thread_cnt, arginfo_rd_kafka_thread_cnt)
	ZEND_FE_END
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Threading;
using SharpGL.SceneGraph;
using SharpGL.SceneGraph.Assets;
using SharpGL.SceneGraph.Cameras;
using SharpGL.SceneGraph.Core;
using SharpGL.SceneGraph.Primitives;
using SharpGL.SceneGraph.Quadrics;
using VirtualScene.BusinessComponents.Core.Factories;
using VirtualScene.BusinessComponents.Core.Properties;
using VirtualScene.Common;
using VirtualScene.Entities;
using VirtualScene.Entities.SceneEntities;
using VirtualScene.Entities.SceneEntities.Factories;

namespace VirtualScene.BusinessComponents.Core
{
    /// <summary>
    /// The 3D scene engine.
    /// </summary>
    public class SceneEngine : ISceneEngine
    {
        private DispatcherTimer _timer;

        private readonly ObservableCollection<SceneViewport> _viewports = new ObservableCollection<SceneViewport>();

        /// <summary>
        /// Initializes a new instance of <see cref="SceneEngine" />
        /// </summary>
        public SceneEngine()
        {
            UpdateRate = Constants.SceneEngine.DefaultUpdateRate;
            SetUpdateRate(Constants.SceneEngine.DefaultUpdateRate);
            Scene = ServiceLocator.Get<SceneFactory>().Create();
            var defaultCamera = ServiceLocator.Get<CameraFactory>().Create<LookAtCamera>(Constants.SceneEngine.DefaultCameraVector, Resources.Title_Navigation_Camera);
            Cameras = new ObservableCollection<Camera>
            {
                defaultCamera,
            };
            Scene.CurrentCamera = defaultCamera;
            SetupTimer();
        }

        /// <summary>
        /// The scene
        /// </summary>
        private Scene Scene { get; set; }

        /// <summary>
        /// The update rate for external modifications.
        /// </summary>
        public int UpdateRate { get; private set; }

        /// <summary>
        /// Set the update rate for external modifications.
        /// </summary>
        /// <param name="value">the update rate (in milliseconds). Minimum: 1 ms</param>
        /// <returns></returns>
        public bool SetUpdateRate(int value)
        {
            if (value < 1)
                return false;
            UpdateRate = value;
            SetupTimer();
            return true;
        }

        private void SetupTimer()
        {
             DisposeTimer();
            _timer = new DispatcherTimer();
            _timer.Tick += TimerTick;
            _timer.Interval = new TimeSpan(0, 0, 0, 0, UpdateRate);
            _timer.Start();
        }

        private void DisposeTimer()
        {
            if (_timer == null)
                return;
            _timer.Tick -= TimerTick;
            if(_timer.IsEnabled)
                _timer.Stop();
        }

        private void TimerTick(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Creates the viewport with a scene. All previously added acene elements are automatically added to the new vieport.
        /// </summary>
        /// <returns>Returnd the new viewport</returns>
        public SceneViewport CreateViewport()
        {
            var viewport = new SceneViewport(Scene);
            _viewports.Add(viewport);
            return viewport;
        }

        /// <summary>
        /// Cameras in the scene
        /// </summary>
        public ObservableCollection<Camera> Cameras { get; private set; }

        /// <summary>
        ///
        /// </summary>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="dz"></param>
        public void Move(float dx, float dy, float dz)
        {
            foreach (var viewport in _viewports)
            {
                viewport.Navigation.Move(dx, dy, dz);
            }
        }

        /// <summary>
        /// Add an entity to the scene
        /// </summary>
        /// <param name="sceneEntity">The entity to be added to the scene</param>
        public void AddSceneEntity(ISceneEntity sceneEntity)
        {
            var sceneElement = sceneEntity.Geometry;
            if (!Scene.SceneContainer.Children.Contains(sceneElement))
                Scene.SceneContainer.AddChild(sceneElement);
        }

        /// <summary>
        /// Remove an entity from the scene
        /// </summary>
        /// <param name="sceneEntity">The entity to be removed from the scene</param>
        public void RemoveSceneEntity(ISceneEntity sceneEntity)
        {
            var sceneElement = sceneEntity.Geometry;
            if (Scene.SceneContainer.Children.Contains(sceneElement))
                Scene.SceneContainer.RemoveChild(sceneElement);
        }

        /// <summary>
        /// Clear the scene
        /// </summary>
        public void Clear()
        {
            var sceneElements = Scene.SceneContainer.Traverse();
            foreach (var sceneElement in sceneElements.Where(sceneElement => sceneElement is Polygon || sceneElement is Quadric).ToList())
                sceneElement.Parent.RemoveChild(sceneElement);
        }

        /// <summary>
        /// Count of SceneElements in the scene
        /// </summary>
        public int SceneElementsCount
        {
            get { return Scene.SceneContainer.Children.Count; }
        }

        /// <summary>
        /// SceneElements of the scene
        /// </summary>
        public ObservableCollection<SceneElement> SceneElements {
            get { return Scene.SceneContainer.Children; }
        }

        /// <summary>
        /// Gets the asset list of epecified type
        /// </summary>
        /// <typeparam name="T">Type of the asset</typeparam>
        /// <returns></returns>
        public IEnumerable<T> GetAssets<T>() where T : Asset
        {
            return Scene.Assets.OfType<T>();
        }

        /// <summary>
        /// Add a new asset to the scene
        /// </summary>
        /// <param name="asset"></param>
        public void AddAsset<T>(T asset) where T : Asset
        {
            Scene.Assets.Add(asset);
        }

        /// <summary>
        /// Load existing or create a new texture.
        /// </summary>
        /// <param name="path">Path to the file of texture</param>
        /// <param name="textureFile">File name of texture</param>
        /// <returns>The texture</returns>
        public Texture LoadOrCreateTexture(string path, string textureFile)
        {
            var texture = GetAssets<Texture>().FirstOrDefault(t => Equals(t.Name, textureFile));
            if (texture != null)
                return texture;

            texture = new Texture();
            if (!File.Exists(textureFile))
            {
                var directoryName = Path.GetDirectoryName(path);
                var fileName = Path.GetFileName(textureFile);
                if (string.IsNullOrWhiteSpace(directoryName) || string.IsNullOrWhiteSpace(fileName))
                    return texture;
                textureFile = Path.Combine(directoryName, fileName);
                if (!File.Exists(textureFile))
                    return texture;
            }

            texture.Create(Scene.OpenGL, textureFile);
            return texture;
        }
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

import Data.Foldable     (for_)
import Data.String       (fromString)
import Test.Hspec        (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)

import Acronym (abbreviate)

main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs

specs :: Spec
specs = describe "abbreviate" $ for_ cases test
  where
    test Case {..} = it description $
      abbreviate (fromString input) `shouldBe` fromString expected

data Case = Case { description :: String
                 , input       :: String
                 , expected    :: String
                 }

cases :: [Case]
cases = [ Case { description = "basic"
               , input       = "Portable Network Graphics"
               , expected    = "PNG"
               }
        , Case { description = "lowercase words"
               , input       = "Ruby on Rails"
               , expected    = "ROR"
               }
        -- Although this case was removed in specification 1.1.0,
        -- the Haskell track has chosen to keep it,
        -- since it makes the problem more interesting.
        , Case { description = "camelcase"
               , input       = "HyperText Markup Language"
               , expected    = "HTML"
               }
        , Case { description = "punctuation"
               , input       = "First In, First Out"
               , expected    = "FIFO"
               }
        , Case { description = "all caps word"
               , input       = "GNU Image Manipulation Program"
               , expected    = "GIMP"
               }
        , Case { description = "punctuation without whitespace"
               , input       = "Complementary metal-oxide semiconductor"
               , expected    = "CMOS"
               }
        , Case { description = "very long abbreviation"
               , input       = "Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me"
               , expected    = "ROTFLSHTMDCOALM"
               }
        , Case { description = "consecutive delimiters"
               , input       = "Something - I made up from thin air"
               , expected    = "SIMUFTA"
               }
        , Case { description = "apostrophes"
               , input       = "Halley's Comet"
               , expected    = "HC"
               }
        , Case { description = "underscore emphasis"
               , input       = "The Road _Not_ Taken"
               , expected    = "TRNT"
               }
        ]

-- ad42f2da40183e017f9c52fd00efe33c6bfe7037


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'pry'

require 'nymph/client'
require 'nymph/service'


text:
echo ""
echo "[Provision-Script] Installing Luke's Yeoman Generator (via Yarn)"
echo ""

yarn global add "@lukechavers/generator-luke"


text:
class AddUserReferenceToToDoItemEvents < ActiveRecord::Migration
  def change
    add_column :to_do_item_events, :user_id, :integer
  end
end


text:
@interface RoomViewController : UIViewController

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class gameOver : MonoBehaviour {
	public Button restartButton;
	public GameObject puntuacion;

	// Use this for initialization
	void Start () {
		Button btn = restartButton.GetComponent<Button>();
		btn.onClick.AddListener(TaskOnClick);

	}

	// Update is called once per frame
	void Update () {
		int puntos = PlayerPrefs.GetInt ("Player Score");
		puntuacion.GetComponent<Text> ().text = "Puntuación: " + puntos.ToString()+ " puntos";
		//Debug.Log (puntos.ToString());
	}

	void TaskOnClick(){
		SceneManager.LoadScene ("Start");
		//Debug.Log ("You have clicked the button!");
	}
}


text:
"""chris_backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import path, include
from django.conf import settings

from plugins import admin as plugin_admin_views

urlpatterns = [
    path('chris-admin/api/v1/',
         plugin_admin_views.PluginAdminList.as_view(),
         name='admin-plugin-list'),

    path('chris-admin/api/v1/computeresources/',
         plugin_admin_views.ComputeResourceAdminList.as_view(),
         name='admin-computeresource-list'),

    path('chris-admin/', admin.site.urls),

    path('api/', include('core.api')),
]

if settings.DEBUG:
    import debug_toolbar

    urlpatterns += [
        path('__debug__/', include(debug_toolbar.urls)),
    ]


text:
/*
 * Do not modify this file. This file is generated from the cognito-identity-2014-06-30.normal.json service model.
 */

using System;

namespace Amazon.CognitoIdentity.Model
{
    /// <summary>
    /// Configuration for accessing Amazon GetCredentialsForIdentity service
    /// </summary>
    public partial class GetCredentialsForIdentityResponse : GetCredentialsForIdentityResult
    {
        /// <summary>
        /// Gets and sets the GetCredentialsForIdentityResult property.
        /// Represents the output of a GetCredentialsForIdentity operation.
        /// </summary>
        [Obsolete(@"This property has been deprecated. All properties of the GetCredentialsForIdentityResult class are now available on the GetCredentialsForIdentityResponse class. You should use the properties on GetCredentialsForIdentityResponse instead of accessing them through GetCredentialsForIdentityResult.")]
        public GetCredentialsForIdentityResult GetCredentialsForIdentityResult
        {
            get
            {
                return this;
            }
        }
    }
}


text:
#include "LabScale.h"

class CLabHorizScale : public CLabScale
{
public:
   CLabHorizScale(CLabBase *parent, double minimum = 0.0, double maximum = 10.0, double increment = 1.0);
   virtual ~CLabHorizScale(){};

   virtual void drawScale(CDC *pDC);
   virtual int translateCoordinate(double coord);
   virtual double translateScreenCoordinate(int coord);
   virtual int getScaleLength();
};

#endif //__QLABHORIZSCALE_H__


text:
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include "GameState.h"
#include "AI.h"
#include <queue>
#include <set>
#include <unistd.h>         // Hmpf; finns inte på VS.

class GameState;
class Heuristic; //TODO!!!!

using namespace std;

vector<GameState*> solve(GameState * gs) {
    cout << "GS "<< gs << std::endl;
	cout << gs->parent << endl;
	priority_queue<GameState*> queue;
	set<unsigned long long> visited; //TODO, fixa egen hashfunction typ

cout << "gs=\n" << *gs << endl;

	visited.insert(gs->hash());
	queue.push(gs);

    cout << "Prepare to enter the loop of delirium!!!11" << endl;
	while(!queue.empty()) {
		cout << "TOP: " << queue.top() << endl;
		GameState* next = queue.top();
		cout << "NEXT: " << next << endl;

		if(next->isSolution()) {
            //cout << "next" << &next << endl;
            //cout << "next.parent" << next.parent << endl;
            //cout << "ISSOULUTION ENTERED" << endl;
			//backtrack through the parent members of the gamestates to place full
			//solution into a vector
			vector<GameState*> retv;
			GameState * gsp = next->parent;
			retv.insert(retv.begin(),next);
            cout << "Prepare to enter the loop of eternal self-reproduction!!!11" << endl;
			while(gsp != NULL) {
                //cout << *gsp << ";Parent:\n" << *(gsp->parent) << endl;
				retv.insert(retv.begin(),gsp);
                //usleep(50000);
                cout << gsp << endl;
                gsp = gsp->parent;
			}
			return retv;
		}
		vector<GameState*> nextMoves = next->findNextMoves();
        //cout << "findnextmo=" << nextMoves.size() << endl;
		cout << "parent should be " << next << endl;
        for(int i = 0;i < nextMoves.size();i++){
            cout << nextMoves[i] << "     " << nextMoves[i]->parent << endl;
        }
		vector<GameState*>::iterator it;
		for(it = nextMoves.begin(); it != nextMoves.end(); it++) { // ++it eller it++?
			GameState* g = *it;
            //cout << "g.hash=" << g.hash() << std::endl;
            //for(set<unsigned long long>::iterator it=visited.begin();it!=visited.end();++it){
            //    cout << "visited:" << *it << endl;
            //}
			if(visited.find(g->hash()) == visited.end()) {
                //cout << "if ENTERED!" << std::endl;
				//g.parent = &next;
				cout << "inserting " << g << " with parent " << g->parent << endl;
				visited.insert(g->hash());
				queue.push(g);
			}
		}
		queue.pop();
	}

	//if we are here, solution has been found
    cout << "WE ARE OUTTA HELL!" << endl;
	return vector<GameState*>(); //return something, or do something
}
/*
int abprune(GameState curGS, int depth, int a, int b, bool maxi)
{
    if (depth == 0) { // || curGS.isEOG()) {
        //fprintf(stderr, "Entered first if. In abprune now with depth %i\n", depth);
        //if (curGS.isDraw()) {
        //    return 0;
        //}
        return 0;
        //return evalHeur(curGS);
    }

    //fprintf(stderr, "In abprune now with depth %i\n", depth);

    std::set<GameState> s = curGS.findNextMoves();
    std::vector<GameState> lNextStates(s.begin(),s.end());

    int vecSize = lNextStates.size();

    if (maxi) { //Maximizing player's turn
        for (int i = 0;i<vecSize;i++) {
            a = std::max(a, abprune(lNextStates[i], depth-1, a, b, !maxi));
            if (b <= a) {
                break;
            }
        }
        return a;
    } else {    //Minimizing player's turn
        for (int i = 0;i<vecSize;i++) {
            b = std::min(b, abprune(lNextStates[i], depth-1, a, b, !maxi));
            if (b <= a) {
                break;
            }
        }
        return b;
    }
}

*/


text:
using Hangfire.Mongo.Database;
using Hangfire.Mongo.Dto;
using Hangfire.Mongo.MongoUtils;
using Hangfire.Mongo.PersistentJobQueue.Mongo;
using Hangfire.Mongo.Tests.Utils;
using System;
using System.Linq;
using System.Threading;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
using MongoDB.Driver;
using Xunit;

namespace Hangfire.Mongo.Tests
{
#pragma warning disable 1591
    [Collection("Database")]
    public class MongoJobQueueFacts
    {
        private static readonly string[] DefaultQueues = { "default" };

        [Fact]
        public void Ctor_ThrowsAnException_WhenConnectionIsNull()
        {
            var exception = Assert.Throws<ArgumentNullException>(
                () => new MongoJobQueue(null, new MongoStorageOptions()));

            Assert.Equal("connection", exception.ParamName);
        }

        [Fact]
        public void Ctor_ThrowsAnException_WhenOptionsValueIsNull()
        {
            UseConnection(connection =>
            {
                var exception = Assert.Throws<ArgumentNullException>(
                   () => new MongoJobQueue(connection, null));

                Assert.Equal("options", exception.ParamName);
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldThrowAnException_WhenQueuesCollectionIsNull()
        {
            UseConnection(connection =>
            {
                var queue = CreateJobQueue(connection);

                var exception = Assert.Throws<ArgumentNullException>(
                    () => queue.Dequeue(null, CreateTimingOutCancellationToken()));

                Assert.Equal("queues", exception.ParamName);
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldThrowAnException_WhenQueuesCollectionIsEmpty()
        {
            UseConnection(connection =>
            {
                var queue = CreateJobQueue(connection);

                var exception = Assert.Throws<ArgumentException>(
                    () => queue.Dequeue(new string[0], CreateTimingOutCancellationToken()));

                Assert.Equal("queues", exception.ParamName);
            });
        }

        [Fact]
        public void Dequeue_ThrowsOperationCanceled_WhenCancellationTokenIsSetAtTheBeginning()
        {
            UseConnection(connection =>
            {
                var cts = new CancellationTokenSource();
                cts.Cancel();
                var queue = CreateJobQueue(connection);

                Assert.Throws<OperationCanceledException>(() => queue.Dequeue(DefaultQueues, cts.Token));
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldWaitIndefinitely_WhenThereAreNoJobs()
        {
            UseConnection(connection =>
            {
                var cts = new CancellationTokenSource(200);
                var queue = CreateJobQueue(connection);

                Assert.Throws<OperationCanceledException>(() => queue.Dequeue(DefaultQueues, cts.Token));
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldFetchAJob_FromTheSpecifiedQueue()
        {
            // Arrange
            UseConnection(connection =>
            {
                var jobQueue = new JobQueueDto
                {
                    JobId = 1,
                    Queue = "default"
                };

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(jobQueue));

                var id = jobQueue.Id;
                var queue = CreateJobQueue(connection);

                // Act
                MongoFetchedJob payload = (MongoFetchedJob)queue.Dequeue(DefaultQueues, CreateTimingOutCancellationToken());

                // Assert
                Assert.Equal(id, payload.Id);
                Assert.Equal("1", payload.JobId);
                Assert.Equal("default", payload.Queue);
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldLeaveJobInTheQueue_ButSetItsFetchedAtValue()
        {
            // Arrange
            UseConnection(connection =>
            {
                var job = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job));

                var jobQueue = new JobQueueDto
                {
                    JobId = job.Id,
                    Queue = "default"
                };
                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(jobQueue));

                var queue = CreateJobQueue(connection);

                // Act
                var payload = queue.Dequeue(DefaultQueues, CreateTimingOutCancellationToken());

                // Assert
                Assert.NotNull(payload);

                var fetchedAt = AsyncHelper.RunSync(() => connection.JobQueue.Find(Builders<JobQueueDto>.Filter.Eq(_ => _.JobId, int.Parse(payload.JobId))).FirstOrDefaultAsync()).FetchedAt;

                Assert.NotNull(fetchedAt);
                Assert.True(fetchedAt > DateTime.UtcNow.AddMinutes(-1));
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldFetchATimedOutJobs_FromTheSpecifiedQueue()
        {
            // Arrange
            UseConnection(connection =>
            {
                var job = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job));

                var jobQueue = new JobQueueDto
                {
                    JobId = job.Id,
                    Queue = "default",
                    FetchedAt = connection.GetServerTimeUtc().AddDays(-1)
                };
                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(jobQueue));

                var queue = CreateJobQueue(connection);

                // Act
                var payload = queue.Dequeue(DefaultQueues, CreateTimingOutCancellationToken());

                // Assert
                Assert.NotEmpty(payload.JobId);
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldSetFetchedAt_OnlyForTheFetchedJob()
        {
            // Arrange
            UseConnection(connection =>
            {
                var job1 = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job1));

                var job2 = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job2));

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(new JobQueueDto
                {
                    JobId = job1.Id,
                    Queue = "default"
                }));

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(new JobQueueDto
                {
                    JobId = job2.Id,
                    Queue = "default"
                }));

                var queue = CreateJobQueue(connection);

                // Act
                var payload = queue.Dequeue(DefaultQueues, CreateTimingOutCancellationToken());

                // Assert
                var otherJobFetchedAt = AsyncHelper.RunSync(() => connection.JobQueue.Find(Builders<JobQueueDto>.Filter.Ne(_ => _.JobId, int.Parse(payload.JobId))).FirstOrDefaultAsync()).FetchedAt;

                Assert.Null(otherJobFetchedAt);
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldFetchJobs_OnlyFromSpecifiedQueues()
        {
            UseConnection(connection =>
            {
                var job1 = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job1));

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(new JobQueueDto
                {
                    JobId = job1.Id,
                    Queue = "critical"
                }));

                var queue = CreateJobQueue(connection);

                Assert.Throws<OperationCanceledException>(() => queue.Dequeue(DefaultQueues, CreateTimingOutCancellationToken()));
            });
        }

        [Fact, CleanDatabase]
        public void Dequeue_ShouldFetchJobs_FromMultipleQueues()
        {
            UseConnection(connection =>
            {
                var job1 = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job1));

                var job2 = new JobDto
                {
                    InvocationData = "",
                    Arguments = "",
                    CreatedAt = connection.GetServerTimeUtc()
                };
                AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job2));

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(new JobQueueDto
                {
                    JobId = job1.Id,
                    Queue = "critical"
                }));

                AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(new JobQueueDto
                {
                    JobId = job2.Id,
                    Queue = "default"
                }));

                var queue = CreateJobQueue(connection);

                var critical = (MongoFetchedJob)queue.Dequeue(
                    new[] { "critical", "default" },
                    CreateTimingOutCancellationToken());

                Assert.NotNull(critical.JobId);
                Assert.Equal("critical", critical.Queue);

                var @default = (MongoFetchedJob)queue.Dequeue(
                    new[] { "critical", "default" },
                    CreateTimingOutCancellationToken());

                Assert.NotNull(@default.JobId);
                Assert.Equal("default", @default.Queue);
            });
        }

        [Fact, CleanDatabase]
        public void Enqueue_AddsAJobToTheQueue()
        {
            UseConnection(connection =>
            {
                var queue = CreateJobQueue(connection);

                queue.Enqueue("default", "1");

                var record = AsyncHelper.RunSync(() => connection.JobQueue.Find(new BsonDocument()).ToListAsync()).Single();
                Assert.Equal("1", record.JobId.ToString());
                Assert.Equal("default", record.Queue);
                Assert.Null(record.FetchedAt);
            });
        }

        private static CancellationToken CreateTimingOutCancellationToken()
        {
            var source = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            return source.Token;
        }

        private static MongoJobQueue CreateJobQueue(HangfireDbContext connection)
        {
            return new MongoJobQueue(connection, new MongoStorageOptions());
        }

        private static void UseConnection(Action<HangfireDbContext> action)
        {
            using (var connection = ConnectionUtils.CreateConnection())
            {
                action(connection);
            }
        }
    }
#pragma warning restore 1591
}


text:
using System;

namespace Azure.AI.AnomalyDetector.Models
{
    /// <summary> The TimeSeriesPoint. </summary>
    public partial class TimeSeriesPoint
    {
        /// <summary> Initializes a new instance of TimeSeriesPoint. </summary>
        /// <param name="value"> The measurement of that point, should be float. </param>
        public TimeSeriesPoint(float value)
        {
            Value = value;
        }

        /// <summary> Optional argument, timestamp of a data point (ISO8601 format). </summary>
        public DateTimeOffset? Timestamp { get; set; }
        /// <summary> The measurement of that point, should be float. </summary>
        public float Value { get; }
    }
}


text:
package com.ruesga.rview.gerrit.model;

import com.google.gson.annotations.SerializedName;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#reviewer-input"
 */
public class ReviewerInput {
    @NonNull @SerializedName("reviewer") public String reviewerId = "";
    @Nullable @SerializedName("state") public AddReviewerState state;
    @Nullable @SerializedName("confirmed") public Boolean confirmed;
}


text:
require_relative 'section_report/generate'

module Thinreports
  class Generate
    def call(report_params, filename: nil)
      SectionReport::Generate.new.call(report_params, filename: filename)
    end
  end
end


text:
QUnit.module("callbacks");

QUnit.test("no canvas element passed", function(assert) {
	$(document).EAN13("5449000096241", {
    	onError: function(desc){
        	assert.ok(true, "onError called");
					assert.equal(desc, "canvas context is null");
        },
        onSuccess: function(){
        	assert.ok(false, "onSuccess called");
        }
    });
});

QUnit.test("checksum", function(assert) {

    $("#ean").EAN13("4012345123456", {
        onValid: function(){
            assert.ok(true, "Valid barcode fires onValid");
        },
        onInvalid: function(){
            assert.ok(false, "Valid barcode fires onInvalid");
        }
    });

    $("#ean").EAN13("5901234123450", {
        onValid: function(){
           ok(false, "Invalid barcode fires onValid");
        },
        onInvalid: function(){
           ok(true, "Invalid barcode fires onInvalid");
        }
    });
});

QUnit.test("number is null", function(assert) {

    $("#ean").EAN13(null, {
        onSuccess: function(){
           ok(false, "onSuccess called");
        },
        onError: function(){
           ok(true, "onError called");
        }
    });
});

QUnit.test("number is not numeric", function(assert) {

    $("#ean").EAN13("foo", {
        onSuccess: function(){
           ok(false, "onSuccess called");
        },
        onError: function(){
           ok(true, "onError called");
        }
    });
});

QUnit.test("check if success callback is fired", function(assert) {

	var number = "5449000096241";

    $("#ean").EAN13("5449000096241", {
      	onSuccess: function(){
	    	assert.ok(true, "onSuccess called");
      	},
      	onError: function(){
      		assert.ok(false, "onError called");
      	}
    });
});

QUnit.test("check if success callback is fired without check digit", function(assert) {

    $("#ean").EAN13("544900009624", {
      	onSuccess: function(number){
	    	assert.ok(true, "onSuccess called");
		assert.equal(number, "5449000096241", "Number is as expected");
      	},
      	onError: function(){
      		assert.ok(false, "onError called");
      	}
    });
});

QUnit.module("encoding");

QUnit.test("read back numbers", function(assert) {
  var canvas = document.getElementById("ean");

  for(var i = 0; i < numbers.length; i++){
    create_and_compare(canvas, numbers[i], assert);
  }
});

function create_and_compare(canvas, number, assert){
  $("#ean").EAN13(number, {
    background: "#fff",
    prefix: false,
    debug: true,
		onSuccess: function(){
      var result = read(canvas);
      assert.equal(result, number, number + " reads back");
    },
    onError: function(){
    	assert.ok(false, "Something went wrong");
    }
	});
}


text:
package org.apache.derby.shared.common.error;

import java.sql.SQLException;

/**
	Class that wraps StandardExceptions in a SQLException.
	This is used to make any public API methods always
	throw SQLException rather than a random collection.
 */
public class PublicAPI
{
	/**
		Generates a SQLException for signalling that the
		operation failed due to a database error.

        @param se The exception to wrap inside a SQLException

        @return a SQLException wrapped around the original exception
	 */
	public static SQLException wrapStandardException(StandardException se) {
        se.markAsPublicAPI();
        return ExceptionFactory.getInstance().getSQLException(
                se.getMessage(), se.getMessageId(), (SQLException) null,
                se.getSeverity(), se, se.getArguments());
	}
}


text:
FROM golang:1.14
LABEL maintainer "tomas@aparicio.me"

ARG LIBVIPS_VERSION=8.9.2
ARG LIBHEIF_VERSION=1.9.1
ARG GOLANGCILINT_VERSION=1.29.0

# Installs libvips + required libraries
RUN DEBIAN_FRONTEND=noninteractive \
  apt-get update && \
  apt-get install --no-install-recommends -y \
  ca-certificates \
  automake build-essential curl \
  gobject-introspection gtk-doc-tools libglib2.0-dev libjpeg62-turbo-dev libpng-dev \
  libwebp-dev libtiff5-dev libgif-dev libexif-dev libxml2-dev libpoppler-glib-dev \
  swig libmagickwand-dev libpango1.0-dev libmatio-dev libopenslide-dev libcfitsio-dev \
  libgsf-1-dev fftw3-dev liborc-0.4-dev librsvg2-dev libimagequant-dev libaom-dev && \
  cd /tmp && \
  curl -fsSLO https://github.com/strukturag/libheif/releases/download/v${LIBHEIF_VERSION}/libheif-${LIBHEIF_VERSION}.tar.gz && \
  tar zvxf libheif-${LIBHEIF_VERSION}.tar.gz && \
  cd /tmp/libheif-${LIBHEIF_VERSION} && \
  ./configure --prefix=/vips && \
  make && \
  make install && \
  echo '/vips/lib' > /etc/ld.so.conf.d/vips.conf && \
  ldconfig -v && \
  export LD_LIBRARY_PATH="/vips/lib:$LD_LIBRARY_PATH" && \
  export PKG_CONFIG_PATH="/vips/lib/pkgconfig:$PKG_CONFIG_PATH" && \
  cd /tmp && \
  curl -fsSLO https://github.com/libvips/libvips/releases/download/v${LIBVIPS_VERSION}/vips-${LIBVIPS_VERSION}.tar.gz && \
  tar zvxf vips-${LIBVIPS_VERSION}.tar.gz && \
  cd /tmp/vips-${LIBVIPS_VERSION} && \
	CFLAGS="-g -O3" CXXFLAGS="-D_GLIBCXX_USE_CXX11_ABI=0 -g -O3" \
    ./configure \
    --disable-debug \
    --disable-dependency-tracking \
    --disable-introspection \
    --disable-static \
    --enable-gtk-doc-html=no \
    --enable-gtk-doc=no \
    --enable-pyvips8=no \
    --prefix=/vips && \
  make && \
  make install && \
  ldconfig

ENV LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"

# Install runtime dependencies
# RUN DEBIAN_FRONTEND=noninteractive \
#   apt-get update && \
#   apt-get install --no-install-recommends -y \
#   libglib2.0-0 libjpeg62-turbo libpng16-16 libopenexr23 \
#   libwebp6 libwebpmux3 libwebpdemux2 libtiff5 libgif7 libexif12 libxml2 libpoppler-glib8 \
#   libmagickwand-6.q16-6 libpango1.0-0 libmatio4 libopenslide0 \
#   libgsf-1-114 fftw3 liborc-0.4-0 librsvg2-2 libcfitsio7 libimagequant0 libheif1 && \
#   apt-get autoremove -y && \
#   apt-get autoclean && \
#   apt-get clean && \
#   rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install Go lint
RUN go get -u golang.org/x/lint/golint

# ENV LD_LIBRARY_PATH="/vips/lib:$LD_LIBRARY_PATH"
# ENV PKG_CONFIG_PATH="/vips/lib/pkgconfig:/usr/local/lib/pkgconfig:/usr/lib/pkgconfig:/usr/X11/lib/pkgconfig"

WORKDIR ${GOPATH}/src/github.com/h2non/bimg
COPY . .

# RUN \
#   # Clean up
#   apt-get remove -y automake curl build-essential && \
#   apt-get autoremove -y && \
#   apt-get autoclean && \
#   apt-get clean && \
#   rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

CMD [ "/bin/bash" ]


text:
package org.apereo.cas.mock;

import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.apereo.cas.ticket.ServiceTicket;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.TicketState;
import org.apereo.cas.ticket.proxy.ProxyGrantingTicket;
import org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

/**
 * Mock service ticket.
 *
 * @author Marvin S. Addison
 * @since 3.0.0
 */
@Getter
@Setter
@EqualsAndHashCode(of = {"id"})
public class MockServiceTicket implements ServiceTicket, TicketState {

    private static final long serialVersionUID = 8203377063087967768L;

    private final String id;

    private final ZonedDateTime created;

    private final Service service;
    private final TicketGrantingTicket parent;
    private ExpirationPolicy expiration = new NeverExpiresExpirationPolicy();
    private boolean expired;

    public MockServiceTicket(final String id, final Service service, final TicketGrantingTicket parent) {
        this.service = service;
        this.id = id;
        this.parent = parent;
        created = ZonedDateTime.now(ZoneOffset.UTC);
    }

    @Override
    public boolean isFromNewLogin() {
        return false;
    }

    @Override
    public boolean isValidFor(final Service service) {
        return this.service.equals(service);
    }

    @Override
    public ProxyGrantingTicket grantProxyGrantingTicket(final String id, final Authentication authentication, final ExpirationPolicy expirationPolicy) {
        return null;
    }

    @Override
    public ExpirationPolicy getExpirationPolicy() {
        return this.expiration;
    }

    @Override
    public String getPrefix() {
        return ServiceTicket.PREFIX;
    }

    @Override
    public boolean isExpired() {
        return this.expired || this.expiration.isExpired(this);
    }

    @Override
    public TicketGrantingTicket getTicketGrantingTicket() {
        return parent;
    }

    @Override
    public ZonedDateTime getCreationTime() {
        return created;
    }

    @Override
    public Authentication getAuthentication() {
        return this.parent.getAuthentication();
    }

    @Override
    public void update() {
    }

    @Override
    public int getCountOfUses() {
        return 0;
    }

    @Override
    public ZonedDateTime getLastTimeUsed() {
        return ZonedDateTime.now();
    }

    @Override
    public ZonedDateTime getPreviousTimeUsed() {
        return ZonedDateTime.now();
    }

    @Override
    public int compareTo(final Ticket o) {
        return this.id.compareTo(o.getId());
    }

    @Override
    public void markTicketExpired() {
        this.expired = true;
    }
}


text:
package com.github.golimpio.atm.services;

import com.github.golimpio.atm.model.Amount;
import com.github.golimpio.atm.model.Cash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

import static com.github.golimpio.atm.services.CashBox.cashBox;
import static javax.ws.rs.core.Response.Status;

@Path("/withdraw")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class Withdraw {
    private static final Logger LOGGER = LoggerFactory.getLogger(Withdraw.class);

    @GET
    @Path("/")
    @Consumes(MediaType.TEXT_PLAIN)
    public List<Cash> withdraw(long value) {
        LOGGER.info("New withdraw: [{}]",
                value);

        try {
            return cashBox().withdraw(value);
        }
        catch (AtmException e) {
            throw new WebApplicationException(
                    Response.status(e.isInternalError() ? Status.INTERNAL_SERVER_ERROR : Status.BAD_REQUEST)
                            .entity(e.getMessage()).build());
        }
        catch (Exception e) {
            throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity(e.getMessage()).build());
        }
    }

    @GET
    @Path("/minimum")
    public Amount minimum() {
        LOGGER.info("Retrieving minimum allowed withdraw...");
        try {
            return new Amount(cashBox().getMinimalWithdrawValue());
        }
        catch (Exception e) {
            throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR)
                                                      .entity(e.getMessage()).build());
        }
    }

    @GET
    @Path("/maximum")
    public Amount maximum() {
        LOGGER.info("Retrieving maximum allowed withdraw...");
        try {
            return new Amount(cashBox().sumInCash());
        }
        catch (Exception e) {
            throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity(e.getMessage()).build());
        }
    }
}


text:
package waldap.core

package object model {
  type Session = slick.jdbc.JdbcBackend#Session
}


text:
<!DOCTYPE html>

    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">

    <link href="lib/jquery.terminal.css" rel="stylesheet"/>

    <link href="lib/bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="lib/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"/>

    <title>Holsen.js</title>

Holsen.js

Holsens småprogrammer for geodetiske beregninger. Nå i JavaScript!

 1. Geodetiske hovedoppgave (l-geo1)

 2. Geodetiske hovedoppgave (l-geo2)

 Krummningsradier (krrad)

 Meridianbue (meridbue)

 Meridiankonvergens (konverg)

 Koordinatomregning (blxy)

 Terminal

 Om holsen.js

1. Geodetiske hovedoppgave

2. Geodetiske hovedoppgave

Krummningsradier

Meridianbue

Meridiankonvergens

Koordinatomregning

Terminal

Om

Holsen.js er en Javascript-port av "Holsens Småprogrammer", skrevet i Fortran av Professor Jon Holsen ved NTH i 1990-1991.
                    Holsen.js er tilgjengelig på GitHub under MIT-lisensen.
                    Holsen.js kan enten brukes via dette web-interfacet, eller som et frittstående javascript-bibliotek.
                    MERK: Det er p.t. noen feil i "blxy". Tester taes imot med takk

Atle Frenvik Sveen har portet koden over til JavaScript, samt laget brukergrensesnittet. Eventuelle feil og mangler er hans skyld.
                    J. Holsen kan ikke stilles ansvarlig for feil og mangler. Bruk programmet på egen risiko.
                    For litteratur og forklaringer, søk i litteraturen (:p).


text:
package com.githang.navigatordemo.adapter;

/**
 * Created by vivian on 15/7/13.
 */

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class CommonAdapter<T> extends BaseAdapter {
    protected LayoutInflater mInflater;
    protected Context mContext;
    protected List<T> mDatas;

    public CommonAdapter(Context context, List<T> mDatas) {
        mInflater = LayoutInflater.from(context);
        this.mContext = context;
        this.mDatas = mDatas;
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes        #-}

module Main
where

import           Control.Applicative      ((<$>), (<*>))
import           Control.Concurrent       (threadDelay)
import           Control.Concurrent.Async
import qualified Control.Foldl            as L
import           Control.Lens             (zoom)
import           Control.Monad            (forever, unless)
import qualified Data.ByteString.Char8    as BC
import           Data.Monoid              ((<>))
import           Pipes
import qualified Pipes.ByteString         as PB
import           Pipes.Parse              (Parser, evalStateT, isEndOfInput)
import qualified Pipes.Parse              as PP
import qualified Pipes.ZMQ4               as PZ
import           System.Random            (randomRIO)
import qualified System.ZMQ4              as Z
import           Text.Printf

zipCode = "10001"

pubServerThread :: Z.Sender t => Z.Socket t -> IO r
pubServerThread s = forever $ do
    threadDelay (10) -- be gentle with the CPU
    zipcode <- randomRIO (10000::Int, 11000)
    temperature <- randomRIO (-10::Int, 35)
    humidity <- randomRIO (10::Int, 60)
    let update = BC.pack $ unwords [show zipcode, show temperature, show humidity]
    Z.send s [] update

bogusServerThread :: Z.Sender t => Z.Socket t -> IO r
bogusServerThread s = forever $ do
    threadDelay (5 * 1000 * 1000)
    let bogusMsg = zipCode <> " 10 bogus"
    Z.send s [] bogusMsg

average :: L.Fold Int Int
average = div <$> L.sum <*> L.length

main :: IO ()
main = do
    -- create and use exactly one context in a single process
    Z.withContext $ \ctx ->
        Z.withSocket ctx Z.Pub $ \pubSocket ->
        Z.withSocket ctx Z.Sub $ \subSocket -> do

            Z.bind pubSocket "inproc://pubserver"
            putStrLn "Starting pub server"
            async $ pubServerThread pubSocket
            async $ bogusServerThread pubSocket

            Z.connect subSocket "inproc://pubserver"
            Z.subscribe subSocket zipCode

            evalStateT reportParser (processedData subSocket)
    where

        reportParser :: Parser (Int, Int) IO ()
        reportParser = loop
            where
                loop = do
                    (avgTemp, avgHum) <- zoom (PP.splitAt 10) (L.purely PP.foldAll averages)
                    liftIO $ printf "-- Report: average temperature is %d°C, average humidity is %d%% \n" avgTemp avgHum
                    eof <- isEndOfInput
                    unless eof loop

        averages :: L.Fold (Int, Int) (Int, Int)
        averages =
            let avgTemp :: L.Fold (Int, Int) Int
                avgTemp = L.premap fst average

                avgHumidity :: L.Fold (Int, Int) Int
                avgHumidity = L.premap snd average

            in  (,) <$> avgTemp <*> avgHumidity

        processedData :: Z.Socket Z.Sub -> Producer (Int, Int) IO ()
        processedData subSocket = for (PZ.fromZMQ subSocket) $ \bs -> do
            case map BC.readInt (BC.words bs) of
                [_, Just (temp, _), Just(hum, _)] -> do
                    liftIO $ printf "At NY City, temperature of %d and humidity %d\n"  temp hum
                    yield (temp, hum)
                [_, _, _]                         -> do
                    liftIO $ putStrLn "BOGUS - Ignore"
                    return()


text:
<?php
class Question_mode_model extends MY_Model{
    protected $table_name = 'question_mode';
}


text:
require 'test_helper'

class Elasticsearch::Model::RecordsTest < Test::Unit::TestCase
  context "Response records" do
    class DummyCollection
      include Enumerable

      def each(&block); ['FOO'].each(&block); end
      def size;         ['FOO'].size;         end
      def empty?;       ['FOO'].empty?;       end
      def foo;          'BAR';                end
    end

    class DummyModel
      def self.index_name;    'foo'; end
      def self.document_type; 'bar'; end

      def self.find(*args)
        DummyCollection.new
      end
    end

    RESPONSE = { 'hits' => { 'total' => 123, 'max_score' => 456, 'hits' => [{'_id' => '1', 'foo' => 'bar'}] } }
    RESULTS  = Elasticsearch::Model::Response::Results.new DummyModel, RESPONSE

    setup do
      search   = Elasticsearch::Model::Searching::SearchRequest.new DummyModel, '*'
      search.stubs(:execute!).returns RESPONSE

      response = Elasticsearch::Model::Response::Response.new DummyModel, search
      @records = Elasticsearch::Model::Response::Records.new  DummyModel, response
    end

    should "access the records" do
      assert_respond_to @records, :records
      assert_equal 1, @records.records.size
      assert_equal 'FOO', @records.records.first
    end

    should "delegate Enumerable methods to records" do
      assert ! @records.empty?
      assert_equal 'FOO', @records.first
    end

    should "delegate methods to records" do
      assert_respond_to   @records, :foo
      assert_equal 'BAR', @records.foo
    end

    should "have each_with_hit method" do
      @records.each_with_hit do |record, hit|
        assert_equal 'FOO', record
        assert_equal 'bar', hit.foo
      end
    end

    should "have map_with_hit method" do
      assert_equal ['FOO---bar'], @records.map_with_hit { |record, hit| "#{record}---#{hit.foo}" }
    end

    should "return the IDs" do
      assert_equal ['1'], @records.ids
    end

    context "with adapter" do
      module DummyAdapter
        module RecordsMixin
          def records
            ['FOOBAR']
          end
        end

        def records_mixin
          RecordsMixin
        end; module_function :records_mixin
      end

      should "delegate the records method to the adapter" do
        Elasticsearch::Model::Adapter.expects(:from_class)
                                     .with(DummyModel)
                                     .returns(DummyAdapter)

        @records = Elasticsearch::Model::Response::Records.new DummyModel,
                                                               RESPONSE

        assert_equal ['FOOBAR'], @records.records
      end
    end

  end
end


text:
import AttributeNode from '../core/AttributeNode.js';
import BypassNode from '../core/BypassNode.js';
import CodeNode from '../core/CodeNode.js';
import ContextNode from '../core/ContextNode.js';
import ExpressionNode from '../core/ExpressionNode.js';
import FunctionCallNode from '../core/FunctionCallNode.js';
import FunctionNode from '../core/FunctionNode.js';
import InstanceIndexNode from '../core/InstanceIndexNode.js';
import PropertyNode from '../core/PropertyNode.js';
import UniformNode from '../core/UniformNode.js';
import VarNode from '../core/VarNode.js';
import VaryNode from '../core/VaryNode.js';

// accessors
import BufferNode from '../accessors/BufferNode.js';
import CameraNode from '../accessors/CameraNode.js';
import MaterialNode from '../accessors/MaterialNode.js';
import MaterialReferenceNode from '../accessors/MaterialReferenceNode.js';
import ModelViewProjectionNode from '../accessors/ModelViewProjectionNode.js';
import NormalNode from '../accessors/NormalNode.js';
import ModelNode from '../accessors/ModelNode.js';
import PointUVNode from '../accessors/PointUVNode.js';
import PositionNode from '../accessors/PositionNode.js';
import ReferenceNode from '../accessors/ReferenceNode.js';
import StorageBufferNode from '../accessors/StorageBufferNode.js';
import TextureNode from '../accessors/TextureNode.js';
import UserDataNode from '../accessors/UserDataNode.js';
import UVNode from '../accessors/UVNode.js';

// display
import FrontFacingNode from '../display/FrontFacingNode.js';

// gpgpu
import ComputeNode from '../gpgpu/ComputeNode.js';

// math
import MathNode from '../math/MathNode.js';
import OperatorNode from '../math/OperatorNode.js';
import CondNode from '../math/CondNode.js';

// utils
import ArrayElementNode from '../utils/ArrayElementNode.js';
import ConvertNode from '../utils/ConvertNode.js';

// shader node utils
import { ShaderNode, nodeObject, nodeObjects, nodeArray, nodeProxy, nodeImmutable, ConvertType, getConstNodeType, cacheMaps } from './ShaderNode.js';

// shader node base

export { ShaderNode, nodeObject, nodeObjects, nodeArray, nodeProxy, nodeImmutable };

export const color = new ConvertType( 'color' );

export const float = new ConvertType( 'float', cacheMaps.float );
export const int = new ConvertType( 'int', cacheMaps.int );
export const uint = new ConvertType( 'uint', cacheMaps.uint );
export const bool = new ConvertType( 'bool', cacheMaps.bool );

export const vec2 = new ConvertType( 'vec2' );
export const ivec2 = new ConvertType( 'ivec2' );
export const uvec2 = new ConvertType( 'uvec2' );
export const bvec2 = new ConvertType( 'bvec2' );

export const vec3 = new ConvertType( 'vec3' );
export const ivec3 = new ConvertType( 'ivec3' );
export const uvec3 = new ConvertType( 'uvec3' );
export const bvec3 = new ConvertType( 'bvec3' );

export const vec4 = new ConvertType( 'vec4' );
export const ivec4 = new ConvertType( 'ivec4' );
export const uvec4 = new ConvertType( 'uvec4' );
export const bvec4 = new ConvertType( 'bvec4' );

export const mat3 = new ConvertType( 'mat3' );
export const imat3 = new ConvertType( 'imat3' );
export const umat3 = new ConvertType( 'umat3' );
export const bmat3 = new ConvertType( 'bmat3' );

export const mat4 = new ConvertType( 'mat4' );
export const imat4 = new ConvertType( 'imat4' );
export const umat4 = new ConvertType( 'umat4' );
export const bmat4 = new ConvertType( 'bmat4' );

// core

// @TODO: ArrayUniformNode

export const func = ( code ) => {

	const node = nodeObject( new FunctionNode( code ) );

	const call = node.call.bind( node );
	node.call = ( params ) => nodeObject( call( params ) );

	return node;

};

export const uniform = ( nodeOrType ) => {

	const nodeType = getConstNodeType( nodeOrType );

	// @TODO: get ConstNode from .traverse() in the future
	const value = nodeOrType.isNode === true ? nodeOrType.node?.value || nodeOrType.value : nodeOrType;

	return nodeObject( new UniformNode( value, nodeType ) );

};

export const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
export const property = ( name, nodeOrType ) => nodeObject( new PropertyNode( name, getConstNodeType( nodeOrType ) ) );

export const bypass = nodeProxy( BypassNode );
export const code = nodeProxy( CodeNode );
export const context = nodeProxy( ContextNode );
export const expression = nodeProxy( ExpressionNode );
export const call = nodeProxy( FunctionCallNode );
export const instanceIndex = nodeImmutable( InstanceIndexNode );
export const label = nodeProxy( VarNode );
export const temp = label;
export const vary = nodeProxy( VaryNode );

// accesors

export const buffer = ( value, nodeOrType, count ) => nodeObject( new BufferNode( value, getConstNodeType( nodeOrType ), count ) );
export const storage = ( value, nodeOrType, count ) => nodeObject( new StorageBufferNode( value, getConstNodeType( nodeOrType ), count ) );

export const cameraProjectionMatrix = nodeImmutable( CameraNode, CameraNode.PROJECTION_MATRIX );
export const cameraViewMatrix = nodeImmutable( CameraNode, CameraNode.VIEW_MATRIX );
export const cameraNormalMatrix = nodeImmutable( CameraNode, CameraNode.NORMAL_MATRIX );
export const cameraWorldMatrix = nodeImmutable( CameraNode, CameraNode.WORLD_MATRIX );
export const cameraPosition = nodeImmutable( CameraNode, CameraNode.POSITION );

export const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
export const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
export const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
export const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
//export const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
export const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
export const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
export const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );

export const diffuseColor = nodeImmutable( PropertyNode, 'DiffuseColor', 'vec4' );
export const roughness = nodeImmutable( PropertyNode, 'Roughness', 'float' );
export const metalness = nodeImmutable( PropertyNode, 'Metalness', 'float' );
export const alphaTest = nodeImmutable( PropertyNode, 'AlphaTest', 'float' );
export const specularColor = nodeImmutable( PropertyNode, 'SpecularColor', 'color' );

export const reference = ( name, nodeOrType, object ) => nodeObject( new ReferenceNode( name, getConstNodeType( nodeOrType ), object ) );
export const materialReference = ( name, nodeOrType, material ) => nodeObject( new MaterialReferenceNode( name, getConstNodeType( nodeOrType ), material ) );
export const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );

export const modelViewProjection = nodeProxy( ModelViewProjectionNode );

export const normalGeometry = nodeImmutable( NormalNode, NormalNode.GEOMETRY );
export const normalLocal = nodeImmutable( NormalNode, NormalNode.LOCAL );
export const normalWorld = nodeImmutable( NormalNode, NormalNode.WORLD );
export const normalView = nodeImmutable( NormalNode, NormalNode.VIEW );
export const transformedNormalView = nodeImmutable( VarNode, normalView, 'TransformedNormalView' );

export const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX );
export const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
export const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
export const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
export const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );

export const positionGeometry = nodeImmutable( PositionNode, PositionNode.GEOMETRY );
export const positionLocal = nodeImmutable( PositionNode, PositionNode.LOCAL );
export const positionWorld = nodeImmutable( PositionNode, PositionNode.WORLD );
export const positionView = nodeImmutable( PositionNode, PositionNode.VIEW );
export const positionViewDirection = nodeImmutable( PositionNode, PositionNode.VIEW_DIRECTION );

export const texture = nodeProxy( TextureNode );
export const sampler = ( texture ) => nodeObject( new ConvertNode( texture.isNode === true ? texture : new TextureNode( texture ), 'sampler' ) );
export const uv = ( ...params ) => nodeObject( new UVNode( ...params ) );
export const pointUV = nodeImmutable( PointUVNode );

// gpgpu

export const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );

// math

export const EPSILON = float( 1e-6 );
export const INFINITY = float( 1e6 );

export const cond = nodeProxy( CondNode );

export const add = nodeProxy( OperatorNode, '+' );
export const sub = nodeProxy( OperatorNode, '-' );
export const mul = nodeProxy( OperatorNode, '*' );
export const div = nodeProxy( OperatorNode, '/' );
export const remainder = nodeProxy( OperatorNode, '%' );
export const equal = nodeProxy( OperatorNode, '==' );
export const assign = nodeProxy( OperatorNode, '=' );
export const lessThan = nodeProxy( OperatorNode, '<' );
export const greaterThan = nodeProxy( OperatorNode, '>' );
export const lessThanEqual = nodeProxy( OperatorNode, '<=' );
export const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
export const and = nodeProxy( OperatorNode, '&&' );
export const or = nodeProxy( OperatorNode, '||' );
export const xor = nodeProxy( OperatorNode, '^^' );
export const bitAnd = nodeProxy( OperatorNode, '&' );
export const bitOr = nodeProxy( OperatorNode, '|' );
export const bitXor = nodeProxy( OperatorNode, '^' );
export const shiftLeft = nodeProxy( OperatorNode, '<<' );
export const shiftRight = nodeProxy( OperatorNode, '>>' );

export const radians = nodeProxy( MathNode, MathNode.RADIANS );
export const degrees = nodeProxy( MathNode, MathNode.DEGREES );
export const exp = nodeProxy( MathNode, MathNode.EXP );
export const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
export const log = nodeProxy( MathNode, MathNode.LOG );
export const log2 = nodeProxy( MathNode, MathNode.LOG2 );
export const sqrt = nodeProxy( MathNode, MathNode.SQRT );
export const inversesqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
export const floor = nodeProxy( MathNode, MathNode.FLOOR );
export const ceil = nodeProxy( MathNode, MathNode.CEIL );
export const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
export const fract = nodeProxy( MathNode, MathNode.FRACT );
export const sin = nodeProxy( MathNode, MathNode.SIN );
export const cos = nodeProxy( MathNode, MathNode.COS );
export const tan = nodeProxy( MathNode, MathNode.TAN );
export const asin = nodeProxy( MathNode, MathNode.ASIN );
export const acos = nodeProxy( MathNode, MathNode.ACOS );
export const atan = nodeProxy( MathNode, MathNode.ATAN );
export const abs = nodeProxy( MathNode, MathNode.ABS );
export const sign = nodeProxy( MathNode, MathNode.SIGN );
export const length = nodeProxy( MathNode, MathNode.LENGTH );
export const negate = nodeProxy( MathNode, MathNode.NEGATE );
export const invert = nodeProxy( MathNode, MathNode.INVERT );
export const dFdx = nodeProxy( MathNode, MathNode.DFDX );
export const dFdy = nodeProxy( MathNode, MathNode.DFDY );
export const saturate = nodeProxy( MathNode, MathNode.SATURATE );
export const round = nodeProxy( MathNode, MathNode.ROUND );

export const min = nodeProxy( MathNode, MathNode.MIN );
export const max = nodeProxy( MathNode, MathNode.MAX );
export const mod = nodeProxy( MathNode, MathNode.MOD );
export const step = nodeProxy( MathNode, MathNode.STEP );
export const reflect = nodeProxy( MathNode, MathNode.REFLECT );
export const distance = nodeProxy( MathNode, MathNode.DISTANCE );
export const dot = nodeProxy( MathNode, MathNode.DOT );
export const cross = nodeProxy( MathNode, MathNode.CROSS );
export const pow = nodeProxy( MathNode, MathNode.POW );
export const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
export const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
export const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
export const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );

export const mix = nodeProxy( MathNode, MathNode.MIX );
export const clamp = nodeProxy( MathNode, MathNode.CLAMP );
export const refract = nodeProxy( MathNode, MathNode.REFRACT );
export const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
export const faceforward = nodeProxy( MathNode, MathNode.FACEFORWARD );

// display

export const frontFacing = nodeImmutable( FrontFacingNode );
export const faceDirection = sub( mul( float( frontFacing ), 2 ), 1 );

// lighting

// utils

export const element = nodeProxy( ArrayElementNode );

// miscellaneous

export const dotNV = saturate( dot( transformedNormalView, positionViewDirection ) );
export const transformedNormalWorld = normalize( transformDirection( transformedNormalView, cameraViewMatrix ) );


text:
<!DOCTYPE html>

    <title>Genius Hour 1st Nine Weeks</title>

How can we make a website from scratch using HTML, CSS, and JavaScript?

By E. Huang, C. Taylor, and L. Gorton

In our example here, we're using CodePen - Front End Developer Playground & Code Editor in the Browser.

You should make an account first to save your work. It's free!

 In this first lesson, we will learn about tags. Tags are hidden keywords that tell the browser what a description is about. Tags are pre-defined, so you cannot make your own tags. :( You can think of tags as a human body. The first tag is Doctype. You can think of Doctype as a cap. Since you wear a cap on top of your head, Doctype comes before Head in HTML.

Hi guys, in our next lesson, we will be learning about the basics of html. In HTML, there are many tags that you can use.

Here are some examples of this.

<p>=paragraphs

<h1 to h6>=header

<!DOCTYPE>=document type

<title>=title

<body>=body

<ol>=ordered list

<ul>=unordered list

<li>=list item


text:
HautziSystemMailBundle
======================

[![SensioLabsInsight](https://insight.sensiolabs.com/projects/7c3d1f06-d02e-44cf-ac24-3cad04ac8ebf/mini.png)](https://insight.sensiolabs.com/projects/7c3d1f06-d02e-44cf-ac24-3cad04ac8ebf)
[![Build Status](https://travis-ci.org/christoph-hautzinger/SystemMailBundle.svg?branch=master)](https://travis-ci.org/christoph-hautzinger/SystemMailBundle)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/christoph-hautzinger/SystemMailBundle/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/christoph-hautzinger/SystemMailBundle/?branch=master)

This bundle abstracts away sending system Messages. If instanciating a `Swift_Message` instance in your controllers
seems fishy to you, this is probably what you are looking for.

This idea of this Bundle is to create some sort of XML configuration for each system mail to be sent (like "you have
registered successfully, please activate your account" or "hey dude, you haven't been wasted your money on our platform
for 10 days, please come back"), leveraging the power of twig.

Hey, why not looking in the code? It's kind of self-explanatory:

```twig
// AppBundle/Resources/emails/send-info.xml.twig
<?xml version="1.0"?>
<email xmlns="http://christoph-hautzinger.de/schema/system-mail-bundle"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://christoph-hautzinger.de/schema/system-mail-bundle http://christoph-hautzinger.de/schema/system-mail-bundle/email-1.0.xsd">
    <to name="{{ user.name }}">{{ user.email }}</to>
    <subject locale="de">Hallo {{ user.name }}</subject>
    <subject locale="en">Hello {{ user.name }}</subject>
    <messageHtml locale="en"><![CDATA[
        Hallo {{ user.name }},
        <a href="{{ url('') }}">please click this link</a>.
    ]]></messageHtml>
    <messageText locale="en" removeIndent="true">
        Hello {{ user.name }},
        please click this link: {{ url('') }}
    </messageText>
</email>
```
Then send out this mail explicitly by simply calling:

```php
// from your code simply call
$container->get('system_mailer')->send('emails/send-info.xml.twig', [
    'user' => $user,
]);
```

Installation
------------

### Step 1: Download the Bundle ###

Open a command console, enter your project directory and execute the
following command to download the latest stable version of this bundle:

```bash
$ composer require hautzi/system-mail-bundle
```

This command requires you to have Composer installed globally, as explained
in the [installation chapter](https://getcomposer.org/doc/00-intro.md)
of the Composer documentation.

### Step 2: Enable the Bundle ###

Then, enable the bundle by adding the following line in the `app/AppKernel.php`
file of your project:

```php
<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...

            new Hautzi\SystemMailBundle\HautziSystemMailBundle(),
        );

        // ...
    }

    // ...
}
```

Configuration Options
---------------------

Right now, you can provide default data

```yaml
# in your app/config.yml
hautzi_system_mail:
    # defaults that are set for each mail, use blank
    # if you don't want to set this
    defaults:
        subject:   ~
        replyTo:   ~
        from:
            email: ~
            name:  ~
        to:
            email: ~
            name:  ~
        cc:
            email: ~
            name:  ~
        bcc:
            email: ~
            name:  ~
```

Examples
--------

```php
$systemMailer = $container->get('system_mailer');

// sends out AppBundle/Resources/emails/registration/confirmUser.xml.twig
$systemMailer->send('emails/registration/confirmUser.xml.twig', ['user' => $user]);

// force locale of sent mail (when the recipient speaks another language than the user in the session)
$systemMailer->send('emails/info-mail.xml.twig', ['user' => $user], 'de');

// attach file to mail (or do something else with the Swift_Message instance)
$systemMailer->send('emails/message-with-pdf.xml.twig', [], null, function (\Swift_Message $message) {
     $message->attach(\Swift_Attachment::fromPath('my-document.pdf'))
});
```

License
-------

This bundle is under the MIT license. See the complete license in the `LICENSE` file in the root dir of the bundle.


text:
using namespace std;					// make std:: accessible

class SinglyNode {						// a node in a list of strings
private:
	string elem;						// element value
	int score;							// score
	SinglyNode* next;					// next item in the list

	friend class SinglyLinkedList;		// provide SinglyLinkedList access
};


text:
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/routing
        http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="root" path="/">
        <default key="_controller">FrameworkBundle:Redirect:redirect</default>
        <default key="route">nelmio_api_doc_index</default>
        <default key="permanent">true</default>
    </route>

</routes>


text:
package com.phloc.commons.state;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Test class for class {@link EValidity}.
 *
 * @author Philip Helger
 */
public final class EValidityTest
{
  @Test
  public void testAll ()
  {
    for (final EValidity e : EValidity.values ())
      assertSame (e, EValidity.valueOf (e.name ()));

    assertTrue (EValidity.VALID.isValid ());
    assertFalse (EValidity.VALID.isInvalid ());
    assertFalse (EValidity.INVALID.isValid ());
    assertTrue (EValidity.INVALID.isInvalid ());
    assertSame (EValidity.VALID, EValidity.valueOf (true));
    assertSame (EValidity.INVALID, EValidity.valueOf (false));
    assertSame (EValidity.VALID, EValidity.VALID.or (EValidity.INVALID));
    assertSame (EValidity.VALID, EValidity.VALID.or (EValidity.VALID));
    assertSame (EValidity.INVALID, EValidity.VALID.and (EValidity.INVALID));
    assertSame (EValidity.VALID, EValidity.VALID.and (EValidity.VALID));
    assertSame (EValidity.INVALID, EValidity.INVALID.or (EValidity.INVALID));
    assertSame (EValidity.VALID, EValidity.INVALID.or (EValidity.VALID));
    assertSame (EValidity.INVALID, EValidity.INVALID.and (EValidity.INVALID));
    assertSame (EValidity.INVALID, EValidity.INVALID.and (EValidity.VALID));
  }
}


text:
class SkCanvas;

namespace cc {
class ImageSerializationProcessor;

class CC_EXPORT FilterDisplayItem : public DisplayItem {
 public:
  FilterDisplayItem(const FilterOperations& filters, const gfx::RectF& bounds);
  explicit FilterDisplayItem(const proto::DisplayItem& proto);
  ~FilterDisplayItem() override;

  void ToProtobuf(proto::DisplayItem* proto,
                  ImageSerializationProcessor* image_serialization_processor)
      const override;
  void Raster(SkCanvas* canvas,
              const gfx::Rect& canvas_target_playback_rect,
              SkPicture::AbortCallback* callback) const override;
  void AsValueInto(const gfx::Rect& visual_rect,
                   base::trace_event::TracedValue* array) const override;
  size_t ExternalMemoryUsage() const override;

  int ApproximateOpCount() const { return 1; }

 private:
  void SetNew(const FilterOperations& filters, const gfx::RectF& bounds);

  FilterOperations filters_;
  gfx::RectF bounds_;
};

class CC_EXPORT EndFilterDisplayItem : public DisplayItem {
 public:
  EndFilterDisplayItem();
  explicit EndFilterDisplayItem(const proto::DisplayItem& proto);
  ~EndFilterDisplayItem() override;

  static std::unique_ptr<EndFilterDisplayItem> Create() {
    return base::WrapUnique(new EndFilterDisplayItem());
  }

  void ToProtobuf(proto::DisplayItem* proto,
                  ImageSerializationProcessor* image_serialization_processor)
      const override;
  void Raster(SkCanvas* canvas,
              const gfx::Rect& canvas_target_playback_rect,
              SkPicture::AbortCallback* callback) const override;
  void AsValueInto(const gfx::Rect& visual_rect,
                   base::trace_event::TracedValue* array) const override;
  size_t ExternalMemoryUsage() const override;

  int ApproximateOpCount() const { return 0; }
  bool IsSuitableForGpuRasterization() const { return true; }
};

}  // namespace cc

#endif  // CC_PLAYBACK_FILTER_DISPLAY_ITEM_H_


text:
import { EncodeArrayBufferToBase64 } from "@dev/core";
import type { GlobalState } from "../globalState";
import { Utilities } from "./utilities";

export class SaveManager {
    public constructor(public globalState: GlobalState) {
        globalState.onSaveRequiredObservable.add(() => {
            if (!this.globalState.currentSnippetTitle || !this.globalState.currentSnippetDescription || !this.globalState.currentSnippetTags) {
                this.globalState.onMetadataWindowHiddenObservable.addOnce((status) => {
                    if (status) {
                        this._saveSnippet();
                    }
                });
                this.globalState.onDisplayMetadataObservable.notifyObservers(true);
                return;
            }
            this._saveSnippet();
        });
    }

    private _saveSnippet() {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = () => {
            if (xmlHttp.readyState === 4) {
                if (xmlHttp.status === 200) {
                    const snippet = JSON.parse(xmlHttp.responseText);
                    if (location.pathname && location.pathname.indexOf("pg/") !== -1) {
                        // full path with /pg/??????
                        if (location.pathname.indexOf("revision") !== -1) {
                            location.href = location.href.replace(/revision\/(\d+)/, "revision/" + snippet.version);
                        } else {
                            location.href = location.href + "/revision/" + snippet.version;
                        }
                    } else if (location.search && location.search.indexOf("pg=") !== -1) {
                        // query string with ?pg=??????
                        const currentQuery = Utilities.ParseQuery();
                        if (currentQuery.revision) {
                            location.href = location.href.replace(/revision=(\d+)/, "revision=" + snippet.version);
                        } else {
                            location.href = location.href + "&revision=" + snippet.version;
                        }
                    } else {
                        // default behavior!
                        const baseUrl = location.href.replace(location.hash, "");
                        let newUrl = baseUrl + "#" + snippet.id;
                        newUrl = newUrl.replace("##", "#");
                        this.globalState.currentSnippetToken = snippet.id;
                        if (snippet.version && snippet.version !== "0") {
                            newUrl += "#" + snippet.version;
                        }
                        location.href = newUrl;
                    }

                    this.globalState.onSavedObservable.notifyObservers();
                } else {
                    this.globalState.onErrorObservable.notifyObservers({ message: "Unable to save your code. It may be too long." });
                }
            }
        };

        xmlHttp.open("POST", this.globalState.SnippetServerUrl + (this.globalState.currentSnippetToken ? "/" + this.globalState.currentSnippetToken : ""), true);
        xmlHttp.setRequestHeader("Content-Type", "application/json");

        const encoder = new TextEncoder();
        const buffer = encoder.encode(this.globalState.currentCode);

        // Check if we need to encode it to store the unicode characters
        let testData = "";

        for (let i = 0; i < buffer.length; i++) {
            testData += String.fromCharCode(buffer[i]);
        }

        const payLoad = JSON.stringify({
            code: this.globalState.currentCode,
            unicode: testData !== this.globalState.currentCode ? EncodeArrayBufferToBase64(buffer) : undefined,
        });

        const dataToSend = {
            payload: payLoad,
            name: this.globalState.currentSnippetTitle,
            description: this.globalState.currentSnippetDescription,
            tags: this.globalState.currentSnippetTags,
        };

        xmlHttp.send(JSON.stringify(dataToSend));
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/. */

/* rendering object for CSS "display: ruby-text-container" */

#ifndef nsRubyTextContainerFrame_h___
#define nsRubyTextContainerFrame_h___

#include "nsBlockFrame.h"

typedef nsContainerFrame nsRubyTextContainerFrameSuper;

/**
 * Factory function.
 * @return a newly allocated nsRubyTextContainerFrame (infallible)
 */
nsContainerFrame* NS_NewRubyTextContainerFrame(nsIPresShell* aPresShell,
                                               nsStyleContext* aContext);

class nsRubyTextContainerFrame final : public nsRubyTextContainerFrameSuper
{
public:
  NS_DECL_FRAMEARENA_HELPERS
  NS_DECL_QUERYFRAME_TARGET(nsRubyTextContainerFrame)
  NS_DECL_QUERYFRAME

  // nsIFrame overrides
  virtual nsIAtom* GetType() const override;
  virtual bool IsFrameOfType(uint32_t aFlags) const override;
  virtual void Reflow(nsPresContext* aPresContext,
                      nsHTMLReflowMetrics& aDesiredSize,
                      const nsHTMLReflowState& aReflowState,
                      nsReflowStatus& aStatus) override;

#ifdef DEBUG_FRAME_DUMP
  virtual nsresult GetFrameName(nsAString& aResult) const override;
#endif

  // nsContainerFrame overrides
  virtual void SetInitialChildList(ChildListID aListID,
                                   nsFrameList& aChildList) override;
  virtual void AppendFrames(ChildListID aListID,
                            nsFrameList& aFrameList) override;
  virtual void InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
                            nsFrameList& aFrameList) override;
  virtual void RemoveFrame(ChildListID aListID,
                           nsIFrame* aOldFrame) override;

  bool IsSpanContainer() const
  {
    return GetStateBits() & NS_RUBY_TEXT_CONTAINER_IS_SPAN;
  }

protected:
  friend nsContainerFrame*
    NS_NewRubyTextContainerFrame(nsIPresShell* aPresShell,
                                 nsStyleContext* aContext);
  explicit nsRubyTextContainerFrame(nsStyleContext* aContext)
    : nsRubyTextContainerFrameSuper(aContext)
    , mISize(0) {}

  void UpdateSpanFlag();

  friend class nsRubyBaseContainerFrame;
  void SetISize(nscoord aISize) { mISize = aISize; }

  // The intended inline size of the ruby text container. It is set by
  // the corresponding ruby base container when the segment is reflowed,
  // and used when the ruby text container is reflowed by its parent.
  nscoord mISize;
};

#endif /* nsRubyTextContainerFrame_h___ */


text:
<?php

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\ProcessBuilder;

class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testInheritEnvironmentVars()
    {
        $_ENV['MY_VAR_1'] = 'foo';

        $proc = ProcessBuilder::create()
            ->add('foo')
            ->getProcess();

        unset($_ENV['MY_VAR_1']);

        $env = $proc->getEnv();
        $this->assertArrayHasKey('MY_VAR_1', $env);
        $this->assertEquals('foo', $env['MY_VAR_1']);
    }

    public function testProcessShouldInheritAndOverrideEnvironmentVars()
    {
        $_ENV['MY_VAR_1'] = 'foo';

        $proc = ProcessBuilder::create()
            ->setEnv('MY_VAR_1', 'bar')
            ->add('foo')
            ->getProcess();

        unset($_ENV['MY_VAR_1']);

        $env = $proc->getEnv();
        $this->assertArrayHasKey('MY_VAR_1', $env);
        $this->assertEquals('bar', $env['MY_VAR_1']);
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
     */
    public function testNegativeTimeoutFromSetter()
    {
        $pb = new ProcessBuilder();
        $pb->setTimeout(-1);
    }

    public function testNullTimeout()
    {
        $pb = new ProcessBuilder();
        $pb->setTimeout(10);
        $pb->setTimeout(null);

        $r = new \ReflectionObject($pb);
        $p = $r->getProperty('timeout');
        $p->setAccessible(true);

        $this->assertNull($p->getValue($pb));
    }

    public function testShouldSetArguments()
    {
        $pb = new ProcessBuilder(array('initial'));
        $pb->setArguments(array('second'));

        $proc = $pb->getProcess();

        $this->assertContains("second", $proc->getCommandLine());
    }

    public function testPrefixIsPrependedToAllGeneratedProcess()
    {
        $pb = new ProcessBuilder();
        $pb->setPrefix('/usr/bin/php');

        $proc = $pb->setArguments(array('-v'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "-v"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' '-v'", $proc->getCommandLine());
        }

        $proc = $pb->setArguments(array('-i'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "-i"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' '-i'", $proc->getCommandLine());
        }
    }

    public function testArrayPrefixesArePrependedToAllGeneratedProcess()
    {
        $pb = new ProcessBuilder();
        $pb->setPrefix(array('/usr/bin/php', 'composer.phar'));

        $proc = $pb->setArguments(array('-v'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "composer.phar" "-v"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' 'composer.phar' '-v'", $proc->getCommandLine());
        }

        $proc = $pb->setArguments(array('-i'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "composer.phar" "-i"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' 'composer.phar' '-i'", $proc->getCommandLine());
        }
    }

    public function testShouldEscapeArguments()
    {
        $pb = new ProcessBuilder(array('%path%', 'foo " bar'));
        $proc = $pb->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertSame('^%"path"^% "foo "\\"" bar"', $proc->getCommandLine());
        } else {
            $this->assertSame("'%path%' 'foo \" bar'", $proc->getCommandLine());
        }
    }

    public function testShouldEscapeArgumentsAndPrefix()
    {
        $pb = new ProcessBuilder(array('arg'));
        $pb->setPrefix('%prefix%');
        $proc = $pb->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertSame('^%"prefix"^% "arg"', $proc->getCommandLine());
        } else {
            $this->assertSame("'%prefix%' 'arg'", $proc->getCommandLine());
        }
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\LogicException
     */
    public function testShouldThrowALogicExceptionIfNoPrefixAndNoArgument()
    {
        ProcessBuilder::create()->getProcess();
    }

    public function testShouldNotThrowALogicExceptionIfNoArgument()
    {
        $process = ProcessBuilder::create()
            ->setPrefix('/usr/bin/php')
            ->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
        }
    }

    public function testShouldNotThrowALogicExceptionIfNoPrefix()
    {
        $process = ProcessBuilder::create(array('/usr/bin/php'))
            ->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.springframework.jms.listener.adapter (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.springframework.jms.listener.adapter

Classes

MessageListenerAdapter

MessageListenerAdapter102

Exceptions

ListenerExecutionFailedException


text:
package com.urswolfer.gerrit.client.rest.http.changes;

import com.google.gerrit.extensions.api.changes.*;
import com.google.gerrit.extensions.common.CommentInfo;
import com.google.gerrit.extensions.common.FileInfo;
import com.google.gerrit.extensions.restapi.BinaryResult;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.Url;
import com.google.gson.JsonElement;
import com.urswolfer.gerrit.client.rest.http.GerritRestClient;
import com.urswolfer.gerrit.client.rest.http.util.BinaryResultUtils;
import org.apache.http.HttpResponse;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Urs Wolfer
 */
public class RevisionApiRestClient extends RevisionApi.NotImplemented implements RevisionApi {

    private final GerritRestClient gerritRestClient;
    private final ChangeApiRestClient changeApiRestClient;
    private final CommentsParser commentsParser;
    private final FileInfoParser fileInfoParser;
    private final DiffInfoParser diffInfoParser;
    private final String revision;

    public RevisionApiRestClient(GerritRestClient gerritRestClient,
                                 ChangeApiRestClient changeApiRestClient,
                                 CommentsParser commentsParser,
                                 FileInfoParser fileInfoParser,
                                 DiffInfoParser diffInfoParser,
                                 String revision) {
        this.gerritRestClient = gerritRestClient;
        this.changeApiRestClient = changeApiRestClient;
        this.commentsParser = commentsParser;
        this.fileInfoParser = fileInfoParser;
        this.diffInfoParser = diffInfoParser;
        this.revision = revision;
    }

    public String revision() {
        return revision;
    }

    @Override
    public void review(ReviewInput reviewInput) throws RestApiException {
        String request = getRequestPath() + "/review";
        String json = gerritRestClient.getGson().toJson(reviewInput);
        gerritRestClient.postRequest(request, json);
    }

    @Override
    public void submit() throws RestApiException {
        submit(new SubmitInput());
    }

    @Override
    public void submit(SubmitInput submitInput) throws RestApiException {
        String request = changeApiRestClient.getRequestPath() + "/submit";
        String json = gerritRestClient.getGson().toJson(submitInput);
        gerritRestClient.postRequest(request, json);
    }

    @Override
    public void setReviewed(String path, boolean reviewed) throws RestApiException {
        String encodedPath = Url.encode(path);
        String url =  String.format("/changes/%s/revisions/%s/files/%s/reviewed", changeApiRestClient.id(), revision, encodedPath);
        if (reviewed) {
            gerritRestClient.putRequest(url);
        } else {
            gerritRestClient.deleteRequest(url);
        }
    }

    /**
     * Support starting from Gerrit 2.7.
     */
    @Override
    public TreeMap<String, List<CommentInfo>> comments() throws RestApiException {
        return comments("comments");
    }

    @Override
    public TreeMap<String, List<CommentInfo>> drafts() throws RestApiException {
        return comments("drafts");
    }

    private TreeMap<String, List<CommentInfo>> comments(String type) throws RestApiException {
        String request = getRequestPath() + '/' + type + '/';
        JsonElement jsonElement = gerritRestClient.getRequest(request);
        return commentsParser.parseCommentInfos(jsonElement);
    }

    @Override
    public DraftApi createDraft(DraftInput in) throws RestApiException {
        String request = getRequestPath() + "/drafts";
        String json = gerritRestClient.getGson().toJson(in);
        JsonElement jsonElement = gerritRestClient.putRequest(request, json);
        CommentInfo commentInfo = commentsParser.parseSingleCommentInfo(jsonElement.getAsJsonObject());
        return new DraftApiRestClient(gerritRestClient, changeApiRestClient, this, commentsParser, commentInfo);
    }

    @Override
    public DraftApi draft(String id) throws RestApiException {
        return new DraftApiRestClient(gerritRestClient, changeApiRestClient, this, commentsParser, id);
    }

    @Override
    public Map<String, FileInfo> files() throws RestApiException {
        String request = getRequestPath() + "/files";
        JsonElement jsonElement = gerritRestClient.getRequest(request);
        return fileInfoParser.parseFileInfos(jsonElement);
    }

    @Override
    public FileApi file(String path) {
        return new FileApiRestClient(gerritRestClient, this, diffInfoParser, path);
    }

    @Override
    public BinaryResult patch() throws RestApiException {
        String request = getRequestPath() + "/patch";
        try {
            HttpResponse response = gerritRestClient.request(request, null, GerritRestClient.HttpVerb.GET);
            return BinaryResultUtils.createBinaryResult(response);
        } catch (IOException e) {
            throw new RestApiException("Failed to get patch.", e);
        }
    }

    protected String getRequestPath() {
        return changeApiRestClient.getRequestPath() + "/revisions/" + revision;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>energykit.pubsub — EnergyKit 0.1.0 documentation</title>

    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="EnergyKit 0.1.0 documentation" href="../../index.html" />
    <link rel="up" title="Module code" href="../index.html" />

Navigation

          index

          modules |

EnergyKit 0.1.0 documentation »

Module code »

Source code for energykit.pubsub

[docs]class PubSub(object):
  def __init__(self):
    self._subscriptions = {}

[docs]  def publish(self, data=None, source=None):
    heard = []
    if source in self._subscriptions.keys():
      for listener in self._subscriptions[source]:
        listener(data, source)
        heard.append(listener)
    if None in self._subscriptions.keys():
      for listener in self._subscriptions[None]:
        if not listener in heard:
          listener(data, source)

[docs]  def subscribe(self, listener, source=None):
    if source in self._subscriptions.keys():
      subscriptions = self._subscriptions[source]
    else:
      subscriptions = []
      self._subscriptions[source] = subscriptions
    subscriptions.append(listener)

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

EnergyKit 0.1.0 documentation »

Module code »

        © Copyright 2013, Sander Dijkhuis, Interactive Institute.
      Created using Sphinx 1.2b1.


text:
import xlrd
from Scholarship import ScholarshipBuilder

methodList = [ScholarshipBuilder.setId, ScholarshipBuilder.setSchoolsList,
              ScholarshipBuilder.setName, ScholarshipBuilder.setIntroduction,
              ScholarshipBuilder.setYear, ScholarshipBuilder.setAmountPerYear,
              ScholarshipBuilder.setNumberOfYears, ScholarshipBuilder.setEthnicityRaceRequirements,
              ScholarshipBuilder.setLocationRequirements, ScholarshipBuilder.setFinancialRequirements,
              ScholarshipBuilder.setAcademicRequirements, ScholarshipBuilder.setOtherRequirements,
              ScholarshipBuilder.setIsRenewable, ScholarshipBuilder.setApplicationProcess,
              ScholarshipBuilder.setURL, ScholarshipBuilder.setSchoolsNameToIDMap]

#parse scholarship data from excel
# sheet: the index of sheet from 0
# start: the first row to parse
# number: total number of scholarships needs to be parsed
def parseDataFrom(sheet, start, number):

    scholarships = []
    # Give the location of the file
    loc = ("Scholarships.xlsx")

    wb = xlrd.open_workbook(loc)
    sheet = wb.sheet_by_index(sheet)
    for row in range(start, start+number):
        scholarship = {}
        for cell in range(0, 15):
            cellValue = sheet.cell_value(row, cell)
            if cellValue:
                methodList[cell](scholarship, cellValue)
        print(scholarship)
        ScholarshipBuilder.setSchoolsNameToIDMap(scholarship)
        scholarships.append(scholarship)
    return scholarships


text:
package com.interview.tree;

/**
 * http://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/
 * This program assumes that both key val1 and val2 are present in tree under root.
 * If it is possible that val1 or val2 wont be present you need extra check to see that
 * whatever node is returned has val1 or val2 under it.
 * Test cases:
 * Both val1 and val2 exists in the tree
 * val1 is ancestor of val2
 * val2 is ancestor of val1
 * val1 and val2 have different ancestor
 * val1 and val2 are siblings
 */
public class LowestCommonAncestorInBinaryTree {

    public Node lowestCommonAncestor(int val1, int val2,Node root){
        if(root == null){
            return null;
        }
        if(root.data == val1 || root.data == val2){
            return root;
        }

        Node left = lowestCommonAncestor(val1, val2, root.left);
        Node right = lowestCommonAncestor(val1, val2, root.right);

        if(left != null && right != null){
            return root;
        }
        return left != null ? left : right;
    }

    public static void main(String args[]){
        BinaryTree bt = new BinaryTree();
        Node root = null;
        root = bt.addNode(10, root);
        root = bt.addNode(25, root);
        root =  bt.addNode(-10, root);
        root = bt.addNode(0, root);
        root = bt.addNode(-20, root);
        root = bt.addNode(15, root);
        root = bt.addNode(18, root);
        root = bt.addNode(35, root);

        LowestCommonAncestorInBinaryTree lca = new LowestCommonAncestorInBinaryTree();
        Node result = lca.lowestCommonAncestor(0, -20, root);
        System.out.print(result.data);
    }
}