text:
using NUnit.Framework;
using RedisMessaging.Tests.UtilTests;
using Spring.Objects.Factory;

namespace RedisMessaging.Tests.ParserTests
{
  [TestFixture]
  public class RedisSentinelParserTests
  {
    private readonly string ConfigConventionPrefix = "Sentinel";

    [Test]
    [TestCase(1, 60, 1000)]
    [TestCase(3, 300, 10)]
    public void TestLoadingValidSentinelConfig(int configId, int expectedMessageTimeout, int expectedInterval)
    {
      var objectFactory = ParserTestsHelper.LoadConfig(ConfigConventionPrefix, configId);

      var sentinel = objectFactory.GetObject<RedisQueueSentinel>("sentinel");

      Assert.NotNull(sentinel);
      Assert.NotNull(sentinel.Connection);
      Assert.AreEqual(expectedMessageTimeout, sentinel.MessageTimeout);
      Assert.AreEqual(expectedInterval, sentinel.Interval);
    }

    [Test]
    public void TestInvalidSentinelConfig()
    {
      Assert.Throws<ObjectDefinitionStoreException>(() =>
      {
        ParserTestsHelper.LoadConfig(ConfigConventionPrefix, 2);
      });
    }

    [Test]
    public void TestWithBrokenRefConnectionArg()
    {
      Assert.Throws<ObjectCreationException>(() =>
      {
        var objectFactory = ParserTestsHelper.LoadConfig(ConfigConventionPrefix, 4);
        objectFactory.GetObject<RedisQueueSentinel>("sentinel");
      });
    }
  }
}


text:
<?php
include 'init.php';
include ROOT_DIR . '/assets/php/functions.php';
//$image_url = $_GET['img'];
global $plex_instances;
foreach ($plex_instances as $instance) {
    $plex_port = $instance[1];
    $network = getNetwork($instance[3]);

    $image_url = $_GET['img'];
    $plexAddress = $network . ':' . $plex_port;
    $addressPosition = strpos($image_url, $plexAddress);
    if ($addressPosition !== false && $addressPosition == 0) {
        $image_src = $image_url . '?X-Plex-Token=' . $plexToken;
        header('Content-type: image/jpeg');
        //header("Content-Length: " . filesize($image_src));
        readfile($image_src);
    } else {
        echo "Bad Plex Image Url";
    }
}
?>

redpajama_set_name: RedPajamaGithub


text:
// npm module
var React = require('react');

// local modules
var Title = require('./Title');
var Issues = require('./Issues');
var Issue = require('./Issues/Issue');

var github = require('./github');

var Root = React.createClass({
  getInitialState: function () {
    return {
      data: [],
      currentPage: 1,
      lastPage: 1,
      abridged: true,
      issueData: {}
    };
  },
  makeRepoName: function () {
    return this.props.org + '/' + this.props.repo;
  },
  loadIssuesFromServer: function () {
    // This data should be cached... it should happen in the github module
    github.issues(this.makeRepoName(), this.state.currentPage, function (err, issues) {
      if (err) {
        /*eslint-disable no-console */
        return console.log(new Error(err));
        /*eslint-enable no-console */
      }
      this.setState({data: issues});
    }.bind(this));
  },
  getCommentsFromServer: function () {
    github.comments(this.state.commentURL, function (err, comments) {
      this.setState({
        comments: comments,
        abridged: !this.state.abridged
      });
    }.bind(this));
  },
  getIssueFromServer: function () {
    github.issue('npm/npm', this.state.issueNumber.toString(), function (err, issue) {
      if (err) {
        /*eslint-disable no-console */
        return console.log(new Error(err));
        /*eslint-enable no-console */
      }
      issue.url = issue.url.replace('https://api.github.com/repos/', 'https://github.com/');
      this.setState({
        issueData: issue,
        commentURL: issue.comments_url
      }, this.getCommentsFromServer);
    }.bind(this));
  },
  getCountOfIssues: function () {
    github.issuePages(this.makeRepoName(), function (err, count) {
      this.setState({
        lastPage: count
      });
    }.bind(this));
  },
  componentDidMount: function () {
    this.loadIssuesFromServer();
    this.getCountOfIssues();
  },
  handlePaginatorClickEvent: function (page) {
    this.setState({
      currentPage: page
    }, this.loadIssuesFromServer);
  },
  handleIssueClickEvent: function (number) {
    if (this.state.abridged) {
      this.setState({
        issueNumber: number
      }, this.getIssueFromServer);
    }
  },
  handleArrowClickEvent: function () {
    this.setState({
      abridged: !this.state.abridged
    });
  },
  render: function () {
    var basePath = this.props.org + '/' + this.props.repo;
    var content;

    if (this.state.abridged) {
      content = <Issues repo={basePath} data={this.state.data} issueOnClickEvent={this.handleIssueClickEvent} paginatorOnClickEvent={this.handlePaginatorClickEvent} repo={basePath} currentPage={this.state.currentPage} lastPage={this.state.lastPage} />;
    }

    else {
      content = <Issue issue={this.state.issueData} comments={this.state.comments}/>;
    }

    return (
      <div id='root'>
        <Title onClickEvent={this.handleArrowClickEvent} org={this.props.org} repo={this.props.repo} abridged={this.state.abridged}/>
        {content}
      </div>
    );
  }
});

module.exports = Root;


text:
package ocp.example2;

public enum ProductColor {
    RED("red"), BLUE("blue"), GREEN("green"), BLACK("black");

    private String value;

    private ProductColor(String value) {
        this.value = value;
    }

    public String getColor(){
        return value;
    }
}


text:
NSString-HEX
============

Hexadecimal utilities category on NSString class.


text:
import React from 'react'

const About = () => (
About
);

export default About;


text:
    #include <time.h>
#elif defined (__gnu_linux__) || defined (__APPLE__)
    #include <sys/time.h>
#endif

///////////////////////////////////////////
//     This File Handles Everything      //
//             Time Related              //
///////////////////////////////////////////

namespace b2d{

	// Init Variables
	double Time::currentTime = 0;
	double Time::previousTime = 0;
	double Time::deltaTime = 0;
    double Time::frameCount = 0;
	double Time::timePerFrame = 0;
	double Time::fps = 0;

	// Gets The Current System Time In Seconds, Minutes, Or Hours
	double Time::GetSystemTime (int SecMinHour){

		// Create Time Variables
		time_t cTime = time (0);
		tm *currentTime = localtime (&cTime);

		// Get Seconds
		if (SecMinHour == 0){
			return currentTime -> tm_sec;
		}

		// Get Minutes
		else if (SecMinHour == 1){
			return currentTime -> tm_min;
		}

		// Get Hours
		else if (SecMinHour == 2){
			return currentTime -> tm_hour;
		}

		// Get Error
		else{

			std::cout << stderr << " Invalid time type selected" << '\n';
			return 0;
		}
	}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// Get Delta Time
	void Time::GetDeltaTime(){

        #if defined (_WIN32) || defined (_WIN64)

            Time::currentTime = clock();
            Time::deltaTime = (Time::currentTime - Time::previousTime) / CLOCKS_PER_SEC;
            Time::previousTime = Time::currentTime;

        #elif defined (__gnu_linux__) || defined (__APPLE__)

            timeval t;
            gettimeofday (&t, NULL);
            Time::currentTime = t.tv_usec;
            Time::deltaTime = (Time::currentTime - Time::previousTime) / 100000 / 10;
            Time::previousTime = Time::currentTime;

            if (Time::deltaTime < 0){

                Time::currentTime = t.tv_usec;
                Time::deltaTime = (Time::currentTime - Time::previousTime) / 100000 / 10;
                Time::previousTime = Time::currentTime;
            }

        #endif
	}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// Reset Delta Time
	void Time::ResetDeltaTime(){

		Time::currentTime = 0.0;
		Time::deltaTime = 0.0;
		Time::previousTime = 0.0;
	}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// Get FPS
	double Time::GetFPS(){

		// If One Second Has Not Passed, Add 1 Frame To Count
		if (Time::timePerFrame < 1){

			++Time::frameCount;
			Time::timePerFrame += Time::deltaTime;
		}

		// Otherwise, Return Frame Count
		else{

			Time::fps = Time::frameCount;
			Time::frameCount = 0;
			Time::timePerFrame = 0;

			return Time::fps;
		}

		return Time::fps;
	}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// Wait For Seconds
	void Time::WaitForSeconds (double WaitTime){

		double timer = 0;

		while (timer < WaitTime){

			Time::GetDeltaTime();
			timer += Time::deltaTime;
		}
	}
}


text:
package org.apereo.cas.web.flow.config;

import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.flow.CasWebflowConfigurer;
import org.apereo.cas.web.flow.SpengoWebflowConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;

/**
 * This is {@link SpnegoWebflowConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Configuration("spnegoWebflowConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class SpnegoWebflowConfiguration {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    @Qualifier("loginFlowRegistry")
    private FlowDefinitionRegistry loginFlowDefinitionRegistry;

    @Autowired
    private FlowBuilderServices flowBuilderServices;

    @ConditionalOnMissingBean(name = "spnegoWebflowConfigurer")
    @Bean
    @DependsOn("defaultWebflowConfigurer")
    public CasWebflowConfigurer spnegoWebflowConfigurer() {
        final CasWebflowConfigurer w = new SpengoWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext, casProperties);
        w.initialize();
        return w;
    }

}


text:
angular.module('pteraformer').config(function($urlRouterProvider, $stateProvider, $locationProvider){
  $locationProvider.html5Mode(true);
  $stateProvider
    .state('corpusEditor', {
      url: '/corpus/:corpusId',
      templateUrl: 'client/components/CorpusEditor/CorpusEditorView.html',
      controller: 'CorpusEditorController'
    })
    .state('docEditor', {
      url: '/doc/:documentId',
      templateUrl: 'client/components/GeoDocumentEditor/GeoDocumentEditorView.html',
      controller: 'GeoDocumentEditorController'
    })
    .state('userDataDashboard', {
      url: '/',
      templateUrl: 'client/components/UserDataDashboard/UserDataDashboardView.html',
      controller: 'UserDataDashboardController'
    });
  $urlRouterProvider.otherwise("/");
});


text:
This repository contains a variety of files and tools for learning new technologies. It is aimed at existing IT professionals who need some help coming up to speed with new technologies, products, or open source projects.

If you're interested in contributing, please see [the guidelines](https://github.com/lowescott/learning-tools/blob/master/CONTRIBUTING.md).

## Contents

The contents of this repository are organized according to primary technology area. Here's a quick breakdown of the major technology areas so far:

* Ansible
* CentOS Atomic Host
* Consul distributed key-value store
* CoreOS Linux
* Debian GNU/Linux
* Docker
* etcd distributed key-value store
* KVM
* LXC and LXD
* Network operating systems (JunOS, EOS, Cumulus, etc.)
* OpenStack
* Open vSwitch (OVS) and Open Virtual Network (OVN)
* Packer
* Photon OS
* The rkt ("Rocket") container runtime
* SSH
* Terraform
* Ubuntu Linux
* Vagrant

More information about the tools, resources, or environments for each of these technology areas can be found inside that area's README.md file.

## Other Useful Projects

Here are some other projects that you may also find useful:

**Kubernetes-CoreOS-Fleet-Flannel**: https://github.com/kelseyhightower/kubernetes-fleet-tutorial

**coreos-kubernetes-digitalocean**: https://github.com/bketelsen/coreos-kubernetes-digitalocean

**Docker-CoreOS-Fleet-Flannel-Etcd-Confd-Nginx**: https://github.com/willrstern/production-docker-ha-architecture

If there are additional projects you feel should be added to this list, please submit a pull request. Thanks!

## License

This content is licensed under the MIT License.


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CcAcca.BaseLibrary;

namespace BaseLibrary.Web.Controllers
{
    public class EntityMetadatasController : Controller
    {
        private BaseLibraryDbContext db = new BaseLibraryDbContext();

        // GET: EntityMetadatas
        public async Task<ActionResult> Index()
        {
            return View(await db.EntityMetadatas.ToListAsync());
        }

        // GET: EntityMetadatas/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EntityMetadata entityMetadata = await db.EntityMetadatas.FindAsync(id);
            if (entityMetadata == null)
            {
                return HttpNotFound();
            }
            return View(entityMetadata);
        }

        // GET: EntityMetadatas/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: EntityMetadatas/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Id,EntityName,DeveloperNotes")] EntityMetadata entityMetadata)
        {
            if (ModelState.IsValid)
            {
                db.EntityMetadatas.Add(entityMetadata);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(entityMetadata);
        }

        // GET: EntityMetadatas/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EntityMetadata entityMetadata = await db.EntityMetadatas.FindAsync(id);
            if (entityMetadata == null)
            {
                return HttpNotFound();
            }
            return View(entityMetadata);
        }

        // POST: EntityMetadatas/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "Id,EntityName,DeveloperNotes")] EntityMetadata entityMetadata)
        {
            if (ModelState.IsValid)
            {
                db.Entry(entityMetadata).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(entityMetadata);
        }

        // GET: EntityMetadatas/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EntityMetadata entityMetadata = await db.EntityMetadatas.FindAsync(id);
            if (entityMetadata == null)
            {
                return HttpNotFound();
            }
            return View(entityMetadata);
        }

        // POST: EntityMetadatas/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            EntityMetadata entityMetadata = await db.EntityMetadatas.FindAsync(id);
            db.EntityMetadatas.Remove(entityMetadata);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


text:
require 'spec_helper'

module BusyBunny # rubocop:disable Style/Documentation
  describe Builder do
    let(:chan) { double('channel') }

    describe '.build_channel' do
      let(:conn) { double('conn') }
      before     { expect(conn).to receive(:create_channel).and_return(chan) }

      shared_examples_for 'returns channel' do
        it 'returns channel' do
          expect(described_class.build_channel(conn, prefetch)).to eq chan
        end
      end # shared_examples_for 'returns channel'

      context 'without prefetch' do
        let(:prefetch) { nil }
        it_behaves_like 'returns channel'
      end # context 'without prefetch'

      context 'with prefetch' do
        let(:prefetch) { 1 }
        before         { expect(chan).to receive(:prefetch).with(prefetch) }
        it_behaves_like 'returns channel'
      end # context 'with prefetch'
    end # describe '.build_channel'

    describe '.build_queue' do
      let(:name) { 'name' }
      before { expect(chan).to receive(:queue).with(name, {}) }

      it 'works' do
        expect { described_class.build_queue(chan, name) }.to_not raise_error
      end
    end # describe '.build_queue'
  end # describe Builder
end # module BusyBunny


text:
using MassiveDynamicProxyGenerator.Tests.TestInterfaces;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MassiveDynamicProxyGenerator.Tests
{
    [TestClass]
    public class MockInterceptorTests
    {
        [TestMethod]
        public void MockInterceptor_ReturnInDictionary_ReturnDefault()
        {
            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(new Dictionary<Type, object>()));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(default(StringBuilder));
            instance.GetLength(string.Empty).ShouldBe(default(int));
            instance.GetVoid();
        }

        [TestMethod]
        public void MockInterceptor_ReturnInFunction_ReturnDefault()
        {
            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(type => null));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(default(StringBuilder));
            instance.GetLength(string.Empty).ShouldBe(default(int));
            instance.GetVoid();
        }

        [TestMethod]
        public void MockInterceptor_ReturnInDictionary_ReturnInt()
        {
            Dictionary<Type, object> mockValues = new Dictionary<Type, object>()
            {
                { typeof(int), 42 }
            };

            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(mockValues));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(default(StringBuilder));
            instance.GetLength(string.Empty).ShouldBe(42);
            instance.GetVoid();
        }

        [TestMethod]
        public void MockInterceptor_ReturnInFunction_ReturnInt()
        {
            Func<Type, object> retValueFactory = type =>
            {
                if (type == typeof(int))
                {
                    return 42;
                }

                return null;
            };

            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(retValueFactory));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(default(StringBuilder));
            instance.GetLength(string.Empty).ShouldBe(42);
            instance.GetVoid();
        }

        [TestMethod]
        public void MockInterceptor_ReturnInDictionary_ReturnStringBuilder()
        {
            StringBuilder defaultSb = new StringBuilder("hello");
            Dictionary<Type, object> mockValues = new Dictionary<Type, object>()
            {
                { typeof(StringBuilder), defaultSb }
            };

            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(mockValues));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(defaultSb);
            instance.GetLength(string.Empty).ShouldBe(default(int));
            instance.GetVoid();
        }

        [TestMethod]
        public void MockInterceptor_ReturnInFunction_ReturnStringBuilder()
        {
            StringBuilder defaultSb = new StringBuilder("hello");
            Func<Type, object> retValueFactory = type =>
            {
                if (type == typeof(StringBuilder))
                {
                    return defaultSb;
                }

                return null;
            };

            ProxyGenerator generator = new ProxyGenerator();
            IReturnTypes instance = generator.GenerateProxy<IReturnTypes>(new MockInterceptor(retValueFactory));

            instance.ShouldNotBeNull();

            instance.CreateSb(string.Empty).ShouldBe(defaultSb);
            instance.GetLength(string.Empty).ShouldBe(default(int));
            instance.GetVoid();
        }
    }
}


text:
using System.Collections.Generic;

namespace Xemio.GameLibrary.Common.Collections.ListActions
{
    internal class ClearAction<T> : IListAction<T>
    {
        #region Implementation of IListAction<T>
        /// <summary>
        /// Clears the list.
        /// </summary>
        /// <param name="list">The list.</param>
        public void Apply(List<T> list)
        {
            list.Clear();
        }
        #endregion
    }
}


text:
#import <iTunesStoreUI/SUViewController.h>

#import "SSDownloadManagerObserver-Protocol.h"

@class NSObject<OS_dispatch_source>, SUClientInterface, SUDownloadManager, SUViewController<SUDownloadsChildViewController>, UIView;

@interface SUDownloadsViewController : SUViewController <SSDownloadManagerObserver>
{
    SUViewController<SUDownloadsChildViewController> *_childViewController;
    SUClientInterface *_clientInterface;
    SUDownloadManager *_downloadManager;
    UIView *_emptyDownloadQueueView;
    _Bool _isUsingNetwork;
    NSObject<OS_dispatch_source> *_reloadFromServerTimer;
    _Bool _isEditing;
}

- (void)_updatePurchasedPlaylistButton;
- (void)_startReloadFromServerTimer;
- (void)_setUsingNetwork:(_Bool)arg1;
- (void)_reloadDownloadManagerFromServer;
- (void)_reloadEmptyDownloadQueueView;
- (void)_reloadDataAnimated:(_Bool)arg1;
- (id)_newChildViewController;
- (void)_cancelReloadFromServerTimer;
- (void)_tabConfigurationChanged:(id)arg1;
- (void)_clientDidStopIgnoringDownloadsNotification:(id)arg1;
- (void)_gotoPurchasedPlaylist:(id)arg1;
- (void)setScriptButtons:(id)arg1;
- (id)scriptButtons;
- (void)downloadManager:(id)arg1 downloadStatesDidChange:(id)arg2;
- (void)downloadManager:(id)arg1 downloadsDidChange:(id)arg2;
- (void)downloadManagerNetworkUsageDidChange:(id)arg1;
- (void)downloadManagerDownloadsDidChange:(id)arg1;
- (void)tabBarControllerDidReselectTabBarItem:(id)arg1;
- (void)reloadData;
- (void)reload;
- (void)loadView;
- (id)copyScriptViewController;
- (id)contentScrollView;
- (void)applicationWillEnterForeground;
- (void)updateTabBarItemsAnimated:(_Bool)arg1;
- (void)dealloc;
- (id)initWithManagerOptions:(id)arg1 preorderItemKinds:(id)arg2;
- (id)initWithManagerOptions:(id)arg1;
- (id)initWithClientInterface:(id)arg1 managerOptions:(id)arg2 preorderItemKinds:(id)arg3;
- (id)init;

@end


text:
Bug Fix: Strings pushed to the client are now properly escaped.
Prior to this fix, a string containing illegal characters such as a newline would be silently discarded.


text:
namespace __cxxabiv1 {

// Allocate some memory from _somewhere_
_LIBCXXABI_HIDDEN void * __aligned_malloc_with_fallback(size_t size);

// Allocate and zero-initialize memory from _somewhere_
_LIBCXXABI_HIDDEN void * __calloc_with_fallback(size_t count, size_t size);

_LIBCXXABI_HIDDEN void __aligned_free_with_fallback(void *ptr);
_LIBCXXABI_HIDDEN void __free_with_fallback(void *ptr);

} // namespace __cxxabiv1

#endif


text:
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#if defined(V8_TARGET_ARCH_X64)

#include "codegen.h"
#include "macro-assembler.h"

namespace v8 {
namespace internal {

// -------------------------------------------------------------------------
// Platform-specific RuntimeCallHelper functions.

void StubRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
  masm->EnterFrame(StackFrame::INTERNAL);
  ASSERT(!masm->has_frame());
  masm->set_has_frame(true);
}

void StubRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
  masm->LeaveFrame(StackFrame::INTERNAL);
  ASSERT(masm->has_frame());
  masm->set_has_frame(false);
}

#define __ masm.

UnaryMathFunction CreateTranscendentalFunction(TranscendentalCache::Type type) {
  size_t actual_size;
  // Allocate buffer in executable space.
  byte* buffer = static_cast<byte*>(OS::Allocate(1 * KB,
                                                 &actual_size,
                                                 true));
  if (buffer == NULL) {
    // Fallback to library function if function cannot be created.
    switch (type) {
      case TranscendentalCache::SIN: return &sin;
      case TranscendentalCache::COS: return &cos;
      case TranscendentalCache::TAN: return &tan;
      case TranscendentalCache::LOG: return &log;
      default: UNIMPLEMENTED();
    }
  }

  MacroAssembler masm(NULL, buffer, static_cast<int>(actual_size));
  // xmm0: raw double input.
  // Move double input into registers.
  __ push(rbx);
  __ push(rdi);
  __ movq(rbx, xmm0);
  __ push(rbx);
  __ fld_d(Operand(rsp, 0));
  TranscendentalCacheStub::GenerateOperation(&masm, type);
  // The return value is expected to be in xmm0.
  __ fstp_d(Operand(rsp, 0));
  __ pop(rbx);
  __ movq(xmm0, rbx);
  __ pop(rdi);
  __ pop(rbx);
  __ Ret();

  CodeDesc desc;
  masm.GetCode(&desc);
  ASSERT(desc.reloc_size == 0);

  CPU::FlushICache(buffer, actual_size);
  OS::ProtectCode(buffer, actual_size);
  return FUNCTION_CAST<UnaryMathFunction>(buffer);
}

UnaryMathFunction CreateSqrtFunction() {
  size_t actual_size;
  // Allocate buffer in executable space.
  byte* buffer = static_cast<byte*>(OS::Allocate(1 * KB,
                                                 &actual_size,
                                                 true));
  if (buffer == NULL) return &sqrt;

  MacroAssembler masm(NULL, buffer, static_cast<int>(actual_size));
  // xmm0: raw double input.
  // Move double input into registers.
  __ sqrtsd(xmm0, xmm0);
  __ Ret();

  CodeDesc desc;
  masm.GetCode(&desc);
  ASSERT(desc.reloc_size == 0);

  CPU::FlushICache(buffer, actual_size);
  OS::ProtectCode(buffer, actual_size);
  return FUNCTION_CAST<UnaryMathFunction>(buffer);
}

#ifdef _WIN64
typedef double (*ModuloFunction)(double, double);
// Define custom fmod implementation.
ModuloFunction CreateModuloFunction() {
  size_t actual_size;
  byte* buffer = static_cast<byte*>(OS::Allocate(Assembler::kMinimalBufferSize,
                                                 &actual_size,
                                                 true));
  CHECK(buffer);
  Assembler masm(NULL, buffer, static_cast<int>(actual_size));
  // Generated code is put into a fixed, unmovable, buffer, and not into
  // the V8 heap. We can't, and don't, refer to any relocatable addresses
  // (e.g. the JavaScript nan-object).

  // Windows 64 ABI passes double arguments in xmm0, xmm1 and
  // returns result in xmm0.
  // Argument backing space is allocated on the stack above
  // the return address.

  // Compute x mod y.
  // Load y and x (use argument backing store as temporary storage).
  __ movsd(Operand(rsp, kPointerSize * 2), xmm1);
  __ movsd(Operand(rsp, kPointerSize), xmm0);
  __ fld_d(Operand(rsp, kPointerSize * 2));
  __ fld_d(Operand(rsp, kPointerSize));

  // Clear exception flags before operation.
  {
    Label no_exceptions;
    __ fwait();
    __ fnstsw_ax();
    // Clear if Illegal Operand or Zero Division exceptions are set.
    __ testb(rax, Immediate(5));
    __ j(zero, &no_exceptions);
    __ fnclex();
    __ bind(&no_exceptions);
  }

  // Compute st(0) % st(1)
  {
    Label partial_remainder_loop;
    __ bind(&partial_remainder_loop);
    __ fprem();
    __ fwait();
    __ fnstsw_ax();
    __ testl(rax, Immediate(0x400 /* C2 */));
    // If C2 is set, computation only has partial result. Loop to
    // continue computation.
    __ j(not_zero, &partial_remainder_loop);
  }

  Label valid_result;
  Label return_result;
  // If Invalid Operand or Zero Division exceptions are set,
  // return NaN.
  __ testb(rax, Immediate(5));
  __ j(zero, &valid_result);
  __ fstp(0);  // Drop result in st(0).
  int64_t kNaNValue = V8_INT64_C(0x7ff8000000000000);
  __ movq(rcx, kNaNValue, RelocInfo::NONE);
  __ movq(Operand(rsp, kPointerSize), rcx);
  __ movsd(xmm0, Operand(rsp, kPointerSize));
  __ jmp(&return_result);

  // If result is valid, return that.
  __ bind(&valid_result);
  __ fstp_d(Operand(rsp, kPointerSize));
  __ movsd(xmm0, Operand(rsp, kPointerSize));

  // Clean up FPU stack and exceptions and return xmm0
  __ bind(&return_result);
  __ fstp(0);  // Unload y.

  Label clear_exceptions;
  __ testb(rax, Immediate(0x3f /* Any Exception*/));
  __ j(not_zero, &clear_exceptions);
  __ ret(0);
  __ bind(&clear_exceptions);
  __ fnclex();
  __ ret(0);

  CodeDesc desc;
  masm.GetCode(&desc);
  OS::ProtectCode(buffer, actual_size);
  // Call the function from C++ through this pointer.
  return FUNCTION_CAST<ModuloFunction>(buffer);
}

#endif

#undef __

// -------------------------------------------------------------------------
// Code generators

#define __ ACCESS_MASM(masm)

void ElementsTransitionGenerator::GenerateMapChangeElementsTransition(
    MacroAssembler* masm) {
  // ----------- S t a t e -------------
  //  -- rax    : value
  //  -- rbx    : target map
  //  -- rcx    : key
  //  -- rdx    : receiver
  //  -- rsp[0] : return address
  // -----------------------------------
  // Set transitioned map.
  __ movq(FieldOperand(rdx, HeapObject::kMapOffset), rbx);
  __ RecordWriteField(rdx,
                      HeapObject::kMapOffset,
                      rbx,
                      rdi,
                      kDontSaveFPRegs,
                      EMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
}

void ElementsTransitionGenerator::GenerateSmiToDouble(
    MacroAssembler* masm, Label* fail) {
  // ----------- S t a t e -------------
  //  -- rax    : value
  //  -- rbx    : target map
  //  -- rcx    : key
  //  -- rdx    : receiver
  //  -- rsp[0] : return address
  // -----------------------------------
  // The fail label is not actually used since we do not allocate.
  Label allocated, new_backing_store, only_change_map, done;

  // Check for empty arrays, which only require a map transition and no changes
  // to the backing store.
  __ movq(r8, FieldOperand(rdx, JSObject::kElementsOffset));
  __ CompareRoot(r8, Heap::kEmptyFixedArrayRootIndex);
  __ j(equal, &only_change_map);

  // Check backing store for COW-ness.  For COW arrays we have to
  // allocate a new backing store.
  __ SmiToInteger32(r9, FieldOperand(r8, FixedDoubleArray::kLengthOffset));
  __ CompareRoot(FieldOperand(r8, HeapObject::kMapOffset),
                 Heap::kFixedCOWArrayMapRootIndex);
  __ j(equal, &new_backing_store);
  // Check if the backing store is in new-space. If not, we need to allocate
  // a new one since the old one is in pointer-space.
  // If in new space, we can reuse the old backing store because it is
  // the same size.
  __ JumpIfNotInNewSpace(r8, rdi, &new_backing_store);

  __ movq(r14, r8);  // Destination array equals source array.

  // r8 : source FixedArray
  // r9 : elements array length
  // r14: destination FixedDoubleArray
  // Set backing store's map
  __ LoadRoot(rdi, Heap::kFixedDoubleArrayMapRootIndex);
  __ movq(FieldOperand(r14, HeapObject::kMapOffset), rdi);

  __ bind(&allocated);
  // Set transitioned map.
  __ movq(FieldOperand(rdx, HeapObject::kMapOffset), rbx);
  __ RecordWriteField(rdx,
                      HeapObject::kMapOffset,
                      rbx,
                      rdi,
                      kDontSaveFPRegs,
                      EMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);

  // Convert smis to doubles and holes to hole NaNs.  The Array's length
  // remains unchanged.
  STATIC_ASSERT(FixedDoubleArray::kLengthOffset == FixedArray::kLengthOffset);
  STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize);

  Label loop, entry, convert_hole;
  __ movq(r15, BitCast<int64_t, uint64_t>(kHoleNanInt64), RelocInfo::NONE);
  // r15: the-hole NaN
  __ jmp(&entry);

  // Allocate new backing store.
  __ bind(&new_backing_store);
  __ lea(rdi, Operand(r9, times_pointer_size, FixedArray::kHeaderSize));
  __ AllocateInNewSpace(rdi, r14, r11, r15, fail, TAG_OBJECT);
  // Set backing store's map
  __ LoadRoot(rdi, Heap::kFixedDoubleArrayMapRootIndex);
  __ movq(FieldOperand(r14, HeapObject::kMapOffset), rdi);
  // Set receiver's backing store.
  __ movq(FieldOperand(rdx, JSObject::kElementsOffset), r14);
  __ movq(r11, r14);
  __ RecordWriteField(rdx,
                      JSObject::kElementsOffset,
                      r11,
                      r15,
                      kDontSaveFPRegs,
                      EMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
  // Set backing store's length.
  __ Integer32ToSmi(r11, r9);
  __ movq(FieldOperand(r14, FixedDoubleArray::kLengthOffset), r11);
  __ jmp(&allocated);

  __ bind(&only_change_map);
  // Set transitioned map.
  __ movq(FieldOperand(rdx, HeapObject::kMapOffset), rbx);
  __ RecordWriteField(rdx,
                      HeapObject::kMapOffset,
                      rbx,
                      rdi,
                      kDontSaveFPRegs,
                      OMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
  __ jmp(&done);

  // Conversion loop.
  __ bind(&loop);
  __ movq(rbx,
          FieldOperand(r8, r9, times_8, FixedArray::kHeaderSize));
  // r9 : current element's index
  // rbx: current element (smi-tagged)
  __ JumpIfNotSmi(rbx, &convert_hole);
  __ SmiToInteger32(rbx, rbx);
  __ cvtlsi2sd(xmm0, rbx);
  __ movsd(FieldOperand(r14, r9, times_8, FixedDoubleArray::kHeaderSize),
           xmm0);
  __ jmp(&entry);
  __ bind(&convert_hole);

  if (FLAG_debug_code) {
    __ CompareRoot(rbx, Heap::kTheHoleValueRootIndex);
    __ Assert(equal, "object found in smi-only array");
  }

  __ movq(FieldOperand(r14, r9, times_8, FixedDoubleArray::kHeaderSize), r15);
  __ bind(&entry);
  __ decq(r9);
  __ j(not_sign, &loop);

  __ bind(&done);
}

void ElementsTransitionGenerator::GenerateDoubleToObject(
    MacroAssembler* masm, Label* fail) {
  // ----------- S t a t e -------------
  //  -- rax    : value
  //  -- rbx    : target map
  //  -- rcx    : key
  //  -- rdx    : receiver
  //  -- rsp[0] : return address
  // -----------------------------------
  Label loop, entry, convert_hole, gc_required, only_change_map;

  // Check for empty arrays, which only require a map transition and no changes
  // to the backing store.
  __ movq(r8, FieldOperand(rdx, JSObject::kElementsOffset));
  __ CompareRoot(r8, Heap::kEmptyFixedArrayRootIndex);
  __ j(equal, &only_change_map);

  __ push(rax);

  __ movq(r8, FieldOperand(rdx, JSObject::kElementsOffset));
  __ SmiToInteger32(r9, FieldOperand(r8, FixedDoubleArray::kLengthOffset));
  // r8 : source FixedDoubleArray
  // r9 : number of elements
  __ lea(rdi, Operand(r9, times_pointer_size, FixedArray::kHeaderSize));
  __ AllocateInNewSpace(rdi, r11, r14, r15, &gc_required, TAG_OBJECT);
  // r11: destination FixedArray
  __ LoadRoot(rdi, Heap::kFixedArrayMapRootIndex);
  __ movq(FieldOperand(r11, HeapObject::kMapOffset), rdi);
  __ Integer32ToSmi(r14, r9);
  __ movq(FieldOperand(r11, FixedArray::kLengthOffset), r14);

  // Prepare for conversion loop.
  __ movq(rsi, BitCast<int64_t, uint64_t>(kHoleNanInt64), RelocInfo::NONE);
  __ LoadRoot(rdi, Heap::kTheHoleValueRootIndex);
  // rsi: the-hole NaN
  // rdi: pointer to the-hole
  __ jmp(&entry);

  // Call into runtime if GC is required.
  __ bind(&gc_required);
  __ pop(rax);
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
  __ jmp(fail);

  // Box doubles into heap numbers.
  __ bind(&loop);
  __ movq(r14, FieldOperand(r8,
                            r9,
                            times_pointer_size,
                            FixedDoubleArray::kHeaderSize));
  // r9 : current element's index
  // r14: current element
  __ cmpq(r14, rsi);
  __ j(equal, &convert_hole);

  // Non-hole double, copy value into a heap number.
  __ AllocateHeapNumber(rax, r15, &gc_required);
  // rax: new heap number
  __ movq(FieldOperand(rax, HeapNumber::kValueOffset), r14);
  __ movq(FieldOperand(r11,
                       r9,
                       times_pointer_size,
                       FixedArray::kHeaderSize),
          rax);
  __ movq(r15, r9);
  __ RecordWriteArray(r11,
                      rax,
                      r15,
                      kDontSaveFPRegs,
                      EMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
  __ jmp(&entry, Label::kNear);

  // Replace the-hole NaN with the-hole pointer.
  __ bind(&convert_hole);
  __ movq(FieldOperand(r11,
                       r9,
                       times_pointer_size,
                       FixedArray::kHeaderSize),
          rdi);

  __ bind(&entry);
  __ decq(r9);
  __ j(not_sign, &loop);

  // Replace receiver's backing store with newly created and filled FixedArray.
  __ movq(FieldOperand(rdx, JSObject::kElementsOffset), r11);
  __ RecordWriteField(rdx,
                      JSObject::kElementsOffset,
                      r11,
                      r15,
                      kDontSaveFPRegs,
                      EMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
  __ pop(rax);
  __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));

  __ bind(&only_change_map);
  // Set transitioned map.
  __ movq(FieldOperand(rdx, HeapObject::kMapOffset), rbx);
  __ RecordWriteField(rdx,
                      HeapObject::kMapOffset,
                      rbx,
                      rdi,
                      kDontSaveFPRegs,
                      OMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);
}

void StringCharLoadGenerator::Generate(MacroAssembler* masm,
                                       Register string,
                                       Register index,
                                       Register result,
                                       Label* call_runtime) {
  // Fetch the instance type of the receiver into result register.
  __ movq(result, FieldOperand(string, HeapObject::kMapOffset));
  __ movzxbl(result, FieldOperand(result, Map::kInstanceTypeOffset));

  // We need special handling for indirect strings.
  Label check_sequential;
  __ testb(result, Immediate(kIsIndirectStringMask));
  __ j(zero, &check_sequential, Label::kNear);

  // Dispatch on the indirect string shape: slice or cons.
  Label cons_string;
  __ testb(result, Immediate(kSlicedNotConsMask));
  __ j(zero, &cons_string, Label::kNear);

  // Handle slices.
  Label indirect_string_loaded;
  __ SmiToInteger32(result, FieldOperand(string, SlicedString::kOffsetOffset));
  __ addq(index, result);
  __ movq(string, FieldOperand(string, SlicedString::kParentOffset));
  __ jmp(&indirect_string_loaded, Label::kNear);

  // Handle cons strings.
  // Check whether the right hand side is the empty string (i.e. if
  // this is really a flat string in a cons string). If that is not
  // the case we would rather go to the runtime system now to flatten
  // the string.
  __ bind(&cons_string);
  __ CompareRoot(FieldOperand(string, ConsString::kSecondOffset),
                 Heap::kEmptyStringRootIndex);
  __ j(not_equal, call_runtime);
  __ movq(string, FieldOperand(string, ConsString::kFirstOffset));

  __ bind(&indirect_string_loaded);
  __ movq(result, FieldOperand(string, HeapObject::kMapOffset));
  __ movzxbl(result, FieldOperand(result, Map::kInstanceTypeOffset));

  // Distinguish sequential and external strings. Only these two string
  // representations can reach here (slices and flat cons strings have been
  // reduced to the underlying sequential or external string).
  Label seq_string;
  __ bind(&check_sequential);
  STATIC_ASSERT(kSeqStringTag == 0);
  __ testb(result, Immediate(kStringRepresentationMask));
  __ j(zero, &seq_string, Label::kNear);

  // Handle external strings.
  Label ascii_external, done;
  if (FLAG_debug_code) {
    // Assert that we do not have a cons or slice (indirect strings) here.
    // Sequential strings have already been ruled out.
    __ testb(result, Immediate(kIsIndirectStringMask));
    __ Assert(zero, "external string expected, but not found");
  }
  // Rule out short external strings.
  STATIC_CHECK(kShortExternalStringTag != 0);
  __ testb(result, Immediate(kShortExternalStringTag));
  __ j(not_zero, call_runtime);
  // Check encoding.
  STATIC_ASSERT(kTwoByteStringTag == 0);
  __ testb(result, Immediate(kStringEncodingMask));
  __ movq(result, FieldOperand(string, ExternalString::kResourceDataOffset));
  __ j(not_equal, &ascii_external, Label::kNear);
  // Two-byte string.
  __ movzxwl(result, Operand(result, index, times_2, 0));
  __ jmp(&done, Label::kNear);
  __ bind(&ascii_external);
  // Ascii string.
  __ movzxbl(result, Operand(result, index, times_1, 0));
  __ jmp(&done, Label::kNear);

  // Dispatch on the encoding: ASCII or two-byte.
  Label ascii;
  __ bind(&seq_string);
  STATIC_ASSERT((kStringEncodingMask & kAsciiStringTag) != 0);
  STATIC_ASSERT((kStringEncodingMask & kTwoByteStringTag) == 0);
  __ testb(result, Immediate(kStringEncodingMask));
  __ j(not_zero, &ascii, Label::kNear);

  // Two-byte string.
  // Load the two-byte character code into the result register.
  STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
  __ movzxwl(result, FieldOperand(string,
                                  index,
                                  times_2,
                                  SeqTwoByteString::kHeaderSize));
  __ jmp(&done, Label::kNear);

  // ASCII string.
  // Load the byte into the result register.
  __ bind(&ascii);
  __ movzxbl(result, FieldOperand(string,
                                  index,
                                  times_1,
                                  SeqAsciiString::kHeaderSize));
  __ bind(&done);
}

#undef __

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_X64


text:
Welcome to Grunt Basics. My name is Kahlil and I will guide you through creating a package.json file.

What is a package.json?

Node modules use package.json files to store package information and dependencies.

Why do we need it for Grunt?

Grunt uses the package.json to consume meta information about the current project in order to use that information in Grunt tasks. Another very useful function is the storing of development dependencies for the project. Having those dependencies stored in the package.json allow you to exclude the node_modules folder from version control because developers can install necessary node modules quickly by using npm install. More on that in a different screencast.

You don't need a package.json file in order to use Grunt but I would highly recommend it. Especially when you work in teams.

Although when you create a grunt plugin the package json is mandatory since you will want to publish it to npm for others to use.

So how do you create a package.json file?

* the first option is when you use the scaffolding tool grunt-init, most of the templates will create a project-specific package.json file. This is actually also true for Yoeman. So when you use one of those scaffolding tools there is nothing else to do, you have your package.json.

* the second option is npm init on the command line which allows you to create a basic package.json file.

* and the third option is just to copy and paste a little snippet of code from gruntjs.com that can be used as a starting point

Since you have npm installed and scaffolding is awesome i will now show you how to use npm init to create your package.json file.

Open your terminal of choice.
Type in npm init and hit return.
As you can see npm then gives you a nice explanation of what is going to happen.
First it wants to know the package name.
It has to be URL friendly in order to be valid.
Next, npm wants to know the version number.
Usually you would choose something like 0.0.1 or 0.1.0 to start with.
You don't need a description for your Grunt project so we are going to skip that.
Same goes for the entry point and the test command.
Once you have Grunt installed you will be able to configure your tests as Grunt tasks and run them with the command grunt test.
On the next one we can insert the link to the git repo of the project if we have one.
If your project is a gruntplugin, or a bower component or an npm module you should enter relevant keywords for the keywords property it will be used in search after you published your project.
Now fill in your name and which license you are using and we're done.
npm then shows you a nice little summary that we confirm with yes.
Then open the package.json file in your favorite editor.
As you can see there is a bunch of stuff in there that we don't need.
Throw out main, scripts and description and add the devDependencies property and we're done.

Now when you install gruntplugins use the save-dev option to store the plugin as a development dependency.  This way you can just commit your package.json to version control and then quickly install your dependencies with npm install on the command line.

Thanks for checking out Grunt Basics. If you have any question hit us up on Twitter or in our IRC channel.


text:
local function _get_color(alpha)
	return alpha * (2^24) + 0xffffff  -- ejoy2d use ARGB color format
end

local blink_action = {action="blink"}
for i=0,255,5 do
	local component = {name="actor", color=_get_color(i)}
	local frame = {component}
	table.insert(blink_action, frame)
end
for i=255,0,-5 do
	local component = {name="actor", color=_get_color(i)}
	local frame = {component}
	table.insert(blink_action, frame)
end

return {

blink_action,

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Jorge
 * Date: 3/04/14
 * Time: 14:05
 */

namespace OpenTable\RestaurantBundle\Controller;

use OpenTable\CoreBundle\Controller\CoreController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

class ProfileController extends Controller {

    protected function extractRestaurantData($restaurant){

        $food_types = array();
        foreach($restaurant->getFoodType() as $ft)
            $food_types[] = $ft->getName();
        sort($food_types);

        $rating = $this->getDoctrine()->getManager()->getRepository('OpenTableBusinessBundle:Restaurant')->getRestaurantRate($restaurant);
        $userProfile = $this->getDoctrine()->getManager()->getRepository('OpenTableBusinessBundle:UserProfileRestaurant')->findBy(array('restaurantid' => $restaurant->getId()));
        $userProfileRestaurant = count($userProfile) > 0 ? $userProfile[0] : null;

        return array(
            'id' => $restaurant->getId(),
            'name' => $restaurant->getName(),
            'address' => $restaurant->getAddress(),
            'description' => $restaurant->getDescription(),
            'position' => array(
                'lat' => $restaurant->getLat(),
                'lon' => $restaurant->getLon()
            ),
            'location' => $restaurant->getLocation()->getName(),
            'price' => $restaurant->getPrice()->getName(),
            'food_types' => $food_types,
            'rating' => $rating,
            'wifi' => $userProfileRestaurant != null ? $userProfileRestaurant->getWifi() : false,
            'kosher' => $userProfileRestaurant != null ? $userProfileRestaurant->getKosher() : false,
            'executive' => $userProfileRestaurant != null ? $userProfileRestaurant->getExecutive() : false,
            'parking' => $userProfileRestaurant != null ? $userProfileRestaurant->getParking() : false,
            'valet' => $userProfileRestaurant != null ? $userProfileRestaurant->getValetParking() : false,
            'delivery' => $userProfileRestaurant != null ? $userProfileRestaurant->getDelivery() : false
        );
    }

    public function indexAction($id, $date = null, $people = 4){
        $em = $this->getDoctrine()->getManager();

        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);
        if(!$restaurant)
            throw $this->createNotFoundException();

        if($date == null){
            $date = new \DateTime();
            $mtime = getdate($date->getTimestamp());
            $date->setTime(($mtime['hours'] + 1) % 20, 0);
            if($date < new \DateTime())
                $date->add(date_interval_create_from_date_string('1 day'));
        }

        return $this->render(
            'OpenTableRestaurantBundle:Profile:home.html.twig',
            array(
                'id' => $id,
                'name' => $restaurant->getName(),
                'date' => $date->format('m/d/Y'),
                'time' => $date->format('h:i'),
                'people' => $people
            )
        );
    }

    public function restaurantRecomendationWidgetAction($id = null){
        $em = $this->getDoctrine()->getManager();
        $restaurant = null;
        if($id){
            $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);
            $mostPopular = $em->getRepository('OpenTableBusinessBundle:Restaurant')->getMostPopularRestaurantsBut($restaurant);
        } else
            $mostPopular = $em->getRepository('OpenTableBusinessBundle:Restaurant')->getMostPopularRestaurants();

        $data = array();
        foreach($mostPopular as $item){
            $food_types = array();
            foreach($item['restaurant']->getFoodType() as $ft)
                if(count($food_types) < 3)
                    $food_types[] = $ft->getName();
                else
                    break;
            sort($food_types);

            $data[] = array(
                'id' => $item['restaurant']->getId(),
                'name' => $item['restaurant']->getName(),
                'location' => $item['restaurant']->getLocation()->getName(),
                'food_types' => $food_types
            );
        }

        return $this->render(
            'OpenTableRestaurantBundle:Profile:recommendations-widget.html.twig',
            array(
                'data' => $data
            )
        );
    }

    public function simpleGaleryAction($id){
        $em = $this->getDoctrine()->getManager();

        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);
        if(!$restaurant)
            throw $this->createNotFoundException();

        $images = array();

        $path = $this->container->getParameter('uploads_path') . "restaurants/$id/galery";
        if(file_exists($path)){
            $dir = dir($path);
            while(false !== ($entry = $dir->read())) {
                if(strripos($entry, '.jpg') == strlen($entry) - 4)
                    $images[] = $entry;
            }
        }

        return $this->render(
            'OpenTableRestaurantBundle:Profile:simple-galery.html.twig',
            array(
                'id' => $id,
                'images' => $images,
                'path' => $path,
                'exists' => file_exists($path)

            )
        );
    }

    public function descriptionAction($id){
        $em = $this->getDoctrine()->getManager();

        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);
        if(!$restaurant)
            throw $this->createNotFoundException();

        return $this->render(
            'OpenTableRestaurantBundle:Profile:restaurant-description.html.twig',
            array(
                'id' => $id,
                'description' => $restaurant->getDescription()
            )
        );
    }

    public function basicDataAction($id){
        $em = $this->getDoctrine()->getManager();

        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);
        $categories = $em->getRepository('OpenTableBusinessBundle:RestaurantScheduleCategory')->findAll();
        $days = array(1 => 'Domingo', 2 => 'Lunes', 3  => 'Martes', 4 => 'Miércoles', 5 => 'Jueves', 6 => 'Viernes', 7 =>'Sábado');

        $schedulesResult = array();

        foreach($categories as $category){
            $shedules = $em->getRepository('OpenTableBusinessBundle:Restaurant')->getRestaurantSchedyle($id, $category->getId());

            $result = array();
            foreach($shedules as $schedule){
                $result[] = $days[$schedule->getStartDay()] . ' a ' . $days[$schedule->getEndDay()] . ' ' . $schedule->getStartHour()->format('h:i A') . ' a ' . $schedule->getEndHour()->format('h:i A');
            }
            if(count($result) > 0)
                $schedulesResult[] = array('category' => $category->getDescription(), 'schedules' => $result);

        }

        if(!$restaurant)
            throw $this->createNotFoundException();

        $data = $this->extractRestaurantData($restaurant);
        $data['schedulesByCategories'] = $schedulesResult;

        return $this->render(
            'OpenTableRestaurantBundle:Profile:restaurant-basic-data.html.twig',
            $data
        );
    }

    public function getRestaurantMenuAction(){
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getManager();
        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($id);

        $categories = array();
        $categoriesData = $em->getRepository('OpenTableBusinessBundle:MenuCategory')->findByRestaurant($restaurant);
        foreach($categoriesData as $category){
            $categories[] = array('id' => $category->getId(),
                                  'name' => $category->getName());
        }

        $html = $this->render(
            'OpenTableRestaurantBundle:Profile:restaurant-menu.html.twig', array('categories' => $categories,
                                                                                'restaurantName' => $restaurant->getName(),
                                                                                'restaurantId' => $restaurant->getId())
        )->getContent();
        return new JsonResponse(array(
            'ok' => true,
            'html' => $html
        ));
    }

    public function itemsByCategoryAction($id, $restaurantId){
        $em = $this->getDoctrine()->getManager();
        $restaurant = $em->getRepository('OpenTableBusinessBundle:Restaurant')->findOneById($restaurantId);
        $plates = $em->getRepository('OpenTableBusinessBundle:MenuPlate')->findBy(array('category'=> $id, 'restaurant' => $restaurant));
        $core = new CoreController($this->container->getParameter('uploads_path'));

        $result = array();
        foreach($plates as $plate){
            $result[] = array(
                'image' => file_exists($core->getRestaurantPlateImagePath($plate->getRestaurantid()->getId(), $plate->getId())) ? $core->getRestaurantPlateImageUrl($plate->getRestaurantid()->getId(), $plate->getId()) : null,
                'plateName' => $plate->getName(),
                'price' => $plate->getPrice(),
                'description' => $plate->getDescription()
            );
        }

       return $this->render(
            'OpenTableRestaurantBundle:Profile:restaurant-menu-items-list.html.twig', array('subCategories' => $result)
        );
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: zein
 * Date: 7/4/14
 * Time: 2:31 PM
 */

namespace common\models\query;

use common\models\ArticleCategory;
use yii\db\ActiveQuery;

class ArticleCategoryQuery extends ActiveQuery
{
    /**
     * @return $this
     */
    public function active()
    {
        $this->andWhere(['status' => ArticleCategory::STATUS_ENABLED]);

        return $this;
    }

    /**
     * @return $this
     */
    public function noParents()
    {
        $this->andWhere('{{%article_category}}.parent_id IS NULL');

        return $this;
    }
}


text: Prebid.js Test


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // Symfony Standard Edition 2.3.0
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            // UserBundle
            new FOS\UserBundle\FOSUserBundle(),
            // Extra bundles
            new JMS\AopBundle\JMSAopBundle(),
            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            // Base bundle
            new \GeorgetteParty\BaseBundle\GeorgettePartyBaseBundle(),
            // Unramalak bundles
            new Krovitch\UnramalakBundle\KrovitchUnramalakBundle(),
            new Krovitch\KrovitchUserBundle\KrovitchUserBundle(),
            new Krovitch\UnramalakFrontBundle\KrovitchUnramalakFrontBundle()
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }
        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
    }
}


text:
package org.scalajs.testsuite.scalalib

import scala.reflect.NameTransformer

import org.junit.Test
import org.junit.Assert._

class NameTransformerTest {

  @Test def decode_issue_1602(): Unit = {
    /* Mostly to make sure it links.
     * We trust the Scala implementation for correctness. And if it isn't,
     * well, behaving the same as Scala is the correct thing do for us
     * anyway.
     */
    assertEquals("+", NameTransformer.decode("$plus"))
    assertEquals("ab+", NameTransformer.decode("ab$plus"))
    assertEquals("-", NameTransformer.decode("$minus"))
    assertEquals("+x-y", NameTransformer.decode("$plusx$minusy"))
    assertEquals("+-", NameTransformer.decode("$plus$minus"))
  }
}


text:
package org.apache.hadoop.fs.s3;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * Thrown when Hadoop cannot read the version of the data stored
 * in {@link S3FileSystem}.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class VersionMismatchException extends S3FileSystemException {
  private static final long serialVersionUID = 1L;

  public VersionMismatchException(String clientVersion, String dataVersion) {
    super("Version mismatch: client expects version " + clientVersion +
        ", but data has version " +
        (dataVersion == null ? "[unversioned]" : dataVersion));
  }
}


text:
module API
  module V1
    class ImageJSONDecorator < Draper::Decorator
      def width
        distance(object.width)
      end

      def height
        distance(object.height)
      end

      def encoding_format
        object.type
      end

      def src
        File.join(h.root_url, Rails.configuration.settings.image_path, path)
      end

      private
        def distance(value)
          "#{value} px"
        end

        def path
          object.relative_filepath
        end
    end
  end
end


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace IBM.Watson.Discovery.v2.Model
{
    /// <summary>
    /// A response that contains the documents and aggregations for the query.
    /// </summary>
    public class QueryResponse
    {
        /// <summary>
        /// The number of matching results for the query. Results that match due to a curation only are not counted in
        /// the total.
        /// </summary>
        [JsonProperty("matching_results", NullValueHandling = NullValueHandling.Ignore)]
        public long? MatchingResults { get; set; }
        /// <summary>
        /// Array of document results for the query.
        /// </summary>
        [JsonProperty("results", NullValueHandling = NullValueHandling.Ignore)]
        public List<QueryResult> Results { get; set; }
        /// <summary>
        /// Array of aggregations for the query.
        /// </summary>
        [JsonProperty("aggregations", NullValueHandling = NullValueHandling.Ignore)]
        public List<QueryAggregation> Aggregations { get; set; }
        /// <summary>
        /// An object contain retrieval type information.
        /// </summary>
        [JsonProperty("retrieval_details", NullValueHandling = NullValueHandling.Ignore)]
        public RetrievalDetails RetrievalDetails { get; set; }
        /// <summary>
        /// Suggested correction to the submitted **natural_language_query** value.
        /// </summary>
        [JsonProperty("suggested_query", NullValueHandling = NullValueHandling.Ignore)]
        public string SuggestedQuery { get; set; }
        /// <summary>
        /// Array of suggested refinements. **Note**: The `suggested_refinements` parameter that identified dynamic
        /// facets from the data is deprecated.
        /// </summary>
        [JsonProperty("suggested_refinements", NullValueHandling = NullValueHandling.Ignore)]
        public List<QuerySuggestedRefinement> SuggestedRefinements { get; set; }
        /// <summary>
        /// Array of table results.
        /// </summary>
        [JsonProperty("table_results", NullValueHandling = NullValueHandling.Ignore)]
        public List<QueryTableResult> TableResults { get; set; }
        /// <summary>
        /// Passages that best match the query from across all of the collections in the project.
        /// </summary>
        [JsonProperty("passages", NullValueHandling = NullValueHandling.Ignore)]
        public List<QueryResponsePassage> Passages { get; set; }
    }

}


text:
'use strict'

// Node.js 4.3 not support destructuring assignment.
// Example: const { SERVERLESS_PROJECT, SERVERLESS_STAGE } = process.env
const SERVERLESS_PROJECT = process.env.SERVERLESS_PROJECT
const SERVERLESS_STAGE = process.env.SERVERLESS_STAGE

let doc = require('dynamodb-doc')
let dynamo = new doc.DynamoDB()

let params = {}
params.TableName = `${SERVERLESS_PROJECT}-users-${SERVERLESS_STAGE}`

module.exports.handler = function (event, context, cb) {
  // event.username = endpoint/users/{username}/resume
  // See more: s-template.json $${readUserResumeApiRequestTemplate}
  params.Key = { userId: event.username }

  dynamo.getItem(params, cb)
}


text:
package eu.matejkormuth.jge.filesystem;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Represents resource injection point.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
    Class<?> value();
}


text: // console.log(interpolate({ message: "{{$triggerData.date}}" }, { $triggerData: { date: 'pwic' } }));


text:
from flask import Blueprint, render_template, flash, redirect, url_for
from app.core.db import db
from app.core.models import Blog, Category
from .models import User
from .forms import CreatePostForm, LoginForm, UpdatePostForm
from werkzeug.security import check_password_hash
from flask.ext.login import current_user, login_user, logout_user, login_required

admin_views = Blueprint('admin', __name__,
                        template_folder='../templates/admin',
                        static_folder='../static')

##################################################
###################Login&Logout###################
##################################################

@admin_views.route('/admin/', methods = ['GET','POST'])
def admin_login():
    if current_user.is_authenticated:
        return redirect(url_for('.admin_home'))
    form = LoginForm()
    error = None
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                return redirect(url_for('.admin_home'))
            error = 'Invalid Password.'
        error = 'Unknown Username.'
    return render_template('login.html', form=form, error=error)

@admin_views.route('/logout/')
@login_required
def admin_logout():
    logout_user()
    flash('You\'re logger Out')
    return redirect(url_for('.admin_login'))

##################################################
###############End of Login&Logout################
##################################################

##################################################
####################Admin Home####################
##################################################

@admin_views.route('/admin/home/')
@login_required
def admin_home():
    user = current_user
    return render_template('home.html',user=user)

@admin_views.route('/admin/create_post', methods=['GET', 'POST'])
@login_required
def create_post():
    form = CreatePostForm()
    if form.validate_on_submit():
        if form.validate():
            category = Category.query.filter_by(name_category = form.category.data).first()
            if category:
                form.category.data = category.id
            else:
                category_create(form.category.data)
                category = Category.query.filter_by(name_category = form.category.data).first()
                form.category.data = category.id
            post = Blog(form.title.data,
                        form.author.data,
                        form.content.data,
                        form.category.data)
            db.session.add(post)
            db.session.commit()
            flash('Your Post are posted.')
            return redirect(url_for('.success_create'))
    return render_template('create_post.html', form=form)

@admin_views.route('/admin/success_create/')
@login_required
def success_create():
	return render_template('create_post_success.html')

@admin_views.route('/admin/update_post/')
@login_required
def update_post():
    blog = Blog.query.all()
    nopost = None
    if not blog:
        nopost = 'No Post'
    return render_template('update_post.html', blog=blog, nopost=nopost)

@admin_views.route('/admin/delete_post/<id_post>')
@login_required
def delete_post(id_post):
    post = Blog.query.filter_by(id = id_post).first()
    flash('{} have been deleted'.format(post.title))
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('.update_post'))

#function for create category to Database
def category_create(name_category):
    new_category = Category(name_category)
    db.session.add(new_category)
    db.session.commit()

@admin_views.route('/admin/edit_post/<id_post>', methods=['GET','POST'])
@login_required
def edit_post(id_post):
    form = UpdatePostForm()
    post = Blog.query.filter_by(id = id_post).first()
    if form.validate_on_submit():
        category = Category.query.filter_by(name_category = form.category.data).first()
        if category:
            form.category.data = category.id
        else:
            category_create(form.category.data)
            category = Category.query.filter_by(name_category = form.category.data).first()
            form.category.data = category.id
        post.title = form.title.data
        post.author = form.author.data
        post.content = form.content.data
        post.category_id = form.category.data
        db.session.commit()
        flash('Your Post are Update.')
        return redirect(url_for('.success_update'))
    return render_template('edit_post.html', form=form,post=post)

@admin_views.route('/admin/success_update/')
@login_required
def success_update():
	return render_template('update_post_success.html')

##################################################
#################End of Admin Home################
##################################################


text:
package org.wso2.carbon.apimgt.rest.api.publisher.dto;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;

import javax.validation.constraints.NotNull;

@ApiModel(description = "")
public class WsdlDTO  {

  @NotNull
  private String name = null;

  private String wsdlDefinition = null;

  /**
   **/
  @ApiModelProperty(required = true, value = "")
  @JsonProperty("name")
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("wsdlDefinition")
  public String getWsdlDefinition() {
    return wsdlDefinition;
  }
  public void setWsdlDefinition(String wsdlDefinition) {
    this.wsdlDefinition = wsdlDefinition;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class WsdlDTO {\n");

    sb.append("  name: ").append(name).append("\n");
    sb.append("  wsdlDefinition: ").append(wsdlDefinition).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
/* global describe, it */

'use strict'

var Creator = require('..').Creator
var validator = require('har-validator').creator

require('should')

describe('Creator', function () {
  it('should throw error when no name', function (done) {
    /* eslint-disable */
    (function () {
      new Creator()
    }).should.throw('name required')
    /* eslint-enable */

    done()
  })

  it('should create a creator object', function (done) {
    var creator = new Creator({
      name: 'foo',
      version: '1.0',
      comment: 'bar'
    })

    creator.should.be.an.Object
    creator.should.have.property('name').and.equal('foo')
    creator.should.have.property('version').and.equal('1.0')
    creator.should.have.property('comment').and.equal('bar')

    validator(creator).should.be.true

    done()
  })
})


text:
package net.iturrioz.marranita;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import net.iturrioz.marranita.domain.Eskue;
import net.iturrioz.marranita.domain.Jokalarie;
import net.iturrioz.marranita.domain.Karta;
import net.iturrioz.marranita.domain.Partida;

public class TapeteaUI {

    final MarranitaActivity activity;

    TapeteaUI(final MarranitaActivity activity) {
        this.activity = activity;
    }

    private View findViewById(final int id) {
        return activity.findViewById(id);
    }

    // Switch to gameplay view.
    public void setGameplayUI() {
        activity.setViewVisibility();

        final Partida partida = activity.partida;
        final Jokalarie[] jokalarik = partida.getJokalarik();
        final Eskue eskue = partida.getEskue();

        final int nerePosizioa = activity.getNerePosizioa();

        setApuntatu(jokalarik[0], R.id.izena_1, R.id.puntuk_1, R.id.bazak_1, mahaikoTokie(0, nerePosizioa));
        setApuntatu(jokalarik[1], R.id.izena_2, R.id.puntuk_2, R.id.bazak_2, mahaikoTokie(1, nerePosizioa));
        setApuntatu(jokalarik[2], R.id.izena_3, R.id.puntuk_3, R.id.bazak_3, mahaikoTokie(2, nerePosizioa));
        setApuntatu(jokalarik[3], R.id.izena_4, R.id.puntuk_4, R.id.bazak_4, mahaikoTokie(3, nerePosizioa));
        setApuntatu(jokalarik[4], R.id.izena_5, R.id.puntuk_5, R.id.bazak_5, mahaikoTokie(4, nerePosizioa));

        final Karta triunfoa = eskue.getTriunfoa();
        if (triunfoa != null) {
            setTextViewText(R.id.triunfo_textue, triunfoa.getKoloreaName());
            setImageViewDrawable(R.id.triunfo_irudie, Karta.getKartaDrawableId(triunfoa));
        }

        final Karta[] kartak = jokalarik[nerePosizioa].getKartak();
        final int[] kartaIdak = new int[] {R.id.karta_0, R.id.karta_1, R.id.karta_2, R.id.karta_3,
                R.id.karta_4, R.id.karta_5, R.id.karta_6, R.id.karta_7};
        for (int i = 0; i < 8; i++) {
            if (i < kartak.length) {
                setImageViewDrawable(kartaIdak[i], Karta.getKartaDrawableId(kartak[i]));
            } else {
                findViewById(kartaIdak[i]).setVisibility(View.GONE);
            }
        }
    }

    private int mahaikoTokie(final int jokalarie, final int nerePosizioa) {
        final int kenketa = jokalarie - nerePosizioa;
        final int id;
        switch (kenketa) {
            case -4: id = R.id.karta_eskuin_beheran;
                break;
            case -3: id = R.id.karta_eskuin_goran;
                break;
            case -2: id = R.id.karta_ezker_goran;
                break;
            case -1: id = R.id.karta_ezker_beheran;
                break;
            case 0: id = R.id.karta_erdin_beheran;
                break;
            case 1: id = R.id.karta_eskuin_beheran;
                break;
            case 2: id = R.id.karta_eskuin_goran;
                break;
            case 3: id = R.id.karta_ezker_goran;
                break;
            case 4: id = R.id.karta_ezker_beheran;
                break;
            default: id = R.id.karta_erdin_beheran;
                break;
        }
        return id;
    }

    private void setApuntatu(final Jokalarie jokalarie,
                             final int izena,
                             final int puntuk,
                             final int bazak,
                             final int mahaikoTokie) {
        setTextViewText(izena, activity.getParticipantDisplayName(jokalarie.getId()));
        setTextViewText(puntuk, String.valueOf(jokalarie.getPuntuk()));
        setTextViewText(bazak, jokalarie.getBazaTextue());

        final Karta karta = jokalarie.getJokatutakoa();
        if (karta != null) {
            setImageViewDrawable(mahaikoTokie, Karta.getKartaDrawableId(karta));
        } else {
            findViewById(mahaikoTokie).setVisibility(View.INVISIBLE);
        }
    }

    private void setTextViewText(final int id, final String text) {
        final TextView textView = (TextView)findViewById(id);
        textView.setText(text);
    }

    private void setImageViewDrawable(final int id, final int drawable) {
        final ImageView imageView = (ImageView)findViewById(id);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(drawable);
    }
}