text:
@implementation DummyAnnotation

-(NSString*)title
{
  return @"Object";
}

@end

redpajama_set_name: RedPajamaGithub


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const phase_1 = require("./phase");
const turn_1 = require("../turn");
const draw_tile_phase_1 = require("./draw-tile-phase");
const immutable_1 = require("immutable");
class NewTurnPhase extends phase_1.Phase {
    update(game) {
        let turn = new turn_1.Turn({ player: this.getNextPlayer(game) });
        let turns = game.turns.push(turn);
        let phase = new draw_tile_phase_1.DrawTilePhase();
        return game.set({ phase, turns });
    }
    actions(game) {
        return immutable_1.List();
    }
    getNextPlayer(game) {
        let players = game.players;
        if (game.turns.isEmpty()) {
            return players.first();
        }
        let currentPlayerIndex = players.indexOf(game.currentTurn.player);
        return players.get((currentPlayerIndex + 1) % players.size);
    }
}
exports.NewTurnPhase = NewTurnPhase;
//# sourceMappingURL=new-turn-phase.js.map


text:
@interface SIViewController ()
@property(nonatomic )  SISocketIOClient *client;
@end

@implementation SIViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.client = [[SISocketIOClient alloc] initWithHost:@"localhost" onPort:3000];
    self.client.delegate = self;
    [self.client open];
	// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction)sendMessage:(id)sender{

    [self.client send:[@"[\"chat message\",\"dsfsdfd\"]" dataUsingEncoding:NSUTF8StringEncoding]];

}

-(void)socketIOClientOnOpen:(SISocketIOClient *)client{

   // [client send:[@"[\"chat message\",\"dsfsdfd\"]" dataUsingEncoding:NSUTF8StringEncoding]];

}

-(void)socketIOClientOnClose:(SISocketIOClient *)client{

}

-(void)socketIOClientOnPacket:(SISocketIOClient *)client packet:(SIEngineIOPacket *)packet{

}

-(void)socketIOClientOnError:(SISocketIOClient *)client error:(NSError *)error{

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
using UnityEngine;
using System.Collections;

public class QA{
	public string title;
	public string preface;
	public string postscript;
	public int usedQuestionLength;
}


text:
<?php

declare(strict_types=1);

namespace Psi\Bridge\ObjectAgent\Doctrine\PhpcrOdm;

use Doctrine\ODM\PHPCR\Query\Builder\AbstractNode;
use Doctrine\ODM\PHPCR\Query\Builder\QueryBuilder;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Composite;
use Psi\Component\ObjectAgent\Query\Expression;

class ExpressionVisitor
{
    private $queryBuilder;
    private $sourceAlias;

    /**
     * @param QueryBuilder $queryBuilder
     */
    public function __construct(QueryBuilder $queryBuilder, string $sourceAlias)
    {
        $this->queryBuilder = $queryBuilder;
        $this->sourceAlias = $sourceAlias;
    }

    /**
     * Walk the given expression to build up the PHPCR-ODM query builder.
     *
     * @param Expression $expr
     * @param AbstractNode|null $parentNode
     */
    public function dispatch(Expression $expr, AbstractNode $parentNode = null)
    {
        if ($parentNode === null) {
            $parentNode = $this->queryBuilder->where();
        }

        switch (true) {
            case $expr instanceof Comparison:
                return $this->walkComparison($expr, $parentNode);

            case $expr instanceof Composite:
                return $this->walkComposite($expr, $parentNode);
        }

        throw new \RuntimeException('Unknown Expression: ' . get_class($expr));
    }

    /**
     * {@inheritdoc}
     */
    private function walkComparison(Comparison $comparison, AbstractNode $parentNode)
    {
        $field = $comparison->getField();
        $value = $comparison->getValue();

        switch ($comparison->getComparator()) {
            case Comparison::EQUALS:
                return $parentNode->eq()->field($this->getField($field))->literal($value)->end();

            case Comparison::NOT_EQUALS:
                return $parentNode->neq()->field($this->getField($field))->literal($value)->end();

            case Comparison::LESS_THAN:
                return $parentNode->lt()->field($this->getField($field))->literal($value)->end();

            case Comparison::LESS_THAN_EQUAL:
                return $parentNode->lte()->field($this->getField($field))->literal($value)->end();

            case Comparison::GREATER_THAN:
                return $parentNode->gt()->field($this->getField($field))->literal($value)->end();

            case Comparison::GREATER_THAN_EQUAL:
                return $parentNode->gte()->field($this->getField($field))->literal($value)->end();

            case Comparison::IN:
                return $this->getInConstraint($parentNode, $field, $value);

            case Comparison::NOT_IN:
                $node = $parentNode->not();
                $this->getInConstraint($node, $field, $value);

                return $node->end();

            case Comparison::CONTAINS:
                return $parentNode->like()->field($this->getField($field))->literal($value)->end();

            case Comparison::NOT_CONTAINS:
                return $parentNode->not()->like()->field($this->getField($field))->literal($value)->end()->end();

            case Comparison::NULL:
                return $parentNode->not()->fieldIsset($this->getField($field))->end();

            case Comparison::NOT_NULL:
                return $parentNode->fieldIsset($this->getField($field));
        }

        throw new \RuntimeException('Unknown comparator: ' . $comparison->getComparator());
    }

    /**
     * {@inheritdoc}
     */
    private function walkComposite(Composite $expression, AbstractNode $parentNode)
    {
        $node = $expression->getType() === Composite::AND ? $parentNode->andX() : $parentNode->orX();

        $expressions = $expression->getExpressions();

        if (empty($expressions)) {
            return $node;
        }

        $leftExpression = array_shift($expressions);
        $this->dispatch($leftExpression, $node);

        $parentNode = $node;
        foreach ($expressions as $index => $expression) {
            if (count($expressions) === $index + 1) {
                $this->dispatch($expression, $parentNode);
                break;
            }

            $this->dispatch($expression, $parentNode);
        }

        return $node;
    }

    /**
     * @param string $field
     *
     * @return string
     */
    private function getField($field): string
    {
        return $this->sourceAlias . '.' . $field;
    }

    /**
     * @param AbstractNode $parentNode
     * @param string $field
     * @param array $values
     */
    private function getInConstraint(AbstractNode $parentNode, $field, array $values)
    {
        $orNode = $parentNode->orx();

        foreach ($values as $value) {
            $orNode->eq()->field($this->getField($field))->literal($value);
        }

        $orNode->end();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

  <View
      android:id="@+id/search_view_scrim"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:alpha="0"
      android:background="?attr/scrimBackground"/>

  <com.google.android.material.internal.ClippableRoundedCornerLayout
      android:id="@+id/search_view_root"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:focusable="true"
      android:focusableInTouchMode="true"
      android:visibility="gone">

    <LinearLayout
        android:id="@+id/search_view_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

      <View
          android:id="@+id/search_view_status_bar_spacer"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:visibility="gone"/>

      <FrameLayout
          android:id="@+id/search_view_header_container"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:visibility="gone"/>

      <FrameLayout
          android:id="@+id/search_view_toolbar_container"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/search_view_dummy_toolbar"
            style="@style/Widget.Material3.SearchView.Toolbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:visibility="gone"/>

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/search_view_toolbar"
            style="@style/Widget.Material3.SearchView.Toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipChildren="false"
            app:navigationContentDescription="@string/searchview_navigation_content_description"
            app:navigationIcon="@drawable/ic_arrow_back_black_24">

          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="@dimen/m3_searchbar_height"
              android:gravity="center_vertical"
              android:orientation="horizontal">

            <TextView
                android:id="@+id/search_view_search_prefix"
                style="?attr/materialSearchViewPrefixStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/search_view_edit_text"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@null"
                android:imeOptions="flagNoExtractUi|actionSearch"
                android:importantForAutofill="no"
                android:inputType="textNoSuggestions"
                android:textDirection="firstStrong"
                tools:ignore="LabelFor"/>

            <ImageButton
                android:id="@+id/search_view_clear_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="16dp"
                android:background="?attr/actionBarItemBackground"
                android:contentDescription="@string/searchview_clear_text_content_description"
                android:visibility="gone"
                app:srcCompat="@drawable/ic_clear_black_24"/>
          </LinearLayout>
        </com.google.android.material.appbar.MaterialToolbar>
      </FrameLayout>

      <View
          android:id="@+id/search_view_divider"
          android:layout_width="match_parent"
          android:layout_height="@dimen/m3_searchview_divider_size"/>

      <com.google.android.material.internal.TouchObserverFrameLayout
          android:id="@+id/search_view_content_container"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>
    </LinearLayout>
  </com.google.android.material.internal.ClippableRoundedCornerLayout>
</merge>


text:
package com.ircclouds.irc.api.dcc;

import com.ircclouds.irc.api.IRCApi;
import com.ircclouds.irc.api.interfaces.Callback;
import com.ircclouds.irc.api.interfaces.IIRCApi;

import net.engio.mbassy.bus.common.DeadMessage;
import net.engio.mbassy.listener.Enveloped;
import net.engio.mbassy.listener.Handler;
import net.engio.mbassy.subscription.MessageEnvelope;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import mockit.Mock;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class TestDCCManager {

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

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    public File saveResource(File output, String name) throws IOException {
        // Step 1:
        InputStream resource = this.getClass().getResourceAsStream(name);
        if (resource == null)
            throw new FileNotFoundException(name + " (resource not found)");
        // Step 2 and automatic step 4
        try(InputStream in = resource;
            OutputStream writer = new BufferedOutputStream(
                    new FileOutputStream(output))) {
            // Step 3
            byte[] buffer = new byte[1024 * 4];
            int length;
            while((length = in.read(buffer)) >= 0) {
                writer.write(buffer, 0, length);
            }
        }
        return output;
    }

    public IIRCApi getApiWithExpectedResponses(final String expectedTarget, final String expectedMessage, final CountDownLatch lock) {
        IIRCApi _api = new IRCApi(false) {
            @Mock
            public void message(String aTarget, String aMessage) {
                assertEquals(expectedTarget, aTarget);
                assertEquals(expectedMessage, aMessage);
            }

            @Mock
            public void message(String aTarget, String aMessage, Callback<String> aCallback) {
                message(aTarget, aMessage);
                assertNull(aCallback);
            }
        };

        _api.register(new Object() {
            @Handler
            public void showDeadMessage(DeadMessage dm) {
                LOG.warn("DEAD MESSAGE! -> " + dm.getClass());
            }

            @Handler
            public void handleReceiverState(DCCReceiver.Event event) {
                LOG.info("receiver event! -> " + event.getClass());
                LOG.info("time taken: " + event.getTimeTaken());
            }

            @Handler
            public void handleSenderState(DCCSender.Event event) {
                LOG.info("sender event! -> " + event.getClass());
                LOG.info("time taken: " + event.getTimeTaken());
            }

            @Handler
            public void handleReceiverProgress(DCCReceiver.Progress event) {
                LOG.info("receiver progress -> " + event.getDeltaBytes());
            }

            @Handler
            public void handleSenderProgress(DCCSender.Progress event) {
                LOG.info("Sender progress -> " + event.getDeltaBytes());
            }

            @Handler
            @Enveloped(messages = {DCCReceiver.Success.class, DCCReceiver.Failure.class, DCCSender.Success.class, DCCSender.Failure.class})
            public void handleDone(MessageEnvelope event) {
                lock.countDown();
            }
        });

        return _api;
    }

    @Test
    public void testDCCAccept() throws IOException, InterruptedException {
        String nick = "ExpectedNick";
        String response = "\001DCC ACCEPT cool_file.doc 1337 0\001";

        File tmpFile = folder.newFile("cool_file.doc");

        CountDownLatch lock = new CountDownLatch(1);

        DCCManager manager = new DCCManager(getApiWithExpectedResponses(nick, response, lock));

        manager.acceptFile(nick, tmpFile, 1337, 0L, 5);

        assertEquals(1, manager.activeDCCSendsCount());

        lock.await(1, TimeUnit.SECONDS);

        assertEquals(0, manager.activeDCCSendsCount());
    }

    @Test
    public void testDCCSend() throws IOException, InterruptedException {
        File tmpFile = folder.newFile("cool_file.doc");

        String nick = "ExpectedNick";
        String response = "\001DCC SEND cool_file.doc localhost 1337 " + tmpFile.length() + "\001";

        CountDownLatch lock = new CountDownLatch(1);

        DCCManager manager = new DCCManager(getApiWithExpectedResponses(nick, response, lock));

        manager.sendFile(nick, tmpFile, "localhost", 1337, 5);

        assertEquals(1, manager.activeDCCSendsCount());

        lock.await(1, TimeUnit.SECONDS);

        assertEquals(0, manager.activeDCCSendsCount());
    }

    @Test
    public void testDCCReceive() throws IOException, InterruptedException {
        File tmpFile = folder.newFile("cool_file.doc");
        File tmpFile1 = folder.newFile("cool_file1.doc");

        saveResource(tmpFile, "test_file.txt");

        LOG.info("LENGTH: " + tmpFile.length());

        String nick = "ExpectedNick";
        String response = "\001DCC SEND cool_file.doc localhost 1337 " + tmpFile.length() + "\001";

        CountDownLatch lock = new CountDownLatch(1);

        DCCManager manager = new DCCManager(getApiWithExpectedResponses(nick, response, lock));

        // Start sender on localhost
        manager.sendFile(nick, tmpFile, "localhost", 1337, 5000);

        // Start download from above sender
        manager.resumeFile(tmpFile1, 0L, tmpFile.length(), new InetSocketAddress("127.0.0.1", 1337));

        assertEquals(1, manager.activeDCCReceivesCount());

        lock.await(1, TimeUnit.SECONDS);

        assertEquals(0, manager.activeDCCReceivesCount());
    }

}


text:
// Code generated by protoc-gen-go.
// source: entropy.proto
// DO NOT EDIT!

/*
Package service is a generated protocol buffer package.

It is generated from these files:
	entropy.proto

It has these top-level messages:
	EntropyRequest
	EntropyResponse
*/
package service

import proto "github.com/chai2010/protorpc/proto"
import math "math"

import "io"
import "log"
import "net"
import "net/rpc"
import "time"
import protorpc "github.com/chai2010/protorpc"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

type EntropyRequest struct {
	Data             *string `protobuf:"bytes,1,req,name=data" json:"data,omitempty"`
	Id               *string `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
	Version          *uint32 `protobuf:"varint,3,opt,name=version" json:"version,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *EntropyRequest) Reset()         { *m = EntropyRequest{} }
func (m *EntropyRequest) String() string { return proto.CompactTextString(m) }
func (*EntropyRequest) ProtoMessage()    {}

func (m *EntropyRequest) GetData() string {
	if m != nil && m.Data != nil {
		return *m.Data
	}
	return ""
}

func (m *EntropyRequest) GetId() string {
	if m != nil && m.Id != nil {
		return *m.Id
	}
	return ""
}

func (m *EntropyRequest) GetVersion() uint32 {
	if m != nil && m.Version != nil {
		return *m.Version
	}
	return 0
}

type EntropyResponse struct {
	Entropy          *float32 `protobuf:"fixed32,1,req,name=entropy" json:"entropy,omitempty"`
	Id               *string  `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
	Version          *uint32  `protobuf:"varint,3,opt,name=version" json:"version,omitempty"`
	XXX_unrecognized []byte   `json:"-"`
}

func (m *EntropyResponse) Reset()         { *m = EntropyResponse{} }
func (m *EntropyResponse) String() string { return proto.CompactTextString(m) }
func (*EntropyResponse) ProtoMessage()    {}

func (m *EntropyResponse) GetEntropy() float32 {
	if m != nil && m.Entropy != nil {
		return *m.Entropy
	}
	return 0
}

func (m *EntropyResponse) GetId() string {
	if m != nil && m.Id != nil {
		return *m.Id
	}
	return ""
}

func (m *EntropyResponse) GetVersion() uint32 {
	if m != nil && m.Version != nil {
		return *m.Version
	}
	return 0
}

func init() {
}

type EntropyService interface {
	Entropy(in *EntropyRequest, out *EntropyResponse) error
}

// AcceptEntropyServiceClient accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func AcceptEntropyServiceClient(lis net.Listener, x EntropyService) {
	srv := rpc.NewServer()
	if err := srv.RegisterName("EntropyService", x); err != nil {
		log.Fatal(err)
	}

	for {
		conn, err := lis.Accept()
		if err != nil {
			log.Fatalf("lis.Accept(): %v\n", err)
		}
		go srv.ServeCodec(protorpc.NewServerCodec(conn))
	}
}

// RegisterEntropyService publish the given EntropyService implementation on the server.
func RegisterEntropyService(srv *rpc.Server, x EntropyService) error {
	if err := srv.RegisterName("EntropyService", x); err != nil {
		return err
	}
	return nil
}

// NewEntropyServiceServer returns a new EntropyService Server.
func NewEntropyServiceServer(x EntropyService) *rpc.Server {
	srv := rpc.NewServer()
	if err := srv.RegisterName("EntropyService", x); err != nil {
		log.Fatal(err)
	}
	return srv
}

// ListenAndServeEntropyService listen announces on the local network address laddr
// and serves the given EntropyService implementation.
func ListenAndServeEntropyService(network, addr string, x EntropyService) error {
	lis, err := net.Listen(network, addr)
	if err != nil {
		return err
	}
	defer lis.Close()

	srv := rpc.NewServer()
	if err := srv.RegisterName("EntropyService", x); err != nil {
		return err
	}

	for {
		conn, err := lis.Accept()
		if err != nil {
			log.Fatalf("lis.Accept(): %v\n", err)
		}
		go srv.ServeCodec(protorpc.NewServerCodec(conn))
	}
}

type EntropyServiceClient struct {
	*rpc.Client
}

// NewEntropyServiceClient returns a EntropyService rpc.Client and stub to handle
// requests to the set of EntropyService at the other end of the connection.
func NewEntropyServiceClient(conn io.ReadWriteCloser) (*EntropyServiceClient, *rpc.Client) {
	c := rpc.NewClientWithCodec(protorpc.NewClientCodec(conn))
	return &EntropyServiceClient{c}, c
}

func (c *EntropyServiceClient) Entropy(in *EntropyRequest, out *EntropyResponse) error {
	return c.Call("EntropyService.Entropy", in, out)
}

// DialEntropyService connects to an EntropyService at the specified network address.
func DialEntropyService(network, addr string) (*EntropyServiceClient, *rpc.Client, error) {
	c, err := protorpc.Dial(network, addr)
	if err != nil {
		return nil, nil, err
	}
	return &EntropyServiceClient{c}, c, nil
}

// DialEntropyServiceTimeout connects to an EntropyService at the specified network address.
func DialEntropyServiceTimeout(network, addr string,
	timeout time.Duration) (*EntropyServiceClient, *rpc.Client, error) {
	c, err := protorpc.DialTimeout(network, addr, timeout)
	if err != nil {
		return nil, nil, err
	}
	return &EntropyServiceClient{c}, c, nil
}


text:
require 'spec_helper'

describe Gitlab::Auth, lib: true do
  let(:gl_auth) { Gitlab::Auth.new }

  describe :find do
    let!(:user) do
      create(:user,
        username: username,
        password: password,
        password_confirmation: password)
    end
    let(:username) { 'John' }     # username isn't lowercase, test this
    let(:password) { 'my-secret' }

    it "should find user by valid login/password" do
      expect( gl_auth.find(username, password) ).to eql user
    end

    it 'should find user by valid email/password with case-insensitive email' do
      expect(gl_auth.find(user.email.upcase, password)).to eql user
    end

    it 'should find user by valid username/password with case-insensitive username' do
      expect(gl_auth.find(username.upcase, password)).to eql user
    end

    it "should not find user with invalid password" do
      password = 'wrong'
      expect( gl_auth.find(username, password) ).not_to eql user
    end

    it "should not find user with invalid login" do
      user = 'wrong'
      expect( gl_auth.find(username, password) ).not_to eql user
    end

    context "with ldap enabled" do
      before do
        allow(Gitlab::LDAP::Config).to receive(:enabled?).and_return(true)
      end

      it "tries to autheticate with db before ldap" do
        expect(Gitlab::LDAP::Authentication).not_to receive(:login)

        gl_auth.find(username, password)
      end

      it "uses ldap as fallback to for authentication" do
        expect(Gitlab::LDAP::Authentication).to receive(:login)

        gl_auth.find('ldap_user', 'password')
      end
    end
  end
end


text:
<?php
/*
 *
 */

namespace RDF\JobDefinitionFormatBundle\Model\JDF\Resource;

use Doctrine\OXM\Mapping as OXM;

/**
 * RDF\JobDefinitionFormatBundle\Model\JDF\Resource\Company
 *
 * @OXM\XmlEntity(xml="Company")
 */
class Company extends Resource
{

}


text:
namespace content {
class WebContents;
}  // namespace content

namespace user_prefs {
class PrefRegistrySyncable;
}  // namespace user_prefs

namespace send_tab_to_self {

void ShowBubble(content::WebContents* web_contents,
                bool show_back_button = false);

void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* user_prefs);

}  // namespace send_tab_to_self

#endif  // CHROME_BROWSER_UI_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_BUBBLE_H_


text:
@interface TJSHomeListDataSourceImpl : NSObject<TJSHomeListDataSource>

@end


text:
const axios = require("axios");
const Cookies = require("../../../../../../shared/lib/cookies").default;

module.exports = class {
    onCreate(input, out) {
        const state = {
            active: false,
            files: [],
            progress: false,
            percentCompleted: 0,
            error: null,
            dropAreaHighlight: false
        };
        this.state = state;
        this.func = {
            setActive: this.setActive.bind(this),
            setDir: this.setDir.bind(this),
        };
        this.i18n = out.global.i18n;
        this.siteId = out.global.siteId;
    }

    onMount() {
        this.fileInput = this.getEl("z3_cr_images_upload_files");
        this.dropArea = this.getEl("z3_cr_images_upload_area");
        this.dropArea.addEventListener("drop", this.handleDragDrop.bind(this), false);
        ["dragenter", "dragover"].map(en => this.dropArea.addEventListener(en, e => {
            e.preventDefault();
            this.state.dropAreaHighlight = true;
        }, false));
        ["dragleave", "drop"].map(en => this.dropArea.addEventListener(en, e => {
            e.preventDefault();
            this.state.dropAreaHighlight = false;
        }, false));
        const cookies = new Cookies(this.cookieOptions);
        this.token = cookies.get(`${this.siteId || "zoia3"}.authToken`);
    }

    handleDragDrop(e) {
        e.preventDefault();
        const {
            files
        } = e.dataTransfer;
        if (files && files.length) {
            this.changeFiles(files);
        }
    }

    setActive(state) {
        this.state.active = state;
        this.state.progress = false;
        this.setState("files", state ? [] : this.state.files);
        this.setState("error", null);
    }

    setDir(dir) {
        this.dir = dir;
    }

    onCloseClick() {
        if (this.state.progress) {
            return;
        }
        this.setActive(false);
    }

    formatBytes(bytes, decimals = 2) {
        const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
        if (bytes === 0) {
            return {
                size: 0,
                unit: sizes[0]
            };
        }
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return {
            size: parseFloat((bytes / (k ** i)).toFixed(dm)),
            unit: sizes[i]
        };
    }

    changeFiles(filesData) {
        const files = Array.from(filesData).map((f, i) => {
            const size = this.formatBytes(f.size);
            return {
                name: f.name,
                size: `${size.size} ${this.i18n.t(size.unit)}`,
                data: filesData[i]
            };
        });
        this.setState("files", files);
    }

    onFileInputChange(e) {
        const filesData = e.target.files;
        this.changeFiles(filesData);
    }

    onFileRemoveClick(e) {
        e.preventDefault();
        const dataset = e.target ? (Object.keys(e.target.dataset).length ? e.target.dataset : Object.keys(e.target.parentNode.dataset).length ? e.target.parentNode.dataset : Object.keys(e.target.parentNode.parentNode.dataset).length ? e.target.parentNode.parentNode.dataset : {}) : e;
        const id = parseInt(dataset.id, 10);
        const {
            files
        } = this.state;
        files.splice(id, 1);
        this.setStateDirty("files", files);
    }

    async onConfirmClick() {
        if (this.state.progress || !this.state.files.length) {
            return;
        }
        this.state.percentCompleted = 0;
        this.state.progress = true;
        const formData = new FormData();
        this.state.files.map(f => {
            formData.append(f.name, f.data);
        });
        formData.append("filesList", JSON.stringify(this.state.files.map(f => f.name)));
        formData.append("currentDir", this.dir);
        try {
            await axios({
                method: "post",
                url: "/api/core/images/upload",
                data: formData,
                headers: {
                    Authorization: `Bearer ${this.token}`
                },
                onUploadProgress: progressEvent => this.state.percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            });
            this.setActive(false);
            this.emit("upload-success");
        } catch (e) {
            this.state.progress = false;
            this.state.error = e && e.response && e.response.data && e.response.data.error ? (e.response.data.error.errorKeyword ? this.i18n.t(e.response.data.error.errorKeyword) : this.i18n.t("couldNotProcess")) : e.message;
            const filesError = e && e.response && e.response.data && e.response.data.error && e.response.data.error.files && e.response.data.error.files.length ? e.response.data.error.files : null;
            if (filesError) {
                const {
                    files
                } = this.state;
                const filesUpdate = files.map(f => {
                    if (filesError.indexOf(f.name) > -1) {
                        f.error = true;
                        return f;
                    }
                    return null;
                }).filter(i => i);
                this.setState("files", filesUpdate);
            }
            this.emit("upload-error");
        }
    }

    onErrorDeleteClick() {
        this.state.error = null;
    }
};


text:
/*
 * This file is part of Openrouteservice.
 *
 * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library;
 * if not, see <https://www.gnu.org/licenses/>.
 */

package org.heigit.ors.routing.graphhopper.extensions.storages;

import com.graphhopper.storage.*;
import org.heigit.ors.routing.RouteExtraInfo;
import org.heigit.ors.routing.RouteSegmentItem;
import org.heigit.ors.routing.RouteWarning;
import org.heigit.ors.routing.graphhopper.extensions.AccessRestrictionType;

/**
 * The graph storage for road access restrictions.
 */
public class RoadAccessRestrictionsGraphStorage implements GraphExtension, WarningGraphExtension {
    private static final int NO_ENTRY = -1;
    private final int efRestrictions;

    protected DataAccess edges;
    protected int edgeEntryIndex = 0;
    protected int edgeEntryBytes;
    protected int edgesCount;
    private byte[] byteData;

    public RoadAccessRestrictionsGraphStorage() {
        efRestrictions = nextBlockEntryIndex(1);
        edgeEntryBytes = edgeEntryIndex;
        edgesCount = 0;
        byteData = new byte[1];
    }

    /**
     * initializes the extended storage to be empty - required for testing purposes as the ext_storage aren't created
     * at the time tests are run
     */
    public void init() {
        if (edgesCount > 0)
            throw new AssertionError("The ORS storage must be initialized only once.");
        Directory d = new RAMDirectory();
        this.edges = d.find("");
    }

    public void init(Graph graph, Directory dir) {
        if (edgesCount > 0)
            throw new AssertionError("The ext_road_access_restrictions storage must be initialized only once.");

        this.edges = dir.find("ext_road_access_restrictions");
    }

    public void setEdgeValue(int edgeId, int restriction) {
        edgesCount++;
        ensureEdgesIndex(edgeId);
        long edgePointer = (long) edgeId * edgeEntryBytes;
        byteData[0] = (byte) restriction;
        edges.setBytes(edgePointer + efRestrictions, byteData, 1);
    }

    public int getEdgeValue(int edgeId, byte[] buffer) {
        long edgeBase = (long) edgeId * edgeEntryBytes;
        edges.getBytes(edgeBase + efRestrictions, buffer, 1);
        return buffer[0] & 0xFF;
    }

    protected final int nextBlockEntryIndex(int size) {
        int res = edgeEntryIndex;
        edgeEntryIndex += size;
        return res;
    }

    public void setSegmentSize(int bytes) {
        edges.setSegmentSize(bytes);
    }

    public GraphExtension create(long initBytes) {
        edges.create(initBytes * edgeEntryBytes);
        return this;
    }

    public void flush() {
        edges.setHeader(0, edgeEntryBytes);
        edges.setHeader(1 * 4, edgesCount);
        edges.flush();
    }

    public void close() {
        edges.close();
    }

    public long getCapacity() {
        return edges.getCapacity();
    }

    public int entries() {
        return edgesCount;
    }

    public boolean loadExisting() {
        if (!edges.loadExisting())
            throw new IllegalStateException("Unable to load storage 'ext_road_access_restrictions'. corrupt file or directory? ");

        edgeEntryBytes = edges.getHeader(0);
        edgesCount = edges.getHeader(4);
        return true;
    }

    void ensureEdgesIndex(int edgeIndex) {
        edges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes);
    }

    public boolean isRequireNodeField() {
        return true;
    }

    public boolean isRequireEdgeField() {
        // we require the additional field in the graph to point to the first
        // entry in the node table
        return true;
    }

    public int getDefaultNodeFieldValue() {
        return -1;
    }

    public int getDefaultEdgeFieldValue() {
        return -1;
    }

    public GraphExtension copyTo(GraphExtension clonedStorage) {
        if (!(clonedStorage instanceof RoadAccessRestrictionsGraphStorage)) {
            throw new IllegalStateException("the extended storage to clone must be the same");
        }

        RoadAccessRestrictionsGraphStorage clonedTC = (RoadAccessRestrictionsGraphStorage) clonedStorage;

        edges.copyTo(clonedTC.edges);
        clonedTC.edgesCount = edgesCount;

        return clonedStorage;
    }

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

    private boolean isUsedForWarnings = false;

    @Override
    public void setIsUsedForWarning(boolean isWarning) {
        isUsedForWarnings = isWarning;
    }

    @Override
    public boolean isUsedForWarning() {
        return isUsedForWarnings;
    }

    @Override
    public String getName() {
        return "roadaccessrestrictions";
    }

    @Override
    public boolean generatesWarning(RouteExtraInfo extra) {
        for (RouteSegmentItem item : extra.getSegments()) {
            if (item.getValue() != NO_ENTRY && item.getValue() != AccessRestrictionType.NONE)
                return true;
        }
        return false;
    }

    @Override
    public RouteWarning getWarning() {
        return new RouteWarning(RouteWarning.ACCESS_RESTRICTION);
    }

}


text:
htl
===

Hidden Text Layer Project


text:
require 'test_helper'
require 'v_object/test_case'

module Tilia
  module VObject
    class BirthdayCalendarGeneratorTest < TestCase
      def test_vcard_string_with_valid_birthday
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_array_of_vcard_strings_with_valid_birthdays
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = []

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;Mr.
FN:John Doe
BDAY:19820210
UID:bar
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:John Doe's Birthday
DTSTART;VALUE=DATE:19820210
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=bar;X-SABRE-VCARD-FN=John Doe:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_array_of_vcard_strings_with_valid_birthdays_via_constructor
        input = []

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;Mr.
FN:John Doe
BDAY:19820210
UID:bar
END:VCARD
VCF

        generator = Tilia::VObject::BirthdayCalendarGenerator.new(input)

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:John Doe's Birthday
DTSTART;VALUE=DATE:19820210
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=bar;X-SABRE-VCARD-FN=John Doe:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_object_with_valid_birthday
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        input = Tilia::VObject::Reader.read(input)

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_array_of_vcard_objects_with_valid_birthdays
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = []

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;Mr.
FN:John Doe
BDAY:19820210
UID:bar
END:VCARD
VCF

        input.map! { |v| Tilia::VObject::Reader.read(v) }

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:John Doe's Birthday
DTSTART;VALUE=DATE:19820210
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=bar;X-SABRE-VCARD-FN=John Doe:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_valid_birthday_with_x_apple_omit_year
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY;X-APPLE-OMIT-YEAR=1604:1604-04-07
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:20000407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump;X-SABRE-OMIT-YEAR=2000:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_valid_birthday_without_year
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:4.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:--04-07
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Birthday
DTSTART;VALUE=DATE:20000407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump;X-SABRE-OMIT-YEAR=2000:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_invalid_birthday
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:foo
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_no_birthday
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_valid_birthday_localized
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:**ANY**
DTSTAMP:**ANY**
SUMMARY:Forrest Gump's Geburtstag
DTSTART;VALUE=DATE:19850407
RRULE:FREQ=YEARLY
TRANSP:TRANSPARENT
X-SABRE-BDAY;X-SABRE-VCARD-UID=foo;X-SABRE-VCARD-FN=Forrest Gump:BDAY
END:VEVENT
END:VCALENDAR
ICS

        generator.objects = input
        generator.format = '%1s\'s Geburtstag'
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_vcard_string_with_empty_birthday_property
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end

      def test_parse_exception
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<INVALID
BEGIN:FOO
FOO:Bar
END:FOO
INVALID

        assert_raises(Tilia::VObject::ParseException) { generator.objects = input }
      end

      def test_invalid_argument_exception
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SUMMARY:Foo
DTSTART;VALUE=DATE:19850407
END:VEVENT
END:VCALENDAR
ICS

        assert_raises(ArgumentError) { generator.objects = input }
      end

      def test_invalid_argument_exception_for_partially_invalid_array
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = []

        input << <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
FN:Forrest Gump
BDAY:19850407
UID:foo
END:VCARD
VCF
        calendar = Tilia::VObject::Component::VCalendar.new

        input = calendar.add(
          'VEVENT',
          'SUMMARY'      => 'Foo',
          'DTSTART'      => Time.zone.parse('NOW')
        )

        assert_raises(ArgumentError) { generator.objects = input }
      end

      def test_broken_vcard_without_fn
        generator = Tilia::VObject::BirthdayCalendarGenerator.new
        input = <<VCF
BEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.
BDAY:19850407
UID:foo
END:VCARD
VCF

        expected = <<ICS
BEGIN:VCALENDAR
VERSION:2.0
END:VCALENDAR
ICS

        generator.objects = input
        output = generator.result

        assert_v_obj_equals(expected, output)
      end
    end
  end
end


text:
namespace Digiseller.Client.Core.Interfaces
{
    interface IDigisellerResponseBase
    {
        int GetRequestStatusCode();
        string GetErrorMessage();
    }
}


text:
require 'delegate'

module Flipper
  module Adapters
    # Internal: Adapter that wraps another adapter with the ability to memoize
    # adapter calls in memory. Used by flipper dsl and the memoizer middleware
    # to make it possible to memoize adapter calls for the duration of a request.
    class Memoizable < SimpleDelegator
      include ::Flipper::Adapter

      FeaturesKey = :flipper_features
      GetAllKey = :all_memoized

      # Internal
      attr_reader :cache

      # Public: The name of the adapter.
      attr_reader :name

      # Internal: The adapter this adapter is wrapping.
      attr_reader :adapter

      # Private
      def self.key_for(key)
        "feature/#{key}"
      end

      # Public
      def initialize(adapter, cache = nil)
        super(adapter)
        @adapter = adapter
        @name = :memoizable
        @cache = cache || {}
        @memoize = false
      end

      # Public
      def features
        if memoizing?
          cache.fetch(FeaturesKey) { cache[FeaturesKey] = @adapter.features }
        else
          @adapter.features
        end
      end

      # Public
      def add(feature)
        @adapter.add(feature).tap { expire_features_set }
      end

      # Public
      def remove(feature)
        @adapter.remove(feature).tap do
          expire_features_set
          expire_feature(feature)
        end
      end

      # Public
      def clear(feature)
        @adapter.clear(feature).tap { expire_feature(feature) }
      end

      # Public
      def get(feature)
        if memoizing?
          cache.fetch(key_for(feature.key)) { cache[key_for(feature.key)] = @adapter.get(feature) }
        else
          @adapter.get(feature)
        end
      end

      # Public
      def get_multi(features)
        if memoizing?
          uncached_features = features.reject { |feature| cache[key_for(feature.key)] }

          if uncached_features.any?
            response = @adapter.get_multi(uncached_features)
            response.each do |key, hash|
              cache[key_for(key)] = hash
            end
          end

          result = {}
          features.each do |feature|
            result[feature.key] = cache[key_for(feature.key)]
          end
          result
        else
          @adapter.get_multi(features)
        end
      end

      def get_all
        if memoizing?
          response = nil
          if cache[GetAllKey]
            response = {}
            cache[FeaturesKey].each do |key|
              response[key] = cache[key_for(key)]
            end
          else
            response = @adapter.get_all
            response.each do |key, value|
              cache[key_for(key)] = value
            end
            cache[FeaturesKey] = response.keys.to_set
            cache[GetAllKey] = true
          end

          # Ensures that looking up other features that do not exist doesn't
          # result in N+1 adapter calls.
          response.default_proc = ->(memo, key) { memo[key] = default_config }
          response
        else
          @adapter.get_all
        end
      end

      # Public
      def enable(feature, gate, thing)
        @adapter.enable(feature, gate, thing).tap { expire_feature(feature) }
      end

      # Public
      def disable(feature, gate, thing)
        @adapter.disable(feature, gate, thing).tap { expire_feature(feature) }
      end

      # Internal: Turns local caching on/off.
      #
      # value - The Boolean that decides if local caching is on.
      def memoize=(value)
        cache.clear
        @memoize = value
      end

      # Internal: Returns true for using local cache, false for not.
      def memoizing?
        !!@memoize
      end

      private

      def key_for(key)
        self.class.key_for(key)
      end

      def expire_feature(feature)
        cache.delete(key_for(feature.key)) if memoizing?
      end

      def expire_features_set
        cache.delete(FeaturesKey) if memoizing?
      end
    end
  end
end


text:
---
layout:     post
title:     	使用Swagger2Markup归档swagger生成的API文档
subtitle:    "\"离线存储 \""
date:       2018-01-30
author:     Mr Chang
header-img: img/post-bg-e2e-ux.jpg
catalog: true
tags:
    - Swagger2Markup
    - swagger

---

# 说明

项目中使用Swagger之后,我们能够很轻松的管理API文档,并非常简单的模拟接口调用,但是构建的文档必须通过在项目中整合 `swagger-ui`、或使用单独部署的 `swagger-ui`和 `/v2/api-docs`返回的配置信息才能展现出您所构建的API文档。本文将在使用Swagger的基础上,再介绍一种生成静态API文档的方法,以便于构建更轻量部署和使用的API文档。

# Swagger2Markup简介

Swagger2Markup是Github上的一个开源项目。该项目主要用来将Swagger自动生成的文档转换成几种流行的格式以便于静态部署和使用,比如:AsciiDoc、Markdown、Confluence。

项目主页:https://github.com/Swagger2Markup/swagger2markup

# 如何使用

在使用Swagger2Markup之前,我们先需要准备一个使用了Swagger的Web项目,可以是直接使用Swagger2的项目

 1. 引入依赖

 		<dependency>
			<groupId>io.github.swagger2markup</groupId>
			<artifactId>swagger2markup</artifactId>
			<version>1.3.1</version>
		</dependency>

		<repositories>
			<repository>
				<snapshots>
					<enabled>true</enabled>
					<updatePolicy>always</updatePolicy>
				</snapshots>
				<id>jcenter-releases</id>
				<name>jcenter</name>
				<url>http://jcenter.bintray.com</url>
			</repository>
		</repositories>

2. 编写一个单元测试用例来生成执行生成文档的代码

		@RunWith(SpringRunner.class)
		@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
		public class SwaggerDemoApplicationTests {

			/**
			 * 生成AsciiDocs格式文档
			 * @throws Exception
			 */
			@Test
			public void generateAsciiDocs() throws Exception {
				//	输出Ascii格式
				Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
						.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
						.withOutputLanguage(Language.ZH)
						.withPathsGroupedBy(GroupBy.TAGS)
						.withGeneratedExamples()
						.withoutInlineSchema()
						.build();

				Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
						.withConfig(config)
						.build()
						.toFolder(Paths.get("./docs/asciidoc/generated"));
			}

			/**
			 * 生成Markdown格式文档
			 * @throws Exception
			 */
			@Test
			public void generateMarkdownDocs() throws Exception {
				//	输出Markdown格式
				Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
						.withMarkupLanguage(MarkupLanguage.MARKDOWN)
						.withOutputLanguage(Language.ZH)
						.withPathsGroupedBy(GroupBy.TAGS)
						.withGeneratedExamples()
						.withoutInlineSchema()
						.build();

				Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
						.withConfig(config)
						.build()
						.toFolder(Paths.get("./docs/markdown/generated"));
			}

			/**
			 * 生成Confluence格式文档
			 * @throws Exception
			 */
			@Test
			public void generateConfluenceDocs() throws Exception {
				//	输出Confluence使用的格式
				Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
						.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
						.withOutputLanguage(Language.ZH)
						.withPathsGroupedBy(GroupBy.TAGS)
						.withGeneratedExamples()
						.withoutInlineSchema()
						.build();

				Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
						.withConfig(config)
						.build()
						.toFolder(Paths.get("./docs/confluence/generated"));
			}

			/**
			 * 生成AsciiDocs格式文档,并汇总成一个文件
			 * @throws Exception
			 */
			@Test
			public void generateAsciiDocsToFile() throws Exception {
				//	输出Ascii到单文件
				Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
						.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
						.withOutputLanguage(Language.ZH)
						.withPathsGroupedBy(GroupBy.TAGS)
						.withGeneratedExamples()
						.withoutInlineSchema()
						.build();

				Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
						.withConfig(config)
						.build()
						.toFile(Paths.get("./docs/asciidoc/generated/all"));
			}

			/**
			 * 生成Markdown格式文档,并汇总成一个文件
			 * @throws Exception
			 */
			@Test
			public void generateMarkdownDocsToFile() throws Exception {
				//	输出Markdown到单文件
				Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
						.withMarkupLanguage(MarkupLanguage.MARKDOWN)
						.withOutputLanguage(Language.ZH)
						.withPathsGroupedBy(GroupBy.TAGS)
						.withGeneratedExamples()
						.withoutInlineSchema()
						.build();

				Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
						.withConfig(config)
						.build()
						.toFile(Paths.get("./docs/markdown/generated/all"));
		}

3. 使用maven插件生成HTML文档

		<plugins>
				<plugin>
					<groupId>org.asciidoctor</groupId>
					<artifactId>asciidoctor-maven-plugin</artifactId>
					<version>1.5.6</version>
					<configuration>
						<sourceDirectory>./docs/asciidoc/generated</sourceDirectory>
						<outputDirectory>./docs/asciidoc/html</outputDirectory>
						<headerFooter>true</headerFooter>
						<doctype>book</doctype>
						<backend>html</backend>
						<sourceHighlighter>coderay</sourceHighlighter>
						<attributes>
							<!--菜单栏在左边-->
							<toc>left</toc>
							<!--多标题排列-->
							<toclevels>3</toclevels>
							<!--自动打数字序号-->
							<sectnums>true</sectnums>
						</attributes>
					</configuration>
				</plugin>
		</plugins>

# 效果

![](https://cdn-blog.oss-cn-beijing.aliyuncs.com/18-1-30/77980397.jpg)

![](https://cdn-blog.oss-cn-beijing.aliyuncs.com/18-1-30/4926790.jpg)

### 实际项目应用后效果

* [实际项目应用后效果](https://cdn-blog.oss-cn-beijing.aliyuncs.com/doc/all.html)

# 代码

    https://github.com/changdaye/swagger-demo

# 鸣谢

   文章出处 : http://blog.didispace.com/swagger2markup-asciidoc/


text:
<?php

/**
 * API Global ACL model
 *
 * @category   Mage
 * @package    Mage_Api2
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Api2_Model_Acl_Global
{
    /**
     * Check if the operation is allowed on resources of given type type for given user type/role
     *
     * @param Mage_Api2_Model_Auth_User_Abstract $apiUser
     * @param string $resourceType
     * @param string $operation
     * @return boolean
     * @throws Mage_Api2_Exception
     */
    public function isAllowed(Mage_Api2_Model_Auth_User_Abstract $apiUser, $resourceType, $operation)
    {
        // skip user without role, e.g. Customer
        if (null === $apiUser->getRole()) {
            return true;
        }
        /** @var $aclInstance Mage_Api2_Model_Acl */
        $aclInstance = Mage::getSingleton(
            'api2/acl',
            array('resource_type' => $resourceType, 'operation' => $operation)
        );

        if (!$aclInstance->hasRole($apiUser->getRole())) {
            throw new Mage_Api2_Exception('Role not found', Mage_Api2_Model_Server::HTTP_UNAUTHORIZED);
        }
        if (!$aclInstance->has($resourceType)) {
            throw new Mage_Api2_Exception('Resource not found', Mage_Api2_Model_Server::HTTP_NOT_FOUND);
        }
        return $aclInstance->isAllowed($apiUser->getRole(), $resourceType, $operation);
    }
}


text:
require("dotenv").config({
    path: ".env.test"
});

const GithubClient = require("../lib/githubClient");
const expect = require("chai").expect;

describe("GithubClient", function() {
    var githubClient;

    describe("using dummy info", function() {
        beforeEach(function() {
            githubClient = new GithubClient("token", "owner/repo");
        });

        describe("#init", function() {
            it("should construct properties properly", function() {
                expect(githubClient.token).to.equal("token");
                expect(githubClient.request).to.not.be.null;
                expect(githubClient.userUrl).to.equal("https://api.github.com/user");
                expect(githubClient.issueUrl).to.equal("https://api.github.com/repos/owner/repo/issues");
            });
        });

        describe("#request", function() {
            it("should set headers", function() {
                const headers = githubClient.request("GET", "example.com").options.headers;

                expect(headers["User-Agent"]).to.equal("GitHub Webhooks");
                expect(headers["Authorization"]).to.equal("token token");
                expect(headers["Content-Type"]).to.equal("application/json");
            });
        });
    });

    describe("using real info", function() {
        beforeEach(function() {
            githubClient = new GithubClient(process.env.GITHUB_TOKEN, "ninjaprox/test-place");
        });

        it("#user should be done", function(done) {
            githubClient.user()
                .then(function() {
                    done();
                })
                .catch(done);
        });

        it("#closeIssue should be done", function(done) {
            githubClient.closeIssue(1)
                .then(function() {
                    done();
                })
                .catch(done);
        });

        it("#createIssue should be done", function(done) {
            githubClient.createIssue("Issue 1", {
                    body: "hello\r\nworld"
                })
                .then(function() {
                    done();
                })
                .catch(done);
        });

        it("#issue should be done", function(done) {
            githubClient.issue(1)
                .then(function() {
                    done();
                })
                .catch(done);
        });

        it("#linkInIssue should be done", function(done) {
            githubClient.linkInIssue(1)
                .then(function(link) {
                    expect(link).to.be.null;
                    done();
                })
                .catch(done);
        });
    });
});


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the ClusterListResult class.
 * @constructor
 * Cluster list results
 *
 * @member {string} [nextLink] The URL to use for getting the next set of
 * results.
 *
 */
class ClusterListResult extends Array {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ClusterListResult
   *
   * @returns {object} metadata of ClusterListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ClusterListResult',
      type: {
        name: 'Composite',
        className: 'ClusterListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ClusterElementType',
                  type: {
                    name: 'Composite',
                    className: 'Cluster'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ClusterListResult;


text:
import codecs
import os
import xml.etree.ElementTree as ET

indir = '../corpora/monk/wright/bibadorned'
first_name = 'John'
surname = 'Arbuckle'

f = codecs.open('output2.txt', 'w', 'utf8')

first_name_tok = first_name.lower()
sentences = []
ntexts = 0
for file in os.listdir(indir):
    print file
    ntexts += 1
    tree = ET.parse(os.path.join(indir, file))
    root = tree.getroot()
    body = root.find('{http://www.tei-c.org/ns/1.0}text/{http://www.tei-c.org/ns/1.0}body')
    doc_sentences = []
    ntoks = 0
    num_sentences = 0
    matching_surnames = set()
    for div in body.findall('{http://www.tei-c.org/ns/1.0}div'):
        current_sentence = []
        between_sentences = True
        contains_name = False
        num_quotes_in_sentence = 0
        prior_tok_is_first_name = False
        for p in div.findall('{http://www.tei-c.org/ns/1.0}p'):
            for el in p:
                if el.tag == '{http://www.tei-c.org/ns/1.0}w':
                    ntoks += 1
                    pos = el.attrib['pos']
                    lem = el.attrib['lem'].lower()
                    if between_sentences:
                        between_sentences = False
                    if prior_tok_is_first_name and (pos in ('np1', 'np-n1') or (pos == 'n1' and el.text[0].isupper())):
                        current_sentence.append(surname)
                        matching_surnames.add(lem)
                    elif prior_tok_is_first_name and (pos == 'npg1' or (pos == 'ng1' and el.text[0].isupper())):
                        current_sentence.append(surname)
                        matching_surnames.add(lem)
                        current_sentence.append("'s")
                    elif pos == 'np1' and lem in matching_surnames:
                        current_sentence.append(surname)
                    elif pos == 'npg1' and lem in matching_surnames:
                        current_sentence.append(surname)
                        current_sentence.append("'s")
                    else:
                        current_sentence.append(el.text)
                    if pos in ('np1', 'npg1') and lem == first_name_tok:
                        contains_name = True
                        prior_tok_is_first_name = True
                    else:
                        prior_tok_is_first_name = False
                    if pos == '"' or lem == '"' or pos == '"' or lem == '"':
                        num_quotes_in_sentence += 1
                    if el.attrib['eos'] == '1':
                        if contains_name and num_quotes_in_sentence % 2 == 0:
                            doc_sentences.append((''.join(current_sentence), ntoks))
                            num_sentences += 1
                        current_sentence = []
                        between_sentences = True
                        contains_name = False
                        num_quotes_in_sentence = 0
                if el.tag == '{http://www.tei-c.org/ns/1.0}c':
                    if not between_sentences:
                        current_sentence.append(el.text)
        doc_sentences.append(('<sectionbreak>', ntoks))
    if ntoks and num_sentences:
        ntoks_total = ntoks
        for sentence, ntoks in doc_sentences:
            sentences.append((sentence, float(ntoks) / ntoks_total))

text = ['Chapter 1\n\n']
chapter_num = 1
nsectionbreaks = 0
last_sentence = '.'
for sentence, ntoks in sorted(sentences, key=lambda x: x[1]):
    if sentence == '<sectionbreak>':
        nsectionbreaks += 1
    else:
        if nsectionbreaks >= ntexts:
            chapter_num += 1
            text.append('\n\n\nChapter ' + str(chapter_num) + '\n\n')
            nsectionbreaks = 0
            last_sentence = '.'
        elif last_sentence.endswith('"') or sentence.startswith('"'):
            text.append('\n\n')
        text.append(sentence + ' ')
        last_sentence = sentence
f.write(''.join(text))


text:
"use strict";

import _ from 'lodash';

export default {
    applyEvents(root, events) {
        _.each(events, modelEvent => applyEvent(root, modelEvent));

        return root;
    },
    applyEvent
}

function applyEvent(root, modelEvent) {
    root.__EventId = modelEvent.id;

    var model = fetchModel(root, modelEvent.route);

    if (modelEvent.payload == null)
    {
        return;
    }

    if (modelEvent.payload.values != null)
    {
        _.assign(model, modelEvent.payload.values);
    }

    if (modelEvent.payload.delete != null)
    {
        _.each(modelEvent.payload.delete, name => delete model[name] );
    }

    return root;
}

function fetchModel(root, route)
{
    var model = root;

    _.each(route, key => {
        model = model[key] || newModel(model, key);
    });

    return model;
}

function newModel(parent, key)
{
    var model = {};

    parent[key] = model;

    return model;
}


text:
/*
neural2d.cpp
https://github.com/davidrmiller/neural2d
David R. Miller, 2014
For more info, see neural2d.h.
*/

#include "neural2d.h"

using namespace std;

int main(int argc, char **argv)
{
    // We need two or three filenames -- we can define them here, or get them from
    // the command line. If they are specified on the command line, they must be in
    // the order: topology, input-data, and optionally, weights.

    string topologyFilename = "";   // Always needed
    string inputDataFilename = ""; // Always needed
    string weightsFilename = "";     // Needed only if saving or restoring weights

    if (argc > 1) topologyFilename  = argv[1];
    if (argc > 2) inputDataFilename = argv[2];
    if (argc > 3) weightsFilename   = argv[3];

    NNet::Net myNet(topologyFilename);   // Create net, neurons, and connections
    myNet.sampleSet.loadSamples(inputDataFilename);

    if (argc > 4 && argv[4][0] == '-' && argv[4][1] == 'p') {
        myNet.isRunning = false;
    }

#if 0
    // Here is an example of TRAINING mode -------------:
    // See the GitHub wiki for example code for VALIDATE and TRAINED modes:
    // https://github.com/davidrmiller/neural2d/wiki

    myNet.eta = 0.001;
    myNet.dynamicEtaAdjust = true;
    myNet.alpha = 0.0;
    myNet.reportEveryNth = 1;
    myNet.repeatInputSamples = true;
    myNet.shuffleInputSamples = true;
    myNet.doneErrorThreshold = 0.01;

    myNet.loadWeights(weightsFilename); // Use weights from a trained net

    do {
        if (myNet.shuffleInputSamples) {
            myNet.sampleSet.shuffle();
        }
        for (uint32_t sampleIdx = 0; sampleIdx < myNet.sampleSet.samples.size(); ++sampleIdx) {
            NNet::Sample &sample = myNet.sampleSet.samples[sampleIdx];
            myNet.feedForward(sample);
            myNet.backProp(sample);
            myNet.reportResults(sample);
            if (myNet.recentAverageError < myNet.doneErrorThreshold) {
                cout << "Solved!   -- Saving weights..." << endl;
                myNet.saveWeights(weightsFilename);
                exit(0);
            }
        }
    } while (myNet.repeatInputSamples);

#endif

#if 0

    // Here is an example of VALIDATE mode -------------:

    myNet.reportEveryNth = 1;
    myNet.repeatInputSamples = false;

    myNet.loadWeights(weightsFilename); // Use weights from a trained net

    do {
        for (uint32_t sampleIdx = 0; sampleIdx < myNet.sampleSet.samples.size(); ++sampleIdx) {
            NNet::Sample &sample = myNet.sampleSet.samples[sampleIdx];
            myNet.feedForward(sample);
            myNet.reportResults(sample);
        }
    } while (myNet.repeatInputSamples);

#endif

#if 0

  // Here is an example of TRAINED mode -------------:

    myNet.reportEveryNth = 1;
    myNet.repeatInputSamples = false;

    myNet.loadWeights(weightsFilename); // Use weights from a trained net

    do {
        for (uint32_t sampleIdx = 0; sampleIdx < myNet.sampleSet.samples.size(); ++sampleIdx) {
            NNet::Sample &sample = myNet.sampleSet.samples[sampleIdx];
            myNet.feedForward(sample);
            myNet.reportResults(sample);
        }
    } while (myNet.repeatInputSamples);

#endif

    cout << "Done." << endl;

    return 0;
}


text:
public class LambdaTest2_neg1 {

    public static void main(String[] args) {
        LambdaTest2_neg1 test = new LambdaTest2_neg1();
        //not convertible - QooRoo is not a SAM
        test.methodQooRoo((Integer i) -> { });
    }

    void methodQooRoo(QooRoo<Integer, Integer, Void> qooroo) { }
}


text:
MonthFormatter::MonthFormatter()
{
	monthNames.push_back("Jan");
	monthNames.push_back("Feb");
	monthNames.push_back("Mar");
	monthNames.push_back("Apr");
	monthNames.push_back("May");
	monthNames.push_back("Jun");
	monthNames.push_back("Jul");
	monthNames.push_back("Aug");
	monthNames.push_back("Sep");
	monthNames.push_back("Oct");
	monthNames.push_back("Nov");
	monthNames.push_back("Dec");
}

MonthFormatter::~MonthFormatter()
{
}

std::string MonthFormatter::formatNumber(const std::string &formatString, int number) throw(Exception &)
{
	std::stringstream stream;

	bool longMonthFormat = (formatString == "MMM");

	if ((formatString != "MM") && !longMonthFormat)
	{
		stream << "DayFormatter::formatNumber: wrong format: " << formatString;
		throw (Exception(stream.str()));
	}

	if ((number < 1) || (number > 12))
	{
		stream << "DayFormatter::formatNumber: number out of range: " << number << " (expecgted 1..12)";
		throw (Exception(stream.str()));
	}

	if (longMonthFormat)
	{
		stream << monthNames[number - 1];
	}
	else
	{
		stream << std::right;
		stream << std::setw(2);
		stream << std::setfill('0');
		stream << number;
	}

	return stream.str();
}

std::string MonthFormatter::formatDate(const std::string &formatString, time_t date) throw(Exception &)
{
	struct tm *dateStruct = localtime(&date);
	return formatNumber(formatString, dateStruct->tm_mon + 1);
}

std::string MonthFormatter::name()
{
	return "Month Formatter";
}


text:
package com.cwenao.datastructure.graph;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Bag is
 * @author cwenao
 * @version $Id Bag.java, v 0.1 2017-08-12 14:33 cwenao Exp $$
 */
public class Bag<T> implements Iterable<T> {

    private GraphNode<T> first;
    private int n;

    public Bag() {
        first = null;
        n = 0;
    }

    public void add(T data) {
        GraphNode<T> oldFirst = first;
        first = new GraphNode<T>(data);
        first.setData(data);
        first.setNext(oldFirst);
        n++;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return n;
    }

    @Override
    public Iterator<T> iterator() {
        return new ListIterator(first);
    }

    private class ListIterator<T extends Comparable> implements Iterator<T> {
        private GraphNode<T> currentNode;

        public ListIterator(GraphNode<T> first) {
            currentNode = first;
        }

        @Override
        public boolean hasNext() {
            return currentNode != null;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            T data = currentNode.getData();
            currentNode = currentNode.getNext();

            return data;
        }
    }
}


text:
from datetime import datetime
import requests

from django.db import models
from django.db.models.signals import post_save

from django.contrib.auth import user_logged_in
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.conf import settings
from foundry.models import Member

# Get imports and errors right for json/simplejson
try:
    import simplejson as json
except ImportError:
    import json

try:
    JSONDecodeError = json.JSONDecodeError
except AttributeError:
    JSONDecodeError = ValueError

# Janrain client id and secret
JANRAIN_URL = settings.JANRAIN_URL

STATUS_SYNCED = 1
STATUS_DIRTY = 2
STATUS_CONFLICT = 4

base_payload = {'client_id': settings.JANRAIN_CLIENT_ID,
           'client_secret': settings.JANRAIN_CLIENT_SECRET,
           'type_name': 'user',
           }

# Mapping user and profile fields to Janrain equivalents. Each tuple is in the
# form (jmbo_name, janrain_name).
field_mappings = (
    ('first_name', 'givenName'),
    ('last_name', 'familyName'),
    ('email', 'email'),
    ('username', 'displayName'),
    )

# TODO: Provide a way for the field mappings to be overridden from settings.py

def map_user_to_janrain(user):
    """
    Given a user object, provide a dictionary of mapped fields and values to
    give to Janrain to update the user.
    """
    maps = {x[0]:x[1] for x in field_mappings}
    attributes = {}
    user_fields = ('first_name', 'last_name', 'username', 'email')

    for field in user_fields:
        value = getattr(user, field, None)
        if value:
            attributes[maps[field]] = value

    return attributes

#TODO: This is for reference only. Remove.
"""
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                    '@/./+/-/_ characters'))
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    last_login = models.DateTimeField(_('last login'), default=timezone.now)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

from prefs:
last_login
date_joined
image
date_taken
view_count
crop_from
effect
facebook_id
twitter_username
address
city
zipcode
province
dob
gender
about_me
mobile_number
receive_sms
receive_email
country
is_profile_complete
    """

@receiver(user_logged_in)
def on_user_logged_in(sender, **kwargs):
    """
    Receiver for when the user logs in. It's placed here on recommendation of
    the Django docs.
    """
    print 'user logged in'
    user = kwargs['user']

    # Get or create the user's Janrain profile
    janrain_profile, created = JanrainProfile.objects.get_or_create(user=user)

    if not janrain_profile:
        janrain_profile = JanrainProfile(user=user)

    # TODO: The following parts may be slow, since the calls are synchronous.
    # Consider queueing.

    # Try to find a user on Janrain to tie to our own user.
    # If no corresponding Janrain user exists, create one.
    # TODO: For now, we don't try to tie these up. We just create a user if we
    # don't have a uuid.
    payload = base_payload.copy()
    if janrain_profile.janrain_uuid:
        # Just update the last logged in time on Janrain. TODO
        pass
    else:
        # Create a Janrain user.
        user_attributes = map_user_to_janrain(user)
        payload ['attributes'] = json.dumps(user_attributes)
        response = requests.post("%s/entity.create" % JANRAIN_URL, data=payload)
        # TODO: Handle response codes other than 200
        struct = json.loads(response.content)
        if struct['stat'] == 'ok':
            janrain_profile.janrain_uuid = struct['uuid']

    janrain_profile.save()
    # Populate the profile of the logged-in user, if possible.

@receiver(post_save, sender=Member)
def on_user_profile_saved(sender, **kwargs):
    """
    Receiver for when the user profile is saved. Push to Janrain.
    """

    # On initial profile save during registration, just return.
    janrain_profiles = JanrainProfile.objects.filter(user=kwargs['instance'])
    if len(janrain_profiles) == 0:
        print 'Initial profile save'
        return

    janrain_profile = janrain_profiles[0]

    # The dirty status is set on profile form save. This prevents spurious
    # overwrites and allows us to retrigger an update if this fails.
    if janrain_profile.status == STATUS_DIRTY:
        payload = base_payload.copy()
        payload['uuid'] = janrain_profile.janrain_uuid
        user_attributes = map_user_to_janrain(janrain_profile.user)
        payload['value'] = json.dumps(user_attributes)
        response = requests.post("%s/entity.update" % JANRAIN_URL, data=payload)
        # TODO: Handle response codes other than 200
        struct = json.loads(response.content)
        if struct['stat'] == 'ok':
            janrain_profile.status = STATUS_SYNCED
            janrain_profile.last_synced = datetime.now()
            #TODO: last synced time set
            janrain_profile.save()

class JanrainProfile(models.Model):

    user = models.ForeignKey(
        User,
        unique=True,
    )

    janrain_uuid = models.CharField(
        max_length=128,
        blank=True,
        null=True,
    )

    last_synced = models.DateTimeField(
        auto_now_add=True,
        null=True,
    )

    # Status indicator. Might be refactored to flags.
    status = models.PositiveIntegerField(
        default=0,
    )

    def __unicode__(self):
        return self.user.username


text:
HWND g_hWnd;
HMENU g_hMenu;
NOTIFYICONDATA g_notifyIconData;

LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM);
void initTrayIcon();
std::string readServerIP();
void websocket_onFailedOrDisconnected();
void CALLBACK timerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime);

int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{
	const char *szClassName = "Hardware-Monitor-AIDA64";

	if (OpenMutexA(MUTEX_ALL_ACCESS, TRUE, szClassName))
	{
		MessageBoxA(0, "Only one instance of this program can be executed at once", "Error", 0);
		return 0;
	}

	CreateMutexA(NULL, TRUE, szClassName);

	auto ip = readServerIP();
	if (!ip.length())
	{
		MessageBoxA(0, "The configuration file 'server_ip.txt' is invalid", "Error", 0);
		return 0;
	}

	websocket_registerCallback(callback_on_fail, (uint32_t) &websocket_onFailedOrDisconnected);
	websocket_registerCallback(callback_on_disconnect, (uint32_t) &websocket_onFailedOrDisconnected);

	if (!websocket_connect(ip.c_str()))
	{
		MessageBoxA(0, "The connection can not be established", "Error", 0);
		return 0;
	}

	MSG messages;
	WNDCLASSEX wincl;

	wincl.hInstance = hThisInstance;
	wincl.lpszClassName = szClassName;
	wincl.lpfnWndProc = wndProc;
	wincl.style = CS_DBLCLKS;
	wincl.cbSize = sizeof (WNDCLASSEX);

	wincl.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	wincl.hIconSm = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	wincl.hCursor = LoadCursor(NULL, IDC_ARROW);
	wincl.lpszMenuName = NULL;
	wincl.cbClsExtra = 0;
	wincl.cbWndExtra = 0;
	wincl.hbrBackground = (HBRUSH) (CreateSolidBrush(RGB(255, 255, 255)));

	if (!RegisterClassEx(&wincl))
		return 0;

	g_hWnd = CreateWindowEx(0, szClassName, "Hardware-Monitor", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, HWND_DESKTOP, NULL, hThisInstance, NULL);

	initTrayIcon();

	ShowWindow(g_hWnd, nCmdShow);
	ShowWindow(g_hWnd, SW_HIDE);

	SetTimer(0, 0, 500, timerProc);

	while (GetMessage(&messages, NULL, 0, 0))
	{
		TranslateMessage(&messages);
		DispatchMessage(&messages);
	}

	websocket_disconnect();
	return messages.wParam;
}

LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_ACTIVATE:
		Shell_NotifyIcon(NIM_ADD, &g_notifyIconData);
		break;
	case WM_CREATE:
		g_hMenu = CreatePopupMenu();
		AppendMenu(g_hMenu, MF_STRING, ID_TRAY_EXIT, TEXT("Exit Hardware-Monitor"));
		break;

	case WM_SYSCOMMAND:
		switch (wParam & 0xFFF0)
		{
		case SC_MINIMIZE:
		case SC_CLOSE:
			return 0;
			break;
		}
		break;
	case WM_SYSICON:
	{
		if (lParam == WM_RBUTTONDOWN)
		{
			POINT curPoint;
			GetCursorPos(&curPoint);

			UINT clicked = TrackPopupMenu(g_hMenu, TPM_RETURNCMD | TPM_NONOTIFY, curPoint.x, curPoint.y, 0, hwnd, NULL);
			if (clicked == ID_TRAY_EXIT)
			{
				Shell_NotifyIcon(NIM_DELETE, &g_notifyIconData);
				PostQuitMessage(0);
			}
		}
		break;
	}

	case WM_NCHITTEST:
	{
		UINT uHitTest = DefWindowProc(hwnd, WM_NCHITTEST, wParam, lParam);
		if (uHitTest == HTCLIENT)
			return HTCAPTION;
		else
			return uHitTest;
	}

	case WM_CLOSE:
		return 0;
		break;

	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}

	return DefWindowProc(hwnd, message, wParam, lParam);
}

void initTrayIcon()
{
	const char *hover = "Hardware-Monitor";

	memset(&g_notifyIconData, 0, sizeof(NOTIFYICONDATA));

	g_notifyIconData.cbSize = sizeof(NOTIFYICONDATA);
	g_notifyIconData.hWnd = g_hWnd;
	g_notifyIconData.uID = ID_TRAY_APP_ICON;
	g_notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
	g_notifyIconData.uCallbackMessage = WM_SYSICON;
	g_notifyIconData.hIcon = (HICON) LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1));
	strncpy(g_notifyIconData.szTip, hover, strlen(hover));
}

std::string readServerIP()
{
	std::fstream fs("server_ip.txt", std::fstream::in);
	if (!fs)
		return{};

	std::stringstream ss;
	ss << fs.rdbuf();

	return ss.str();
}

void websocket_onFailedOrDisconnected()
{
	Sleep(500);
	websocket_connect(readServerIP().c_str());
}

void CALLBACK timerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	execute_safe([&]()
	{
		aida64::API api;
		if (!api.refreshData())
			return;

		using namespace json_spirit;

		TCHAR computerName[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
		DWORD dwSize = MAX_COMPUTERNAME_LENGTH;
		GetComputerName(computerName, &dwSize);

		Object mainJsonObject;
		Array sensorValues;
		for (const auto& i : api.data())
		{
			Object sensorValue;
			sensorValue.push_back(Pair("category", i.category));
			sensorValue.push_back(Pair("id", i.id));
			sensorValue.push_back(Pair("label", i.label));
			sensorValue.push_back(Pair("value", i.value));
			sensorValues.push_back(sensorValue);
		}

		mainJsonObject.push_back(Pair("computerName", computerName));
		mainJsonObject.push_back(Pair("sensorValues", sensorValues));

		std::string data = write_formatted(Value(mainJsonObject));

		websocket_send(data.c_str(), data.length(), false);
	});
}


text:
<?php namespace EstGroupe\Taggable\Contracts;

use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Collection;

interface TaggableContract {

	/**
	 * Return collection of tagged rows related to the tagged model
	 *
	 * @return \Illuminate\Database\Eloquent\Builder
	 */
	public function tagged();

	/**
	 * Perform the action of tagging the model with the given string
	 *
	 * @param $tagName string or array
	 */
	public function tag($tagNames);

	/**
	 * Return array of the tag names related to the current model
	 *
	 * @return array
	 */
	public function tagNames();

	/**
	 * Return array of the tag slugs related to the current model
	 *
	 * @return array
	 */
	public function tagSlugs();

	/**
	 * Remove the tag from this model
	 *
	 * @param $tagName string or array (or null to remove all tags)
	 */
	public function untag($tagNames=null);

	/**
	 * Replace the tags from this model
	 *
	 * @param $tagName string or array
	 */
	public function retag($tagNames);

	/**
	 * Filter model to subset with the given tags
	 *
	 * @param $tagNames array|string
	 */
	public function scopeWithAllTags($query, $tagNames);

	/**
	 * Filter model to subset with the given tags
	 *
	 * @param $tagNames array|string
	 */
	public function scopeWithAnyTag($query, $tagNames);

	/**
	 * Return an array of all of the tags that are in use by this model
	 *
	 * @return \Illuminate\Database\Eloquent\Collection
	 */
	public static function existingTags();

	/**
	 * Should untag on delete
	 */
	public static function untagOnDelete();

	/**
	 * Delete tags that are not used anymore
	 */
	public static function shouldDeleteUnused();

}


text:
package org.apache.flink.state.changelog.restore;

import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.runtime.state.heap.InternalKeyContext;
import org.apache.flink.runtime.state.internal.InternalKvState;
import org.apache.flink.runtime.state.internal.InternalValueState;
import org.apache.flink.state.changelog.StateChangeOperation;

class ValueStateChangeApplier<K, N, T> extends KvStateChangeApplier<K, N> {
    private final InternalValueState<K, N, T> state;

    protected ValueStateChangeApplier(
            InternalKeyContext<K> keyContext, InternalValueState<K, N, T> state) {
        super(keyContext);
        this.state = state;
    }

    @Override
    protected InternalKvState<K, N, ?> getState() {
        return state;
    }

    protected void applyInternal(StateChangeOperation operation, DataInputView in)
            throws Exception {
        switch (operation) {
            case SET:
                state.update(state.getValueSerializer().deserialize(in));
                break;
            case CLEAR:
                state.clear();
                break;
            default:
                throw new IllegalArgumentException("Unknown state change operation: " + operation);
        }
    }
}


text:
.class public interface abstract Landroid/support/v4/view/ed;
.super Ljava/lang/Object;

# virtual methods
.method public abstract a(I)V
.end method

.method public abstract a(IFI)V
.end method

.method public abstract b(I)V
.end method


text:
package com.github.misberner.duzzt.exceptions;

public class SubExpressionParseException extends IllegalArgumentException {
	private static final long serialVersionUID = 1L;

	public SubExpressionParseException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
<#ftl output_format="HTML" auto_esc=true>
<#import "layout/default.html" as layout>
<@layout.default>

Dear ${notificationTarget.name},

You have been invited to be the knowledge transfer adviser for the Innovation Funding Service application:

${applicationId} : ${applicationName}

<@layout.button href="${inviteUrl}" text="Review the invitation" />

Yours sincerely

<@layout.senderHTML />
</@layout.default>


text:
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Stratis.SmartContracts.CLR
{
    ///
    /// Creates gas spend operations with the correct costs
    ///
    public static class GasPriceList
    {
        /// The base cost trying to execute a smart contract.
        public const ulong BaseCost = 10_000;

        /// The cost to create and execute the constructor of a contract. To account for validation and code storage.
        public const ulong CreateCost = 12_000;

        /// The cost for transferring funds to a P2PKH from inside a contract.
        public const ulong TransferCost = 1_000;

        public const int StoragePerByteSavedGasCost = 20;
        public const int StoragePerByteRetrievedGasCost = 1;
        public const int LogPerTopicByteCost = 2;
        public const int LogPerByteCost = 1;
        public const int MethodCallGasCost = 5;
        public const int InstructionGasCost = 1;
        public const ulong StorageCheckContractExistsCost = 5;

        ///
        /// Get the gas cost for a specific instruction. For v1 all instructions are priced equally.
        ///
        public static RuntimeObserver.Gas InstructionOperationCost(Instruction instruction)
        {
            OpCode opcode = instruction.OpCode;
            RuntimeObserver.Gas cost;

            switch (opcode.Name)
            {
                default:
                    cost = (RuntimeObserver.Gas)InstructionGasCost;
                    break;
            }

            return cost;
        }

        ///
        /// Gas cost to log an event inside a contract.
        ///
        public static RuntimeObserver.Gas LogOperationCost(IEnumerable<byte[]> topics, byte[] data)
        {
            int topicCost = topics.Select(x => x.Length * LogPerTopicByteCost).Sum();
            int dataCost = data.Length * LogPerByteCost;
            return (RuntimeObserver.Gas)(ulong) (topicCost + dataCost);
        }

        ///
        /// Get cost to store this key and value.
        ///
        public static RuntimeObserver.Gas StorageSaveOperationCost(byte[] keyBytes, byte[] valueBytes)
        {
            int keyLen = keyBytes != null ? keyBytes.Length : 0;
            int valueLen = valueBytes != null ? valueBytes.Length : 0;

            var cost = (RuntimeObserver.Gas)(ulong)(StoragePerByteSavedGasCost * keyLen + StoragePerByteSavedGasCost * valueLen);
            return cost;
        }

        ///
        /// Get cost to retrieve this value via key.
        ///
        public static RuntimeObserver.Gas StorageRetrieveOperationCost(byte[] keyBytes, byte[] valueBytes)
        {
            int keyLen = keyBytes != null ? keyBytes.Length : 0;
            int valueLen = valueBytes != null ? valueBytes.Length : 0;

            var cost = (RuntimeObserver.Gas)(ulong)(StoragePerByteRetrievedGasCost * keyLen + StoragePerByteRetrievedGasCost * valueLen);
            return cost;
        }

        ///
        /// TODO - Add actual costs
        ///
        public static RuntimeObserver.Gas MethodCallCost(MethodReference methodToCall)
        {
            return (RuntimeObserver.Gas)MethodCallGasCost;
        }
    }
}


text:
import os
import unittest
from unittest import mock

from moto import mock_s3

from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator

BUCKET_NAME = os.environ.get("BUCKET_NAME", "test-airflow-bucket")
TASK_ID = os.environ.get("TASK_ID", "test-s3-operator")

class TestS3CreateBucketOperator(unittest.TestCase):
    def setUp(self):
        self.create_bucket_operator = S3CreateBucketOperator(
            task_id=TASK_ID,
            bucket_name=BUCKET_NAME,
        )

    @mock_s3
    @mock.patch.object(S3Hook, "create_bucket")
    @mock.patch.object(S3Hook, "check_for_bucket")
    def test_execute_if_bucket_exist(self, mock_check_for_bucket, mock_create_bucket):
        mock_check_for_bucket.return_value = True
        # execute s3 bucket create operator
        self.create_bucket_operator.execute({})
        mock_check_for_bucket.assert_called_once_with(BUCKET_NAME)
        mock_create_bucket.assert_not_called()

    @mock_s3
    @mock.patch.object(S3Hook, "create_bucket")
    @mock.patch.object(S3Hook, "check_for_bucket")
    def test_execute_if_not_bucket_exist(self, mock_check_for_bucket, mock_create_bucket):
        mock_check_for_bucket.return_value = False
        # execute s3 bucket create operator
        self.create_bucket_operator.execute({})
        mock_check_for_bucket.assert_called_once_with(BUCKET_NAME)
        mock_create_bucket.assert_called_once_with(bucket_name=BUCKET_NAME, region_name=None)

class TestS3DeleteBucketOperator(unittest.TestCase):
    def setUp(self):
        self.delete_bucket_operator = S3DeleteBucketOperator(
            task_id=TASK_ID,
            bucket_name=BUCKET_NAME,
        )

    @mock_s3
    @mock.patch.object(S3Hook, "delete_bucket")
    @mock.patch.object(S3Hook, "check_for_bucket")
    def test_execute_if_bucket_exist(self, mock_check_for_bucket, mock_delete_bucket):
        mock_check_for_bucket.return_value = True
        # execute s3 bucket delete operator
        self.delete_bucket_operator.execute({})
        mock_check_for_bucket.assert_called_once_with(BUCKET_NAME)
        mock_delete_bucket.assert_called_once_with(bucket_name=BUCKET_NAME, force_delete=False)

    @mock_s3
    @mock.patch.object(S3Hook, "delete_bucket")
    @mock.patch.object(S3Hook, "check_for_bucket")
    def test_execute_if_not_bucket_exist(self, mock_check_for_bucket, mock_delete_bucket):
        mock_check_for_bucket.return_value = False
        # execute s3 bucket delete operator
        self.delete_bucket_operator.execute({})
        mock_check_for_bucket.assert_called_once_with(BUCKET_NAME)
        mock_delete_bucket.assert_not_called()


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - UpdateVirtualMachineFilesResult

Returned by

UpdateVirtualMachineFiles_Task

Extends

DynamicData

See also

UpdateVirtualMachineFilesResultFailedVmFileInfo

Since

vSphere API 4.1

Data Object
                  Description

         UpdateVirtualMachineFilesResult is the result returned
  to the UpdateVirtualMachineFiles_Task method.

Properties

	          Name

	          Type

	          Description

failedVmFile*	UpdateVirtualMachineFilesResultFailedVmFileInfo[]

         The list of virtual machines files the server has attempted
  to update but failed to update.

						Properties inherited from DynamicData

dynamicProperty, dynamicType

*Need not be set

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="UpdateVirtualMachineFilesResult">
            <complexContent>
               <extension base="vim25:DynamicData">
                  <sequence>
                     <element name="failedVmFile" type="vim25:UpdateVirtualMachineFilesResultFailedVmFileInfo" minOccurs="0" maxOccurs="unbounded"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods


text:
package io.r3k.gamify9dotcom.services.challenge1;

import io.r3k.gamify9dotcom.domain.ChallengeReponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class RunGameAndScoreServiceTest {

  @Test
  public void shouldRespondWithSuccessForSinglePointAndGameStartedIndicators() {
    //given
    String givenString = "Java version is: 9\n"
            + "-> support for BufferedImage\n"
            + "Version helper for 1.2+ initialized!\n"
            + "-> using BufferedImage\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Software renderer disposed\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Adding Lightsource: 0\n"
            + "Worker created using 7 queues!\n"
            + "New WorldProcessor created using 1 thread(s) and granularity of 1!\n"
            + "Creating new world processor buffer for thread main\n"
            + "Software renderer disposed\n"
            + "Scored point. Player now has 1 point";
    //when
    RunGameAndScoreService underTest = new RunGameAndScoreService();
    ResponseEntity<ChallengeReponse> response = underTest.readInput(givenString);
    //then
    assertNull(response.getBody().getMessage());
    assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());

  }

  public void shouldRespondWithFailureBecauseAnOldVersionOfJavaIsUsed() {
    //given
    String givenString = "Java version is: 8\n"
            + "-> support for BufferedImage\n"
            + "Version helper for 1.2+ initialized!\n"
            + "-> using BufferedImage\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Software renderer disposed\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Adding Lightsource: 0\n"
            + "Worker created using 7 queues!\n"
            + "New WorldProcessor created using 1 thread(s) and granularity of 1!\n"
            + "Creating new world processor buffer for thread main\n"
            + "Software renderer disposed\n"
            + "Scored point. Player now has 1 point";
    //when
    RunGameAndScoreService underTest = new RunGameAndScoreService();
    ResponseEntity<ChallengeReponse> response = underTest.readInput(givenString);
    //then
    assertEquals("The game has started, but you are runnning with an old version of Java", response.getBody().getMessage());
    assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
  }

  @Test
  public void shouldRespondWithErrorIfNoPointIsScored() {
    //given
    String givenString = "Java version is: 9\n"
            + "-> support for BufferedImage\n"
            + "Version helper for 1.2+ initialized!\n"
            + "-> using BufferedImage\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Software renderer disposed\n"
            + "Software renderer (OpenGL mode) initialized\n"
            + "Adding Lightsource: 0\n"
            + "Worker created using 7 queues!\n"
            + "New WorldProcessor created using 1 thread(s) and granularity of 1!\n"
            + "Creating new world processor buffer for thread main\n"
            + "Software renderer disposed\n";
    //when
    RunGameAndScoreService underTest = new RunGameAndScoreService();
    ResponseEntity<ChallengeReponse> response = underTest.readInput(givenString);
    //then
    assertEquals("The game has started, but you have not scored a point", response.getBody().getMessage());
    assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
  }

  @Test
  public void shouldRespondWithErrorIfInputIsEmpty() {
    //given
    String givenString = "";
    //when
    RunGameAndScoreService underTest = new RunGameAndScoreService();
    ResponseEntity<ChallengeReponse> response = underTest.readInput(givenString);
    //then
    assertEquals("Output does not match the required input for the game", response.getBody().getMessage());
    assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
  }

}