text:
using System;
using System.Collections.Generic;
using System.Linq;
using Baseline;

namespace Marten.Testing.Events.Projections
{
    #region sample_QuestParty
    public class QuestParty
    {
        public List<string> Members { get; set; } = new();
        public IList<string> Slayed { get; } = new List<string>();
        public string Key { get; set; }
        public string Name { get; set; }

        // In this particular case, this is also the stream id for the quest events
        public Guid Id { get; set; }

        // These methods take in events and update the QuestParty
        public void Apply(MembersJoined joined) => Members.Fill(joined.Members);
        public void Apply(MembersDeparted departed) => Members.RemoveAll(x => departed.Members.Contains(x));
        public void Apply(QuestStarted started) => Name = started.Name;

        public override string ToString()
        {
            return $"Quest party '{Name}' is {Members.Join(", ")}";
        }
    }
    #endregion

    public class QuestFinishingParty: QuestParty
    {
        private readonly string _exMachina;

        public QuestFinishingParty()
        {
        }

        public QuestFinishingParty(string exMachina)
        {
            _exMachina = exMachina;
        }

        public void Apply(MembersEscaped escaped)
        {
            if (_exMachina == null)
            {
                throw new NullReferenceException("Can't escape w/o an Ex Machina");
            }

            Members.RemoveAll(x => escaped.Members.Contains(x));
        }
    }

}


text:
"use strict";

module.exports = function doubleRotatorFactory (rng, speed, generosity, difficulty) {
    var bulletSpeed = 40 + speed * 30,
        bulletNumber = Math.max(2, Math.min(4, Math.floor(2 + Math.sqrt(generosity) * 2))),
        waitTime = 100 / 70 * bulletSpeed + 15 * (bulletNumber - 2),
        spread = 1.5;

    var def = [];

    def.push(
        ['setBulletSpeed', bulletSpeed + 10, 0],
        ['wait', waitTime * 5],
        ['setAngle', 0, true],
        ['setBulletSprite', 'enemy-bullet-white'],
        ['burst', 60, Math.PI * 2, 0, false],
        ['setBulletSprite', 'enemy-bullet-black'],
        ['wait', waitTime * 2]
    );

    for (var i = 0; i < 15; i++) {
        def.push(['setBulletSpeed', bulletSpeed - i * 1.5 / 70 * bulletSpeed, 0]);
        def.push(['wait', waitTime]);
        def.push(['burst', bulletNumber, Math.PI / spread, (i / 80) * Math.PI * 2, false]);
        def.push(['burst', bulletNumber, Math.PI / spread, (i / 80) * Math.PI * -2, false]);
        def.push(['burst', bulletNumber, Math.PI / spread, Math.PI + (i / 80) * Math.PI * 2, false]);
        def.push(['burst', bulletNumber, Math.PI / spread, Math.PI + (i / 80) * Math.PI * -2, false]);
    }

    def.push(['wait', 3500]);

    return def;
};

redpajama_set_name: RedPajamaGithub


text:
.page_admin>.container-fluid
{
 padding:0 !important;
}
#admin-page-wrapper
{
 background:#c3c3c3;
 text-align:center;
 padding:25px;
}
#login-box
{
 display:inline-block;
 margin-top:150px;
 margin-bottom:150px;
 border:1px solid #d3d3d3;
}
@media screen and (max-width:320px)
{
 #login-box
 {
  width:100%;
 }
}
@media screen and (min-width:320px) and (max-width:768px)
{
 #login-box
 {
  width:60%;
 }
}
@media screen and (min-width:768px)
{
 #login-box
 {
  width:40%;
 }
}
#login-box>h3
{
 font-family:sans-serif,calibri,arial;
 font-size:20px;
 color:#fff;
 background:#222222;
 padding:10px;
 margin:0;
 text-align:left;
}
#login-box>.form-horizontal>.form-content
{
 padding:30px 10px;
 background:#fff;
 text-align:left;
}
#login-box>.form-horizontal>.submit_row
{
 background:#222222;
 padding:10px;
 text-align:right;
}


text:
package com.example.listmaker.app.client.handler;

import java.util.Map;

import com.google.gwt.event.shared.EventHandler;
import com.example.listmaker.app.client.domain.NoteList;

public interface NoteListsModifiedEventHandler extends EventHandler
{
	void onNoteListsModified(Map<Long, NoteList> noteLists);
}


text:
/**
* Contains: mud constants and values.
*/
#pragma once
#ifndef MUD_H
#define MUD_H
#include "conf.h"
/**
* @todo move to utils.h
*/
//used to show where an exception was thrown:
#define WHERE() std::string(" In ")+std::string(__FUNCTION__)+std::string(" at ")+std::string(__FILE__)+std::string(".")

//typedefs:
typedef int FLAG; //bitfield flags
typedef int VNUM;

struct range
{
    int min;
    int max;
};

/**
* @todo remove these or as many as possible, put forward declarations in the files that require them.
*/
//forward declarations
class Entity;
class Socket;
class Player;
class Component;
class BaseObject;
class StaticObject;
class Zone;

//olc forward declarations
struct OLC_DATA;

//player rankings:
#define RANK_PLAYER 1<<1
#define RANK_NEWBIE 1<<2
#define RANK_BUILDER 1<<3
#define RANK_ADMIN 1<<29
#define RANK_GOD 1<<30

//player flags
#define PF_SILENCE 1<<1 //player can't broadcast
#define PF_FROZEN 1<<2 //player can't do anything.
#define PF_NOTITLE 1<<3 //player can't set a title
//room flags
#define RF_NOSAY 1<<1
#define RF_NOMOB 1<<2
//NPC flags
#define MF_STATIC 1<<1 //mob does not move
#define MF_SCAVENGER 1<<2 //mob picks up eq on the ground.
#define M_AGGRESSIVE 1<<3 //mob is aggro
#define MF_ZONELOCK 1<<4 //mob doesn't leave zone
#define MF_WIMPY 1<<5 //mob flees when it gets hurt.
#define MF_MEMORY 1<<6 //remember attackers.
#define MF_ASSIST 1<<7 //assist other mobs fighting.
#define MF_NOKILL 1<<8 //mob can't be killed.

//logger levels
enum LOG_LEVEL {INFORM,WARN,ERR,CRIT,SCRIPT, PLAYER, CONNECTION};
//Message types:
enum MessageType {MSG_NORMAL, MSG_ERROR,MSG_INFO,MSG_CRITICAL,MSG_CHANNEL,MSG_LIST};

//terrain types:
enum class TERRAIN
{
    OCEAN, UNDERWATER, AIR, PLANE, DESERT, UNDERGROUND, SWAMP, HILLS, MOUNTAIN, FOREST, LIGHTFOREST, CITY, INSIDE, MAX
};
#define POSITION_ANY 0
#define POSITION_UNCONCIOUS 1<<1
#define POSITION_SLEEPING 1<<2
#define POSITION_SITTING 1<<3
#define POSITION_STANDING 1<<4

//exit/room constants:
#define EXIT_NOWHERE -1
#define ROOM_NOWHERE -1
#define ROOM_START 1

//Direction defines for subcmd.
#define DIR_NORTH 1
#define DIR_SOUTH 2
#define DIR_EAST 3
#define DIR_WEST 4
#define DIR_NORTHEAST 5
#define DIR_NORTHWEST 6
#define DIR_SOUTHEAST 7
#define DIR_SOUTHWEST 8
#define DIR_UP 9
#define DIR_DOWN 10

enum ExitDirection
{
    nowhere, north, south, east, west, northeast, northwest, southeast, southwest, up, down
};
//colors:
#define C_NORMAL "\x1B[0m"
#define C_RED "\x1B[31m"
#define C_GREEN "\x1B[32m"
#define C_YELLOW "\x1B[33m"
#define C_BLUE "\x1B[34m"
#define C_MAGENTA "\x1B[35m"
#define C_CYAN "\x1B[36m"
#define C_WHITE "\x1B[37m"
#define C_RESET "\033[0m"
//bold
#define CB_RED "\x1B[1;31m"
#define CB_GREEN "\x1B[1;32m"
#define CB_YELLOW "\x1B[1;33m"
#define CB_BLUE "\x1B[1;34m"
#define CB_MAGENTA "\x1B[1;35m"
#define CB_CYAN "\x1B[1;36m"
#define CB_WHITE "\x1B[1;37m"

//msdp defines.
#define MSDP_VAR                       1
#define MSDP_VAL                       2
#define MSDP_TABLE_OPEN                3
#define MSDP_TABLE_CLOSE               4
#define MSDP_ARRAY_OPEN                5
#define MSDP_ARRAY_CLOSE               6
#define MAX_MSDP_SIZE                  100
//MSDP indexes

#define MSDP_CHARNAME 0
#define MSDP_SERVERTIME 1
#define MSDP_AFFECTS 2
#define MSDP_EXPERIENCE 3
#define MSDP_MAXEXPERIENCE 4
#define MSDP_TNL 5
#define MSDP_HEALTH 6
#define MSDP_MAXHEALTH 7
#define MSDP_LEVEL 8
#define MSDP_MONEY 9
#define MSDP_STR 10
#define MSDP_DEX 11
#define MSDP_CON 12
#define MSDP_INT 13
#define MSDP_PER 14
#define MSDP_BASESTR 15
#define MSDP_BASEDEX 16
#define MSDP_BASECON 17
#define MSDP_BASEINT 18
#define MSDP_BASEPER 19
#define MSDP_OPPONENTHEALTH 20
#define MSDP_MAXOPPONENTHEALTH 21
#define MSDP_OPPONENTNAME 22
#define MSDP_AREA 23
#define MSDP_EXITS 24
#define MSDP_ROOM 25
#define MSDP_RVNUM 29
#define MSDP_MAX 30
#endif


text:
type: post100
title:  Management Center
categories: XAP100ADM
parent: none
weight: 100
---

XAP Management Center is a GUI that allows you to view spaces, containers, and clusters and configure them, using the Space Browser tab. You can also deploy and manage services using the Deployments tab.

<br>

{{%fpanel%}}

[Menus and Buttons](./gigaspaces-browser-menus-and-buttons.html){{<wbr>}}
Using the File menu, Container menu, Space menu, Cluster menu, Windows menu, Help menu, button toolbar, and address bar.

[Tree Panel and Configurations](./gigaspaces-browser-tree-panel-and-configuration-panel.html){{<wbr>}}
Using the Grid Tree and the Configuration Panel on the right.

[Space Containers](./gigaspaces-browser-managing-space-container.html){{<wbr>}}
Using the Space Container Configuration tab of a container node in the Grid Tree, and tool buttons relevant for containers.

[Working with Clusters](./working-with-clusters-gigaspaces-browser.html){{<wbr>}}
Creating a cluster, replication options, load-balancing options, failover options, verifying and editing cluster definitions, visualizing clusters.

[Working with Spaces](./working-with-spaces-gigaspaces-browser.html){{<wbr>}}
Performing operations on a space in the XAP Browser.

[Pending Notifications](./pending-notify-templates-information.html){{<wbr>}}
Information regarding pending notify templates
 {{%/fpanel%}}


text:
package eventsourcex_test

import (
	"testing"

	"github.com/nats-io/go-nats"
	"github.com/stretchr/testify/assert"
)

func TestSubscribeNotices(t *testing.T) {
	nc, err := nats.Connect(nats.DefaultURL)
	assert.Nil(t, err)
	defer nc.Close()
}


text:
package main

import (
	"bufio"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"camlistore.org/pkg/cmdmain"
	"camlistore.org/pkg/context"
	"camlistore.org/pkg/deploy/gce"

	"camlistore.org/third_party/golang.org/x/oauth2"
)

type gceCmd struct {
	project  string
	zone     string
	machine  string
	instName string
	hostname string
	certFile string
	keyFile  string
	sshPub   string
	verbose  bool
}

func init() {
	cmdmain.RegisterCommand("gce", func(flags *flag.FlagSet) cmdmain.CommandRunner {
		cmd := new(gceCmd)
		flags.StringVar(&cmd.project, "project", "", "Name of Project.")
		flags.StringVar(&cmd.zone, "zone", gce.Zone, "GCE zone.")
		flags.StringVar(&cmd.machine, "machine", gce.Machine, "e.g. n1-standard-1, f1-micro, g1-small")
		flags.StringVar(&cmd.instName, "instance_name", gce.InstanceName, "Name of VM instance.")
		flags.StringVar(&cmd.hostname, "hostname", "", "Hostname for the instance and self-signed certificates. Must be given if generating self-signed certs.")
		flags.StringVar(&cmd.certFile, "cert", "", "Certificate file for TLS. A self-signed one will be generated if this flag is omitted.")
		flags.StringVar(&cmd.keyFile, "key", "", "Key file for the TLS certificate. Must be given with --cert")
		flags.StringVar(&cmd.sshPub, "ssh_public_key", "", "SSH public key file to authorize. Can modify later in Google's web UI anyway.")
		flags.BoolVar(&cmd.verbose, "verbose", false, "Be verbose.")
		return cmd
	})
}

const (
	clientIdDat     = "client-id.dat"
	clientSecretDat = "client-secret.dat"
	helpEnableAuth  = `Enable authentication: in your project console, navigate to "APIs and auth", "Credentials", click on "Create new Client ID", and pick "Installed application", with type "Other". Copy the CLIENT ID to ` + clientIdDat + `, and the CLIENT SECRET to ` + clientSecretDat
)

func (c *gceCmd) Describe() string {
	return "Deploy Camlistore on Google Compute Engine."
}

func (c *gceCmd) Usage() {
	fmt.Fprintf(os.Stderr, "Usage:\n\n    %s\n    %s\n\n",
		"camdeploy gce --project=<project> --hostname=<hostname> [options]",
		"camdeploy gce --project=<project> --cert=<cert file> --key=<key file> [options]")
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "\nTo get started:\n")
	printHelp()
}

func printHelp() {
	for _, v := range []string{gce.HelpCreateProject, helpEnableAuth, gce.HelpEnableAPIs} {
		fmt.Fprintf(os.Stderr, "%v\n", v)
	}
}

func (c *gceCmd) RunCommand(args []string) error {
	if c.verbose {
		gce.Verbose = true
	}
	if c.project == "" {
		return cmdmain.UsageError("Missing --project flag.")
	}
	if (c.certFile == "") != (c.keyFile == "") {
		return cmdmain.UsageError("--cert and --key must both be given together.")
	}
	if c.certFile == "" && c.hostname == "" {
		return cmdmain.UsageError("Either --hostname, or --cert & --key must provided.")
	}
	config := gce.NewOAuthConfig(readFile(clientIdDat), readFile(clientSecretDat))
	config.RedirectURL = "urn:ietf:wg:oauth:2.0:oob"

	instConf := &gce.InstanceConf{
		Name:     c.instName,
		Project:  c.project,
		Machine:  c.machine,
		Zone:     c.zone,
		CertFile: c.certFile,
		KeyFile:  c.keyFile,
		Hostname: c.hostname,
	}
	if c.sshPub != "" {
		instConf.SSHPub = strings.TrimSpace(readFile(c.sshPub))
	}

	depl := &gce.Deployer{
		Client: oauth2.NewClient(oauth2.NoContext, oauth2.ReuseTokenSource(nil,
			&tokenSource{config: config, cacheFile: c.project + "-token.json"})),
		Conf: instConf,
	}
	inst, err := depl.Create(context.TODO())
	if err != nil {
		return err
	}

	log.Printf("Instance is up at %s", inst.NetworkInterfaces[0].AccessConfigs[0].NatIP)
	return nil
}

func readFile(v string) string {
	slurp, err := ioutil.ReadFile(v)
	if err != nil {
		if os.IsNotExist(err) {
			msg := fmt.Sprintf("%v does not exist.", v)
			if v == clientIdDat || v == clientSecretDat {
				msg = fmt.Sprintf("%v\n%s", msg, helpEnableAuth)
			}
			log.Fatal(msg)
		}
		log.Fatalf("Error reading %s: %v", v, err)
	}
	return strings.TrimSpace(string(slurp))
}

type tokenSource struct {
	config    *oauth2.Config
	cacheFile string
}

func (src tokenSource) Token() (*oauth2.Token, error) {
	tok := new(oauth2.Token)
	tokenData, err := ioutil.ReadFile(src.cacheFile)
	if err == nil {
		err = json.Unmarshal(tokenData, tok)
		if err == nil {
			if tok.Valid() {
				return tok, nil
			}
			err = errors.New("invalid token")
		}
	}
	fmt.Printf("Error getting token from %s: %v\n", src.cacheFile, err)
	fmt.Println("Get auth code from:")
	fmt.Printf("%v\n", src.config.AuthCodeURL("my-state", oauth2.AccessTypeOffline, oauth2.ApprovalForce))
	fmt.Println("Enter auth code:")
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	authCode := strings.TrimSpace(sc.Text())
	tok, err = src.config.Exchange(oauth2.NoContext, authCode)
	if err != nil {
		return nil, fmt.Errorf("could not exchange auth code for a token: %v", err)
	}
	tokenData, err = json.Marshal(&tok)
	if err != nil {
		return nil, fmt.Errorf("could not encode token as json: %v", err)
	}
	if err := ioutil.WriteFile(src.cacheFile, tokenData, 0600); err != nil {
		return nil, fmt.Errorf("could not cache token in %v: %v", src.cacheFile, err)
	}
	return tok, nil
}


text:
package org.hisp.dhis.webapi.mvc.messageconverter;

import static org.hisp.dhis.webapi.mvc.messageconverter.MessageConverterUtils.getContentDispositionHeaderValue;
import static org.hisp.dhis.webapi.mvc.messageconverter.MessageConverterUtils.isAttachment;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Nonnull;

import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.common.Compression;
import org.hisp.dhis.node.NodeService;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;

/**
 * Abstract base class for HTTP message converters that convert root nodes.
 *
 * @author Volker Schmidt <volker@dhis2.org>
 */
public abstract class AbstractRootNodeMessageConverter extends AbstractHttpMessageConverter<RootNode>
{
    private static final String METADATA_ATTACHMENT = "metadata";

    private final NodeService nodeService;

    private final String contentType;

    private final String fileExtension;

    private final Compression compression;

    protected AbstractRootNodeMessageConverter( @Nonnull NodeService nodeService, @Nonnull String contentType,
        @Nonnull String fileExtension, Compression compression )
    {
        this.nodeService = nodeService;
        this.contentType = contentType;
        this.fileExtension = fileExtension;
        this.compression = compression;
    }

    protected Compression getCompression()
    {
        return compression;
    }

    @Override
    protected boolean supports( Class<?> clazz )
    {
        return RootNode.class.equals( clazz );
    }

    @Override
    protected boolean canRead( MediaType mediaType )
    {
        return false;
    }

    @Override
    protected RootNode readInternal( Class<? extends RootNode> clazz, HttpInputMessage inputMessage )
    {
        return null;
    }

    @Override
    protected void writeInternal( RootNode rootNode, HttpOutputMessage outputMessage )
        throws IOException,
        HttpMessageNotWritableException
    {
        final String contentDisposition = outputMessage.getHeaders()
            .getFirst( ContextUtils.HEADER_CONTENT_DISPOSITION );
        final boolean attachment = isAttachment( contentDisposition );
        final String extensibleAttachmentFilename = StringUtils
            .substringBefore( ContextUtils.getAttachmentFileName( contentDisposition ), "." );

        if ( Compression.GZIP == compression )
        {
            if ( !attachment || (extensibleAttachmentFilename != null
                && extensibleAttachmentFilename.equalsIgnoreCase( METADATA_ATTACHMENT )) )
            {
                outputMessage.getHeaders().set( ContextUtils.HEADER_CONTENT_DISPOSITION,
                    getContentDispositionHeaderValue( extensibleAttachmentFilename, "gz" ) );
                outputMessage.getHeaders().set( ContextUtils.HEADER_CONTENT_TRANSFER_ENCODING, "binary" );
            }

            GZIPOutputStream outputStream = new GZIPOutputStream( outputMessage.getBody() );
            nodeService.serialize( rootNode, contentType, outputStream );
            outputStream.close();
        }
        else if ( Compression.ZIP == compression )
        {
            if ( !attachment || (extensibleAttachmentFilename != null
                && extensibleAttachmentFilename.equalsIgnoreCase( METADATA_ATTACHMENT )) )
            {
                outputMessage.getHeaders().set( ContextUtils.HEADER_CONTENT_DISPOSITION,
                    getContentDispositionHeaderValue( extensibleAttachmentFilename, "zip" ) );
                outputMessage.getHeaders().set( ContextUtils.HEADER_CONTENT_TRANSFER_ENCODING, "binary" );
            }

            ZipOutputStream outputStream = new ZipOutputStream( outputMessage.getBody() );
            outputStream.putNextEntry( new ZipEntry( extensibleAttachmentFilename + "." + fileExtension ) );

            nodeService.serialize( rootNode, contentType, outputStream );
            outputStream.close();
        }
        else
        {
            if ( extensibleAttachmentFilename != null
                && extensibleAttachmentFilename.equalsIgnoreCase( METADATA_ATTACHMENT ) )
            {
                outputMessage.getHeaders().set( ContextUtils.HEADER_CONTENT_DISPOSITION,
                    getContentDispositionHeaderValue( extensibleAttachmentFilename, null ) );
            }

            nodeService.serialize( rootNode, contentType, outputMessage.getBody() );
            outputMessage.getBody().close();
        }
    }
}


text:
BSLS_IDENT("$Id$ $CSID$")

#include <bslstl_badweakptr.h>
#include <bslstl_deque.h>              // for testing only
#include <bslstl_list.h>               // for testing only
#include <bslstl_map.h>                // for testing only
#include <bslstl_string.h>             // for testing only
#include <bslstl_vector.h>             // for testing only

#include <bsls_alignmentutil.h>
#include <bsls_exceptionutil.h>

namespace BloombergLP {
namespace bslstl {

                             // -------------------
                             // class SharedPtrUtil
                             // -------------------

// MANIPULATORS
bsl::shared_ptr<char>
SharedPtrUtil::createInplaceUninitializedBuffer(
                                              size_t            bufferSize,
                                              bslma::Allocator *basicAllocator)
{
    basicAllocator = bslma::Default::allocator(basicAllocator);
                                                       // allocator is optional

    // We have alignment concerns here: there are no alignment issues with
    // 'bslstl::SharedPtrRep', but the buffer address (i.e., the address of
    // 'd_instance' in the 'bslstl::SharedPtrInplaceRep' object) must be at
    // least *naturally* *aligned* to 'bufferSize'.  See the 'bslma' package-
    // level documentation for a definition of natural alignment.)  We achieve
    // this in the simplest way by always maximally aligning the returned
    // pointer.

    typedef bslma::SharedPtrInplaceRep<bsls::AlignmentUtil::MaxAlignedType>
                                                                           Rep;

    enum {
        k_ALIGNMENT_MASK = ~(bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT - 1)
    };

    size_t repSize = (sizeof(Rep) + bufferSize - 1) & k_ALIGNMENT_MASK;

    Rep *rep = new (basicAllocator->allocate(repSize)) Rep(basicAllocator);

    return bsl::shared_ptr<char>(reinterpret_cast<char *>(rep->ptr()), rep);
}

void SharedPtr_ImpUtil::throwBadWeakPtr()
{
    BSLS_THROW(bsl::bad_weak_ptr());
}

}  // close package namespace
}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
module RubyChessBoard
  # Encapsulates a {BoardFiles} object, which allows it to track
  # the positions of pieces in a chess game.
  class Board
    class <<self
      # The board file names as an array of Symbols.
      # @return [Array<Symbol>]
      def file_names
        ('a'..'h').map(&:to_sym)
      end

      # The board rank names as an array of Integers.
      # @return [Array<Integer>]
      def rank_names
        (1..8).to_a
      end
    end

    # Initializes the board. If a {Board} is provided,
    # the piece positions will be the same. If none is provided
    # the board will be setup for a new game.
    # @param [Board] board the board to mirror
    def initialize(board = nil)
      if board
        @files = board.files.clone
      else
        @files = BoardFiles.new
        setup
      end
    end

    # Returns the board representation as a string.
    # @return [String]
    def print
      BoardPrinter.new(self).print
    end

    attr_reader :files

    # Returns the Coordinate of the piece provided if it
    # is on the board; otherwise returns nil.
    # @param [Piece] piece
    # @return [Coordinate, nil]
    def coordinates_of(piece)
      file = files.find { |f| f.has_piece?(piece) }

      return nil if file.nil?

      x = files.index(file)
      y = file.ranks.index(piece)

      Coordinate.new(x, y)
    end

    # Moves whatever is on one square to another.
    # @param [Symbol] from square name
    # @param [Symbol] to square name
    # @return [void]
    def move_piece(from, to)
      moving_piece = at_square(from)

      set_square(from, nil)
      set_square(to, moving_piece)
    end

    # Sets the chess board up.
    # @return [void]
    def setup
      Setup.new(board: self).setup
    end

    # Returns the value of a square, i.e. a1, h8.
    # @return [Piece, EmptySquare]
    def at_square(square_name)
      file, rank = file_and_rank(square_name)

      files[file].at_rank(rank)
    end

    # Sets the value of a square, i.e. a1, h8.
    # @return [void]
    def set_square(square_name, value)
      file, rank = file_and_rank(square_name)

      files[file].set_rank(rank, value)
    end

    # Returns all pieces of a given color.
    # @param [Symbol] color :white or :black
    # @return [Array<Piece>]
    def pieces(color)
      files.pieces(color)
    end

    Board.file_names.each do |file|
      Board.rank_names.each do |rank|
        square = "#{file}#{rank}"

        define_method(square) do
          at_square(square)
        end

        define_method("#{square}=") do |value|
          set_square(square, value)
        end
      end
    end

    private

    def file_and_rank(square_name)
      square_name = square_name.to_s
      file, rank  = square_name.split('')

      file = file.to_sym
      rank = rank.to_i

      return file, rank
    end
  end
end


text:
package com.example.android.sunshine.app;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import com.example.android.sunshine.app.data.IndexBDRestaurant;
import com.example.android.sunshine.app.data.RestaurantContract;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity  implements LoaderManager.LoaderCallbacks<Cursor> {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private Uri mUri;
    static final String DETAIL_URI = "URI";

    private static final int DETAIL_LOADER_MAP = 0;
    public static final String[] RESTAURANT_COLUMNS = {
            RestaurantContract.RestaurantEntry.TABLE_NAME + "." + RestaurantContract.RestaurantEntry._ID,
            RestaurantContract.RestaurantEntry.COLUMN_NAME,
            RestaurantContract.RestaurantEntry.COLUMN_ADRESSE,
            RestaurantContract.RestaurantEntry.COLUMN_VILLE,
            RestaurantContract.RestaurantEntry.COLUMN_CODEPOSTAL,
            RestaurantContract.RestaurantEntry.COLUMN_DESCRIPTION,
            RestaurantContract.RestaurantEntry.COLUMN_IMG_LIST,
            RestaurantContract.RestaurantEntry.COLUMN_IMAGE_FICHE,
            RestaurantContract.RestaurantEntry.COLUMN_LATITUDE,
            RestaurantContract.RestaurantEntry.COLUMN_LONGITUDE,
            RestaurantContract.RestaurantEntry.COLUMN_TELEPHONE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            System.out.println("onCreate");
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps2);
            setUpMapIfNeeded();

            // Enabling MyLocation Layer of Google Map
            mMap.setMyLocationEnabled(true);

            mUri = RestaurantContract.RestaurantEntry.CONTENT_URI;
            System.out.println("mUri" + mUri);

            // Invoke LoaderCallbacks to retrieve and draw already saved locations in map
            getSupportLoaderManager().initLoader(DETAIL_LOADER_MAP, null, this);
        }
        catch(Exception e)
        {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

//    private void getListRestaurants()
//    {
//        Cursor cursor = new Cursor();
//    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
    }

    private void ShowMarkerAtPosition(LatLng position, String sNomRestaurant, String sResume, Bitmap imageBitmap)
    {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(position);
        markerOption.draggable(false);
        markerOption.flat(false);//contre la carte ou face a la camero
        markerOption.visible(true);

        //Pour la bulle d'info du marker
        markerOption.title(sNomRestaurant);
//        markerOption.icon(BitmapDescriptorFactory.fromBitmap(imageBitmap));
        markerOption.snippet(sResume);

        mMap.addMarker(markerOption);
    }

    private void ShowCircleAtPosition(LatLng position)
    {
        //Configure le cercle
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(position);
        circleOptions.radius(5000);
        circleOptions.visible(true);

        //interieur du cercle
        circleOptions.fillColor(Color.BLUE);

        //contour du cercle
        circleOptions.strokeWidth(10);
        circleOptions.strokeColor(Color.CYAN);

        //Affiche le cercle
        mMap.addCircle(circleOptions);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int arg0,
                                         Bundle arg1) {
        System.out.println("Entre dans onCreateLoader ");

        // Uri to the content provider LocationsContentProvider
        Uri uri = mUri;// LocationsContentProvider.CONTENT_URI;

        // Fetches all the rows from locations table
        System.out.println("On sort onCreateLoader ");
        System.out.println("muri :  "+mUri);
        if (uri != null)
            return new CursorLoader(this, uri, RESTAURANT_COLUMNS, null, null, null);

        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor)
    {
        System.out.println("On est dans le onLoadFinished");
        int locationCount = 0;
        String nom = "";
        String description = "";
        Double latitude = 0.0;
        Double longitude = 0.0;

        //recuperation de l'image du restaurant
        Bitmap imageBitmap = null;

        //Affiche un cercle autour de la position actuelle
        Location currentLocation = mMap.getMyLocation();
        if (currentLocation != null) {
            Double currentLatitude = currentLocation.getLatitude();
            Double currentLongitude = currentLocation.getLongitude();
            if (currentLatitude != null && currentLongitude != null) {
                ShowCircleAtPosition(new LatLng(currentLatitude, currentLongitude));
            }
        }

        if (cursor == null) {
            return;
        }

        // Number of locations available in the SQLite database table
        locationCount = cursor.getCount();

        // Move the current record pointer to the first row of the table
        cursor.moveToFirst();

        for(int i=0;i<locationCount;i++)
        {
            //Initialisation des variables
            nom = cursor.getString(IndexBDRestaurant.INDEX_NOM);
            description = cursor.getString(IndexBDRestaurant.INDEX_DESCRIPTION);
            latitude = cursor.getDouble(IndexBDRestaurant.INDEX_LATITUDE);
            longitude = cursor.getDouble(IndexBDRestaurant.INDEX_LONGITUDE);
            //pour l'image
//            byte[] image = cursor.getBlob(IndexBDRestaurant.INDEX_IMAGE_LISTE);
//            if (image != null) {
//                imageBitmap = Utility.getImage(image);
//
//            }
            // Drawing the marker in the Google Maps
            ShowMarkerAtPosition(new LatLng(latitude, longitude), nom, description,imageBitmap);

            // Traverse the pointer to the next row
            cursor.moveToNext();
        }

        if(locationCount>0){
            // Moving CameraPosition to last clicked position
            mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(0, 0)));

            // Setting the zoom level in the map on last position  is clicked
            mMap.animateCamera(CameraUpdateFactory.zoomTo(0));
        }
        System.out.println("On sort du onLoadFinished");
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
    }
}


text:
using System;
using System.Threading.Tasks;

namespace KatanaContrib.Security.Odnoklassniki
{
    public class OdnoklassnikiAuthenticationProvider : IOdnoklassnikiAuthenticationProvider
    {
        public OdnoklassnikiAuthenticationProvider()
        {
            OnAuthenticated = context => Task.FromResult<object>(null);
            OnReturnEndpoint = context => Task.FromResult<object>(null);
        }

        public Func<OdnoklassnikiAuthenticatedContext, Task> OnAuthenticated { get; set; }
        public Func<OdnoklassnikiReturnEndpointContext, Task> OnReturnEndpoint { get; set; }

        public virtual Task Authenticated(OdnoklassnikiAuthenticatedContext context)
        {
            return OnAuthenticated(context);
        }

        public virtual Task ReturnEndpoint(OdnoklassnikiReturnEndpointContext context)
        {
            return OnReturnEndpoint(context);
        }
    }
}


text:
package org.sonar.plugins.oauth2.provider;

import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.sonar.api.config.Settings;

public interface OAuth2Provider {

  String getAuthzEndpoint();

  String getProviderName();

  String getTokenEndpoint();

  OAuthClientRequest.AuthenticationRequestBuilder createRedirectRequestBuilder(Settings settings);

  OAuthClientRequest.TokenRequestBuilder createTokenRequestBuilder(Settings settings, String code);

}


text:
layout: shell
application_name: workspace
design_title: Settings form People
---

        {{ page.workspace_name }}

        	{{ content }}

				         .tabs-content; source: #workspace-settings > .tabs-content">General
				         .tabs-content; source: #workspace-settings > .tabs-content">Members
				         .tabs-content; source: #workspace-settings > .tabs-content">Security
				         .tabs-content; source: #workspace-settings > .tabs-content">Advanced

					    {% include item-selector.html action="/feedback/batch-change-roles.html" autosubmit="false" inject="target: body::after; source: #content" feedback="/feedback/batch-change-roles.html" mode="users" toggle="true" listitems="follow" buttons="batch-operations add-members" controls="pull-menu" title="Members" labels="true" id="member-list" followinject="source: #document-body; target: #document-body" %}


text:
package org.jbox2d.util.blob;

import org.jbox2d.common.Vec2;

public class BlobPoint {
	public Vec2 position;
	public float mass = 1.0f;

	public BlobPoint(float x, float y) {
		position = new Vec2(x,y);
	}
}


text:
package me.nithanim.gw2api.v2.api.worlds;

import me.nithanim.gw2api.v2.ApiEndpoint;

/** This resource returns information about the available worlds, or servers. */
public interface WorldsResource extends ApiEndpoint {
  /**
   * A list with all possible ids.
   *
   * @return
   */
  int[] getOverview();

  World get(int id);

  World[] get(int[] ids);

  World get(int id, String language);

  World[] get(int[] ids, String language);
}


text:
<!DOCTYPE html>

        <title>Riverrun</title>
        <meta charset="utf-8">
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
        <link href="/static/index.css" rel="stylesheet">

                        <input type="text" placeholder="Search by title, authors, …">