text:
package com.yobin.stee.tassel.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.yobin.stee.tassel.base.MyApplication;

/**
 * Created by laucherish on 16/3/30.
 */
public class PrefUtil {

    private static final String PRE_NAME = "com.yobin.stee.tassel_preferences";
    private static final String PRE_NIGHT = "night";

    private static SharedPreferences getSharedPreferences() {
        return MyApplication.getContext()
                .getSharedPreferences(PRE_NAME, Context.MODE_PRIVATE);
    }

    public static void setNight(){
        getSharedPreferences().edit().putBoolean(PRE_NIGHT, true).commit();
    }

    public static void setDay(){
        getSharedPreferences().edit().putBoolean(PRE_NIGHT, false).commit();
    }

    public static void changeDayNight(){
        boolean change = !getSharedPreferences().getBoolean(PRE_NIGHT, false);
        getSharedPreferences().edit().putBoolean(PRE_NIGHT, change).commit();
    }

    public static boolean isNight(){
        return getSharedPreferences().getBoolean(PRE_NIGHT, false);
    }

//    public static int getThemeRes(){
//        if (!isNight()) {
//            return Constant.RESOURCES_DAYTHEME;
//        } else {
//            return Constant.RESOURCES_NIGHTTHEME;
//        }
//    }
}


text:
from __future__ import with_statement

import unittest

import IECore
import IECoreGL

IECoreGL.init( False )

class TestState( unittest.TestCase ) :

	def testConstructor( self ) :

		s = IECoreGL.State( False )
		self.assert_( not s.isComplete() )

		s = IECoreGL.State( True )
		self.assert_( s.isComplete() )

	def testUserAttributes( self ) :

		s = IECoreGL.State( False)

		self.assertEqual( s.userAttributes(), IECore.CompoundData() )
		self.failUnless( s.userAttributes().isSame( s.userAttributes() ) )

		s.userAttributes()["test"] = IECore.IntData( 1 )
		self.assertEqual( s.userAttributes(), IECore.CompoundData( { "test" : IECore.IntData( 1 ) } ) )

		s2 = IECoreGL.State( s )
		self.assertEqual( s.userAttributes(), s2.userAttributes() )

		s2.userAttributes()["test2"] = IECore.IntData( 20 )
		self.assertEqual( s.userAttributes(), IECore.CompoundData( { "test" : IECore.IntData( 1 ) } ) )
		self.assertEqual( s2.userAttributes(), IECore.CompoundData( { "test" : IECore.IntData( 1 ), "test2" : IECore.IntData( 20 ) } ) )

	def testScopedBinding( self ) :

		state1 = IECoreGL.State( True )
		state1.add( IECoreGL.NameStateComponent( "billy" ) )
		state2 = IECoreGL.State( False )
		state2.add( IECoreGL.NameStateComponent( "bob" ) )

		self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "billy" )
		self.assertEqual( state2.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

		with IECoreGL.State.ScopedBinding( state2, state1 ) :

			self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )
			self.assertEqual( state2.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

		self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "billy" )
		self.assertEqual( state2.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

	def testOverrides( self ) :

		state1 = IECoreGL.State( True )
		state1.add( IECoreGL.NameStateComponent( "billy" ) )

		state2 = IECoreGL.State( False )
		state2.add( IECoreGL.NameStateComponent( "bob" ), override = True )

		state3 = IECoreGL.State( False )
		state3.add( IECoreGL.NameStateComponent( "jane" ), override = False )

		with IECoreGL.State.ScopedBinding( state2, state1 ) :

			self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

			with IECoreGL.State.ScopedBinding( state3, state1 ) :

				self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

			self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

		self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "billy" )

		with IECoreGL.State.ScopedBinding( state3, state1 ) :

			self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "jane" )

			with IECoreGL.State.ScopedBinding( state2, state1 ) :

				self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "bob" )

			self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "jane" )

		self.assertEqual( state1.get( IECoreGL.NameStateComponent.staticTypeId() ).name(), "billy" )

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

redpajama_set_name: RedPajamaGithub


text:
class NullMixedNumber

	def initialize

	end

	def ==(other)
		other == nil
	end

	def nil?
		true
	end

	def to_m
		nil
	end

	def method_missing(name, *args, &block)
		nil
	end

end


text:
// <auto-generated />
using DTuriasCore.Models;
using DTuriasData.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;

namespace DTuriasData.Migrations
{
    [DbContext(typeof(DataContext))]
    partial class DataContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.0.0-rtm-26452")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("DTuriasCore.Models.CoordinateModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<double>("Latitude");

                    b.Property<double>("Longitude");

                    b.HasKey("Id");

                    b.ToTable("CoordinateModel");
                });

            modelBuilder.Entity("DTuriasCore.Models.DTuriasUserModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Nick");

                    b.HasKey("Id");

                    b.ToTable("DTuriasUsers");
                });

            modelBuilder.Entity("DTuriasCore.Models.HashTagModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Text");

                    b.Property<long?>("TweetModelId");

                    b.HasKey("Id");

                    b.HasIndex("TweetModelId");

                    b.ToTable("HashTags");
                });

            modelBuilder.Entity("DTuriasCore.Models.PlaceModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Country");

                    b.Property<string>("CountryCode");

                    b.Property<string>("FullName");

                    b.Property<string>("Name");

                    b.HasKey("Id");

                    b.ToTable("Places");
                });

            modelBuilder.Entity("DTuriasCore.Models.SentimentModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("State");

                    b.HasKey("Id");

                    b.ToTable("Sentiments");
                });

            modelBuilder.Entity("DTuriasCore.Models.TodoItem", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<bool>("IsComplete");

                    b.Property<string>("Name");

                    b.HasKey("Id");

                    b.ToTable("TodoItems");
                });

            modelBuilder.Entity("DTuriasCore.Models.TweetModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Captured");

                    b.Property<long?>("CapturedById");

                    b.Property<long?>("CoordinatesId");

                    b.Property<DateTime>("CreatedAt");

                    b.Property<long?>("CreatedById");

                    b.Property<long?>("DTuriasUserId");

                    b.Property<int>("FavoriteCount");

                    b.Property<bool>("Favorited");

                    b.Property<string>("FullText");

                    b.Property<bool>("IsRetweet");

                    b.Property<bool>("IsTweetDestroyed");

                    b.Property<bool>("IsTweetPublished");

                    b.Property<string>("Language");

                    b.Property<long?>("PlaceId");

                    b.Property<bool>("PossiblySensitive");

                    b.Property<long>("QuotedTweet");

                    b.Property<int>("RetweetCount");

                    b.Property<bool>("Retweeted");

                    b.Property<long>("RetweetedTweet");

                    b.Property<long?>("SentimentModel");

                    b.Property<string>("Source");

                    b.Property<string>("Text");

                    b.Property<string>("Url");

                    b.HasKey("Id");

                    b.HasIndex("CapturedById");

                    b.HasIndex("CoordinatesId");

                    b.HasIndex("CreatedById");

                    b.HasIndex("DTuriasUserId");

                    b.HasIndex("PlaceId");

                    b.HasIndex("SentimentModel");

                    b.ToTable("Tweets");
                });

            modelBuilder.Entity("DTuriasCore.Models.UserModel", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Name");

                    b.Property<string>("ScreenName");

                    b.HasKey("Id");

                    b.ToTable("Users");
                });

            modelBuilder.Entity("DTuriasCore.Models.HashTagModel", b =>
                {
                    b.HasOne("DTuriasCore.Models.TweetModel", "TweetModel")
                        .WithMany("HashTags")
                        .HasForeignKey("TweetModelId");
                });

            modelBuilder.Entity("DTuriasCore.Models.TweetModel", b =>
                {
                    b.HasOne("DTuriasCore.Models.UserModel", "CapturedBy")
                        .WithMany()
                        .HasForeignKey("CapturedById");

                    b.HasOne("DTuriasCore.Models.CoordinateModel", "Coordinates")
                        .WithMany()
                        .HasForeignKey("CoordinatesId");

                    b.HasOne("DTuriasCore.Models.UserModel", "CreatedBy")
                        .WithMany()
                        .HasForeignKey("CreatedById");

                    b.HasOne("DTuriasCore.Models.DTuriasUserModel", "DTuriasUser")
                        .WithMany()
                        .HasForeignKey("DTuriasUserId");

                    b.HasOne("DTuriasCore.Models.PlaceModel", "Place")
                        .WithMany()
                        .HasForeignKey("PlaceId");

                    b.HasOne("DTuriasCore.Models.SentimentModel", "Sentiment")
                        .WithMany()
                        .HasForeignKey("SentimentModel");
                });
#pragma warning restore 612, 618
        }
    }
}


text:
class PeopleController < InheritedResources::Base
  respond_to :html

  def index
    respond_to do |format|
      format.html do
        if params[:search]
          @people = Person.search(params[:search])
        else
          @people = Person.alphabetical_group(params[:letter])
        end
      end
      format.js { render :template => 'people/index.erb.js' }
    end
  end

  create! do |success, failure|
    failure.html do
      flash[:error] = "Couldn't add person"
      redirect_to people_url
    end
  end

  def make_student
    object.make_student!
    redirect_to person_path(object)
  end

  def basic_information
    @person = object
  end

  def address
    @person = object
    @person.address ||= Address.new
  end

  def siblings
    @person = object
  end

  def photo
    @person = object
  end

  def public_education_info
    @person = object
    @person.public_education_info ||= PublicEducationInfo.new
  end

  def obligations
    @person = object
    @person.obligations ||= Obligations.new
  end

  def social_development_info
    @person = object
    @person.social_development_info ||= SocialDevelopmentInfo.new
  end

  def add_sibling
    @person = object
    @person.add_sibling(Person.find(params[:person_id]))
    redirect_to siblings_person_path(object)
  end

  def remove_sibling
    @person = object
    @person.remove_sibling(Person.find(params[:sibling_id]))
    redirect_to siblings_person_path(@person)
  end

  def caretakers
    @person = object
  end

  def add_caretaker
    @person = object
    caretaker = Person.find(params[:person_id])
    @person.add_caretaker(caretaker)
    redirect_to(caretakers_person_path(@person))
  end

  def remove_caretaker
    @person = object
    caretaker = Person.find(params[:caretaker_id])
    @person.remove_caretaker(caretaker)
    redirect_to(caretakers_person_path(@person))
  end

private
  def object
    Person.find(params[:id])
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diatrype pustulans Ellis & Everh.

### Remarks
null


text:
package com.growthbeat.utils;

import org.json.JSONObject;

public final class JSONObjectUtils {

    public static boolean hasAndIsNotNull(JSONObject jsonObject, String name) {
        return (jsonObject != null && jsonObject.has(name) && !jsonObject.isNull(name));
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

msg: {{msg}}

      <validation :name="'validation1'">
      <validate field="field1" :validators="{ required: true, min: 1 }">
        <input type="text" v-model="msg">
      </validate>

force break line

      <validate field="field2" :validators="{ required: true, max: 1 }">
        <input type="text" v-model="msg">
      </validate>
      </validation>


text:
@interface Example1VisperViewController ()

@end

@implementation Example1VisperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)example2ButtonPressed:(id)sender {
    NSObject <IVISPERViewEvent> *event = [self.visperServiceProvider
                                          createEventWithName:@"example2ButtonPressed" sender:sender info:nil];
    [self notifyPresentersOfView:self.view withEvent:event];
}

- (IBAction)example3ButtonPressed:(id)sender {
    NSObject <IVISPERViewEvent> *event = [self.visperServiceProvider
                                          createEventWithName:@"example3ButtonPressed" sender:sender info:nil];
    [self notifyPresentersOfView:self.view withEvent:event];
}

- (IBAction)loadDataButtonPressed:(id)sender {

    NSObject <IVISPERViewEvent> *event = [self.visperServiceProvider
                                          createEventWithName:@"loadDataButtonPressed" sender:sender info:nil];
    [self notifyPresentersOfView:self.view withEvent:event];
}
@end


text:
package com.garmin.fit;

public enum StrokeType {
   NO_EVENT((short)0),
   OTHER((short)1),
   SERVE((short)2),
   FOREHAND((short)3),
   BACKHAND((short)4),
   SMASH((short)5),
   INVALID((short)255);

   protected short value;

   private StrokeType(short value) {
     this.value = value;
   }

   public static StrokeType getByValue(final Short value) {
      for (final StrokeType type : StrokeType.values()) {
         if (value == type.value)
            return type;
      }

      return StrokeType.INVALID;
   }

   public short getValue() {
      return value;
   }

}


text: export * from './bidLive.component';


text:
package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/hex"
	"errors"
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
	"time"
)

const githubEventType = "X-GitHub-Event"
const githubSignature = "X-Hub-Signature"
const githubSignaturePrefix = "sha1="
const githubUserAgent = "GitHub-Hookshot/"
const statusHtml = `<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Lanky</title>

Lanky

Key	Value

Started	{{.StartDate}}

Version	{{.Version}}

# Goroutines	{{.NumGoroutine}}

1XX	{{.Status1xx}}

2XX	{{.Status2xx}}

3XX	{{.Status3xx}}

4XX	{{.Status4xx}}

5XX	{{.Status5xx}}

Bytes from System	{{.Sys}}

Heap in Use	{{.HeapInuse}}

Heap System	{{.HeapSys}}

Total Allocation	{{.TotalAlloc}}

`

const rootHtml = `<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Lanky</title>
	<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

Lanky

Last {{.Len}} builds sorted by:
	{{if .ByDate}}
	date, status
	{{else}}
	date, status
	{{end}}

	{{range .Project}}

{{.BuildTime}} - {{.Name}} (#{{.LastBuildLabel}})
	{{end}}

`

const repositoryHtml = `<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lanky</title>
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

Lanky

{{.Len}} repositories.

{{range .}}

{{.FullName}}
{{end}}

`

var rootTemplate = template.Must(template.New("root").Parse(rootHtml))
var statusTemplate = template.Must(template.New("status").Parse(statusHtml))
var repositoryTemplate = template.Must(template.New("repository").Parse(repositoryHtml))

func statusHandler(w http.ResponseWriter, r *http.Request, config *Config, stats *RuntimeStats) error {
	stats.Update()

	// lock all of the reads to ensure a consistent point in time measurement
	stats.RLock()
	err := statusTemplate.Execute(w, stats)
	stats.RUnlock()

	if err != nil {
		return err
	}

	return nil
}

func rootHandler(w http.ResponseWriter, r *http.Request, config *Config) error {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return nil
	}

	j := NewJenkins(config)
	if j == nil {
		return errors.New("Jenkins configuration is invalid.")
	}

	by := r.URL.Query().Get("by")
	p := &Projects{}
	err := j.TrayFeed(p, by)
	if err != nil {
		return err
	}

	err = rootTemplate.Execute(w, p)
	if err != nil {
		return err
	}

	return nil
}

func builderHandler(w http.ResponseWriter, r *http.Request, config *Config) (err error) {
	http.Error(w, "Not implemented yet", http.StatusInternalServerError)
	return
}

func sign(payload []byte, key string) []byte {
	mac := hmac.New(sha1.New, []byte(key))
	mac.Write(payload)
	return mac.Sum(nil)
}

func githubHandler(w http.ResponseWriter, r *http.Request, config *Config) (err error) {
	if r.Method != "POST" {
		http.Error(w, "Unauthorized", http.StatusMethodNotAllowed)
		return
	}

	if !strings.HasPrefix(r.UserAgent(), githubUserAgent) {
		http.Error(w, "Unauthorized.", http.StatusUnauthorized)
		return
	}

	signatureHeader := r.Header.Get(githubSignature)
	if !strings.HasPrefix(signatureHeader, githubSignaturePrefix) {
		http.Error(w, "Invalid signature.", http.StatusBadRequest)
		return
	}

	reqSignature, err := hex.DecodeString(signatureHeader[len(githubSignaturePrefix):])
	if err != nil {
		http.Error(w, "Invalid signature.", http.StatusBadRequest)
		return
	}

	body, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		http.Error(w, "Unable to read message body.", http.StatusInternalServerError)
		return
	}

	localSignature := sign(body, config.Github.HookSecret)
	if !hmac.Equal(localSignature, reqSignature) {
		http.Error(w, "Invalid signature.", http.StatusBadRequest)
		return
	}

	event := r.Header.Get(githubEventType)
	switch event {
	case "push":
		http.Error(w, "Not implemented yet", http.StatusInternalServerError)
		return
	case "ping":
		fmt.Fprint(w, "OK: 1")
		return
	}

	http.Error(w, "Invalid event type specified.", http.StatusBadRequest)
	return
}

func hubotHandler(w http.ResponseWriter, r *http.Request, config *Config) (err error) {
	http.Error(w, "Not implemented yet", http.StatusInternalServerError)
	return
}

var repos *Repositories = new(Repositories)
var lastUpdated time.Time
var reposSync sync.Mutex
var reposSwap sync.RWMutex

func repositoryHandler(w http.ResponseWriter, r *http.Request, config *Config) (err error) {
	if r.Method != "GET" {
		http.Error(w, "Unauthorized", http.StatusMethodNotAllowed)
		return
	}

	cl := NewGithub(config)
	if cl == nil {
		return errors.New("Github configuration is invalid.")
	}

	if r.URL.Query().Get("update") == "now" {
		reposSync.Lock()
		defer reposSync.Unlock()
		now := time.Now()
		isAfter := now.After(lastUpdated.Add(5 * time.Minute))

		reps := make(Repositories, 0, 100)
		if isAfter {
			err = cl.ListRepositories(config.Github.Organization, &reps)
			if err != nil {
				return err
			}

			lastUpdated = time.Now()

			reposSwap.Lock()
			repos = &reps
			reposSwap.Unlock()
		}
	}

	reposSwap.RLock()
	err = repositoryTemplate.Execute(w, *repos)
	reposSwap.RUnlock()
	if err != nil {
		return err
	}

	return nil
}


text:
package entity;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Temporal;

@Entity(name="Administrador")
public class Administrador  extends Usuario implements Serializable {

    //mostra que não pode ser id pq se não terá vários ids

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date ultimoLogin;

    //Get e Set

    public Date getUltimoLogin() {
        return ultimoLogin;
    }

    public void setUltimoLogin(Date ultimoLogin) {
        this.ultimoLogin = ultimoLogin;
    }

}


text:
package org.baade.eel.core.player;

import org.baade.eel.core.ILifecycle;
import org.baade.eel.core.message.IMessage;
import org.baade.eel.core.processor.IProcessor;

public interface IPlayer extends ILifecycle {

	public void send(IMessage message);

	public IProcessor getProcessor();
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var rxjs_1 = require("rxjs");
var merge_1 = require("../../operator/merge");
rxjs_1.Observable.prototype.merge = merge_1.merge;
//# sourceMappingURL=merge.js.map


text:
// @ts-check
const { log, dump, DEBUG, RETVAL } = require('./util')
const path = require('path')
const fs = require('fs')
const { spawnSync } = require('child_process')

/**
 * setup elm runtime
 * @param {string} elm
 * @param {boolean} watch
 */
function makeElmRuntime(elm, watch) {
  /** extract source folder from elm.json */
  const cwd = (() => {
    try {
      const data = fs.readFileSync('elm.json')
      return JSON.parse(data.toString())['source-directories'][0]
    } catch (e) {
      return './'
    }
  })()

  /**
   * run elm make to make sure test code compiles
   * @param {string} elm
   * @param {string} testfilename
   * @param {string} elmfile
   */
  function checkElmMake(elm, testfilename, elmfile) {
    dump(`checkElmMake(${elm}, ${testfilename}, ${elmfile}) called`)
    const { stdout, status, stderr } = spawnSync(
      elm,
      ['make', testfilename, '--output=/dev/null'],
      { encoding: 'utf8' }
    )
    if (status !== 0) {
      log(`status: ${status}`)
      log(`stdout: ${stdout}`)
      if (stderr) log(stderr.replace(testfilename, elmfile))
      log(`elm make failed. aborting`)
      return status
    }
    return status
  }

  // load main Elm script
  // @ts-ignore
  const app = require('./elm').Elm.Main.init()

  /** read elm source file and send it back to runtime
   */
  app.ports.readfile.subscribe((elmfile) => {
    try {
      const elmsrc = fs.readFileSync(elmfile, 'utf8')
      log(`\n processing: ${elmfile}`)
      app.ports.srccode.send({ code: elmsrc, filename: elmfile })
    } catch (e) {
      log(`failed to run tests: ${e}`)
      process.exit(RETVAL.EXCEPTION)
    }
  })

  /** receive evaluate message from Elm and elm make and evaluate
   * test cases, then send it back to Elm.
   */
  app.ports.evaluate.subscribe(({ src, runner, filename, modulename }) => {
    dump('----------- evaluate called.')
    dump([src, runner, filename])
    if (src.length === 0) return
    const tempModulePath = path.resolve(cwd, `${modulename}.elm`)
    fs.writeFileSync(tempModulePath, src)
    try {
      if (checkElmMake(elm, tempModulePath, filename) !== 0) {
        throw new Error('elm make exited with error')
      }
      const { stdout, stderr, status } = spawnSync(
        elm,
        ['repl', '--no-colors'],
        {
          input: runner,
          encoding: 'utf8',
        }
      )
      if (DEBUG) fs.writeFileSync('runner.elm', runner)
      dump(`stdout: ${stdout}`)
      if (status !== 0 || stderr) {
        if (stderr) log(stderr)
        throw new Error(`elm repl failed with some error.`)
      } else {
        const match = stdout.match(/^> (.+)/gm)
        if (!match) throw new Error('elm repl did not produce output')
        dump(`match: ${match[0]}`)
        const resultStr = match[0].replace(/[^"]*(".+").*/, '$1')
        dump(resultStr)
        app.ports.result.send({
          stdout: JSON.parse(resultStr),
          filename: filename,
          failed: false,
        })
      }
    } catch (e) {
      app.ports.result.send({
        stdout: e.message,
        filename: filename,
        failed: true,
      })
    } finally {
      if (!DEBUG && fs.existsSync(tempModulePath)) fs.unlinkSync(tempModulePath)
    }
  })

  /** Receive report message from Elm and
   * display results
   */
  app.ports.report.subscribe((report) => {
    log(report.text)
    app.ports.next.send(watch)
  })

  /** exit the process with failure */
  app.ports.exit.subscribe(() => {
    process.exit(RETVAL.FAIL)
  })

  return {
    addfiles: function (/** @type {string[]} */ o) {
      app.ports.addfiles.send(o)
    },
    runnext: function (/** @type {boolean} */ o) {
      app.ports.next.send(o)
    },
  }
}

module.exports = { makeElmRuntime }


text:
layout: page
title: Just for fun
permalink: /fun/
---

This is a landing page to quick link to some fun stuff.

+   [D&D Spell lists]({{ site.baseurl }}/spell_lists/index.html)
+   [D&D Character sheets]({{ site.baseurl }}/dnd/index.html)


text:
export interface Project {
  id: string;
  name: string;
  description?: string;
  created_at: string;
  created_by: string;
  status: string;
}


text:
@interface LCHColorHelper : NSObject

+ (UIColor*)lunchieRed;

+ (UIColor*)lunchieLightGrey;
+ (UIColor*)lunchieDarkGrey;
+ (UIColor*)lunchieBlack;

+ (UIColor*)lunchiePurple;

@end


text:
package com.codeaspect.sheldon.intg;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

import com.codeaspect.sheldon.AuditChecker;
import com.codeaspect.sheldon.entity.Action;
import com.codeaspect.sheldon.entity.AuditChangeEntry;
import com.codeaspect.sheldon.intg.model.Child;
import com.codeaspect.sheldon.intg.model.Parent;

public class ListChangeTest {

	private Parent getSameParent() {
		return new Parent("A", 1L);
	}

	@Test
	public void testListAddition() {
		Parent p1 = getSameParent();
		Parent p2 = getSameParent().addChild(new Child(1L, "1", "3"));

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2);

		assertEquals(1, entries.size());
		AuditChangeEntry entry = entries.get(0);
		assertEquals(Action.CREATE, entry.getAction());
	}

	@Test
	public void testListAdditionWithoutGroup() {
		Parent p1 = getSameParent();
		Parent p2 = getSameParent().addChild(new Child(1L, "1", "3"));

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2, "dummy");

		assertEquals(0, entries.size());
	}

	@Test
	public void testListDeletion() {
		Parent p1 = getSameParent().addChild(new Child(1L, "1", "3"));
		Parent p2 = getSameParent();

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2);

		assertEquals(1, entries.size());
		AuditChangeEntry entry = entries.get(0);
		assertEquals(Action.DELETE, entry.getAction());
	}

	@Test
	public void testListChange() {
		Parent p1 = getSameParent().addChild(new Child(1L, "1", "2"));
		Parent p2 = getSameParent().addChild(new Child(1L, "1", "3"));

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2);

		assertEquals(1, entries.size());
		AuditChangeEntry entry = entries.get(0);
		assertEquals("2", entry.getValue1());
		assertEquals("3", entry.getValue2());
		assertEquals("children.fld2", entry.getPath().getPathString());
		assertEquals(Action.MODIFY, entry.getAction());
	}

	@Test
	public void testLargeListChange() {
		Parent p1 = getSameParent().addChild(new Child(1L, "1", "2")).addChild(new Child(2L, "1", "2"))
				.addChild(new Child(3L, "1", "2")).addChild(new Child(4L, "1", "2"));
		Parent p2 = getSameParent().addChild(new Child(1L, "1", "2")).addChild(new Child(2L, "1", "2"))
				.addChild(new Child(3L, "1", "B")).addChild(new Child(4L, "1", "2"));

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2);

		assertEquals(1, entries.size());
		AuditChangeEntry entry = entries.get(0);
		assertEquals("2", entry.getValue1());
		assertEquals("B", entry.getValue2());
		assertEquals("children.fld2", entry.getPath().getPathString());
		assertEquals(Action.MODIFY, entry.getAction());
	}

	@Test
	public void testListChangeForMultipleChanges() {
		Parent p1 = getSameParent().addChild(new Child(1L, "1", "A"));
		Parent p2 = getSameParent().addChild(new Child(1L, "2", "B"));

		List<AuditChangeEntry> entries = new AuditChecker<Parent>().checkObjects(p1, p2);

		assertEquals(2, entries.size());
	}

	@Test
	public void testListChangeWithGroup() {
		Parent p1 = getSameParent().addChild(new Child(1L, "1", "A"));
		Parent p2 = getSameParent().addChild(new Child(1L, "2", "B"));

		assertEquals(2, new AuditChecker<Parent>().checkObjects(p1, p2, "standard").size());
		assertEquals(1, new AuditChecker<Parent>().checkObjects(p1, p2, "wacky").size());
	}

}


text:
FOUNDATION_EXPORT double DataBasisVersionNumber;

//! Project version string for DataBasis.
FOUNDATION_EXPORT const unsigned char DataBasisVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <DataBasis/PublicHeader.h>


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

<title>SampleManager</title>
<meta name="date" content="2014-11-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.beadsproject.beads.data

Class SampleManager

java.lang.Object

net.beadsproject.beads.data.SampleManager

public class SampleManager
extends java.lang.Object

SampleManager provides a static repository for Sample data and provides methods to organise samples into groups.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static interface
SampleManager.SampleGroupListener

Interface for notificaiton of changes to a group.

Constructor Summary

Constructors

Constructor and Description

SampleManager()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
addGroupListener(SampleManager.SampleGroupListener l)

static void
addToGroup(java.lang.String group,
          java.util.List<Sample> newSamples)

Add a new list of Samples to the specified group.

static void
addToGroup(java.lang.String group,
          Sample sample)

Add a new Sample to a group.

static void
destroyGroup(java.lang.String groupName)

Removes the specified group, and removes all of the samples found in the
 group from the sample repository.

static Sample
fromGroup(java.lang.String groupName,
         int index)

Gets the Sample at the specified index from the specified group.

static java.util.ArrayList<Sample>
getGroup(java.lang.String groupName)

Gets the specified group in the form ArrayList<Sample>.

static java.lang.String
getGroupDir(java.lang.String groupName)

Gets the directory path of the group.

static java.util.List<java.lang.String>
getSampleNameList()

Returns an ArrayList containing all of the Sample names.

static java.util.List<Sample>
group(java.lang.String groupName,
     Sample[] sampleList)

Generates a new group with the given group name and list of Samples to be
 added to the group.

static java.util.List<Sample>
group(java.lang.String groupName,
     java.lang.String folderName)

Generates a new group with the given group name and a string that
 specifies where to load samples to be added to the group.

static java.util.List<Sample>
group(java.lang.String groupName,
     java.lang.String[] fileNameList)

Generates a new group with the given group name and a list of file names
 to be added to the group.

static java.util.List<Sample>
group(java.lang.String groupName,
     java.lang.String[] fileNameList,
     int maxItems)

Generates a new group with the given group name and a list of file names
 to be added to the group, with number of elements loaded limited to maxItems.

static java.util.List<Sample>
group(java.lang.String groupName,
     java.lang.String folderName,
     int maxItems)

Generates a new group with the given group name and a string that
 specifies where to load samples to be added to the group, and also limits the number of items loaded from the folder to maxItems.

static java.util.Set<java.lang.String>
groups()

Gets the set of group names.

static java.util.List<java.lang.String>
groupsAsList()

List the groups by name as a list of Strings.

static boolean
isVerbose()

Determines if SampleManager is being verbose.

static void
logSamplePaths(java.lang.String toFile)

Creates a text file at the specified path containing a list of all of the
 file names of Samples loaded so far.

static void
printSampleList()

Prints a list of all Samples to System.out.

static Sample
randomFromGroup(java.lang.String groupName)

Gets a random sample from the specified group.

static void
removeGroup(java.lang.String groupName)

Removes the specified group, without removing the samples.

static void
removeGroupListener(SampleManager.SampleGroupListener l)

static void
removeSample(Sample sample)

Removes the Sample.

static void
removeSample(java.lang.String sampleName)

Removes the named Sample.

static Sample
sample(java.lang.String fn)

Returns a new Sample from the given filename.

static void
sample(java.lang.String name,
      Sample sample)

Adds a sample by name to the sample list.

static Sample
sample(java.lang.String ref,
      java.lang.String fn)

Like sample(String) but with the option to specify the name with which this Sample is indexed.

static void
setVerbose(boolean verbose)

Tells SampleManager to produce verbose output.

static void
transferSamples(java.lang.String sourceRootDir,
               java.lang.String destRootDir,
               boolean force)

Takes all of the Samples currently stored and attempts to relocate
 them so that their position relative to destRootDir duplicates their position
 relative to sourceRootDir.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SampleManager

public SampleManager()

Method Detail

sample

public static Sample sample(java.lang.String fn)

Returns a new Sample from the given filename. If the Sample has already
 been loaded, it will not be loaded again, but will simply be retrieved
 from the static repository.

Parameters:

fn - the file path.

Returns:

the sample.

sample

public static void sample(java.lang.String name,
                          Sample sample)

Adds a sample by name to the sample list. This lets you load samples with a different buffering regime.

Parameters:

name -

sample -

sample

public static Sample sample(java.lang.String ref,
                            java.lang.String fn)

Like sample(String) but with the option to specify the name with which this Sample is indexed.

Parameters:

ref - the name with which to index this Sample.

fn - the file path.

Returns:

the sample.

group

public static java.util.List<Sample> group(java.lang.String groupName,
                                           Sample[] sampleList)

Generates a new group with the given group name and list of Samples to be
 added to the group.

Parameters:

groupName - the group name.

sampleList - the sample list.

group

public static java.util.List<Sample> group(java.lang.String groupName,
                                           java.lang.String folderName)

Generates a new group with the given group name and a string that
 specifies where to load samples to be added to the group. The string is interpreted firstly as a URL, and if that fails, as a folder path.

Parameters:

groupName - the group name.

folderName - the folder address (URL or file path).

group

public static java.util.List<Sample> group(java.lang.String groupName,
                                           java.lang.String folderName,
                                           int maxItems)

Generates a new group with the given group name and a string that
 specifies where to load samples to be added to the group, and also limits the number of items loaded from the folder to maxItems. The string is interpreted firstly as a URL, and if that fails, as a folder path.

Parameters:

groupName - the group name.

folderName - the folder address (URL or file path).

maxItems - number of items to limit to.

group

public static java.util.List<Sample> group(java.lang.String groupName,
                                           java.lang.String[] fileNameList)

Generates a new group with the given group name and a list of file names
 to be added to the group.

Parameters:

groupName - the group name.

fileNameList - the file name list.

group

public static java.util.List<Sample> group(java.lang.String groupName,
                                           java.lang.String[] fileNameList,
                                           int maxItems)

Generates a new group with the given group name and a list of file names
 to be added to the group, with number of elements loaded limited to maxItems.

Parameters:

groupName - the group name.

fileNameList - the file name list.

maxItems - number of items to limit to.

addToGroup

public static void addToGroup(java.lang.String group,
                              Sample sample)

Add a new Sample to a group. Create the group if it doesn't exist.

Parameters:

group - the group to add to.

sample - the Sample to add.

addToGroup

public static void addToGroup(java.lang.String group,
                              java.util.List<Sample> newSamples)

Add a new list of Samples to the specified group. Create the group if it doesn't exist.

Parameters:

group - the group to add to.

newSamples - the list of Samples to add.

groups

public static java.util.Set<java.lang.String> groups()

Gets the set of group names.

Returns:

Set of Strings representing group names.

groupsAsList

public static java.util.List<java.lang.String> groupsAsList()

List the groups by name as a list of Strings.

Returns:

a List of Strings.

getGroup

public static java.util.ArrayList<Sample> getGroup(java.lang.String groupName)

Gets the specified group in the form ArrayList<Sample>.

Parameters:

groupName - the group name.

Returns:

the group.

getGroupDir

public static java.lang.String getGroupDir(java.lang.String groupName)

Gets the directory path of the group.

Parameters:

groupName -

Returns:

directory path.

randomFromGroup

public static Sample randomFromGroup(java.lang.String groupName)

Gets a random sample from the specified group.

Parameters:

groupName - the group.

Returns:

a random Sample.

fromGroup

public static Sample fromGroup(java.lang.String groupName,
                               int index)

Gets the Sample at the specified index from the specified group. If index is greater than the size of the group
 then the value index % sizeOfGroup is used.

Parameters:

groupName - the group name.

index - the index.

Returns:

the Sample.

removeSample

public static void removeSample(java.lang.String sampleName)

Removes the named Sample.

Parameters:

sampleName - the sample name.

removeSample

public static void removeSample(Sample sample)

Removes the Sample.

Parameters:

sample - the Sample.

removeGroup

public static void removeGroup(java.lang.String groupName)

Removes the specified group, without removing the samples.

Parameters:

groupName - the group name.

destroyGroup

public static void destroyGroup(java.lang.String groupName)

Removes the specified group, and removes all of the samples found in the
 group from the sample repository.

Parameters:

groupName - the group name.

addGroupListener

public static void addGroupListener(SampleManager.SampleGroupListener l)

removeGroupListener

public static void removeGroupListener(SampleManager.SampleGroupListener l)

printSampleList

public static void printSampleList()

Prints a list of all Samples to System.out.

getSampleNameList

public static java.util.List<java.lang.String> getSampleNameList()

Returns an ArrayList containing all of the Sample names.

Returns:

ArrayList of Sample names.

isVerbose

public static boolean isVerbose()

Determines if SampleManager is being verbose.

Returns:

true if verbose.

setVerbose

public static void setVerbose(boolean verbose)

Tells SampleManager to produce verbose output.

Parameters:

verbose - true for verbose output.

logSamplePaths

public static void logSamplePaths(java.lang.String toFile)

Creates a text file at the specified path containing a list of all of the
 file names of Samples loaded so far. Useful if you need to gather
 all of your sample data into one place using a script. Puts all file names in
 double quotes.

Parameters:

toFile - destination of the file.

transferSamples

public static void transferSamples(java.lang.String sourceRootDir,
                                   java.lang.String destRootDir,
                                   boolean force)

Takes all of the Samples currently stored and attempts to relocate
 them so that their position relative to destRootDir duplicates their position
 relative to sourceRootDir. This only applies to Samples that were loaded
 from a position below sourceRootDir.

Parameters:

sourceRootDir - root that you want to transfer from

destRootDir - place you want to transfer to

force - set to true to force overwrite existing files - take care!

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System;
using ArethruNotifier.Helix;

namespace ArethruNotifier {
    abstract class CmdNode {
        public delegate void PrintMethod(string s);
        protected PrintMethod OutM;
        protected CmdNode[] cmds;
        protected string Out { set { OutM(value + "\n"); } }

        public abstract void Main(PrintMethod p);
        public abstract void Execute(string[] args);
    }

    class CmdMain : CmdNode {
        public override void Main(PrintMethod p) {
            cmds = new CmdNode[] {
                new CmdGet()
            };
            foreach (var item in cmds) {
                item.Main(p);
            }
        }
        public override void Execute(string[] args) {
            var c = args[0];
            if (c.Equals("GET")) {
                cmds[0].Execute(args);
            }
        }
    }

    class CmdGet : CmdNode {
        public override void Main(PrintMethod p) {
            OutM = p;
        }
        public override void Execute(string[] args) {
            var c = args[1];
            if (args.Length > 2) {
                if (c.Equals("USER")) {
                    User(args[2]);
                }
                if (c.Equals("FOLLOWS")) {
                    Follows(args[2]);
                }
                if (c.Equals("STREAMS")) {
                    Streams(args[2]);
                }
            }
            else {
                Out = "More arguments needed!";
                Out = "[GET OBJECT VALUE]";
            }
        }

        private async void User(string param) {
            var user = await HelixAPI.GetUserBy(param);
            if (user.User.Count > 0) {
                Out = user.User[0].Id;
            }
        }

        private async void Follows(string param) {
            int i;
            if (!int.TryParse(param, out i)) {
                return;
            }
            var follows = await HelixAPI.GetFollows(param);
            Out = "[ Users Follows ]";
            foreach (var item in follows.Follow) {
                Out = item.Name;
            }
        }

        private async void Streams(string param) {
            int i;
            if (!int.TryParse(param, out i)) {
                return;
            }
            var follows = await HelixAPI.GetFollows(param);
            string ids = follows.GenerateUserIds();
            var streams = await HelixAPI.GetStreams(ids);
            Out = "[ Users Live Followed Streams ]";
            foreach (var item in streams.Stream) {
                Out = item.Channel;
            }
        }
    }

    class AN_Console {
        MainWindow mainWin;

        // Clear Method Delegate
        public delegate void PrintMethod(string s);
        PrintMethod Acout;
        public delegate void ClearMethod();
        ClearMethod Acclear;

        // Pushes a string to the Output display (richtextbox)
        public string Out { set { Acout(value + "\n"); } }

        // Recieves an unformatted string with commands
        public string In { set { CommandParse(value); } }

        // The main guy. See abstract class CmdNode
        CmdMain main;

        public AN_Console(System.Windows.Controls.RichTextBox textbox, MainWindow textboxOwner) {
            mainWin = textboxOwner;
            Acout = textbox.AppendText;
            Acclear = textbox.Document.Blocks.Clear;
            main = new CmdMain();
            main.Main(textbox.AppendText);
        }

        void CommandParse(string s) {
            s = s.ToUpper();
            string[] cmds = s.Split(null);
            if (cmds[0].Equals("CLEAR")) {
                Acclear();
            }
            try {
                main.Execute(cmds);
            }
            catch (IndexOutOfRangeException) {
                Out = "Unknown Command";
            }
        }
    }
}


text:
/* @flow strict */

import React from 'react';
import { render } from '@testing-library/react';

import BpkModal from './BpkModal';

describe('BpkModal', () => {
  it('should render correctly in the given target if renderTarget is supplied', () => {
    const customRenderTarget = document.createElement('div');

    const { asFragment } = render(
      <BpkModal
        id="my-modal"
        title="Modal title"
        onClose={jest.fn()}
        closeLabel="Close"
        dialogRef={jest.fn()}
        isIphone={false}
        getApplicationElement={jest.fn()}
        isOpen
        renderTarget={() => customRenderTarget}
      >
        Modal content inside a custom target
      </BpkModal>,
    );

    expect(asFragment()).toMatchSnapshot();
    expect(customRenderTarget).toMatchSnapshot();
  });
});


text:
#pragma once

#include <Param.hpp>
#include <common/deprecated.hpp>
#include <common/dispatch.hpp>
#include <common/kernel_cache.hpp>
#include <debug_opencl.hpp>
#include <kernel_headers/regions.hpp>
#include <math.hpp>
#include <memory.hpp>
#include <traits.hpp>
#include <af/defines.h>

AF_DEPRECATED_WARNINGS_OFF
#include <boost/compute/algorithm/adjacent_difference.hpp>
#include <boost/compute/algorithm/exclusive_scan.hpp>
#include <boost/compute/algorithm/sort.hpp>
#include <boost/compute/algorithm/transform.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/iterator/counting_iterator.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/lambda/placeholders.hpp>
AF_DEPRECATED_WARNINGS_ON

#include <array>
#include <string>
#include <vector>

namespace compute = boost::compute;

namespace opencl {
namespace kernel {

template<typename T>
std::array<Kernel, 3> getRegionsKernels(const bool full_conn,
                                        const int n_per_thread) {
    using std::string;
    using std::vector;

    constexpr int block_dim = 16;
    constexpr int num_warps = 8;

    ToNumStr<T> toNumStr;
    vector<TemplateArg> targs = {
        TemplateTypename<T>(),
        TemplateArg(full_conn),
        TemplateArg(n_per_thread),
    };
    vector<string> options = {
        DefineKeyValue(T, dtype_traits<T>::getName()),
        DefineKeyValue(BLOCK_DIM, block_dim),
        DefineKeyValue(NUM_WARPS, num_warps),
        DefineKeyValue(N_PER_THREAD, n_per_thread),
        DefineKeyValue(LIMIT_MAX, toNumStr(maxval<T>())),
    };
    if (full_conn) { options.emplace_back(DefineKey(FULL_CONN)); }
    options.emplace_back(getTypeBuildDefinition<T>());

    return {
        common::getKernel("initial_label", {regions_cl_src}, targs, options),
        common::getKernel("final_relabel", {regions_cl_src}, targs, options),
        common::getKernel("update_equiv", {regions_cl_src}, targs, options),
    };
}

template<typename T>
void regions(Param out, Param in, const bool full_conn,
             const int n_per_thread) {
    using cl::Buffer;
    using cl::EnqueueArgs;
    using cl::NDRange;

    constexpr int THREADS_X = 16;
    constexpr int THREADS_Y = 16;

    auto kernels = getRegionsKernels<T>(full_conn, n_per_thread);

    const NDRange local(THREADS_X, THREADS_Y);

    const int blk_x = divup(in.info.dims[0], THREADS_X * 2);
    const int blk_y = divup(in.info.dims[1], THREADS_Y * 2);

    const NDRange global(blk_x * THREADS_X, blk_y * THREADS_Y);

    auto ilOp = kernels[0];
    auto ueOp = kernels[2];
    auto frOp = kernels[1];

    ilOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data,
         in.info);
    CL_DEBUG_FINISH(getQueue());

    int h_continue     = 1;
    Buffer* d_continue = bufferAlloc(sizeof(int));

    while (h_continue) {
        h_continue = 0;
        getQueue().enqueueFillBuffer(*d_continue, h_continue, 0, sizeof(int));
        ueOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info,
             *d_continue);
        CL_DEBUG_FINISH(getQueue());
        getQueue().enqueueReadBuffer(*d_continue, CL_TRUE, 0, sizeof(int),
                                     &h_continue);
    }
    bufferFree(d_continue);

    // Now, perform the final relabeling.  This converts the equivalency
    // map from having unique labels based on the lowest pixel in the
    // component to being sequentially numbered components starting at
    // 1.
    int size = in.info.dims[0] * in.info.dims[1];

    compute::command_queue c_queue(getQueue()());

    // Wrap raw device ptr
    compute::context context(getContext()());
    compute::vector<T> tmp(size, context);
    clEnqueueCopyBuffer(getQueue()(), (*out.data)(), tmp.get_buffer().get(), 0,
                        0, size * sizeof(T), 0, NULL, NULL);

    // Sort the copy
    compute::sort(tmp.begin(), tmp.end(), c_queue);

    // Take the max element which is the number
    // of label assignments to compute.
    T last_label;
    clEnqueueReadBuffer(getQueue()(), tmp.get_buffer().get(), CL_TRUE,
                        (size - 1) * sizeof(T), sizeof(T), &last_label, 0, NULL,
                        NULL);
    const int num_bins = (int)last_label + 1;

    // If the number of label assignments is two,
    // then either the entire input image is one big
    // component(1's) or it has only one component other than
    // background(0's). Either way, no further
    // post-processing of labels is required.
    if (num_bins <= 2) return;

    Buffer labels(getContext(), CL_MEM_READ_WRITE, num_bins * sizeof(T));
    compute::buffer c_labels(labels());
    compute::buffer_iterator<T> labels_begin =
        compute::make_buffer_iterator<T>(c_labels, 0);
    compute::buffer_iterator<T> labels_end =
        compute::make_buffer_iterator<T>(c_labels, num_bins);

    // Find the end of each section of values
    compute::counting_iterator<T> search_begin(0);

    int tmp_size = size;
    BOOST_COMPUTE_CLOSURE(int, upper_bound_closure, (int v), (tmp, tmp_size), {
        int start = 0, n = tmp_size, i;
        while (start < n) {
            i = (start + n) / 2;
            if (v < tmp[i]) {
                n = i;
            } else {
                start = i + 1;
            }
        }
        return start;
    });

    BOOST_COMPUTE_FUNCTION(int, clamp_to_one, (int i),
                           { return (i >= 1) ? 1 : i; });

    compute::transform(search_begin, search_begin + num_bins, labels_begin,
                       upper_bound_closure, c_queue);
    compute::adjacent_difference(labels_begin, labels_end, labels_begin,
                                 c_queue);

    // Perform the scan -- this can computes the correct labels for each
    // component
    compute::transform(labels_begin, labels_end, labels_begin, clamp_to_one,
                       c_queue);

    compute::exclusive_scan(labels_begin, labels_end, labels_begin, c_queue);

    // Apply the correct labels to the equivalency map
    // Buffer labels_buf(tmp.get_buffer().get());
    frOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data,
         in.info, labels);
    CL_DEBUG_FINISH(getQueue());
}
}  // namespace kernel
}  // namespace opencl


text:
namespace net {

class X509Certificate;

// The result of certificate verification.
class NET_EXPORT CertVerifyResult {
 public:
  CertVerifyResult();
  CertVerifyResult(const CertVerifyResult& other);
  ~CertVerifyResult();

  void Reset();

  // Returns true if all the members of |this| are equal to |other|'s (including
  // the |verified_cert| intermediates).
  bool operator==(const CertVerifyResult& other) const;

  // The certificate chain that was constructed during verification.
  //
  // Note: Although |verified_cert| will match the originally supplied
  // certificate to be validated, the results of intermediate_buffers()
  // may be substantially different, both in order and in content, then the
  // originally supplied intermediates.
  //
  // In the event of validation failures, this may contain the originally
  // supplied certificate chain or a partially constructed path, depending on
  // the implementation.
  //
  // In the event of validation success, the trust anchor will be
  // |verified_cert->intermediate_buffers().back()| if
  // there was a certificate chain to the trust anchor, and will
  // be |verified_cert->cert_buffer()| if the certificate was
  // the trust anchor.
  scoped_refptr<X509Certificate> verified_cert;

  // Bitmask of CERT_STATUS_* from net/cert/cert_status_flags.h. Note that
  // these status flags apply to the certificate chain returned in
  // |verified_cert|, rather than the originally supplied certificate
  // chain.
  CertStatus cert_status;

  // Hash algorithms used by the certificate chain, excluding the trust
  // anchor.
  bool has_md2;
  bool has_md4;
  bool has_md5;
  bool has_sha1;
  bool has_sha1_leaf;

  // If the certificate was successfully verified then this contains the
  // hashes for all of the SubjectPublicKeyInfos of the chain (target,
  // intermediates, and trust anchor)
  //
  // The ordering of the hashes in this vector is unspecified. Both the SHA1
  // and SHA256 hash will be present for each certificate.
  HashValueVector public_key_hashes;

  // is_issued_by_known_root is true if we recognise the root CA as a standard
  // root.  If it isn't then it's probably the case that this certificate was
  // generated by a MITM proxy whose root has been installed locally. This is
  // meaningless if the certificate was not trusted.
  bool is_issued_by_known_root;

  // is_issued_by_additional_trust_anchor is true if the root CA used for this
  // verification came from the list of additional trust anchors.
  bool is_issued_by_additional_trust_anchor;

  // Verification of stapled OCSP response, if present.
  OCSPVerifyResult ocsp_result;
};

}  // namespace net

#endif  // NET_CERT_CERT_VERIFY_RESULT_H_


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

namespace GeoViewer.Common.Utils
{
    [TestClass]
    public class EnumerableHelperTest
    {
        [TestMethod]
        public void TestYield()
        {
            var testValue = new object();

            var enumerable = EnumerableHelper.Yield(testValue);

            Assert.AreEqual(testValue, enumerable.Single());
        }

        [TestMethod]
        public void TestYieldNull()
        {
            var testValue = (object)null;

            var enumerable = EnumerableHelper.Yield(testValue);

            Assert.AreEqual(testValue, enumerable.Single());
        }
    }
}


text:
/* doc in malloc.c */
/* @(#)nmalloc.c 1 (Caltech) 2/21/82
 *  This is a very fast storage allocator.  It allocates blocks of a small
 *  number of different sizes, and keeps free lists of each size.  Blocks that
 *  don't exactly fit are passed up to the next larger size.  In this
 *  implementation, the available sizes are (2^n)-4 (or -12) bytes long.
 *  This is designed for use in a program that uses vast quantities of memory,
 *  but bombs when it runs out.  To make it a little better, it warns the
 *  user when he starts to get near the end.
 *
 *  The smallest recorded block is 8 bytes.
 *
 * This code will work equally well in environments with 4 byte pointers
 * and 8 byte pointers.  Don't do anything to break this!
 *
 * This file contains only the reentrant versions of malloc().  All newlib
 * routines must call these routines directly, and not malloc().  Otherwise
 * an application might supply it's own malloc() and some newlib routines
 * would use it, while other routines would use the one below.
 */

#include <_ansi.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <reent.h>
#include <unistd.h>
#include "malloc.h"

#ifdef SMALL_MEMORY
#define ROUND_TO 0x3
#define CHUNK_POWER 9
#else
#define ROUND_TO 0x3ff
#define CHUNK_POWER 11
#endif

/* VxWorks provides its own version of malloc, and we can't use this
   one because VxWorks does not provide sbrk.  So we have a hook to
   not compile this code.  */

#ifdef MALLOC_PROVIDED

_PTR
_DEFUN (_malloc_r, (ptr, nbytes),
	struct _reent * ptr _AND
	size_t nbytes)		/* get a block */
{
  return malloc (nbytes);
}

void
_DEFUN (_free_r, (ptr, aptr),
	struct _reent *ptr _AND
	_PTR aptr)
{
  free (aptr);
}

_PTR
_DEFUN (_realloc_r, (ptr, ap, nbytes),
	struct _reent * ptr _AND
	_PTR ap _AND
	size_t nbytes)
{
  return realloc (ap, nbytes);
}

#else

#ifdef MSTATS
#include <stdio.h>
#endif	/* MSTATS */

#ifdef WARN_VLIMIT
#include <sys/vlimit.h>		/* warn the user when near the end */
#endif

extern char etext;		/* end of the program */

/*      The overhead on a block is a pointer, rounded up to meet alignment
 *  requirements.  When free, it will contain a pointer to the next free block,
 *  and the bottom bits must be zero.
 *  When in use, the first byte will be set to 0xFF, and the next
 *  byte will be the size index.  Any other bytes are only used for
 *  alignment.  If you are range checking, and the size of the block will fit
 *  into two bytes, then the top two bytes hold the size of the requested block
 *  plus the range checking words, and the header word MINUS ONE.
 */

static _VOID
_DEFUN (_morecore_r, (ptr, nu),	/* ask system for more memory */
	struct _reent *ptr _AND
	register int nu)	/* size index to get more of  */
{
  register mptr cp;
  register int rnu;	/* 2^rnu bytes will be requested */
  register int nblks;	/* that becomes nblks blocks of the desired size */
  register int siz;	/* size in ints, not bytes */
#ifdef WARN_VLIMIT
  static int warnlevel = 0;
#endif

  if (ptr->_nextf[nu] != NULL)
    return;

  cp = (mptr) _sbrk_r (ptr, 0);

#ifdef WARN_VLIMIT
  {
    register size_t used;
    used = cp - (mptr) & etext;
    siz = vlimit (LIM_DATA, -1);	/* find out how much we can get */
    switch (warnlevel)
      {
      case 0:
	if (used > (siz / 4) * 3)
	  {
	    write (2, "warning: past 75% of memory limit\7\n", 35);
	    warnlevel = 1;
	  }
	break;
      case 1:
	if (used > (siz / 20) * 17)
	  {
	    write (2, "warning: past 85% of memory limit\7\n", 35);
	    warnlevel = 2;
	  }
	break;
      case 2:
	if (used > (siz / 20) * 19)
	  {
	    write (2, "warning: past 95% of memory limit\7\n", 35);
	    warnlevel = 3;
	  }
	break;
      }
  }				/* end of warning switch */
#endif

  /* Round up */
  if ((((size_t) cp) & ROUND_TO) != 0)
    _sbrk_r (ptr, (ROUND_TO+1) - (((size_t) cp) & ROUND_TO));

  /* take 2k unless the block is bigger than that */
  rnu = (nu <= CHUNK_POWER - 3) ? CHUNK_POWER : nu + 3;

  nblks = 1 << (rnu - (nu + 3));/* how many blocks to get */
  if (rnu < nu)
    rnu = nu;
  /* FIXME: We assume sign extension here if sizeof(size_t) < sizeof(char *) */
  if ((cp = (mptr) _sbrk_r (ptr, 1 << rnu)) == (mptr) -1)
    return;			/* no more room! */

  /* Work out the rounding so that it will work whatever the size
     of the pointer, regardless of the size of size_t. */

  if ((siz = (int) cp & 7) != 0)
    {
      cp = (mptr) ((char *) cp - siz);
      nblks--;
    }

  ptr->_nextf[nu] = cp;

  /* We chop the block up into nblk free blocks,
     go through the empty block filling in the free pointer stuff */

  siz = 1 << (nu + 3);		/* +3: blocks are multiples of 8 bytes */

  while (--nblks > 0)
    {
      *(mptr *) cp = (mptr) & ((char *) cp)[siz];
      cp = *(mptr *) cp;
    }

  *(mptr *) cp = NULL;	/* NULL terminate the list */
}

_PTR
_DEFUN (_malloc_r, (ptr, nbytes),
	struct _reent * ptr _AND
	size_t nbytes)		/* get a block */
{
  register unsigned char *p;
  register int nunits = 0;
  register unsigned shiftr;

  nbytes += OVERHEAD;
  nbytes = ALIGN (nbytes);
  shiftr = (nbytes - 1) >> 2;

  while ((shiftr >>= 1) != 0)	/* apart from this loop, this is O(1) */
    nunits++;
  if (ptr->_nextf[nunits] == NULL)	/* needed block, nunits is the size index */
    _morecore_r (ptr, nunits);
  if ((p = (unsigned char *) (ptr->_nextf[nunits])) == NULL)
    return (NULL);
  ptr->_nextf[nunits] = *(mptr *) (ptr->_nextf[nunits]);
  p[0] = 0xff;
  p[1] = nunits;

#ifdef MSTATS
  ptr->_nmalloc[nunits]++;
#endif	/* MSTATS */

#ifdef rcheck
  if (nbytes <= 0x10000)
    ((unsigned short *) p)[1] = (unsigned short) nbytes - 1;
  *((INT32 *) (p + 4)) = MAGIC;
  *((INT32 *) (p + nbytes - 4)) = MAGIC;
  return ((char *) (p + ALIGN (8)));
#else
  return ((char *) (p + ALIGN (4)));
#endif
}

void
_DEFUN (_free_r, (ptr, aptr),
	struct _reent *ptr _AND
	_PTR aptr)
{
  register int si;
  char *ap = aptr;

  if (ap == NULL)
    return;
#ifdef rcheck
  ap -= ALIGN (8);
  ASSERT (*(INT32 *) (ap + 4) == MAGIC);
#else
  ap -= ALIGN (4);
#endif

#ifdef debug
  ASSERT (ap[0] == (char) 0xff); /* make sure it was in use */
#else
  if (ap[0] != (char) 0xff)
    return;
#endif

#ifdef rcheck
  if (ap[1] <= 13)
    {
      si = ((unsigned short *) ap)[1] - 11;	/* get the size of the data */
      ASSERT (*((INT32 *) (ap + si + 8)) == MAGIC); /* check for overflow */
    }
#endif

  ASSERT (ap[1] <= 29);
  si = ap[1];
  *((mptr *) ap) = ptr->_nextf[si];
  ptr->_nextf[si] = (mptr) ap;

#ifdef MSTATS
  ptr->_nmalloc[si]--;
#endif	/* MSTATS */
}

_PTR
_DEFUN (_realloc_r, (ptr, ap, nbytes),
	struct _reent * ptr _AND
	_PTR ap _AND
	size_t nbytes)
{
  register char *res;
  register unsigned int onb;
  register char *p;

  if (ap == NULL)
    return (_malloc_r (ptr, nbytes));
#ifdef rcheck
  p = (char*)ap - ALIGN (8);
  if (p[1] < 13)
    onb = ((unsigned short *) p)[1] - (OVERHEAD - 1);	/* old number of data bytes only */
  else
    onb = (1 << (p[1] + 3)) - OVERHEAD;
#else
  p = (char*)ap - ALIGN (4);
  onb = (1 << (p[1] + 3)) - OVERHEAD;
#endif
  if ((res = _malloc_r (ptr, nbytes)) == NULL)
    return (NULL);
  memcpy (res, ap, (nbytes < onb) ? nbytes : onb);
  _free_r (ptr, ap);
  return (res);
}

#ifdef MSTATS

/* ****************************************************************
 * mstats - print out statistics about malloc
 *
 * Prints two lines of numbers, one showing the length of the free list
 * for each size category, the second showing the number of mallocs -
 * frees for each size category.
 */

void
_DEFUN (_mstats_r, (ptr, s),
	struct _reent *ptr _AND
	char *s)
{
  register int i, j;
  register mptr p;
  int totfree = 0, totused = 0;

  fprintf (_stderr_r (ptr), "Memory allocation statistics %s\nfree:\t", s);
  for (i = 0; i < _N_LISTS; i++)
    {
      p = ptr->_nextf[i];

      for (j = 0; p; j++)
	p = *(mptr *) p;
      fprintf (_stderr_r (ptr), " %d", j);
      totfree += j * (1 << (i + 3));
    }
  fprintf (_stderr_r (ptr), "\nused:\t");
  for (i = 0; i < _N_LISTS; i++)
    {
      fprintf (_stderr_r (ptr), " %d", ptr->_nmalloc[i]);
      totused += ptr->_nmalloc[i] * (1 << (i + 3));
    }
  fprintf (_stderr_r (ptr), "\n\tTotal in use: %d, total free: %d\n");
}

#endif /* ! defined (MSTATS) */

#endif /* ! defined (MALLOC_PROVIDED) */


text:
package com.comandante.creeper.world.model;

import com.comandante.creeper.core_game.GameManager;
import com.comandante.creeper.core_game.service.TimeTracker;
import com.comandante.creeper.entity.CreeperEntity;
import com.comandante.creeper.items.Forage;
import com.comandante.creeper.items.Item;
import com.comandante.creeper.merchant.Merchant;
import com.comandante.creeper.npc.Npc;
import com.comandante.creeper.player.Player;
import com.comandante.creeper.spawner.ItemSpawner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class Room extends CreeperEntity {

    private final Integer roomId;

    public void setRoomTitle(String roomTitle) {
        this.roomTitle = roomTitle;
    }

    public void setRoomDescription(String roomDescription) {
        this.roomDescription = roomDescription;
    }

    private String roomTitle;
    private final Integer floorId;
    private Optional<Integer> northId;
    private Optional<Integer> westId;
    private Optional<Integer> eastId;
    private Optional<Integer> southId;
    private Optional<Integer> downId;
    private Optional<Integer> upId;
    private List<RemoteExit> enterExits = Lists.newArrayList();
    private String roomDescription;
    private final Set<String> presentPlayerIds = Sets.<String>newConcurrentHashSet();
    private final Set<String> npcIds = Sets.newConcurrentHashSet();
    private final Set<String> itemIds = Sets.newConcurrentHashSet();
    private List<ItemSpawner> itemSpawners = Lists.newArrayList();
    private Set<Area> areas = Sets.newConcurrentHashSet();
    private Optional<String> mapData = Optional.empty();
    private final Set<String> roomTags;
    private final Set<Merchant> merchants = Sets.newConcurrentHashSet();
    private Map<String, Forage> forages = Maps.newHashMap();
    private final Map<String, String> notables;
    private final GameManager gameManager;

    public Room(Integer roomId,
                String roomTitle,
                Integer floorId,
                Optional<Integer> northId,
                Optional<Integer> southId,
                Optional<Integer> eastId,
                Optional<Integer> westId,
                Optional<Integer> upId,
                Optional<Integer> downId,
                List<RemoteExit> enterExits,
                String roomDescription, Set<String> roomTags,
                Set<Area> areas,
                Map<String, String> notables,
                GameManager gameManager) {
        this.roomId = roomId;
        this.roomTitle = roomTitle;
        this.floorId = floorId;
        this.northId = northId;
        this.westId = westId;
        this.eastId = eastId;
        this.southId = southId;
        this.upId = upId;
        this.downId = downId;
        this.roomDescription = roomDescription;
        this.roomTags = roomTags;
        this.areas = areas;
        this.enterExits = enterExits;
        this.notables = notables;
        this.gameManager = gameManager;
    }

    public List<ItemSpawner> getItemSpawners() {
        return itemSpawners;
    }

    public void setItemSpawners(List<ItemSpawner> itemSpawners) {
        this.itemSpawners = itemSpawners;
    }

    public Set<Merchant> getMerchants() {
        return merchants;
    }

    public void addMerchant(Merchant merchant) {
        merchants.add(merchant);
    }

    public Set<String> getRoomTags() {
        return roomTags;
    }

    public void setNorthId(Optional<Integer> northId) {
        this.northId = northId;
    }

    public void setWestId(Optional<Integer> westId) {
        this.westId = westId;
    }

    public void setEastId(Optional<Integer> eastId) {
        this.eastId = eastId;
    }

    public void setSouthId(Optional<Integer> southId) {
        this.southId = southId;
    }

    public void setDownId(Optional<Integer> downId) {
        this.downId = downId;
    }

    public void setUpId(Optional<Integer> upId) {
        this.upId = upId;
    }

    public void addTag(String tag) {
        roomTags.add(tag);
    }
    public Integer getFloorId() {
        return floorId;
    }

    public Optional<String> getMapData() {
        return mapData;
    }

    public void setMapData(Optional<String> mapData) {
        this.mapData = mapData;
    }

    public Set<Area> getAreas() {
        return areas;
    }

    public void setAreas(Set<Area> areas) {
        this.areas = areas;
    }

    public String getRoomTitle() {
        return roomTitle;
    }

    public void addPresentItem(String itemId) {
        itemIds.add(itemId);
    }

    public Set<String> getItemIds() {
        return itemIds;
    }

    public void removePresentItem(String itemId) {
        itemIds.remove(itemId);

    }

    public void addPresentNpc(String npcId) {
        npcIds.add(npcId);
    }

    public void removePresentNpc(String npcId) {
        npcIds.remove(npcId);
    }

    public Set<String> getNpcIds() {
        return npcIds;
    }

    public Set<String> getPresentPlayerIds() {
        return presentPlayerIds.stream().filter(playerId -> gameManager.getPlayerManager().getPlayer(playerId) != null).collect(Collectors.toSet());
    }

    public Set<Player> getPresentPlayers() {
        Set<Player> players = Sets.newHashSet();
        for (String playerId : presentPlayerIds) {
            Player player = gameManager.getPlayerManager().getPlayer(playerId);
            if (player != null) {
                players.add(player);
            }
        }
        return ImmutableSet.copyOf(players);
    }

    public void addPresentPlayer(String playerId) {
        presentPlayerIds.add(playerId);

    }

    public void removePresentPlayer(String playerId) {
        presentPlayerIds.remove(playerId);
    }

    public String getRoomDescription() {
        return roomDescription;
    }

    public Integer getRoomId() {
        return roomId;
    }

    public Optional<Integer> getNorthId() {
        return northId;
    }

    public Optional<Integer> getWestId() {
        return westId;
    }

    public Optional<Integer> getEastId() {
        return eastId;
    }

    public Optional<Integer> getSouthId() {
        return southId;
    }

    public Optional<Integer> getUpId() {
        return upId;
    }

    public Optional<Integer> getDownId() {
        return downId;
    }

    public List<RemoteExit> getEnterExits() {
        return enterExits;
    }

    public void addEnterExit(RemoteExit remoteExit) {
        enterExits.add(remoteExit);
    }

    public void setEnterExits(List<RemoteExit> enterExits) {
        this.enterExits = enterExits;
    }

    public void addItemSpawner(ItemSpawner itemSpawner) {
        itemSpawners.add(itemSpawner);
    }

    public Map<String, Forage> getForages() {
        return forages;
    }

    public void addForage(Forage forage) {
        this.forages.put(forage.getInternalItemName(), forage);
    }

    public Map<String, String> getNotables() {
        return notables;
    }

    public void addNotable(String notableName, String description) {
        notables.put(notableName, description);
    }

    public GameManager getGameManager() {
        return gameManager;
    }

    public List<Npc> getPresentNpcs() {
        return npcIds.stream().map(s -> gameManager.getEntityManager().getNpcEntity(s)).collect(Collectors.toList());
    }

    @Override
    public void run() {
        for (String itemId : itemIds) {
            Optional<Item> itemOptional = gameManager.getEntityManager().getItemEntity(itemId);
            if (!itemOptional.isPresent()) {
                removePresentItem(itemId);
                continue;
            }
            Item itemEntity = itemOptional.get();
            if (itemEntity.isHasBeenWithPlayer()) {
                continue;
            }
            Set<TimeTracker.TimeOfDay> itemValidTimeOfDays = itemEntity.getValidTimeOfDays();
            TimeTracker.TimeOfDay timeOfDay = gameManager.getTimeTracker().getTimeOfDay();
            if (itemValidTimeOfDays.size() > 0 && !itemValidTimeOfDays.contains(timeOfDay)) {
                gameManager.getEntityManager().removeItem(itemId);
                removePresentItem(itemId);
                gameManager.writeToRoom(roomId, itemEntity.getItemName() + " turns to dust.\r\n");
            }
        }
    }
}


text:
package org.dswarm.persistence.service.schema.test.internalmodel;

import java.util.LinkedList;

import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;

import org.dswarm.persistence.GuicedTest;
import org.dswarm.persistence.model.schema.Attribute;
import org.dswarm.persistence.model.schema.AttributePath;
import org.dswarm.persistence.model.schema.utils.NameSpacePrefixRegistry;
import org.dswarm.persistence.model.schema.Schema;
import org.dswarm.persistence.model.schema.SchemaAttributePathInstance;
import org.dswarm.persistence.service.schema.test.utils.AttributePathServiceTestUtils;
import org.dswarm.persistence.service.schema.test.utils.AttributeServiceTestUtils;
import org.dswarm.persistence.service.schema.test.utils.SchemaAttributePathInstanceServiceTestUtils;

public class AttributePathBuilder extends GuicedTest {

	//private static final Logger									LOG			= LoggerFactory.getLogger(AttributePathBuilder.class);

	private AttributePath pathUnderConstruction;

	private LinkedList<Attribute> attributeList;

	// private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class);

	private final NameSpacePrefixRegistry registry;

	private String prefixPaths = "";

	private SchemaAttributePathInstanceServiceTestUtils schemaAPinstanceServiceTestUtils;
	private AttributePathServiceTestUtils               apServiceTestUtils;
	private AttributeServiceTestUtils                   attributeServiceTestUtils;

	public AttributePathBuilder() {

		super();

		registry = new NameSpacePrefixRegistry();

		schemaAPinstanceServiceTestUtils = new SchemaAttributePathInstanceServiceTestUtils();
		apServiceTestUtils = new AttributePathServiceTestUtils();
		attributeServiceTestUtils = new AttributeServiceTestUtils();
	}

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

		schemaAPinstanceServiceTestUtils = new SchemaAttributePathInstanceServiceTestUtils();
		apServiceTestUtils = new AttributePathServiceTestUtils();
		attributeServiceTestUtils = new AttributeServiceTestUtils();
	}

	public AttributePathBuilder start() {
		attributeList = Lists.newLinkedList();
		return this;
	}

	public AttributePathBuilder add(final String fullURI) throws Exception {
		attributeList.add(attributeServiceTestUtils.createObject(fullURI, getLocalName(fullURI)));
		return this;
	}

	public AttributePath getPath() throws Exception {

		pathUnderConstruction = apServiceTestUtils.createAttributePath(attributeList);
		return pathUnderConstruction;
	}

	public AttributePath parseAsAttributePath(final String pathInPrefixNotation) throws Exception {

		// temp store prefix paths as a summary
		prefixPaths += pathInPrefixNotation + System.lineSeparator();

		start();

		final String[] attributesInPrefixNotation = pathInPrefixNotation.split("/");

		for (int i = 0; i < attributesInPrefixNotation.length; i++) {

			final String attributeInPrefixNotation = attributesInPrefixNotation[i];

			final String[] attributeParts = attributeInPrefixNotation.split(":");

			final String prefix = attributeParts[0];
			final String localName = attributeParts[1];
			final String namespace = registry.getNamespace(prefix);

			add(namespace + localName);
		}

		return getPath();

	}

	public SchemaAttributePathInstance parseAsAttributePathInstance(final String pathInPrefixNotation) throws Exception {

		AttributePath attributePath = parseAsAttributePath(pathInPrefixNotation);

		return schemaAPinstanceServiceTestUtils.createSchemaAttributePathInstance(attributePath);
	}

	public SchemaAttributePathInstance parseAsAttributePathInstance(final String pathInPrefixNotation, Schema subSchema) throws Exception {

		AttributePath attributePath = parseAsAttributePath(pathInPrefixNotation);

		return schemaAPinstanceServiceTestUtils.createSchemaAttributePathInstance(null, attributePath, subSchema);
	}

	public String getPrefixPaths() {
		return prefixPaths;
	}

	private String getLocalName(final String fullURI) {

		String localName = "";

		if (fullURI.contains("#")) {
			localName = fullURI.substring(StringUtils.lastIndexOf(fullURI, "#") + 1);
		} else {
			localName = fullURI.substring(StringUtils.lastIndexOf(fullURI, "/") + 1);
		}

		return localName;
	}
}


text:
using System;

namespace FileSystem.Commands
{
    public class ListCommand : Command
    {
        public override bool Execute(params string[] _args)
        {
            foreach (var node in fileSystem.currentNode.children)
            {
                if (node.Value != null)
                {
                    Console.WriteLine(string.Format(" {0,-30}  {1:-40}  {2}", node.Key, node.Value.PrintTime(), node.Value.PrintPermissions()));
                }
            }
            return true;
        }
    }
}


text:
.. RxCS documentation master file, created by
   sphinx-quickstart on Wed May 14 16:39:35 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to RxCS's documentation!
================================

Contents:

.. toctree::
   :maxdepth: 1

  introduction
  modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
#include <aws/inspector2/model/ImageLayerAggregation.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Inspector2
{
namespace Model
{

ImageLayerAggregation::ImageLayerAggregation() :
    m_layerHashesHasBeenSet(false),
    m_repositoriesHasBeenSet(false),
    m_resourceIdsHasBeenSet(false),
    m_sortBy(ImageLayerSortBy::NOT_SET),
    m_sortByHasBeenSet(false),
    m_sortOrder(SortOrder::NOT_SET),
    m_sortOrderHasBeenSet(false)
{
}

ImageLayerAggregation::ImageLayerAggregation(JsonView jsonValue) :
    m_layerHashesHasBeenSet(false),
    m_repositoriesHasBeenSet(false),
    m_resourceIdsHasBeenSet(false),
    m_sortBy(ImageLayerSortBy::NOT_SET),
    m_sortByHasBeenSet(false),
    m_sortOrder(SortOrder::NOT_SET),
    m_sortOrderHasBeenSet(false)
{
  *this = jsonValue;
}

ImageLayerAggregation& ImageLayerAggregation::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("layerHashes"))
  {
    Array<JsonView> layerHashesJsonList = jsonValue.GetArray("layerHashes");
    for(unsigned layerHashesIndex = 0; layerHashesIndex < layerHashesJsonList.GetLength(); ++layerHashesIndex)
    {
      m_layerHashes.push_back(layerHashesJsonList[layerHashesIndex].AsObject());
    }
    m_layerHashesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("repositories"))
  {
    Array<JsonView> repositoriesJsonList = jsonValue.GetArray("repositories");
    for(unsigned repositoriesIndex = 0; repositoriesIndex < repositoriesJsonList.GetLength(); ++repositoriesIndex)
    {
      m_repositories.push_back(repositoriesJsonList[repositoriesIndex].AsObject());
    }
    m_repositoriesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("resourceIds"))
  {
    Array<JsonView> resourceIdsJsonList = jsonValue.GetArray("resourceIds");
    for(unsigned resourceIdsIndex = 0; resourceIdsIndex < resourceIdsJsonList.GetLength(); ++resourceIdsIndex)
    {
      m_resourceIds.push_back(resourceIdsJsonList[resourceIdsIndex].AsObject());
    }
    m_resourceIdsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("sortBy"))
  {
    m_sortBy = ImageLayerSortByMapper::GetImageLayerSortByForName(jsonValue.GetString("sortBy"));

    m_sortByHasBeenSet = true;
  }

  if(jsonValue.ValueExists("sortOrder"))
  {
    m_sortOrder = SortOrderMapper::GetSortOrderForName(jsonValue.GetString("sortOrder"));

    m_sortOrderHasBeenSet = true;
  }

  return *this;
}

JsonValue ImageLayerAggregation::Jsonize() const
{
  JsonValue payload;

  if(m_layerHashesHasBeenSet)
  {
   Array<JsonValue> layerHashesJsonList(m_layerHashes.size());
   for(unsigned layerHashesIndex = 0; layerHashesIndex < layerHashesJsonList.GetLength(); ++layerHashesIndex)
   {
     layerHashesJsonList[layerHashesIndex].AsObject(m_layerHashes[layerHashesIndex].Jsonize());
   }
   payload.WithArray("layerHashes", std::move(layerHashesJsonList));

  }

  if(m_repositoriesHasBeenSet)
  {
   Array<JsonValue> repositoriesJsonList(m_repositories.size());
   for(unsigned repositoriesIndex = 0; repositoriesIndex < repositoriesJsonList.GetLength(); ++repositoriesIndex)
   {
     repositoriesJsonList[repositoriesIndex].AsObject(m_repositories[repositoriesIndex].Jsonize());
   }
   payload.WithArray("repositories", std::move(repositoriesJsonList));

  }

  if(m_resourceIdsHasBeenSet)
  {
   Array<JsonValue> resourceIdsJsonList(m_resourceIds.size());
   for(unsigned resourceIdsIndex = 0; resourceIdsIndex < resourceIdsJsonList.GetLength(); ++resourceIdsIndex)
   {
     resourceIdsJsonList[resourceIdsIndex].AsObject(m_resourceIds[resourceIdsIndex].Jsonize());
   }
   payload.WithArray("resourceIds", std::move(resourceIdsJsonList));

  }

  if(m_sortByHasBeenSet)
  {
   payload.WithString("sortBy", ImageLayerSortByMapper::GetNameForImageLayerSortBy(m_sortBy));
  }

  if(m_sortOrderHasBeenSet)
  {
   payload.WithString("sortOrder", SortOrderMapper::GetNameForSortOrder(m_sortOrder));
  }

  return payload;
}

} // namespace Model
} // namespace Inspector2
} // namespace Aws


text:
require 'rails_helper'

RSpec.feature 'Admin scoreboard', type: :feature do
  let(:contest) { Contest.instance }

  before do
    contest.start
    contest.save
  end

  scenario 'admin scoreboard is not accessible to participants' do
    visit admin_contest_scoreboard_path(contest)

    expect(current_path).to eq(new_session_path)
  end

  context "as an admin" do
    include_context "an authorized admin"

    scenario 'admin scoreboard is accessible to admins' do
      # TODO Update when authorization is in place
      visit admin_contest_scoreboard_path(contest)

      expect(current_path).to eq(admin_contest_scoreboard_path(contest))
    end

    scenario 'a team without activity is shown', :include_contest do
      team = Team.create!(contest: contest, name: 'Team 1')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('Team 1')
    end

    scenario 'a team with activity is shown' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem = Problem.create!(contest: contest)
      submission = Submission.create!(team: team, problem: problem)

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('Team 1')

    end

    scenario 'teams are ranked by current score' do
      team_1 = Team.create!(contest: contest, name: 'Team 1')
      team_2 = Team.create!(contest: contest, name: 'Team 2')
      problem = Problem.create!(contest: contest)

      Submission.create!(problem: problem, team: team_1, status: 'failed')
      Submission.create!(problem: problem, team: team_2, status: 'passed')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text(/Team 2.*Team 1/)
    end

    scenario 'ties are broken by time' do
      team_1 = Team.create!(contest: contest, name: 'Team 1')
      team_2 = Team.create!(contest: contest, name: 'Team 2')
      problem = Problem.create!(contest: contest)

      submission_1 = Submission.create!(problem: problem, team: team_2, status: 'passed')
      submission_2 = Submission.create!(problem: problem, team: team_1, status: 'passed')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text(/Team 2.*Team 1/)
    end

    scenario 'problem numbers are shown in the table header' do
      8.times { Problem.create!(contest: contest) }

      visit admin_contest_scoreboard_path(contest)

      8.times do |index|
        expect(page).to have_text(index + 1)
      end
    end

    scenario 'there is a team column' do
      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text(/Team/)
    end

    scenario 'there is a score column' do
      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text(/Score/)
    end

    scenario 'there is a time + penalty column' do
      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text(/Time \+ Penalty/)
    end

    scenario 'unattempted problems show a 0 total number of submissions' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem = Problem.create!(contest: contest)

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('0')
    end

    scenario 'unsolved problems show the total number of submissions' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem = Problem.create!(contest: contest)

      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('4')
    end

    scenario 'solved problems show the total number of submissions' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem = Problem.create!(contest: contest)

      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'passed')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('4')
    end

    scenario 'problems show the total number of submissions up to the first success' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem = Problem.create!(contest: contest)

      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'passed')
      submission = Submission.create!(team: team, problem: problem, status: 'failed')
      submission = Submission.create!(team: team, problem: problem, status: 'passed')

      visit admin_contest_scoreboard_path(contest)

      expect(page).to have_text('4')
    end

    scenario 'score is shown for each team' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem_1 = Problem.create!(contest: contest)
      problem_2 = Problem.create!(contest: contest)
      problem_3 = Problem.create!(contest: contest)

      submission = Submission.create!(team: team, problem: problem_1, status: 'failed')
      submission = Submission.create!(team: team, problem: problem_1, status: 'failed')
      submission = Submission.create!(team: team, problem: problem_1, status: 'failed')
      submission = Submission.create!(team: team, problem: problem_1, status: 'passed')

      submission = Submission.create!(team: team, problem: problem_2, status: 'failed')
      submission = Submission.create!(team: team, problem: problem_2, status: 'failed')
      submission = Submission.create!(team: team, problem: problem_2, status: 'failed')

      submission = Submission.create!(team: team, problem: problem_3, status: 'passed')

      visit admin_contest_scoreboard_path(contest)

      within('tbody') do
        expect(page).to have_text('2')
      end
    end

    scenario 'time + penalty is shown for each team' do
      team = Team.create!(contest: contest, name: 'Team 1')
      problem_1 = Problem.create!(contest: contest)
      problem_2 = Problem.create!(contest: contest)
      problem_3 = Problem.create!(contest: contest)

      Submission.create!(team: team, problem: problem_1, status: 'failed')
      Submission.create!(team: team, problem: problem_1, status: 'failed')
      Submission.create!(team: team, problem: problem_1, status: 'failed')
      submission_1 = Submission.create!(team: team, problem: problem_1, status: 'passed')

      Submission.create!(team: team, problem: problem_2, status: 'failed')
      Submission.create!(team: team, problem: problem_2, status: 'failed')
      Submission.create!(team: team, problem: problem_2, status: 'failed')

      submission_2 = Submission.create!(team: team, problem: problem_3, status: 'passed')

      submission_1.reload
      submission_2.reload

      visit admin_contest_scoreboard_path(contest)

      time_plus_penalty =
        (submission_1.created_at - Contest.instance.started_at) +
        (submission_2.created_at - Contest.instance.started_at) +
        Rails.configuration.failed_submission_time_penalty * 3

      within('tbody') do
        expect(page).to have_text(Time.at(time_plus_penalty).utc.strftime('%H:%M:%S'))
      end
    end
  end
end


text:
package org.apache.commons.configuration2.builder.combined;

import java.util.Collection;

import org.apache.commons.configuration2.builder.BuilderParameters;
import org.apache.commons.configuration2.builder.FileBasedBuilderParametersImpl;
import org.apache.commons.configuration2.ex.ConfigurationException;

/**
 *

 * A specialized implementation of {@link ConfigurationBuilderProvider} which
 * determines the name of the result configuration class based on the extension
 * of the file to load.
 *

 *

 * This class works analogously to its base class {@link BaseConfigurationBuilderProvider};
 * especially, the resulting builder is created based on reflection. It extends
 * the super class's functionality by a specific mechanism for determining the
 * resulting configuration class: At construction time two configuration class
 * names and a file extension are passed in. If a file name is provided in the
 * builder's initialization parameters and this file name has the specified
 * extension, then the first configuration class name is used; otherwise the
 * default configuration class name is selected.
 *

 *

 * There are some tags for {@code CombinedConfigurationProvider} which can
 * produce different results depending on the configuration files they have to
 * load. This class can be used to implement this feature in a generic way.
 *

 *
 * @version $Id$
 * @since 2.0
 */
public class FileExtensionConfigurationBuilderProvider extends
        BaseConfigurationBuilderProvider
{
    /** Constant for the file extension separator. */
    private static final char EXT_SEPARATOR = '.';

    /** The matching configuration class. */
    private final String matchingConfigurationClass;

    /** The file extension. */
    private final String extension;

    /**
     * Creates a new instance of
     * {@code FileExtensionConfigurationBuilderProvider}.
     *
     * @param bldrCls the name of the builder class
     * @param reloadBldrCls the name of a builder class to be used if reloading
     *        support is required (null if reloading is not supported)
     * @param matchingConfigCls the name of the configuration class to be used
     *        if the provided file extension matches (must not be null)
     * @param defConfigClass the name of the configuration class to be used if
     *        the provided file extension does not match (must not be
     *        null)
     * @param ext the file extension to select the configuration class (must not
     *        be null)
     * @param paramCls a collection with the names of parameters classes; an
     *        instance of a parameters object with basic properties is created
     *        automatically and does not need to be contained in this list; the
     *        collection can be null if no additional parameter objects
     *        are needed
     * @throws IllegalArgumentException if a required parameter is missing
     */
    public FileExtensionConfigurationBuilderProvider(String bldrCls,
            String reloadBldrCls, String matchingConfigCls,
            String defConfigClass, String ext, Collection<String> paramCls)
    {
        super(bldrCls, reloadBldrCls, defConfigClass, paramCls);
        if (matchingConfigCls == null)
        {
            throw new IllegalArgumentException(
                    "Matching configuration class must not be null!");
        }
        if (ext == null)
        {
            throw new IllegalArgumentException(
                    "File extension must not be null!");
        }

        matchingConfigurationClass = matchingConfigCls;
        extension = ext;
    }

    /**
     * Returns the name of the matching configuration class. This class is used
     * if the file extension matches the extension of this provider.
     *
     * @return the matching configuration class
     */
    public String getMatchingConfigurationClass()
    {
        return matchingConfigurationClass;
    }

    /**
     * Returns the file extension of this provider.
     *
     * @return the file extension to match
     */
    public String getExtension()
    {
        return extension;
    }

    /**
     * {@inheritDoc} This implementation tries to find a
     * {@link FileBasedBuilderParametersImpl} object in the parameter objects. If
     * one is found, the extension of the file name is obtained and compared
     * against the stored file extension. In case of a match, the matching
     * configuration class is selected, otherwise the default one.
     */
    @Override
    protected String determineConfigurationClass(ConfigurationDeclaration decl,
            Collection<BuilderParameters> params) throws ConfigurationException
    {
        String currentExt = extractExtension(fetchCurrentFileName(params));
        return getExtension().equalsIgnoreCase(currentExt) ? getMatchingConfigurationClass()
                : getConfigurationClass();
    }

    /**
     * Tries to obtain the current file name from the given list of parameter
     * objects.
     *
     * @param params the parameter objects
     * @return the file name or null if unspecified
     */
    private static String fetchCurrentFileName(
            Collection<BuilderParameters> params)
    {
        for (BuilderParameters p : params)
        {
            if (p instanceof FileBasedBuilderParametersImpl)
            {
                FileBasedBuilderParametersImpl fp = (FileBasedBuilderParametersImpl) p;
                return fp.getFileHandler().getFileName();
            }
        }
        return null;
    }

    /**
     * Extracts the extension from the given file name. The name can be
     * null.
     *
     * @param fileName the file name
     * @return the extension (null if there is none)
     */
    private static String extractExtension(String fileName)
    {
        if (fileName == null)
        {
            return null;
        }

        int pos = fileName.lastIndexOf(EXT_SEPARATOR);
        return (pos < 0) ? null : fileName.substring(pos + 1);
    }
}