text:
package memorytopo

import (
	"fmt"
	"path"

	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/vt/topo"

	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

// UpdateShardReplicationFields implements topo.Impl.UpdateShardReplicationFields
func (mt *MemoryTopo) UpdateShardReplicationFields(ctx context.Context, cell, keyspace, shard string, update func(*topodatapb.ShardReplication) error) error {
	p := path.Join(keyspacesPath, keyspace, shardsPath, shard, topo.ShardReplicationFile)

	for {
		data, version, err := mt.Get(ctx, cell, p)
		sr := &topodatapb.ShardReplication{}
		switch err {
		case topo.ErrNoNode:
			// Empty node, version is nil
		case nil:
			// Use any data we got.
			if err = proto.Unmarshal(data, sr); err != nil {
				return fmt.Errorf("bad ShardReplication data %v", err)
			}
		default:
			return err
		}

		err = update(sr)
		switch err {
		case topo.ErrNoUpdateNeeded:
			return nil
		case nil:
			// keep going
		default:
			return err
		}

		// marshall and save
		data, err = proto.Marshal(sr)
		if err != nil {
			return err
		}
		if version == nil {
			// We have to create, and we catch ErrNodeExists.
			_, err = mt.Create(ctx, cell, p, data)
			if err != topo.ErrNodeExists {
				return err
			}
		} else {
			// We have to update, and we catch ErrBadVersion.
			_, err = mt.Update(ctx, cell, p, data, version)
			if err != topo.ErrBadVersion {
				return err
			}
		}
	}
}

// GetShardReplication implements topo.Impl.GetShardReplication
func (mt *MemoryTopo) GetShardReplication(ctx context.Context, cell, keyspace, shard string) (*topo.ShardReplicationInfo, error) {
	p := path.Join(keyspacesPath, keyspace, shardsPath, shard, topo.ShardReplicationFile)
	data, _, err := mt.Get(ctx, cell, p)
	if err != nil {
		return nil, err
	}

	sr := &topodatapb.ShardReplication{}
	if err = proto.Unmarshal(data, sr); err != nil {
		return nil, fmt.Errorf("bad ShardReplication data %v", err)
	}

	return topo.NewShardReplicationInfo(sr, cell, keyspace, shard), nil
}

// DeleteShardReplication implements topo.Impl.DeleteShardReplication
func (mt *MemoryTopo) DeleteShardReplication(ctx context.Context, cell, keyspace, shard string) error {
	p := path.Join(keyspacesPath, keyspace, shardsPath, shard, topo.ShardReplicationFile)
	return mt.Delete(ctx, cell, p, nil)
}

// DeleteKeyspaceReplication implements topo.Impl.DeleteKeyspaceReplication
func (mt *MemoryTopo) DeleteKeyspaceReplication(ctx context.Context, cell, keyspace string) error {
	p := path.Join(keyspacesPath, keyspace)
	return mt.Delete(ctx, cell, p, nil)
}


text:
package org.sewas.service;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sewas.client.OpenLigaDBClient;
import org.sewas.domain.model.LeagueTable;
import org.sewas.domain.model.Match;
import org.sewas.domain.model.TeamPosition;
import org.sewas.exception.OpenLigaDbNotOkException;
import org.sewas.exception.SeasonNotAvailableException;
import org.sewas.rest.dto.MatchDTO;
import org.sewas.util.ListSearch;
import org.sewas.util.MatchBuilder;
import org.sewas.util.MatchResultBuilder;
import org.sewas.util.TeamBuilder;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;

/**
 * Created by sebastian on 16/06/17.
 */
@RunWith(MockitoJUnitRunner.class)
public class LeagueTableServiceGuestTeamWinTest {

    @InjectMocks
    private LeagueTableService underTest;

    @Mock
    private OpenLigaDBClient mockClient;

    TeamPosition tp1;
    TeamPosition tp2;

    @Before
    public void setUp() throws SeasonNotAvailableException, OpenLigaDbNotOkException {
        ListSearch listSearch = new ListSearch();

        // given
        Match match4test = new MatchBuilder()
                .withTeam1(new TeamBuilder()
                        .withTeamName("HomeTeam")
                        .build())
                .withTeam2(new TeamBuilder()
                        .withTeamName("GuestTeam")
                        .build())
                .withResult(new MatchResultBuilder()
                        .withPointsForTeam1(0)
                        .withPointsForTeam2(0)
                        .build())
                .withResult(new MatchResultBuilder()
                        .withPointsForTeam1(0)
                        .withPointsForTeam2(1)
                        .build())
                .isFinished(true)
                .build();

        MatchDTO mockMatchDto = new MatchDTO();
        mockMatchDto.setMatches(Arrays.asList(match4test));

        given(this.mockClient.getMatchesForLeagueMatchday(anyString(), anyString())).willReturn(mockMatchDto);

        // when
        LeagueTable receivedLeagueTable = this.underTest.returnCurrentLeagueTable("anyLeagueID", "anyYear");

        this.tp1 = listSearch.findTeamPositionByTeamname("HomeTeam", receivedLeagueTable);
        this.tp2 = listSearch.findTeamPositionByTeamname("GuestTeam", receivedLeagueTable);
    }

    @Test
    public void shouldCalculatePoints() {
        // then
        assertThat(this.tp1.getPoints()).isEqualTo(0);
        assertThat(this.tp2.getPoints()).isEqualTo(3);
    }

    @Test
    public void shouldCalculatePositions() {
        // then
        assertThat(this.tp1.getPosition()).isEqualTo(2);
        assertThat(this.tp2.getPosition()).isEqualTo(1);
    }

    @Test
    public void shouldCalculateVictoryTieLoss() {
        // then
        assertThat(tp1.getNumberOfLoss()).isEqualTo(1);
        assertThat(tp1.getNumberOfTies()).isEqualTo(0);
        assertThat(tp1.getNumberOfVictories()).isEqualTo(0);
        assertThat(tp1.getNumberOfMatchDays()).isEqualTo(1);

        assertThat(tp2.getNumberOfLoss()).isEqualTo(0);
        assertThat(tp2.getNumberOfTies()).isEqualTo(0);
        assertThat(tp2.getNumberOfVictories()).isEqualTo(1);
        assertThat(tp2.getNumberOfMatchDays()).isEqualTo(1);
    }

    @Test
    public void shouldCalculateGoalDifference() {
        // then
        assertThat(tp1.getGoalsFor()).isEqualTo(0);
        assertThat(tp1.getGoalsAgainst()).isEqualTo(1);

        assertThat(tp2.getGoalsFor()).isEqualTo(1);
        assertThat(tp2.getGoalsAgainst()).isEqualTo(0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Avalonia;
using Avalonia.Browser.Blazor;

namespace ControlCatalog.Browser.Blazor;

public partial class App
{
    protected override void OnParametersSet()
    {
        AppBuilder.Configure<ControlCatalog.App>()
            .UseBlazor()
            // .With(new SkiaOptions { CustomGpuFactory = null }) // uncomment to disable GPU/GL rendering
            .SetupWithSingleViewLifetime();

        base.OnParametersSet();
    }
}


text:
namespace tesseract {

ELISTIZE(WorkingPartSet)

// Add the partition to this WorkingPartSet. Unrelated partitions are
// stored in the order in which they are received, but if the partition
// has a SingletonPartner, make sure that it stays with its partner.
void WorkingPartSet::AddPartition(ColPartition* part) {
  ColPartition* partner = part->SingletonPartner(true);
  if (partner != nullptr) {
    ASSERT_HOST(partner->SingletonPartner(false) == part);
  }
  if (latest_part_ == nullptr || partner == nullptr) {
    // This partition goes at the end of the list
    part_it_.move_to_last();
  } else if (latest_part_->SingletonPartner(false) != part) {
    // Reposition the iterator to the correct partner, or at the end.
    for (part_it_.move_to_first(); !part_it_.at_last() &&
         part_it_.data() != partner;
         part_it_.forward());
  }
  part_it_.add_after_then_move(part);
  latest_part_ = part;
}

// Make blocks out of any partitions in this WorkingPartSet, and append
// them to the end of the blocks list. bleft, tright and resolution give
// the bounds and resolution of the source image, so that blocks can be
// made to fit in the bounds.
// All ColPartitions go in the used_parts list, as they need to be kept
// around, but are no longer needed.
void WorkingPartSet::ExtractCompletedBlocks(const ICOORD& bleft,
                                            const ICOORD& tright,
                                            int resolution,
                                            ColPartition_LIST* used_parts,
                                            BLOCK_LIST* blocks,
                                            TO_BLOCK_LIST* to_blocks) {
  MakeBlocks(bleft, tright, resolution, used_parts);
  BLOCK_IT block_it(blocks);
  block_it.move_to_last();
  block_it.add_list_after(&completed_blocks_);
  TO_BLOCK_IT to_block_it(to_blocks);
  to_block_it.move_to_last();
  to_block_it.add_list_after(&to_blocks_);
}

// Insert the given blocks at the front of the completed_blocks_ list so
// they can be kept in the correct reading order.
void WorkingPartSet::InsertCompletedBlocks(BLOCK_LIST* blocks,
                                           TO_BLOCK_LIST* to_blocks) {
  BLOCK_IT block_it(&completed_blocks_);
  block_it.add_list_before(blocks);
  TO_BLOCK_IT to_block_it(&to_blocks_);
  to_block_it.add_list_before(to_blocks);
}

// Make a block using lines parallel to the given vector that fit between
// the min and max coordinates specified by the ColPartitions.
// Construct a block from the given list of partitions.
void WorkingPartSet::MakeBlocks(const ICOORD& bleft, const ICOORD& tright,
                                int resolution, ColPartition_LIST* used_parts) {
  part_it_.move_to_first();
  while (!part_it_.empty()) {
    // Gather a list of ColPartitions in block_parts that will be split
    // by linespacing into smaller blocks.
    ColPartition_LIST block_parts;
    ColPartition_IT block_it(&block_parts);
    ColPartition* next_part = nullptr;
    bool text_block = false;
    do {
      ColPartition* part = part_it_.extract();
      if (part->blob_type() == BRT_UNKNOWN ||
          (part->IsTextType() && part->type() != PT_TABLE))
        text_block = true;
      part->set_working_set(nullptr);
      part_it_.forward();
      block_it.add_after_then_move(part);
      next_part = part->SingletonPartner(false);
      if (part_it_.empty() || next_part != part_it_.data()) {
        // Sequences of partitions can get split by titles.
        next_part = nullptr;
      }
      // Merge adjacent blocks that are of the same type and let the
      // linespacing determine the real boundaries.
      if (next_part == nullptr && !part_it_.empty()) {
        ColPartition* next_block_part = part_it_.data();
        const TBOX& part_box = part->bounding_box();
        const TBOX& next_box = next_block_part->bounding_box();

        // In addition to the same type, the next box must not be above the
        // current box, nor (if image) too far below.
        PolyBlockType type = part->type(), next_type = next_block_part->type();
        if (ColPartition::TypesSimilar(type, next_type) &&
            !part->IsLineType() && !next_block_part->IsLineType() &&
            next_box.bottom() <= part_box.top() &&
            (text_block || part_box.bottom() <= next_box.top()))
          next_part = next_block_part;
      }
    } while (!part_it_.empty() && next_part != nullptr);
    if (!text_block) {
      TO_BLOCK* to_block = ColPartition::MakeBlock(bleft, tright,
                                                   &block_parts, used_parts);
      if (to_block != nullptr) {
        TO_BLOCK_IT to_block_it(&to_blocks_);
        to_block_it.add_to_end(to_block);
        BLOCK_IT block_it(&completed_blocks_);
        block_it.add_to_end(to_block->block);
      }
    } else {
      // Further sub-divide text blocks where linespacing changes.
      ColPartition::LineSpacingBlocks(bleft, tright, resolution, &block_parts,
                                      used_parts,
                                      &completed_blocks_, &to_blocks_);
    }
  }
  part_it_.set_to_list(&part_set_);
  latest_part_ = nullptr;
  ASSERT_HOST(completed_blocks_.length() == to_blocks_.length());
}

}  // namespace tesseract.


text:
def cvt(s):
    if isinstance(s, str):
        return unicode(s)
    return s

class GWTCanvasImplDefault:

    def createElement(self):
        e = DOM.createElement("CANVAS")
        self.setCanvasContext(e.MozGetIPCContext(u'2d'))
        return e


text:
{% extends "base.html" %}
{% load static %}
{% load i18n %}
{% load thumbnail %}
{% load humanize %}
{% load filter_tags %}
{% block content %}
  {% include 'includes/search-form.html' %}

            Distance

            <form action="{% url 'sales:distance' %}" method="POST">
                {% csrf_token %}

                        {{distance.distance|add_css:'form-control'}}

                        <input type="submit" class="btn btn-primary btn-block" value="Update Search">

            </form>

            {% if subscribed %}
              Unsubscribe
            {% else %}
              Subscribe
            {% endif %}

        </form>

          {% include 'includes/messages.html' %}
          {% for property in object_list %}

                  {% with property.salepicture_set.all|first as picture %}
                    {% thumbnail picture.attachment "285x200" crop="center" as im %}

                    {% endthumbnail %}
                  {% endwith %}

{{property.title}}

{{ property.display_address }}{{property.get_qualifier_display}} £{{property.price|floatformat|intcomma}}

{{property.summary}}

          {% empty %}

{% trans 'No properties were found for your search' %}

          {% endfor %}
          {% include 'includes/pagination.html' %}

{% endblock %}
{% block footer_scripts%}
  {{block.super}}

{% endblock %}


text:
package org.kaaproject.kaa.server.admin.shared.services;

public class KaaAdminServiceException extends Exception {

  private static final long serialVersionUID = 1L;

  private ServiceErrorCode errorCode;

  public KaaAdminServiceException() {
    super();
  }

  public KaaAdminServiceException(ServiceErrorCode errorCode) {
    this.errorCode = errorCode;
  }

  public KaaAdminServiceException(String message, ServiceErrorCode errorCode) {
    super(message);
    this.errorCode = errorCode;
  }

  public KaaAdminServiceException(String message, Throwable cause, ServiceErrorCode errorCode) {
    super(message, cause);
    this.errorCode = errorCode;
  }

  public KaaAdminServiceException(Throwable cause, ServiceErrorCode errorCode) {
    super(cause);
    this.errorCode = errorCode;
  }

  public ServiceErrorCode getErrorCode() {
    return errorCode;
  }

}


text:
import net.quasardb.qdb.exception.*;
import net.quasardb.qdb.*;
import net.quasardb.qdb.exception.*;
import org.junit.*;

public class QdbClusterFindNodeForTest {
    @Test
    public void returnsAddressAndPort() {
        QdbCluster cluster = Helpers.createCluster();
        String alias = Helpers.createUniqueAlias();

        QdbNode node = cluster.findNodeFor(alias);
        Assert.assertEquals("127.0.0.1", node.hostName());
        Assert.assertEquals(Daemon.port(), node.port());
    }

    @Test(expected = ClusterClosedException.class)
    public void throwsClusterClosed_afterCallingClose() {
        QdbCluster cluster = Helpers.createCluster();
        String alias = Helpers.createUniqueAlias();

        cluster.close();
        cluster.findNodeFor(alias); // <- throws
    }
}


text:
/*
Zenburn style from voldmar.ru (c) Vladimir Epifanov <voldmar@voldmar.ru>
based on dark.css by Ivan Sagalaev
*/

.hljs {
  display: block;
  overflow-x: auto;
  color: #dcdcdc;
  -webkit-text-size-adjust: none;
}

.hljs-keyword,
.hljs-tag,
.css .hljs-class,
.css .hljs-id,
.lisp .hljs-title,
.nginx .hljs-title,
.hljs-request,
.hljs-status,
.clojure .hljs-attribute {
  color: #bbdaff;
}

.django .hljs-template_tag,
.django .hljs-variable,
.django .hljs-filter .hljs-argument {
  color: #dcdcdc;
}

.hljs-number,
.hljs-date {
  color: #8cd0d3;
}

.dos .hljs-envvar,
.dos .hljs-stream,
.hljs-variable,
.apache .hljs-sqbracket,
.hljs-name {
  color: #efdcbc;
}

.dos .hljs-flow,
.diff .hljs-change,
.python .exception,
.python .hljs-built_in,
.hljs-literal,
.tex .hljs-special {
  color: #efefaf;
}

.diff .hljs-chunk,
.hljs-subst {
  color: #8f8f8f;
}

.dos .hljs-keyword,
.hljs-decorator,
.hljs-title,
.hljs-type,
.diff .hljs-header,
.ruby .hljs-class .hljs-parent,
.apache .hljs-tag,
.nginx .hljs-built_in,
.tex .hljs-command,
.hljs-prompt {
  color: #efef8f;
}

.dos .hljs-winutils,
.ruby .hljs-symbol,
.ruby .hljs-symbol .hljs-string,
.ruby .hljs-string {
  color: #dca3a3;
}

.diff .hljs-deletion,
.hljs-string,
.hljs-tag .hljs-value,
.hljs-preprocessor,
.hljs-pragma,
.hljs-built_in,
.smalltalk .hljs-class,
.smalltalk .hljs-localvars,
.smalltalk .hljs-array,
.css .hljs-rule .hljs-value,
.hljs-attr_selector,
.hljs-pseudo,
.apache .hljs-cbracket,
.tex .hljs-formula,
.coffeescript .hljs-attribute {
  color: #d1f1a9;
}

.hljs-shebang,
.diff .hljs-addition,
.hljs-comment,
.hljs-annotation,
.hljs-pi,
.hljs-doctype {
  color: #7f9f7f;
}

.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
  opacity: 0.5;
}

pre code {
  display: block;
  font-family: "Fira Mono", "Source Code Pro", "Inconsolata", Menlo, monospace !important;
  line-height: 1.5 !important;
  padding: 10px;
}


text:
<?php
namespace TFox\PangalinkBundle\Connector\IPizza;

use Symfony\Component\HttpFoundation\Request;
use TFox\PangalinkBundle\Response\BankResponse;
use TFox\PangalinkBundle\Exception\CertificateNotFoundException;
use TFox\PangalinkBundle\Exception\BadSignatureException;
use TFox\PangalinkBundle\Exception\UnsupportedServiceIdException;
use TFox\PangalinkBundle\Exception\CannotGenerateSignatureException;
use TFox\PangalinkBundle\Exception\MissingMandatoryParameterException;
use TFox\PangalinkBundle\Connector\AbstractConnector;
use TFox\PangalinkBundle\Exception\KeyFileNotFoundException;

/**
 * Common methods for IPizza protocol
 */
abstract class AbstractIPizzaConnector extends AbstractConnector
{

    public function getPrivateKey()
    {
        $keyFilePath = sprintf('%s%s%s', $this->getPangalinkService()->getKernelRootPath(),
            DIRECTORY_SEPARATOR, $this->getConfigurationValue('private_key'));

        if (false == file_exists($keyFilePath)) {
            throw new KeyFileNotFoundException($keyFilePath);
        }

        $key = file_get_contents($keyFilePath);
        return $key;
    }

    public function getBankCertificate()
    {
        $keyFilePath = sprintf('%s%s%s', $this->getPangalinkService()->getKernelRootPath(),
            DIRECTORY_SEPARATOR, $this->getConfigurationValue('bank_certificate'));

        if (false == file_exists($keyFilePath)) {
            throw new KeyFileNotFoundException($keyFilePath);
        }

        $key = file_get_contents($keyFilePath);
        return $key;
    }
}


text:
package main

/* generates our javascript object for custom skins */

import(
 "path/filepath"
 "fmt"
 "strings"
 "os/exec"
)

var path = "i/";

func main() {
	files, _ := filepath.Glob(path + "*")
	namesSlice := []string{};
	for _,basename := range files {
		name := strings.TrimSuffix(basename, filepath.Ext(basename))
		namesSlice = append(namesSlice, strings.Replace(name, path, "", -1));
	}
	fmt.Print("var ourskins = \"");
	fmt.Print(strings.Join(namesSlice, ":"));
	fmt.Println("\";");
	fmt.Println("grabbing source from github");
return;
	/* a work in progress */
	cmd := exec.Command("git", "clone", "https://github.com/electronoob/agarmods.git");
	err := cmd.Start();
	if err != nil {
		fmt.Println("some dome error occured: ", err);
	}
	err = cmd.Wait();
	if err != nil {
		fmt.Println("Command finished with: ", err);
	} else {
		cmd := exec.Command("cp", "agarmods/mods.js", "mods.js");
		cmd.Start();
		cmd.Wait();
		cmd = exec.Command("rm", "-rf", "agarmods");
		cmd.Start();
		cmd.Wait();
	}

}


text:
import * as angular from 'angular';
import errorInterceptor from './error.interceptor';
import {RequestService, IRequestServiceProvider} from './request-utils.provider';
import {UtilsService} from './utils.service';
import {ErrorService} from './error.service';
import Core from '../../core';

export default angular
    .module('app.utils', [
        Core
    ])
    .factory('errorInterceptor', ['$injector', '$q', errorInterceptor])
    .provider('RequestService', RequestService)
    .service('UtilsService', UtilsService)
    .service('ErrorService', ErrorService)
    .config([
        '$httpProvider',
        'RequestServiceProvider',
        '$logProvider',
        ($httpProvider: ng.IHttpProvider,
            RequestServiceProvider: IRequestServiceProvider,
            $logProvider: ng.ILogProvider) => {
            $httpProvider.interceptors.push('errorInterceptor');
            var host = window.location.hostname;
            if (!RequestServiceProvider.getBaseUrl()) {
                switch (host) {
                    case 'production':
                        break;
                    default:
                        RequestServiceProvider.setBaseUrl('http://localhost:1717/api/private/v1/');
                        /**
                         * log application events in dev
                         * using $log provider [$log.debug(...)]
                         */
                        $logProvider.debugEnabled(true);
                        break;
                }
            }
        }])
    .name;


text:
package main

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/google/googlesource-auth-tools/credentials"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatalf("Usage: %s PROMPT", os.Args[0])
	}

	if os.Args[1] != "get" {
		return
	}

	sc := bufio.NewScanner(os.Stdin)
	var protocol, host, path string
	for sc.Scan() {
		s := strings.TrimSpace(sc.Text())
		if s == "" {
			break
		}
		ss := strings.SplitN(s, "=", 2)
		if len(ss) != 2 {
			log.Fatalf("Cannot parse the git-credential input: %s", sc.Text())
		}
		switch ss[0] {
		case "protocol":
			protocol = ss[1]
		case "host":
			host = ss[1]
		case "path":
			path = ss[1]
		}
	}
	if err := sc.Err(); err != nil {
		log.Fatalf("Cannot parse the git-credential input: %v", err)
	}

	if host != "source.developers.google.com" && !strings.HasSuffix(host, ".googlesource.com") {
		return
	}

	u := &url.URL{}
	u.Scheme = protocol
	u.Host = host
	u.Path = path

	switch protocol {
	case "https":
		// OK
	case "http":
		gitBinary, err := credentials.FindGitBinary()
		if err != nil {
			log.Fatalf("Cannot find the git binary: %v", err)
		}
		g := gitBinary.WithURL(u)
		allowHTTP, err := g.BoolConfig(context.Background(), "google.allowHTTPForCredentialHelper")
		if err != nil {
			log.Fatalf("Cannot get a config for google.allowHTTPForCredentialHelper: %v", err)
		}
		if !allowHTTP {
			log.Fatalf("%s won't support HTTP protocol", os.Args[0])
		}
	default:
		log.Fatalf("Unknown protocol: %s", protocol)
	}

	gitBinary, err := credentials.FindGitBinary()
	if err != nil {
		log.Fatalf("Cannot find the git binary: %v", err)
	}

	token, err := credentials.MakeToken(context.Background(), gitBinary, u)
	if err != nil {
		log.Fatalf("Cannot get a token: %v", err)
	}

	fmt.Printf("protocol=%s\n", protocol)
	fmt.Printf("host=%s\n", host)
	fmt.Printf("username=git-service-account\n")
	fmt.Printf("password=%s\n", token.AccessToken)
}


text:
#define __cexpf __cexpf_not_defined
#define cexpf cexpf_not_defined

#include <complex.h>
#include <math.h>

#undef __cexpf
#undef cexpf
#define __cexpf internal_cexpf

static _Complex float internal_cexpf (_Complex float x);

#include <math/s_cexpf.c>
#include "cfloat-compat.h"

#undef __cexpf

c1_cfloat_rettype
__c1_cexpf (c1_cfloat_decl (x))
{
  _Complex float r = internal_cexpf (c1_cfloat_value (x));
  return c1_cfloat_return (r);
}

c2_cfloat_rettype
__c2_cexpf (c2_cfloat_decl (x))
{
  _Complex float r = internal_cexpf (c2_cfloat_value (x));
  return c2_cfloat_return (r);
}

cfloat_versions (cexpf);


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('speakers', '0003_remove_speaker_sessions_preference'),
    ]

    operations = [
        migrations.AddField(
            model_name='speaker',
            name='mobile_number',
            field=models.CharField(help_text='Your mobile number, that we can use to contact you at PyCon if your talk has been accepted and put on the schedule but we cannot find you when it is time.', max_length=40, blank=True),
        ),
    ]


text:
namespace
{
/// Sample vertex shader code
const std::string vertexShader =
	"varying vec4 vertColor;\n"
	"void main(void)\n"
	"{\n"
	"	gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
	"	vertColor.rgb = gl_Normal;\n"
	"	vertColor.a = 1.0;\n"
	"}\n";

/// Sample geometry shader code
const std::string geometryShader =
	"#version 150\n"
	"#extension GL_EXT_gpu_shader4 : enable\n"
	"#extension GL_EXT_geometry_shader4 : enable\n"
	"layout(triangles) in;\n"
	"layout(triangle_strip, max_vertices=3) out;\n"
	"in vec4 vertColor[3];\n"
	"out vec4 geomColor;\n"
	"void main()\n"
	"{\n"
	"	for (int i = 0; i < gl_VerticesIn; ++i)\n"
	"	{\n"
	"		gl_Position = gl_PositionIn[i];\n"
	"		geomColor = vertColor[i];\n"
	"		EmitVertex();\n"
	"	}\n"
	"	EndPrimitive();\n"
	"};";

/// Sample fragment shader code
const std::string fragmentShader =
	"varying vec4 geomColor;\n"
	"void main(void)\n"
	"{\n"
	"	gl_FragColor = geomColor;\n"
	"}";
}

namespace SurgSim
{
namespace Graphics
{

TEST(OsgProgramTests, InitTest)
{
	OsgProgram program;

	EXPECT_NE(nullptr, program.getOsgProgram());

	EXPECT_EQ(0u, program.getOsgProgram()->getNumShaders());
}

TEST(OsgProgramTests, StateSetTest)
{
	OsgProgram program;

	// Create an OSG state set
	osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet();

	const osg::StateSet::AttributeList& attributes = stateSet->getAttributeList();
	EXPECT_EQ(0u, attributes.size());

	/// Add the program to the state set
	program.addToStateSet(stateSet.get());

	EXPECT_EQ(1u, attributes.size()) << "State set has no attributes, one program should have been added!";
	EXPECT_EQ(program.getOsgProgram(),
			  attributes.at(osg::StateAttribute::TypeMemberPair(osg::StateAttribute::PROGRAM, 0)).first)
			<< "First attribute in state set should be the added program!";

	/// Remove the program from the state set
	program.removeFromStateSet(stateSet.get());

	EXPECT_EQ(0u, attributes.size())
			<< "State set should no longer have any attributes, the program should have been removed!";
}

TEST(OsgProgramTests, SetShaderSourceTest)
{
	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	EXPECT_FALSE(program->hasVertexShader());
	EXPECT_FALSE(program->hasGeometryShader());
	EXPECT_FALSE(program->hasFragmentShader());

	{
		SCOPED_TRACE("Set vertex shader source");
		program->setVertexShaderSource(vertexShader);

		std::string resultVertexShader;
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_TRUE(program->getVertexShaderSource(&resultVertexShader));
		EXPECT_EQ(vertexShader, resultVertexShader);

		EXPECT_EQ(1u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Set geometry shader source");
		program->setGeometryShaderSource(geometryShader);

		std::string resultGeometryShader;
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_TRUE(program->getGeometryShaderSource(&resultGeometryShader));
		EXPECT_EQ(geometryShader, resultGeometryShader);

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Set fragment shader source");
		program->setFragmentShaderSource(fragmentShader);

		std::string resultFragmentShader;
		EXPECT_TRUE(program->hasFragmentShader());
		EXPECT_TRUE(program->getFragmentShaderSource(&resultFragmentShader));
		EXPECT_EQ(fragmentShader, resultFragmentShader);

		EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

void expectFileContents(const std::string& filePath, const std::string& contents)
{
	boost::filesystem::ifstream fileStream(filePath);
	std::stringstream resultStream(contents);

	ASSERT_FALSE(fileStream.bad());

	std::string fileLine;
	std::string resultLine;
	while (!fileStream.eof() && !resultStream.eof())
	{
		fileStream >> fileLine;
		resultStream >> resultLine;

		// Skip possible trailing newlines
		fileStream >> std::ws;
		resultStream >> std::ws;

		EXPECT_EQ(fileLine, resultLine);
	}
	EXPECT_TRUE(fileStream.eof());
	EXPECT_TRUE(resultStream.eof());
	fileStream.close();
}

TEST(OsgProgramTests, LoadShaderSourceTest)
{
	SurgSim::Framework::ApplicationData data("config.txt");

	std::string vertexShaderPath   = data.findFile("OsgProgramTests/shader.vert");
	std::string geometryShaderPath = data.findFile("OsgProgramTests/shader.geom");
	std::string fragmentShaderPath = data.findFile("OsgProgramTests/shader.frag");

	ASSERT_NE("", vertexShaderPath) << "Could not find vertex shader!";
	ASSERT_NE("", geometryShaderPath) << "Could not find geometry shader!";
	ASSERT_NE("", fragmentShaderPath) << "Could not find fragment shader!";

	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	{
		SCOPED_TRACE("Load vertex shader source from file");
		EXPECT_TRUE(program->loadVertexShader(vertexShaderPath));
		std::string resultVertexShader;
		EXPECT_TRUE(program->getVertexShaderSource(&resultVertexShader));
		expectFileContents(vertexShaderPath, resultVertexShader);

		EXPECT_EQ(1u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Load geometry shader source from file");
		EXPECT_TRUE(program->loadGeometryShader(geometryShaderPath));
		std::string resultGeometryShader;
		EXPECT_TRUE(program->getGeometryShaderSource(&resultGeometryShader));
		expectFileContents(geometryShaderPath, resultGeometryShader);

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}

	{
		SCOPED_TRACE("Load fragment shader source from file");
		EXPECT_TRUE(program->loadFragmentShader(fragmentShaderPath));
		std::string resultFragmentShader;
		EXPECT_TRUE(program->getFragmentShaderSource(&resultFragmentShader));
		expectFileContents(fragmentShaderPath, resultFragmentShader);

		EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

TEST(OsgProgramTests, ClearShaderTest)
{
	std::shared_ptr<OsgProgram> osgProgram = std::make_shared<OsgProgram>();
	std::shared_ptr<Program> program = osgProgram;

	// Set vertex, geometry, and fragment shaders
	EXPECT_FALSE(program->hasVertexShader());
	program->setVertexShaderSource(vertexShader);
	EXPECT_TRUE(program->hasVertexShader());

	EXPECT_FALSE(program->hasGeometryShader());
	program->setGeometryShaderSource(geometryShader);
	EXPECT_TRUE(program->hasGeometryShader());

	EXPECT_FALSE(program->hasFragmentShader());
	program->setFragmentShaderSource(fragmentShader);
	EXPECT_TRUE(program->hasFragmentShader());

	EXPECT_EQ(3u, osgProgram->getOsgProgram()->getNumShaders());

	{
		SCOPED_TRACE("Clear vertex shader");
		program->clearVertexShader();
		EXPECT_FALSE(program->hasVertexShader());
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_TRUE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setVertexShaderSource(vertexShader);
	EXPECT_TRUE(program->hasVertexShader());

	{
		SCOPED_TRACE("Clear geometry shader");
		program->clearGeometryShader();
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_FALSE(program->hasGeometryShader());
		EXPECT_TRUE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setGeometryShaderSource(geometryShader);
	EXPECT_TRUE(program->hasGeometryShader());

	{
		SCOPED_TRACE("Clear fragment shader");
		program->clearFragmentShader();
		EXPECT_TRUE(program->hasVertexShader());
		EXPECT_TRUE(program->hasGeometryShader());
		EXPECT_FALSE(program->hasFragmentShader());

		EXPECT_EQ(2u, osgProgram->getOsgProgram()->getNumShaders());
	}
	program->setFragmentShaderSource(fragmentShader);
	EXPECT_TRUE(program->hasFragmentShader());

	{
		SCOPED_TRACE("Clear the entire shader");
		program->clear();
		EXPECT_FALSE(program->hasVertexShader());
		EXPECT_FALSE(program->hasGeometryShader());
		EXPECT_FALSE(program->hasFragmentShader());

		EXPECT_EQ(0u, osgProgram->getOsgProgram()->getNumShaders());
	}
}

}  // namespace Graphics
}  // namespace SurgSim


text:
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      PROGRAM EXMPL8
C   Example 8: Monte Carlo simulation of the two-dimensional Ising Model
C  COMPUTATIONAL PHYSICS (FORTRAN VERSION)
C  by Steven E. Koonin and Dawn C. Meredith
C  Copyright 1989, Addison-Wesley Publishing Company, Inc.
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      CALL INIT           !display header screen, setup parameters
5     CONTINUE            !main loop/ execute once for each set of param
        CALL PARAM        !get input from screen
        CALL ARCHON       !calculate the thermodynamic quantities
      GOTO 5
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE ARCHON
C calculates the thermodynamic quantities:  energy, magnetization
C susceptibility, and specific heat at constant field and intrctn strngth
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
      INCLUDE 'IO.ALL'
C Local variables:
      INTEGER SPIN(MAXX,MAXY)    !spin configuration
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization
      REAL ENERGY(3,3)           !energy
      REAL CB(3,3)               !specific heat
      REAL CHI(3,3)              !susceptibility
      INTEGER ITHERM             !thermalization index
      INTEGER ITER               !iteration index
      REAL ACCPT                 !acceptance ratio
      INTEGER IX,IY              !horiz and vert indices
      INTEGER NLINES             !number of lines printed to terminal
      INTEGER MORE,IGRP          !how many more groups, group index
      INTEGER ISWEEP             !sweep index
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
C Functions:
      REAL GETFLT                !get floating point number from screen
      INTEGER YESNO              !get yes/no answer from screen
      LOGICAL LOGCVT             !change from 1,0 to true and false
      INTEGER GETINT             !get integer data from screen
      REAL RANNOS                !generates a random number
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     output summary of parameters
      IF (TTERM) CALL PRMOUT(OUNIT,NLINES)
      IF (TFILE) CALL PRMOUT(TUNIT,NLINES)
      IF (GFILE) CALL PRMOUT(GUNIT,NLINES)
C
      DO 5 IX=1,NX              !random initial spin configuration
         DO 6 IY=1,NY
              IF (RANNOS(DSEED) .GT. .5) THEN
                 SPIN(IX,IY)=1
              ELSE
                 SPIN (IX,IY)=-1
              END IF
6        CONTINUE
5     CONTINUE
C
      DO 10 ITHERM=1,NTHERM     !thermalize init config
         CALL METROP(SPIN,ACCPT)
         IF (TTERM) WRITE (OUNIT,7) ITHERM,ACCPT
         IF (TFILE) WRITE (TUNIT,7) ITHERM,ACCPT
7        FORMAT (5X,' thermalization sweep ',I4,
     +           ', acceptance ratio =',F5.3)
10    CONTINUE
      IF (TTERM) CALL PAUSE('to begin summing...',1)
C
      CALL ZERO(TOTAL,MAG,ENERGY,CHI,CB)  !zero total averages
      MORE=NGROUP
C
15    CONTINUE                                !allow for more groups
        DO 20 IGRP=NGROUP-MORE+1,NGROUP       !loop over groups
           CALL ZERO(GROUP,MAG,ENERGY,CHI,CB) !zero group averages
C
           IF ((TTERM) .AND. (.NOT. GTERM) .AND. (.NOT. TERSE))
     +              CALL TITLES(OUNIT,NLINES)
           IF ((TFILE) .AND. (.NOT. TERSE)) CALL TITLES(TUNIT,NLINES)
C
           DO 30 ITER=1,NFREQ*NSIZE
              CALL METROP(SPIN,ACCPT)     !make a sweep of the lattice
C
              IF (MOD(ITER,NFREQ) .EQ. 0) THEN  !include in averages
                  ISWEEP=ITER/NFREQ               !which sweep is it
                  CALL ZERO(SWEEP,MAG,ENERGY,CHI,CB) !zero sweep totals
                  CALL SUM(SPIN,MAG,ENERGY)!sweep totals, add to group
C
                  IF (GTERM) THEN          !display data
                     CALL DISPLY(OUNIT,SPIN,MAG,
     +                       ENERGY,ACCPT,IGRP,ISWEEP)
                  ELSE IF ((TTERM) .AND. (.NOT. TERSE)) THEN
                     CALL
     +               SWPOUT(OUNIT,MAG,ENERGY,ACCPT,IGRP,ISWEEP,NLINES)
                  END IF
                  IF ((TFILE) .AND. (.NOT. TERSE)) CALL
     +               SWPOUT(TUNIT,MAG,ENERGY,ACCPT,IGRP,ISWEEP,NLINES)
                  IF ((GFILE) .OR. (GHRDCP)) CALL
     +               DISPLY(GUNIT,SPIN,MAG,ENERGY,ACCPT,IGRP,ISWEEP)
C
              END IF
30         CONTINUE
           CALL AVERAG(MAG,ENERGY,CHI,CB,IGRP) !calc total averages
20      CONTINUE
C
        MORE=GETINT(10,0,1000,'How many more groups?')
      IF (MORE .GT. 0) THEN
           NGROUP=NGROUP+MORE
           NLINES=0
           IF ((TTERM) .AND. (.NOT. TERSE))CALL CLEAR
           GOTO 15
      END IF
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE METROP(SPIN,ACCPT)
C make one sweep of the lattice using the Metropolis algorithm
C to generate a new configuration
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
C Input/Output variables:
      INTEGER SPIN(MAXX,MAXY)     !spin configuration (I/O)
      REAL ACCPT                  !acceptance ratio (output)
C Local variables:
      INTEGER IX,IY               !horiz and vert indices
      INTEGER IXM1,IXP1,IYM1,IYP1 !indices of nearest neighbors
      INTEGER NNSUM               !sum of nearest neighbors
C Function:
      REAL RANNOS                 !generates a random number
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      ACCPT=0.                          !zero acceptance ratio
      DO 10 IX=1,NX
        IXP1=IX+1                       !nearest neighbors
        IF (IX .EQ. NX) IXP1=1          !with periodic b.c.
        IXM1=IX-1
        IF (IX .EQ. 1) IXM1=NX
C
        DO 20 IY=1,NY
          IYP1=IY+1                     !nearest neighbors
          IF (IY .EQ. NY) IYP1=1        !with periodic b.c.
          IYM1=IY-1
          IF (IY .EQ. 1) IYM1=NY
C                                       !term to weight new config
          NNSUM=SPIN(IX,IYP1)+SPIN(IX,IYM1)+SPIN(IXP1,IY)+SPIN(IXM1,IY)
C
          IF (RANNOS(DSEED) .LT. RATIO(NNSUM,SPIN(IX,IY))) THEN
             SPIN(IX,IY)=-SPIN(IX,IY)   !flip the spin
             ACCPT=ACCPT+1              !update accept count
          END IF
C
20      CONTINUE
10    CONTINUE
      ACCPT=ACCPT/NSPIN                 !make it a ratio
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE SUM(SPIN,MAG,ENERGY)
C calculate magnetization and energy for this sweep
C add these values to the group averages
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
C Input/output variables:
      INTEGER SPIN(MAXX,MAXY)    !spin configuration (input)
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the quantity: value, square, or sigma**2
      REAL MAG(3,3)              !magnetization (I/O)
      REAL ENERGY(3,3)           !energy (I/O)
C Local variables:
      INTEGER PAIRS              !interaction sum
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
      INTEGER IX,IY              !horiz and vert indices
      INTEGER IXM1,IYM1          !neighbor indices
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      PAIRS=0                      !zero pair sum
      DO 10 IY=1,NY
         IYM1=IY-1                 !neighbor just below
         IF (IY .EQ. 1) IYM1=NY    !periodic b.c.
         DO 20 IX=1,NX
           IXM1=IX-1               !neighbor to the left
           IF (IX .EQ. 1) IXM1=NX  !periodic b.c.
C
C          this method of summing pairs does not count twice
           PAIRS=PAIRS+SPIN(IX,IY)*(SPIN(IX,IYM1)+SPIN(IXM1,IY))
C          magnetization is the sum of the spins  (Eq. 8.21a)
           MAG(SWEEP,VALUE)=MAG(SWEEP,VALUE)+SPIN(IX,IY)
C
20       CONTINUE
10    CONTINUE
C
      MAG(SWEEP,SQUARE)=MAG(SWEEP,VALUE)**2
      ENERGY(SWEEP,VALUE)=-J*PAIRS-B*MAG(SWEEP,VALUE)   !Eq 8.18
      ENERGY(SWEEP,SQUARE)=ENERGY(SWEEP,VALUE)**2
C
C     add sweep contributions to group sums
      MAG(GROUP,VALUE)=MAG(GROUP,VALUE)+MAG(SWEEP,VALUE)
      MAG(GROUP,SQUARE)=MAG(GROUP,SQUARE)+MAG(SWEEP,SQUARE)
      ENERGY(GROUP,VALUE)=ENERGY(GROUP,VALUE)+ENERGY(SWEEP,VALUE)
      ENERGY(GROUP,SQUARE)=ENERGY(GROUP,SQUARE)+ENERGY(SWEEP,SQUARE)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE AVERAG(MAG,ENERGY,CHI,CB,IGROUP)
C find group averages from group sums and add these to total averages;
C calculate uncertainties and display results
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
      INCLUDE 'IO.ALL'
C Input/Output variables:
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization
      REAL ENERGY(3,3)           !energy
      REAL CB(3,3)               !specific heat
      REAL CHI(3,3)              !susceptibility
      INTEGER IGROUP             !group index (input)
C Local variables:
      REAL M,MSIG1,MSIG2         !magnetization and uncertainties
      REAL E,ESIG1,ESIG2         !energy and uncertainties
      REAL SUS,SUSSIG            !susceptibility and uncertainty
      REAL C,CSIG                !specific heat and uncertainty
      INTEGER IQUANT             !index the quantity
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     calculate group averages and uncertainties from group sums
      DO 10 IQUANT=VALUE,SQUARE
         MAG(GROUP,IQUANT)=MAG(GROUP,IQUANT)/NSIZE
         ENERGY(GROUP,IQUANT)=ENERGY(GROUP,IQUANT)/NSIZE
10    CONTINUE
      CHI(GROUP,VALUE)=MAG(GROUP,SQUARE)-MAG(GROUP,VALUE)**2
      MAG(GROUP,SIGSQ)=CHI(GROUP,VALUE)/NSIZE
      IF (MAG(GROUP,SIGSQ) .LT. 0.) MAG(GROUP,SIGSQ)=0.
      CB(GROUP,VALUE)=ENERGY(GROUP,SQUARE)-ENERGY(GROUP,VALUE)**2
      ENERGY(GROUP,SIGSQ)=CB(GROUP,VALUE)/NSIZE
      IF (ENERGY(GROUP,SIGSQ) .LT. 0.) ENERGY(GROUP,SIGSQ)=0.
      CHI(GROUP,SQUARE)=CHI(GROUP,VALUE)**2
      CB(GROUP,SQUARE)=CB(GROUP,VALUE)**2
C
C     add group averages to total sums
      DO 20 IQUANT=VALUE,SIGSQ
         MAG(TOTAL,IQUANT)=MAG(TOTAL,IQUANT)+MAG(GROUP,IQUANT)
         ENERGY(TOTAL,IQUANT)=ENERGY(TOTAL,IQUANT)+ENERGY(GROUP,IQUANT)
         CHI(TOTAL,IQUANT)=CHI(TOTAL,IQUANT)+CHI(GROUP,IQUANT)
         CB(TOTAL,IQUANT)=CB(TOTAL,IQUANT)+CB(GROUP,IQUANT)
20    CONTINUE
C
C     find total averages using total sums accumulated so far
      M=MAG(TOTAL,VALUE)/IGROUP
      MSIG1=(MAG(TOTAL,SQUARE)/IGROUP-M**2)/IGROUP/NSIZE
      IF (MSIG1 .LT. 0) MSIG1=0.
      MSIG1=SQRT(MSIG1)
      MSIG2=SQRT(MAG(TOTAL,SIGSQ))/IGROUP
C
      E=ENERGY(TOTAL,VALUE)/IGROUP
      ESIG1=(ENERGY(TOTAL,SQUARE)/IGROUP-E**2)/IGROUP/NSIZE
      IF (ESIG1 .LT. 0) ESIG1=0.
      ESIG1=SQRT(ESIG1)
      ESIG2=SQRT(ENERGY(TOTAL,SIGSQ))/IGROUP
C
      SUS=CHI(TOTAL,VALUE)/IGROUP
      SUSSIG=(CHI(TOTAL,SQUARE)/IGROUP-SUS**2)/IGROUP
      IF (SUSSIG .LT. 0.) SUSSIG=0.
      SUSSIG=SQRT(SUSSIG)
C
      C=CB(TOTAL,VALUE)/IGROUP
      CSIG=(CB(TOTAL,SQUARE)/IGROUP-C**2)/IGROUP
      IF (CSIG .LT. 0.) CSIG=0.
      CSIG=SQRT(CSIG)
C
C     write out summary
      IF (TTERM) CALL TXTOUT(MAG,ENERGY,CB,CHI,E,ESIG1,ESIG2,
     +    M,MSIG1,MSIG2,SUS,SUSSIG,C,CSIG,IGROUP,OUNIT)
      IF (TFILE) CALL TXTOUT(MAG,ENERGY,CB,CHI,E,ESIG1,ESIG2,
     +    M,MSIG1,MSIG2,SUS,SUSSIG,C,CSIG,IGROUP,TUNIT)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE ZERO(ILEVEL,MAG,ENERGY,CHI,CB)
C zero sums for ILEVEL thermodynamic values
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Input/Output variables:
      INTEGER ILEVEL             !which level to zero  (input)
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization (output)
      REAL ENERGY(3,3)           !energy (output)
      REAL CB(3,3)               !specific heat (output)
      REAL CHI(3,3)              !susceptibility (output)
C Local variable:
      INTEGER IQUANT             !which quantity
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      DO 10 IQUANT=1,3
           MAG(ILEVEL,IQUANT)=0.
           ENERGY(ILEVEL,IQUANT)=0.
           CHI(ILEVEL,IQUANT)=0.
           CB(ILEVEL,IQUANT)=0.
10    CONTINUE
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE INIT
C initializes constants, displays header screen,
C initializes menu arrays for input parameters
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'MENU.ALL'
      INCLUDE 'PARAM.E8'
C Local parameters:
      CHARACTER*80 DESCRP          !program description
      DIMENSION DESCRP(20)
      INTEGER NHEAD,NTEXT,NGRAPH   !number of lines for each description
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     get environment parameters
      CALL SETUP
C
C     display header screen
      DESCRP(1)= 'EXAMPLE 8'
      DESCRP(2)= 'Monte Carlo simulation of the 2-D Ising Model'
      DESCRP(3)= 'using the Metropolis algorithm'
      NHEAD=3
C
C     text output description
      DESCRP(4)= 'acceptance rate, energy, magnetization, specific heat'
      DESCRP(5)= 'and susceptibility (all are values per spin)'
      NTEXT=2
C
C     graphics output description
      DESCRP(6)= 'spin configuration (blank=-1; X=+1)'
      NGRAPH=1
C
      CALL HEADER(DESCRP,NHEAD,NTEXT,NGRAPH)
C
C     setup menu arrays, beginning with constant part
      CALL MENU
C
      MTYPE(13)=FLOAT
      MPRMPT(13)='Enter value for magnetic field (units of kT)'
      MTAG(13)='Magnetic field (units of kT)'
      MLOLIM(13)=-20.
      MHILIM(13)=20.
      MREALS(13)=0.
C
      MTYPE(14)=FLOAT
      MPRMPT(14)='Enter value for interaction strength (units of kT)'
      MTAG(14)='interaction strength (units of kT)'
      MLOLIM(14)=-20.
      MHILIM(14)=20.
      MREALS(14)=.3
C
      MTYPE(15)=SKIP
      MREALS(15)=35.
C
      MTYPE(38)=NUM
      MPRMPT(38)= 'Enter number of X lattice points'
      MTAG(38)= 'Number of X lattice points'
      MLOLIM(38)=2.
      MHILIM(38)=MAXX
      MINTS(38)=20
C
      MTYPE(39)=NUM
      MPRMPT(39)= 'Enter number of Y lattice points'
      MTAG(39)= 'Number of Y lattice points'
      MLOLIM(39)=2.
      MHILIM(39)=MAXY
      MINTS(39)=20
C
      MTYPE(40)=NUM
      MPRMPT(40)= 'Integer random number seed for init fluctuations'
      MTAG(40)= 'Random number seed'
      MLOLIM(40)=1000.
      MHILIM(40)=99999.
      MINTS(40)=54767
C
      MTYPE(41)=NUM
      MPRMPT(41)= 'Number of thermalization sweeps'
      MTAG(41)= 'Thermalization sweeps'
      MLOLIM(41)=0
      MHILIM(41)=1000
      MINTS(41)=20
C
      MTYPE(42)=NUM
      MPRMPT(42)=  'Enter sampling frequency (to avoid correlations)'
      MTAG(42)= 'Sampling frequency'
      MLOLIM(42)=1
      MHILIM(42)=100
      MINTS(42)=5
C
      MTYPE(43)=NUM
      MPRMPT(43)= 'Number of samples in a group'
      MTAG(43)= 'Group size'
      MLOLIM(43)=1
      MHILIM(43)=1000
      MINTS(43)=10
C
      MTYPE(44)=NUM
      MPRMPT(44)= 'Enter number of groups'
      MTAG(44)= 'Number of groups'
      MLOLIM(44)=1
      MHILIM(44)=1000
      MINTS(44)=10
C
      MTYPE(45)=SKIP
      MREALS(45)=60.
C
      MSTRNG(MINTS(75))= 'exmpl8.txt'
C
      MTYPE(76)=BOOLEN
      MPRMPT(76)='Do you want the short version of the output?'
      MTAG(76)='Short version of output'
      MINTS(76)=0
C
      MTYPE(77)=SKIP
      MREALS(77)=80.
C
      MSTRNG(MINTS(86))= 'exmpl8.grf'
C
      MTYPE(87)=SKIP
      MREALS(87)=90.
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE PARAM
C gets parameters from screen
C ends program on request
C closes old files
C maps menu variables to program variables
C opens new files
C calculates all derivative parameters
C performs checks on parameters
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'MENU.ALL'
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E8'
C Local variables:
      INTEGER IF              !possible values for sum of neighb. spins
C map between menu indices and parameters
      INTEGER IB,IJ,INX,INY,IDSEED,INTHRM,INFREQ,INSIZE,INGRP,ITERSE
      PARAMETER (IB     = 13)
      PARAMETER (IJ     = 14)
      PARAMETER (INX    = 38)
      PARAMETER (INY    = 39)
      PARAMETER (IDSEED = 40)
      PARAMETER (INTHRM = 41)
      PARAMETER (INFREQ = 42)
      PARAMETER (INSIZE = 43)
      PARAMETER (INGRP  = 44)
      PARAMETER (ITERSE = 76)
C Functions:
      LOGICAL LOGCVT          !converts 1 and 0 to true and false
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     get input from terminal
      CALL CLEAR
      CALL ASK(1,ISTOP)
C
C     stop program if requested
      IF (MREALS(IMAIN) .EQ. STOP) CALL FINISH
C
C     close files if necessary
      IF (TNAME .NE. MSTRNG(MINTS(ITNAME)))
     +     CALL FLCLOS(TNAME,TUNIT)
      IF (GNAME .NE. MSTRNG(MINTS(IGNAME)))
     +     CALL FLCLOS(GNAME,GUNIT)
C
C     set new parameter values
C     physical and numerical
      B=MREALS(IB)
      J=MREALS(IJ)
      NX=MINTS(INX)
      NY=MINTS(INY)
      DSEED=DBLE(MINTS(IDSEED))
      NTHERM=MINTS(INTHRM)
      NFREQ=MINTS(INFREQ)
      NSIZE=MINTS(INSIZE)
      NGROUP=MINTS(INGRP)
C
C     text output
      TTERM=LOGCVT(MINTS(ITTERM))
      TFILE=LOGCVT(MINTS(ITFILE))
      TNAME=MSTRNG(MINTS(ITNAME))
      TERSE=LOGCVT(MINTS(ITERSE))
C
C     graphics output
      GTERM=LOGCVT(MINTS(IGTERM))
      GHRDCP=LOGCVT(MINTS(IGHRD))
      GFILE=LOGCVT(MINTS(IGFILE))
      GNAME=MSTRNG(MINTS(IGNAME))
C
C     open files
      IF (TFILE) CALL FLOPEN(TNAME,TUNIT)
      IF (GFILE) CALL FLOPEN(GNAME,GUNIT)
      !files may have been renamed
      MSTRNG(MINTS(ITNAME))=TNAME
      MSTRNG(MINTS(IGNAME))=GNAME
C
      CALL CLEAR
C
C     calculate derivative parameters
      NSPIN=NX*NY
      DO 10 IF=-4,4,2    !ratio of prob.; not all matrix elem are used
            RATIO(IF,-1)=EXP(2*(J*IF+B))
            RATIO(IF,1) =1./RATIO(IF,-1)
10    CONTINUE
C
C     calculate parameters for best looking text display
      IF (2*NX .LE. TRMWID) THEN
           XSKIP=.TRUE.              !skip spaces in x
           XCNTR=(TRMWID-2*NX)/2     !how to center display
      ELSE
           XSKIP=.FALSE.
           XCNTR=(TRMWID-NX)/2
      END IF
      IF (XCNTR .LT. 1) XCNTR=1

      IF (2*NY .LE. TRMLIN-5) THEN
          YSKIP=.TRUE.               !skip lines in y
          YCNTR=(TRMLIN-2*NY)/2-3    !how to center display
      ELSE
          YSKIP=.FALSE.
          YCNTR=(TRMLIN-NY)/2-3
      END IF
      IF (YCNTR .LT. 0) YCNTR=0
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE PRMOUT(MUNIT,NLINES)
C write out parameter summary to MUNIT
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E8'
C Input variables:
      INTEGER MUNIT                   !fortran unit number
      INTEGER NLINES                  !number of lines sent to terminal
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      IF (MUNIT .EQ. OUNIT) CALL CLEAR
C
      WRITE (MUNIT,5)
      WRITE (MUNIT,6)
      WRITE (MUNIT,7) B
      WRITE (MUNIT,8) J
      WRITE (MUNIT,10) NX,NY
      WRITE (MUNIT,15) NTHERM
      WRITE (MUNIT,20) NFREQ,NSIZE
      WRITE (MUNIT,*) ' '
      NLINES=8
C
5     FORMAT (' Output from example 8:')
6     FORMAT (' Monte Carlo Simulation of the'
     +        ' 2-D Ising Model using the Metropolis Algorithm')
7     FORMAT (' Magnetic field (units of kT) =',1PE12.5)
8     FORMAT (' Interaction strength (units of kT) =',1PE12.5)
10    FORMAT (' NX =',I3,5X,' NY =',I3)
15    FORMAT (' number of thermalization sweeps =',I4)
20    FORMAT (' sweep frequency = ',I4,' group size =',I4)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE DISPLY(MUNIT,SPIN,MAG,ENERGY,ACCPT,IGROUP,ISWEEP)
C display spin configuration (spin=-1 is a blank, spin=1 is an X)
C and write out data for this sweep
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
      INCLUDE 'IO.ALL'
C Input variables:
      INTEGER SPIN(MAXX,MAXY)    !spin configuration
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization
      REAL ENERGY(3,3)           !energy
      REAL ACCPT                 !acceptance ratio
      INTEGER MUNIT              !unit we're writing to
      INTEGER ISWEEP,IGROUP      !sweep and group index
C Local variables:
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
      INTEGER IX,IY              !lattice indices
      CHARACTER*1 CSPIN(MAXX)    !spin as character data
      CHARACTER*80 BLNK          !blanks for centering in X
      DATA BLNK /' '/
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      IF (MUNIT .EQ. OUNIT) THEN
        CALL CLEAR
        DO 20 IY=1,YCNTR                   !center output
           WRITE (OUNIT,*) ' '
20      CONTINUE
      END IF
      WRITE (MUNIT,11) IGROUP,ISWEEP,NSIZE,ACCPT,
     +          ENERGY(SWEEP,VALUE)/NSPIN,MAG(SWEEP,VALUE)/NSPIN
11    FORMAT (' group ',I3,', sweep ',I3,' out of ',I3,5X,
     +        ' accpt =',F5.3,'  Energy = ',F7.3,'  Mag =',F6.3)
C
      DO 100 IY=NY,1,-1                    !change +-1 to X and blank
         DO 50 IX=1,NX
            IF (SPIN(IX,IY) .EQ. 1) THEN
                CSPIN(IX)='X'
            ELSE
                CSPIN(IX)=' '
            END IF
50       CONTINUE
C        write out a line at a time (no centering done for TUNIT)
         IF (MUNIT .EQ. TUNIT) THEN
                  WRITE (TUNIT,16) (CSPIN(IX),IX=1,NX)
         ELSE
           IF (XSKIP) THEN
             WRITE (MUNIT,10) BLNK(1:XCNTR),(CSPIN(IX),IX=1,NX)
           ELSE
             WRITE (MUNIT,15) BLNK(1:XCNTR),(CSPIN(IX),IX=1,NX)
           END IF
           IF (YSKIP) WRITE (MUNIT,*) ' '
         END IF
10       FORMAT (1X,A,100(A1,1X))
15       FORMAT (1X,A,100(A1))
16       FORMAT (1X,100(A1))
100   CONTINUE
      IF (MUNIT .EQ. OUNIT) CALL PAUSE('to continue...',0)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE SWPOUT(MUNIT,MAG,ENERGY,ACCPT,IGROUP,ISWEEP,NLINES)
C and write out data for this sweep
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
      INCLUDE 'IO.ALL'
C Input variables:
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization
      REAL ENERGY(3,3)           !energy
      REAL ACCPT                 !acceptance ratio
      INTEGER MUNIT              !unit we're writing to
      INTEGER ISWEEP,IGROUP      !sweep and group index
      INTEGER NLINES             !lines written to terminal (I/O)
C Local variables:
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      WRITE (MUNIT,11) IGROUP,ISWEEP,NSIZE,ACCPT,
     +       ENERGY(SWEEP,VALUE)/NSPIN,MAG(SWEEP,VALUE)/NSPIN
11    FORMAT (7X,I3,7X,I3,'/',I3,7X,F5.3,7X,F9.5,7X,F9.3)
      IF (MUNIT .EQ. OUNIT) NLINES=NLINES+1
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE TXTOUT(MAG,ENERGY,CB,CHI,E,ESIG1,ESIG2,
     +    M,MSIG1,MSIG2,SUS,SUSSIG,C,CSIG,IGROUP,MUNIT)
C write out averages and uncertaintes to MUNIT
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E8'
      INCLUDE 'IO.ALL'
C Input variables:
C     all of the thermodynamic quant have 2 indices
C     (not all array elements are used, e.g. CHI(sweep,value))
C     first index is the level: sweep, group, or total
C     second index is the value: quantity, quant**2, or sigma**2
      REAL MAG(3,3)              !magnetization
      REAL ENERGY(3,3)           !energy
      REAL CB(3,3)               !specific heat
      REAL CHI(3,3)              !susceptibility
      INTEGER IGROUP             !group index
      REAL M,MSIG1,MSIG2         !magnetization and uncertainties
      REAL E,ESIG1,ESIG2         !energy and uncertainties
      REAL SUS,SUSSIG            !susceptibility and uncertainty
      REAL C,CSIG                !specific heat and uncertainty
      INTEGER MUNIT              !which unit number
C Local variables:
      INTEGER SWEEP,GROUP,TOTAL  !which level of calculation
      INTEGER VALUE,SQUARE,SIGSQ !which quantity
      DATA SWEEP,GROUP,TOTAL/1,2,3/
      DATA VALUE,SQUARE,SIGSQ/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      WRITE (MUNIT,30) IGROUP,NGROUP
      WRITE (MUNIT,32)
      WRITE (MUNIT,33)
      WRITE (MUNIT,35)
     +  ENERGY(GROUP,VALUE)/NSPIN,SQRT(ENERGY(GROUP,SIGSQ))/NSPIN,
     +  MAG(GROUP,VALUE)/NSPIN,SQRT(MAG(GROUP,SIGSQ))/NSPIN,
     +  CHI(GROUP,VALUE)/NSPIN,CB(GROUP,VALUE)/NSPIN
      WRITE (MUNIT,40) E/NSPIN,ESIG1/NSPIN,ESIG2/NSPIN,
     +  M/NSPIN,MSIG1/NSPIN,MSIG2/NSPIN,
     +  SUS/NSPIN,SUSSIG/NSPIN,C/NSPIN,CSIG/NSPIN
      WRITE (MUNIT,*) ' '
      IF ((MUNIT .EQ. OUNIT) .AND. (.NOT. TERSE))
     +        CALL PAUSE(' to continue...',1)
C
30    FORMAT ('  Group ',I3,' (out of ',I4,') averages')
32    FORMAT (14X,'Energy',13X,'Magnetization',5X,'Susceptibility',
     +        2X,'Specific Heat')
33    FORMAT (14X,'------',13X,'-------------',5X,'--------------',
     +        2X,'-------------')
35    FORMAT ('  group ',2(1X,F7.3,'+-',F5.3,6X),
     +        2(2X,F6.3,7X))
40    FORMAT ('  total ',2(1X,F7.3,'+-',F5.3,'/',F5.3),
     +        2(1X,F6.3,'+-',F6.3))
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE TITLES(MUNIT,NLINES)
C write out text data titles
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
C Input/Output variables:
      INTEGER MUNIT                   !output unit (input)
      INTEGER NLINES                  !number of lines written (I/O)
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      IF (MUNIT .EQ. OUNIT) CALL CLEAR
C
      WRITE (MUNIT,10)
      WRITE (MUNIT,11)
10    FORMAT (6X,'Group',3X,'Sweep/Out of',5X,'Accpt',9X,'Energy',
     +       6X,'Magnetization')
11    FORMAT (6X,'-----',3X,'------------',5X,'-----',9X,'------',
     +       6X,'-------------')
C
      IF (MUNIT .EQ. OUNIT) NLINES=NLINES+2
C
      RETURN
      END


text:
use actix::prelude::*;
use actix_http::ws::Codec;
use actix_web::{web, App, HttpRequest};
use actix_web_actors::ws;
use bytes::Bytes;
use futures_util::{SinkExt, StreamExt};

struct Ws;

impl Actor for Ws {
    type Context = ws::WebsocketContext<Self>;
}

impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            Ok(ws::Message::Close(reason)) => ctx.close(reason),
            _ => ctx.close(Some(ws::CloseCode::Error.into())),
        }
    }
}

const MAX_FRAME_SIZE: usize = 10_000;
const DEFAULT_FRAME_SIZE: usize = 10;

async fn common_test_code(mut srv: actix_test::TestServer, frame_size: usize) {
    // client service
    let mut framed = srv.ws().await.unwrap();

    framed.send(ws::Message::Text("text".into())).await.unwrap();
    let item = framed.next().await.unwrap().unwrap();
    assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));

    let bytes = Bytes::from(vec![0; frame_size]);
    framed
        .send(ws::Message::Binary(bytes.clone()))
        .await
        .unwrap();
    let item = framed.next().await.unwrap().unwrap();
    assert_eq!(item, ws::Frame::Binary(bytes));

    framed.send(ws::Message::Ping("text".into())).await.unwrap();
    let item = framed.next().await.unwrap().unwrap();
    assert_eq!(item, ws::Frame::Pong(Bytes::copy_from_slice(b"text")));

    framed
        .send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
        .await
        .unwrap();
    let item = framed.next().await.unwrap().unwrap();
    assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
}

#[actix_rt::test]
async fn simple_builder() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream).start()
            },
        ))
    });

    common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn builder_with_frame_size() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .frame_size(MAX_FRAME_SIZE)
                    .start()
            },
        ))
    });

    common_test_code(srv, MAX_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn builder_with_frame_size_exceeded() {
    const MAX_FRAME_SIZE: usize = 64;

    let mut srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .frame_size(MAX_FRAME_SIZE)
                    .start()
            },
        ))
    });

    // client service
    let mut framed = srv.ws().await.unwrap();

    // create a request with a frame size larger than expected
    let bytes = Bytes::from(vec![0; MAX_FRAME_SIZE + 1]);
    framed.send(ws::Message::Binary(bytes)).await.unwrap();

    let frame = framed.next().await.unwrap().unwrap();
    let close_reason = match frame {
        ws::Frame::Close(Some(reason)) => reason,
        _ => panic!("close frame expected"),
    };
    assert_eq!(close_reason.code, ws::CloseCode::Error);
}

#[actix_rt::test]
async fn builder_with_codec() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .codec(Codec::new())
                    .start()
            },
        ))
    });

    common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn builder_with_protocols() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .protocols(&["A", "B"])
                    .start()
            },
        ))
    });

    common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn builder_with_codec_and_frame_size() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .codec(Codec::new())
                    .frame_size(MAX_FRAME_SIZE)
                    .start()
            },
        ))
    });

    common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn builder_full() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move {
                ws::WsResponseBuilder::new(Ws, &req, stream)
                    .frame_size(MAX_FRAME_SIZE)
                    .codec(Codec::new())
                    .protocols(&["A", "B"])
                    .start()
            },
        ))
    });

    common_test_code(srv, MAX_FRAME_SIZE).await;
}

#[actix_rt::test]
async fn simple_start() {
    let srv = actix_test::start(|| {
        App::new().service(web::resource("/").to(
            |req: HttpRequest, stream: web::Payload| async move { ws::start(Ws, &req, stream) },
        ))
    });

    common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}


text:
<?php

namespace App\Controller;

use App\Entity\Address;
use App\Form\AddressType;
use App\Helper\PersonHelper;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Address controller.
 *
 * @Route("/address")
 * @/Security("has_role('ROLE_ADMIN')")
 */
class AddressController extends AbstractController
{
    private $translator;

    private $paginator;

    private EntityManagerInterface $entityManager;

    public function __construct(
        TranslatorInterface $translator,
        PaginatorInterface $paginator,
        EntityManagerInterface $entityManager
    ) {
        $this->translator = $translator;
        $this->paginator = $paginator;
        $this->entityManager = $entityManager;
    }

    /**
     * Lists all Address entities.
     *
     * @Route("/index", name="app.address.index", defaults={"_locale"="de"})
     */
    public function index(Request $request, PersonHelper $personHelper): Response
    {
        $repo = $this->entityManager->getRepository(Address::class); /* @var $repo \App\Repository\AddressRepository */

        $filter = $request->get('filter', array());
        if (!empty($filter['no-photo'])) {
            $filter['no-photo'] = $personHelper->getPersonIdsWithoutPhoto();
        }

        $pagination = $this->paginator->paginate(
            $repo->getListFilterQb($filter),
            $request->query->get('page', 1)/*page number*/,
            15, /*limit per page*/
            array(
                'wrap-queries' => true,
                'defaultSortFieldName' => array('address.familyName', 'person.dob'),
                'defaultSortDirection' => 'asc',
            )
        );

        if ($pagination->count() === 1) {
            return $this->redirectToRoute('app.address.edit', [
                'id' => $pagination[0]->getId(),
            ]);
        }

        return $this->render('/address/index.html.twig', array(
            'pagination' => $pagination,
            'person_ids_without_photo' => $personHelper->getPersonIdsWithoutPhoto(),
            //'persons_with_picture' => $personsWithPicture,
        ));
    }

    /**
     * Displays a form to create a new Address entity.
     *
     * @Route("/new", name="app.address.new", methods={"GET", "POST"})
     */
    public function new(Request $request): Response
    {
        $address = new Address();
        $form = $this->createForm(AddressType::class, $address, ['method' => 'POST']);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $this->entityManager->persist($address);
                $this->entityManager->flush();

                $this->addFlash('success', 'The entry has been created.');

                return $this->redirectToRoute('app.address.edit', ['id' => $address->getId()]);
            }

            $this->addFlash('error', 'The submitted data is invalid. Please check your inputs.');
        }

        return $this->render('address/form.html.twig', [
            'entity' => $address,
            'form' => $form->createView(),
        ]);
    }

    /**
     * Displays a form to edit an existing Address entity.
     *
     * @Route("/{id}/edit", name="app.address.edit", methods={"GET", "PUT"})
     */
    public function edit(Address $address, Request $request, PersonHelper $personHelper): Response
    {
        $form = $this->createForm(AddressType::class, $address, ['method' => 'PUT']);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->entityManager->flush();

            // person picture file
            foreach ($request->files->get('person-picture-file', []) as $index => $file) {
                /** @var UploadedFile $file */
                $person = $address->getPersons()->get($index);

                if (!$file) {
                    continue;
                }

                if ($this->isJpegImage($file)) {
                    $file->move($personHelper->getPersonPhotoPath(), $personHelper->getPersonPhotoFilename($person));
                } else {
                    $this->addFlash('warning', $this->translator->trans(
                        'The uploaded photo for "%name%" is not a valid JPEG file.',
                        ['%name%' => $person->getFirstname()]
                    ));
                }
            }

            $this->addFlash('success', 'All changes have been saved.');

            return $this->redirectToRoute('app.address.edit', [
                'id' => $address->getId(),
                'referrer' => $request->query->get('referrer'),
            ]);
        }

        return $this->render('address/form.html.twig', [
            'entity' => $address,
            'form' => $form->createView(),
        ]);
    }

    /**
     * Deletes a Address entity.
     *
     * @Route("/{id}/delete", name="app.address.delete")
     */
    public function delete(Request $request, $id): Response
    {
        $address = $this->entityManager->getRepository(Address::class)->find($id);
        /* @var $address Address */

        if (!$address) {
            throw $this->createNotFoundException('Unable to find Address entity.');
        }

        foreach ($address->getPersons() as $person) {
            if ($person->getLeaderOf()) {
                $person->getLeaderOf()->setLeader(null);
            }
        }

        $this->entityManager->remove($address);
        $this->entityManager->flush();

        $this->addFlash('success', 'The entry has been deleted.');

        if ($referrer = $request->query->get('referrer')) {
            return $this->redirect($referrer);
        }

        return $this->redirectToRoute('app.address.index');
    }

    /**
     * Check if an uploaded file is real jpeg image.
     */
    private static function isJpegImage(UploadedFile $file): bool
    {
        $res = @imagecreatefromjpeg($file->getPathname());

        return $res !== false;
    }
}


text:
package statistics

import (
	"encoding/binary"
	"math"

	"github.com/pingcap/tidb/mysql"
	"github.com/pingcap/tidb/sessionctx/stmtctx"
	"github.com/pingcap/tidb/types"
)

// calcFraction is used to calculate the fraction of the interval [lower, upper] that lies within the [lower, value]
// using the continuous-value assumption.
func calcFraction(lower, upper, value float64) float64 {
	if upper <= lower {
		return 0.5
	}
	if value <= lower {
		return 0
	}
	if value >= upper {
		return 1
	}
	frac := (value - lower) / (upper - lower)
	if math.IsNaN(frac) || math.IsInf(frac, 0) || frac < 0 || frac > 1 {
		return 0.5
	}
	return frac
}

func convertDatumToScalar(value *types.Datum, commonPfxLen int) float64 {
	switch value.Kind() {
	case types.KindMysqlDecimal:
		scalar, err := value.GetMysqlDecimal().ToFloat64()
		if err != nil {
			return 0
		}
		return scalar
	case types.KindMysqlTime:
		valueTime := value.GetMysqlTime()
		var minTime types.Time
		switch valueTime.Type {
		case mysql.TypeDate:
			minTime = types.Time{
				Time: types.MinDatetime,
				Type: mysql.TypeDate,
				Fsp:  types.DefaultFsp,
			}
		case mysql.TypeDatetime:
			minTime = types.Time{
				Time: types.MinDatetime,
				Type: mysql.TypeDatetime,
				Fsp:  types.DefaultFsp,
			}
		case mysql.TypeTimestamp:
			minTime = types.MinTimestamp
		}
		sc := &stmtctx.StatementContext{TimeZone: types.BoundTimezone}
		return float64(valueTime.Sub(sc, &minTime).Duration)
	case types.KindString, types.KindBytes:
		bytes := value.GetBytes()
		if len(bytes) <= commonPfxLen {
			return 0
		}
		return convertBytesToScalar(bytes[commonPfxLen:])
	default:
		// do not know how to convert
		return 0
	}
}

// PreCalculateScalar converts the lower and upper to scalar. When the datum type is KindString or KindBytes, we also
// calculate their common prefix length, because when a value falls between lower and upper, the common prefix
// of lower and upper equals to the common prefix of the lower, upper and the value. For some simple types like `Int64`,
// we do not convert it because we can directly infer the scalar value.
func (hg *Histogram) PreCalculateScalar() {
	len := hg.Len()
	if len == 0 {
		return
	}
	switch hg.GetLower(0).Kind() {
	case types.KindMysqlDecimal, types.KindMysqlTime:
		hg.scalars = make([]scalar, len)
		for i := 0; i < len; i++ {
			hg.scalars[i] = scalar{
				lower: convertDatumToScalar(hg.GetLower(i), 0),
				upper: convertDatumToScalar(hg.GetUpper(i), 0),
			}
		}
	case types.KindBytes, types.KindString:
		hg.scalars = make([]scalar, len)
		for i := 0; i < len; i++ {
			lower, upper := hg.GetLower(i), hg.GetUpper(i)
			common := commonPrefixLength(lower.GetBytes(), upper.GetBytes())
			hg.scalars[i] = scalar{
				commonPfxLen: common,
				lower:        convertDatumToScalar(lower, common),
				upper:        convertDatumToScalar(upper, common),
			}
		}
	}
}

func (hg *Histogram) calcFraction(index int, value *types.Datum) float64 {
	lower, upper := hg.Bounds.GetRow(2*index), hg.Bounds.GetRow(2*index+1)
	switch value.Kind() {
	case types.KindFloat32:
		return calcFraction(float64(lower.GetFloat32(0)), float64(upper.GetFloat32(0)), float64(value.GetFloat32()))
	case types.KindFloat64:
		return calcFraction(lower.GetFloat64(0), upper.GetFloat64(0), value.GetFloat64())
	case types.KindInt64:
		return calcFraction(float64(lower.GetInt64(0)), float64(upper.GetInt64(0)), float64(value.GetInt64()))
	case types.KindUint64:
		return calcFraction(float64(lower.GetUint64(0)), float64(upper.GetUint64(0)), float64(value.GetUint64()))
	case types.KindMysqlDuration:
		return calcFraction(float64(lower.GetDuration(0, 0).Duration), float64(upper.GetDuration(0, 0).Duration), float64(value.GetMysqlDuration().Duration))
	case types.KindMysqlDecimal, types.KindMysqlTime:
		return calcFraction(hg.scalars[index].lower, hg.scalars[index].upper, convertDatumToScalar(value, 0))
	case types.KindBytes, types.KindString:
		return calcFraction(hg.scalars[index].lower, hg.scalars[index].upper, convertDatumToScalar(value, hg.scalars[index].commonPfxLen))
	}
	return 0.5
}

func commonPrefixLength(lower, upper []byte) int {
	minLen := len(lower)
	if minLen > len(upper) {
		minLen = len(upper)
	}
	for i := 0; i < minLen; i++ {
		if lower[i] != upper[i] {
			return i
		}
	}
	return minLen
}

func convertBytesToScalar(value []byte) float64 {
	// Bytes type is viewed as a base-256 value, so we only consider at most 8 bytes.
	var buf [8]byte
	copy(buf[:], value)
	return float64(binary.BigEndian.Uint64(buf[:]))
}


text:
Copyright (c) 2015, Robert 'Bobby' Zenz
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]

MaskBasedPlacer = {
	MASK_VALUE_IGNORE = -1,

	nodes = {}
}

function MaskBasedPlacer:new()
	local instance = {
		nodes = {},
	}

	setmetatable(instance, self)
	self.__index = self

	return instance
end

function MaskBasedPlacer.get_surroundings(manipulator, x, z, y)
	-- We are assigning them explicitly because get_node returns
	-- two values, which means that the resulting table might have
	-- 9 values instead of 8, resulting in a broken logic.
	return {
		[1] = manipulator:get_node(x - 1, z + 1, y),
		[2] = manipulator:get_node(x, z + 1, y),
		[3] = manipulator:get_node(x + 1, z + 1, y),
		[4] = manipulator:get_node(x + 1, z, y),
		[5] = manipulator:get_node(x + 1, z - 1, y),
		[6] = manipulator:get_node(x, z - 1, y),
		[7] = manipulator:get_node(x - 1, z - 1, y),
		[8] = manipulator:get_node(x - 1, z, y)
	}
end

function MaskBasedPlacer.mask_equals(current_surroundings, expected_surroundings)
	if type(expected_surroundings) == "table" then
		if expected_surroundings["not"] ~= nil then
			if type(expected_surroundings["not"]) == "table" then
				for key, value in pairs(expected_surroundings["not"]) do
					if value == current_surroundings then
						return false
					end
				end
			else
				if expected_surroundings["not"] == current_surroundings then
					return false
				end
			end
		else
			for key, value in pairs(expected_surroundings) do
				if value == current_surroundings then
					return true
				end
			end
		end
	elseif expected_surroundings ~= MaskBasedPlacer.MASK_VALUE_IGNORE then
		if expected_surroundings ~= current_surroundings then
			return false
		end
	end

	return true
end

function MaskBasedPlacer.rotate_rotation(rotation, count)
	rotation = rotation or rotationutil.ROT_0

	for counter = 1, count, 1 do
		rotation = rotationutil.increment(rotation)
	end

	return rotation
end

function MaskBasedPlacer.test_nodes(definition, node_above, node_below)
	return MaskBasedPlacer.test_node_single(node_above, definition.node_above)
		and MaskBasedPlacer.test_node_single(node_below, definition.node_below)
		and MaskBasedPlacer.test_node_multiple(node_above, definition.nodes_above)
		and MaskBasedPlacer.test_node_multiple(node_below, definition.nodes_below)
		and MaskBasedPlacer.test_node_single_not(node_above, definition.node_not_above)
		and MaskBasedPlacer.test_node_single_not(node_below, definition.node_not_below)
		and MaskBasedPlacer.test_node_multiple_not(node_above, definition.nodes_not_above)
		and MaskBasedPlacer.test_node_multiple_not(node_below, definition.nodes_not_below)
		and MaskBasedPlacer.test_node_name_single(node_above, definition.node_name_above)
		and MaskBasedPlacer.test_node_name_single(node_below, definition.node_name_below)
		and MaskBasedPlacer.test_node_name_multiple(node_above, definition.node_names_above)
		and MaskBasedPlacer.test_node_name_multiple(node_below, definition.node_names_below)
		and MaskBasedPlacer.test_node_name_single_not(node_above, definition.node_name_not_above)
		and MaskBasedPlacer.test_node_name_single_not(node_below, definition.node_name_not_below)
		and MaskBasedPlacer.test_node_name_multiple_not(node_above, definition.node_names_not_above)
		and MaskBasedPlacer.test_node_name_multiple_not(node_below, definition.node_names_not_below)
end

function MaskBasedPlacer.test_node_multiple_not(node_to_test, expected_nodes)
	if expected_nodes == nil then
		return true
	end

	for key, expected_node in pairs(expected_nodes) do
		if node_to_test == expected_node then
			return false
		end
	end

	return true
end

function MaskBasedPlacer.test_node_name_multiple(node_to_test, expected_nodes)
	if expected_nodes == nil then
		return true
	end

	node_to_test = nodeutil.get_name(node_to_test)

	for key, expected_node in pairs(expected_nodes) do
		if string.match(node_to_test, expected_node) == nil then
			return false
		end
	end

	return true
end

function MaskBasedPlacer.test_node_name_multiple_not(node_to_test, expected_nodes)
	if expected_nodes == nil then
		return true
	end

	node_to_test = nodeutil.get_name(node_to_test)

	for key, expected_node in pairs(expected_nodes) do
		if string.match(node_to_test, expected_node) ~= nil then
			return false
		end
	end

	return true
end

function MaskBasedPlacer.test_node_name_single(node_to_test, expected_node)
	return expected_node == nil
		or string.match(nodeutil.get_name(node_to_test), expected_node) ~= nil
end

function MaskBasedPlacer.test_node_name_single_not(node_to_test, expected_node)
	return expected_node == nil
		or string.match(nodeutil.get_name(node_to_test), expected_node) == nil
end

function MaskBasedPlacer.test_node_single_not(node_to_test, expected_node)
	return expected_node == nil
		or node_to_test ~= expected_node
end

function MaskBasedPlacer.test_node_multiple(node_to_test, expected_nodes)
	if expected_nodes == nil then
		return true
	end

	for key, expected_node in pairs(expected_nodes) do
		if node_to_test == expected_node then
			return true
		end
	end

	return false
end

function MaskBasedPlacer.test_node_single(node_to_test, expected_node)
	return expected_node == nil
		or node_to_test == expected_node
end

function MaskBasedPlacer:register_node(definition)
	local cloned_definition = tableutil.clone(definition)

	cloned_definition.initial_rotation = cloned_definition.initial_rotation or rotationutil.ROT_0

	cloned_definition.node = nodeutil.get_id(cloned_definition.node)

	cloned_definition.node_above = nodeutil.get_id(cloned_definition.node_above)
	cloned_definition.node_below = nodeutil.get_id(cloned_definition.node_below)

	if cloned_definition.nodes_above ~= nil then
		for key, value in pairs(cloned_definition.nodes_above) do
			cloned_definition.nodes_above[key] = nodeutil.get_id(value)
		end
	end

	if cloned_definition.nodes_below ~= nil then
		for key, value in pairs(cloned_definition.nodes_below) do
			cloned_definition.nodes_below[key] = nodeutil.get_id(value)
		end
	end

	cloned_definition.node_not_above = nodeutil.get_id(cloned_definition.node_not_above)
	cloned_definition.node_not_below = nodeutil.get_id(cloned_definition.node_not_below)

	if cloned_definition.nodes_not_above ~= nil then
		for key, value in pairs(cloned_definition.nodes_not_above) do
			cloned_definition.nodes_not_above[key] = nodeutil.get_id(value)
		end
	end

	if cloned_definition.nodes_not_below ~= nil then
		for key, value in pairs(cloned_definition.nodes_not_below) do
			cloned_definition.nodes_not_below[key] = nodeutil.get_id(value)
		end
	end

	cloned_definition.replacement_node = nodeutil.get_id(cloned_definition.replacement_node)

	for key, value in pairs(cloned_definition.surroundings) do
		if type(value) == "table" then
			if value["not"] ~= nil then
				if type(value["not"]) == "table" then
					for sub_key, sub_value in pairs(value["not"]) do
						value["not"][sub_key] = nodeutil.get_id(sub_value)
					end
				else
					value["not"] = nodeutil.get_id(value["not"])
				end
			else
				for sub_key, sub_value in pairs(value) do
					value[sub_key] = nodeutil.get_id(sub_value)
				end
			end
		elseif value ~= MaskBasedPlacer.MASK_VALUE_IGNORE then
			cloned_definition.surroundings[key] = nodeutil.get_id(value)
		end
	end

	if self.nodes[cloned_definition.node] == nil then
		self.nodes[cloned_definition.node] = List:new()
	end

	self.nodes[cloned_definition.node]:add(cloned_definition)
end

function MaskBasedPlacer:run(manipulator, minp, maxp)
	for y = minp.y - 1, maxp.y + 1, 1 do
		for x = minp.x - 1, maxp.x + 1, 1 do
			for z = minp.z - 1, maxp.z + 1, 1 do
				self:run_on_coordinates(manipulator, x, z, y)
			end
		end
	end
end

function MaskBasedPlacer:run_on_coordinates(manipulator, x, z, y)
	local current_node = manipulator:get_node(x, z, y)
	local definitions = self.nodes[current_node]

	if definitions == nil then
		return
	end

	local node_above = manipulator:get_node(x, z, y + 1)
	local node_below = manipulator:get_node(x, z, y - 1)

	if node_above == minetest.CONTENT_IGNORE
		or node_below == minetest.CONTENT_IGNORE then
		return
	end

	local surrounding_nodes = MaskBasedPlacer.get_surroundings(manipulator, x, z, y)

	for key, value in pairs(surrounding_nodes) do
		if value == minetest.CONTENT_IGNORE then
			return
		end
	end

	definitions:foreach(function(definition, index)
		local upside_down = false

		if not MaskBasedPlacer.test_nodes(definition, node_above, node_below) then
			if definition.upside_down
				and MaskBasedPlacer.test_nodes(definition, node_below, node_above) then

				upside_down = true
			else
				return
			end
		end

		local start_index = arrayutil.index(surrounding_nodes, definition.surroundings, MaskBasedPlacer.mask_equals, 2)

		if start_index >= 1 then
			local rotation = MaskBasedPlacer.rotate_rotation(
				definition.initial_rotation,
				math.floor(start_index / 2))

			if upside_down then
				rotation = facedirutil.upsidedown(rotation, definition.upside_down_pseudo_mirroring)
			end

			manipulator:set_node(x, z, y, definition.replacement_node, rotation)

			if definition.after_place ~= nil then
				definition.after_place(x, z, y, definition, rotation, upside_down, manipulator)
			end
		end
	end)
end


text:
<?php declare(strict_types=1);
/**
 * This file is part of the BEAR.Resource package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace BEAR\Resource;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Cache\ArrayCache;
use Ray\Di\Injector;

class FakeRoot extends ResourceObject
{
    public function onGet()
    {
        $fakeChild = (new FakeRo)(new FakeChild);
        $this->body = [
            'one' => 1,
            'two' => new Request((new InvokerFactory)(), $fakeChild)
        ];

        return $this;
    }
}


text:
'use strict';
(function(module) {
  try {
    module = angular.module('tink.tabpanel');
  } catch (e) {
    module = angular.module('tink.tabpanel', []);
  }
  module.directive('tinkTabPanelContent', ['$sce','$compile',function ($sce,$compile) {
    return {
      restrict: 'EA',
      replace: false,
      compile:function compile(tElement, tAttrs, transclude) {
         return {
          pre: function preLink(scope, iElement, iAttrs, controller) { },
          post: function postLink(scope, iElement, iAttrs, controller) {
            scope.changeContent = function(content){
              iElement.html(content);
              $compile(iElement)(scope);
            }
          }
        }
      }
    };
  }]);
})();


text:
using namespace blitz;

class Material {
public:
    virtual double density() const = 0;
};

class Air {
public:
    virtual double density() const { return 0.291; }
};

class Water {
public:
    virtual double density() const { return 0.335; }
};

int main()
{
    Array<Material*,1> A(4);
}


text:
{-# LANGUAGE TemplateHaskell, FunctionalDependencies #-}

{-| Implementation of the Ganeti Instance config object.

-}

{-

Copyright (C) 2014 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Ganeti.Objects.Nic where

import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Types

$(buildParam "Nic" "nicp"
  [ simpleField "mode" [t| NICMode |]
  , simpleField "link" [t| String  |]
  , simpleField "vlan" [t| String |]
  ])

$(buildObject "PartialNic" "nic" $
  [ simpleField "mac" [t| String |]
  , optionalField $ simpleField "ip" [t| String |]
  , simpleField "nicparams" [t| PartialNicParams |]
  , optionalField $ simpleField "network" [t| String |]
  , optionalField $ simpleField "name" [t| String |]
  ] ++ uuidFields)

instance UuidObject PartialNic where
  uuidOf = nicUuid


text:
using System.Configuration;

namespace DynamicaLabs.XrmTools.Data
{
    public class ConnectionSettings : ConfigurationSection
    {
        [ConfigurationProperty("username", IsRequired = false)]
        public string Username
        {
            get { return this["username"].ToString(); }
            set { this["username"] = value; }
        }

        [ConfigurationProperty("password", IsRequired = false)]
        public string Password
        {
            get { return this["password"].ToString(); }
            set { this["password"] = value; }
        }

        [ConfigurationProperty("url", IsRequired = false)]
        public string Url
        {
            get { return this["url"].ToString(); }
            set { this["url"] = value; }
        }

        [ConfigurationProperty("debug", IsRequired = false)]
        public bool Debug
        {
            get { return bool.Parse(this["debug"].ToString()); }
            set { this["debug"] = value; }
        }

        public string ToConnectionString()
        {
            return $"Url={Url}; Username={Username}; Password={Password}";
        }
    }
}


text:
package org.apache.flink.runtime.checkpoint;

import org.apache.flink.core.execution.SavepointFormatType;

import java.util.Objects;

/** The type of checkpoint to perform. */
public class SavepointType implements SnapshotType {

    private final String name;
    private final PostCheckpointAction postCheckpointAction;
    private final SavepointFormatType formatType;

    private SavepointType(
            final String name,
            final PostCheckpointAction postCheckpointAction,
            final SavepointFormatType formatType) {
        this.postCheckpointAction = postCheckpointAction;
        this.name = name;
        this.formatType = formatType;
    }

    public static SavepointType savepoint(SavepointFormatType formatType) {
        return new SavepointType("Savepoint", PostCheckpointAction.NONE, formatType);
    }

    public static SavepointType terminate(SavepointFormatType formatType) {
        return new SavepointType("Terminate Savepoint", PostCheckpointAction.TERMINATE, formatType);
    }

    public static SavepointType suspend(SavepointFormatType formatType) {
        return new SavepointType("Suspend Savepoint", PostCheckpointAction.SUSPEND, formatType);
    }

    public boolean isSavepoint() {
        return true;
    }

    public boolean isSynchronous() {
        return postCheckpointAction != PostCheckpointAction.NONE;
    }

    public PostCheckpointAction getPostCheckpointAction() {
        return postCheckpointAction;
    }

    public boolean shouldAdvanceToEndOfTime() {
        return shouldDrain();
    }

    public boolean shouldDrain() {
        return getPostCheckpointAction() == PostCheckpointAction.TERMINATE;
    }

    public boolean shouldIgnoreEndOfInput() {
        return getPostCheckpointAction() == PostCheckpointAction.SUSPEND;
    }

    public String getName() {
        return name;
    }

    public SavepointFormatType getFormatType() {
        return formatType;
    }

    public SharingFilesStrategy getSharingFilesStrategy() {
        return SharingFilesStrategy.NO_SHARING;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SavepointType that = (SavepointType) o;
        return name.equals(that.name)
                && postCheckpointAction == that.postCheckpointAction
                && formatType == that.formatType;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, postCheckpointAction, formatType);
    }

    @Override
    public String toString() {
        return "SavepointType{"
                + "name='"
                + name
                + '\''
                + ", postCheckpointAction="
                + postCheckpointAction
                + ", formatType="
                + formatType
                + '}';
    }

    /** What's the intended action after the checkpoint (relevant for stopping with savepoint). */
    public enum PostCheckpointAction {
        NONE,
        SUSPEND,
        TERMINATE
    }
}


text:
package com.sparetimelabs.serial;

/**
 * The type Pure java comm driver.
 */
public class PureJavaCommDriver implements CommDriver {

    @Override
    public CommPort getCommPort(String name, int type) {
        return null;
    }

    @Override
    public void initialize() {
    }
}