text:
<?php

namespace BlockCypher\AppWallet\Infrastructure\Persistence\Flywheel;

use BlockCypher\AppWallet\Domain\Transaction\EncryptedTransaction;
use BlockCypher\AppWallet\Domain\Transaction\EncryptedTransactionRepository;
use BlockCypher\AppWallet\Domain\Transaction\EncryptedTransactionSpecification;
use BlockCypher\AppWallet\Domain\Transaction\Transaction;
use BlockCypher\AppWallet\Domain\Transaction\TransactionId;
use BlockCypher\AppWallet\Domain\Wallet\WalletId;
use BlockCypher\AppWallet\Infrastructure\Persistence\Flywheel\Document\EncryptedTransactionDocument;
use JamesMoss\Flywheel\Config;
use JamesMoss\Flywheel\Repository;
use JamesMoss\Flywheel\Result;

/**
 * Class FlywheelEncryptedTransactionRepository
 * @package BlockCypher\AppWallet\Infrastructure\Persistence\Flywheel
 */
class FlywheelEncryptedTransactionRepository implements EncryptedTransactionRepository
{
    /**
     * @var Repository
     */
    private $repository;

    /**
     * Constructor
     * @param string $dataDir
     */
    public function __construct($dataDir)
    {
        $config = new Config($dataDir);
        $this->repository = new Repository('transactions', $config);
    }

    /**
     * @param TransactionId $transactionId
     * @return Transaction
     */
    public function transactionOfId(TransactionId $transactionId)
    {
        /** @var Result $result */
        $result = $this->repository->query()
            ->where('id', '==', $transactionId->getValue())
            ->execute();

        if ($result === false) {
            return null;
        }

        if ($result->count() == 0) {
            return null;
        }

        $encryptedTransaction = $this->documentToEncryptedTransaction($result->first());

        return $encryptedTransaction;
    }

    /**
     * @param EncryptedTransactionDocument $encryptedTransactionDocument
     * @return EncryptedTransaction
     */
    private function documentToEncryptedTransaction($encryptedTransactionDocument)
    {
        //DEBUG
        //var_dump($encryptedTransactionDocument);
        //die();

        /** @var EncryptedTransaction $encryptedTransaction */
        $encryptedTransaction = unserialize($encryptedTransactionDocument->data);

        //DEBUG
        //var_dump($encryptedTransaction);
        //die();

        return $encryptedTransaction;
    }

    /**
     * @param string $address
     * @param WalletId $walletId
     * @return EncryptedTransaction
     */
    public function transactionOfWalletId($address, WalletId $walletId)
    {
        // TODO: Code Review: Flywheel does no support multiple where conditions.
        // I have added indexes fields to metadata. It could be done with EncryptedTransactionSpecification
        // on in this method, getting first all wallet transactions and then filtering the transaction.
        // Really we could get the transaction searching only by transactions if we do not allow two wallets to have
        // the same transactions. For for the time being that's possible, although it seems not to be useful.
        // Maybe: two users importing the same address, one of them a watch only wallet and the other one
        // with spend permissions.
        // Or two users sharing a wallet but each of them with his own token.

        /** @var Result $result */
        $result = $this->repository->query()
            ->where('hash-walletId', '==', $address . '-' . $walletId->getValue())
            ->execute();

        if ($result === false) {
            return null;
        }

        if ($result->count() == 0) {
            return null;
        }

        $encryptedTransaction = $this->documentToEncryptedTransaction($result->first());

        return $encryptedTransaction;
    }

    /**
     * @param WalletId $walletId
     * @return EncryptedTransaction
     */
    public function transactionsOfWalletId(WalletId $walletId)
    {
        /** @var EncryptedTransactionDocument[] $result */
        $result = $this->repository->query()
            ->where('walletId', '==', $walletId->getValue())
            ->execute();

        $encryptedTransactions = $this->documentArrayToObjectArray($result);

        return $encryptedTransactions;
    }

    /**
     * @param EncryptedTransactionDocument[] $encryptedTransactionDocuments
     * @return EncryptedTransaction[]
     */
    private function documentArrayToObjectArray($encryptedTransactionDocuments)
    {
        $encryptedTransactions = array();
        foreach ($encryptedTransactionDocuments as $encryptedTransactionDocument) {
            $encryptedTransaction = $this->documentToEncryptedTransaction($encryptedTransactionDocument);
            $encryptedTransactions[] = $encryptedTransaction;
        }
        return $encryptedTransactions;
    }

    /**
     * @param EncryptedTransaction $encryptedTransaction
     * @throws \Exception
     */
    public function insert(EncryptedTransaction $encryptedTransaction)
    {
        $transactionDocument = $this->encryptedTransactionToDocument($encryptedTransaction);
        $this->repository->store($transactionDocument);
    }

    /**
     * @param EncryptedTransaction $encryptedTransaction
     * @return EncryptedTransactionDocument
     */
    private function encryptedTransactionToDocument(EncryptedTransaction $encryptedTransaction)
    {
        $searchFields = array(
            'id' => $encryptedTransaction->getId()->getValue(),
            'walletId' => $encryptedTransaction->getWalletId()->getValue(),
            'hash' => $encryptedTransaction->getHash(),
            'description' => $encryptedTransaction->getDescription(),
            'creationTime' => clone $encryptedTransaction->getCreationTime(),
            // Indexes
            // TODO: use a EncryptedTransactionSpecification
            'hash-walletId' => $encryptedTransaction->getHash() . '-' . $encryptedTransaction->getWalletId()->getValue(),
        );

        $docArray = $searchFields;
        $docArray['data'] = serialize($encryptedTransaction);

        $encryptedTransactionDocument = new EncryptedTransactionDocument($docArray);
        $encryptedTransactionDocument->setId($encryptedTransaction->getId()->getValue());

        return $encryptedTransactionDocument;
    }

    /**
     * @param EncryptedTransaction[] $encryptedTransactions
     * @throws \Exception
     */
    public function insertAll($encryptedTransactions)
    {
        // TODO: Implement insertAll() method.
        throw new \Exception('Not implemented');
    }

    /**
     * @param EncryptedTransaction $encryptedTransaction
     * @throws \Exception
     */
    public function update(EncryptedTransaction $encryptedTransaction)
    {
        // DEBUG
        //var_dump($encryptedTransaction);
        //die();

        $encryptedTransactionDocument = $this->encryptedTransactionToDocument($encryptedTransaction);

        // DEBUG
        //var_dump($encryptedTransactionDocument);
        //die();

        if (!$this->repository->update($encryptedTransactionDocument)) {
            // TODO: custom exception
            throw new \Exception("Error updating encrypted transaction repository");
        };

    }

    /**
     * @param EncryptedTransaction[] $encryptedTransactions
     * @throws \Exception
     */
    public function updateAll($encryptedTransactions)
    {
        // TODO: Implement updateAll() method.
        throw new \Exception('Not implemented');
    }

    /**
     * @param EncryptedTransaction $encryptedTransaction
     * @throws \Exception
     */
    public function delete(EncryptedTransaction $encryptedTransaction)
    {
        // TODO: Implement delete() method.
        throw new \Exception('Not implemented');
    }

    /**
     * @param EncryptedTransaction[] $encryptedTransactions
     * @throws \Exception
     */
    public function deleteAll($encryptedTransactions)
    {
        // TODO: Implement deleteAll() method.
        throw new \Exception('Not implemented');
    }

    /**
     * @param EncryptedTransactionSpecification $specification
     * @return Transaction[]
     * @throws \Exception
     */
    public function query($specification)
    {
        // TODO: Implement query() method.
        throw new \Exception('Not implemented');
    }

    /**
     * @return EncryptedTransaction[]
     */
    public function findAll()
    {
        /** @var EncryptedTransactionDocument[] $result */
        $result = $this->repository->findAll();

        $encryptedTransactions = $this->documentArrayToObjectArray($result);

        return $encryptedTransactions;
    }
}


text:
using Newtonsoft.Json;

namespace AfricasTalkingCS
{
    public class OTPConverter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
                                                                     {
                                                                         MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                                                                         DateParseHandling = DateParseHandling.None,
                                                                     };
    }
}

redpajama_set_name: RedPajamaGithub


text:
class AddNameToAdmins < ActiveRecord::Migration
  def change
    add_column :admins, :name, :string
  end
end


text:
package com.sun.xml.internal.messaging.saaj.soap;

import java.io.*;
import java.util.logging.Logger;

import javax.xml.soap.*;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentType;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParseException;
import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl;
import com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl;
import com.sun.xml.internal.messaging.saaj.soap.ver1_2.Message1_2Impl;
import com.sun.xml.internal.messaging.saaj.util.LogDomainConstants;
import com.sun.xml.internal.messaging.saaj.util.TeeInputStream;

/**
 * A factory for creating SOAP messages.
 *
 * Converted to a placeholder for common functionality between SOAP
 * implementations.
 *
 * @author Phil Goodwin (phil.goodwin@sun.com)
 */
public class MessageFactoryImpl extends MessageFactory {

    protected static final Logger log =
        Logger.getLogger(LogDomainConstants.SOAP_DOMAIN,
                         "com.sun.xml.internal.messaging.saaj.soap.LocalStrings");

    protected  OutputStream listener;

    protected boolean lazyAttachments = false;

    public  OutputStream listen(OutputStream newListener) {
        OutputStream oldListener = listener;
        listener = newListener;
        return oldListener;
    }

    public SOAPMessage createMessage() throws SOAPException {
        throw new UnsupportedOperationException();
    }

    public SOAPMessage createMessage(boolean isFastInfoset,
        boolean acceptFastInfoset) throws SOAPException
    {
        throw new UnsupportedOperationException();
    }

    public SOAPMessage createMessage(MimeHeaders headers, InputStream in)
        throws SOAPException, IOException {
        String contentTypeString = MessageImpl.getContentType(headers);

        if (listener != null) {
            in = new TeeInputStream(in, listener);
        }

        try {
            ContentType contentType = new ContentType(contentTypeString);
            int stat = MessageImpl.identifyContentType(contentType);

            if (MessageImpl.isSoap1_1Content(stat)) {
                return new Message1_1Impl(headers,contentType,stat,in);
            } else if (MessageImpl.isSoap1_2Content(stat)) {
                return new Message1_2Impl(headers,contentType,stat,in);
            } else {
                log.severe("SAAJ0530.soap.unknown.Content-Type");
                throw new SOAPExceptionImpl("Unrecognized Content-Type");
            }
        } catch (ParseException e) {
            log.severe("SAAJ0531.soap.cannot.parse.Content-Type");
            throw new SOAPExceptionImpl(
                "Unable to parse content type: " + e.getMessage());
        }
    }

    protected static final String getContentType(MimeHeaders headers) {
        String[] values = headers.getHeader("Content-Type");
        if (values == null)
            return null;
        else
            return values[0];
    }

    public void setLazyAttachmentOptimization(boolean flag) {
        lazyAttachments = flag;
    }

}


text:
                <button type="button" class="close" aria-hidden="true" data-ng-click="cancel()">×</button>

{{actionRisk}} confirmation

{{confirmationText}}

                <button type="button" class="btn btn-primary" data-ng-click="approve()">Yes</button>
                <button type="button" name="cancelConfirmation" class="btn btn-default" data-ng-click="cancel()">No</button>


text:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Junshoong의 기술블로그</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
        <link rel="stylesheet" href="../../theme/css/pygment.css" />
        <link rel="stylesheet" href="../../theme/css/style.css" />
        <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

 Junshoong의 기술블로그

[Linux] ThinkPad 랩탑 배터리관리 패키지 (tlp) 설치

    2016-10-31, Mon

tlp 설치

이전에도 사용했던 ThinkPad를 위한 배터리관리 패키지인 tlp를 설치했다. 그냥 설치해두고 잊어버려도 되는 편리한 패키지였는데 리눅스를 새로 설치하는 김에 다시 받았다. 실제로 체감은 잘 모르겠어서 당분간 써보고 통계자료를 뽑아볼 수 있으면 다시 추가하도록 하겠다. 배터리 사용 관련 그래프를 나타내주는 패키지로는 gnome-power-manager 가 있다.

$ sudo aura -S tlp
$ sudo tlp start
$ sudo aura -S acpi_call
$ sudo systemctl enable tlp.service
$ sudo systemctl enable tlp-sleep.service
$ sudo systemctl mask systemd-rfkill.service

자세한 배터리 정보와 상태를 확인할 수 있다.

$ sudo tlp stat

간결한 상태를 보고 싶으면 아래 명령어도 유용하다.

$ upower -d

배터리 사용 history 그래프는 gnome-power-manager로 볼 수 있다.

$ sudo aura -S gnome-power-manager
$ gnome-power-statistics

참고 자료

tlp 공식 문서 - arch install

ArchWiki - TLP

Gnome Help - Gnome Power Manager

Arch Forum - Tool for reporting battery stats?

 Category

            Agile
            (2)

            Angular
            (1)

            Blog
            (3)

            Book
            (3)

            CSS
            (1)

            CTF
            (4)

            DevOps
            (2)

            Django
            (6)

            Docker
            (2)

            Editor
            (3)

            English
            (2)

            ETC
            (11)

            Game
            (2)

            Git
            (2)

            Life
            (22)

            Linux
            (19)

            Mac
            (1)

            Movie
            (1)

            Nginx
            (2)

            Pelican
            (1)

            Python
            (8)

            Regex
            (1)

            Shell
            (2)

 Social

         email
         facebook
         linkedin
         slideshare
         github
         stack-overflow
         FEED


text:
@interface PodsDummy_WaniKit : NSObject
@end
@implementation PodsDummy_WaniKit
@end


text:
var VIEW_TYPE = {
  /*
  Default view, fills up the entire page
  */
  PAGE:0,
  /*
  Simple message in middle of screen
  */
  MESSAGE:1,
};

function stopMessage(){
   var body = $('body');
   body.css('visibility','visible');
   $('#message').remove();

   //we dont want the page to spaz out as all the transitions trigger... so using some black magic, we disable transitions, flush the css, and then renable them.
   body.toggleClass('notransition');
   body[0].offsetHeight;//trigger a flush. this works... somehow.
   $('#main-stylesheet').append('*{transition: all 0.3s ease 0s;}');
   body.toggleClass('notransition');
}

function pushView(type,content){
  if(type===VIEW_TYPE.MESSAGE){
    stopMessage();
    var body = $('body');
    body.css('visibility','hidden');
    body.append('
'+content+'
');
  }else if(type===VIEW_TYPE.PAGE){
    //this removes the message, which overloads
    stopMessage();

    $('#page').empty().html(content);
  }
}


text:
#ifndef  __SB_LISTENING_H__
#define  __SB_LISTENING_H__

#include "sb.h"

typedef void (*sb_connection_handler_pt)(sb_connection_t *c);
struct sb_listening_s
{
	int fd;
	int backlog;

	struct sockaddr    *sockaddr;
	socklen_t           socklen;    /* size of sockaddr */

	int                 rcvbuf;
	int                 sndbuf;

	/* handler of accepted connection */
	sb_connection_handler_pt   handler;

	sb_connection_t    *connection;
};

int init_listen();
void   sb_init_connection(sb_connection_t *c);

#endif


text:
/*
 * The Dragonite Project
 * -------------------------
 * See the LICENSE file in the root directory for license information.
 */

package com.vecsight.dragonite.proxy.acl;

import com.vecsight.dragonite.proxy.acl.item.ACLItem;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ParsedACL {

    private final String title;

    private final String author;

    private final ACLItemMethod defaultMethod;

    private final List<ACLItem> items;

    private final ConcurrentHashMap<String, ACLItemMethod> domainCacheMap = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<ByteBuffer, ACLItemMethod> ipCacheMap = new ConcurrentHashMap<>();

    public ParsedACL(final String title, final String author, final ACLItemMethod defaultMethod, final List<ACLItem> items) {
        this.title = title;
        this.author = author;
        this.defaultMethod = defaultMethod;
        this.items = items;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public List<ACLItem> getItems() {
        return items;
    }

    public ACLItemMethod getDefaultMethod() {
        return defaultMethod;
    }

    public ACLItemMethod checkDomain(final String address) {
        final ACLItemMethod cachedMethod = domainCacheMap.get(address);
        if (cachedMethod != null) return cachedMethod;

        byte[] ip;
        try {
            ip = InetAddress.getByName(address).getAddress();
        } catch (final UnknownHostException e) {
            ip = null;
        }

        for (final ACLItem item : items) {
            if (item.match(address) || (ip != null && item.match(ip))) {
                domainCacheMap.put(address, item.getMethod());
                return item.getMethod();
            }
        }
        return defaultMethod;
    }

    public ACLItemMethod checkIP(final byte[] ip) {
        final ACLItemMethod cachedMethod = ipCacheMap.get(ByteBuffer.wrap(ip));
        if (cachedMethod != null) return cachedMethod;

        for (final ACLItem item : items) {
            if (item.match(ip)) {
                ipCacheMap.put(ByteBuffer.wrap(ip), item.getMethod());
                return item.getMethod();
            }
        }

        return defaultMethod;
    }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Runtime.Remoting;

namespace Roslyn.VisualStudio.Test.Utilities
{
    /// <summary>Provides a means of executing code in the Visual Studio host process.</summary>
    /// <remarks>This object exists in the Visual Studio host and is marhsalled across the process boundary.</remarks>
    internal class IntegrationService : MarshalByRefObject
    {
        // Make the channel name well known by using a static base and appending the process ID of the host
        public static readonly string PortNameFormatString = $"{nameof(IntegrationService)}_{{0}}";

        private ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>();

        public string Execute(string assemblyFilePath, string typeFullName, string methodName, BindingFlags bindingFlags, params object[] parameters)
        {
            var assembly = Assembly.LoadFrom(assemblyFilePath);
            var type = assembly.GetType(typeFullName);
            var methodInfo = type.GetMethod(methodName, bindingFlags);
            var result = methodInfo.Invoke(null, parameters);

            if (methodInfo.ReturnType == typeof(void))
            {
                return null;
            }

            // Create a unique URL for each object returned, so that we can communicate with each object individually
            var resultType = result.GetType();
            var marshallableResult = (MarshalByRefObject)(result);
            var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}";
            var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType);

            if (!_marshalledObjects.TryAdd(objectUri, marshalledObject))
            {
                throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})");
            }

            return objectUri;
        }
    }
}


text:
package excelize

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"image"
	"io"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
)

// parsePictureOptions provides a function to parse the format settings of
// the picture with default value.
func parsePictureOptions(opts string) (*pictureOptions, error) {
	format := pictureOptions{
		FPrintsWithSheet: true,
		XScale:           1,
		YScale:           1,
	}
	err := json.Unmarshal(fallbackOptions(opts), &format)
	return &format, err
}

// AddPicture provides the method to add picture in a sheet by given picture
// format set (such as offset, scale, aspect ratio setting and print settings)
// and file path. This function is concurrency safe. For example:
//
//	package main
//
//	import (
//	    _ "image/gif"
//	    _ "image/jpeg"
//	    _ "image/png"
//
//	    "github.com/xuri/excelize/v2"
//	)
//
//	func main() {
//	    f := excelize.NewFile()
//	    // Insert a picture.
//	    if err := f.AddPicture("Sheet1", "A2", "image.jpg", ""); err != nil {
//	        fmt.Println(err)
//	    }
//	    // Insert a picture scaling in the cell with location hyperlink.
//	    if err := f.AddPicture("Sheet1", "D2", "image.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`); err != nil {
//	        fmt.Println(err)
//	    }
//	    // Insert a picture offset in the cell with external hyperlink, printing and positioning support.
//	    if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "hyperlink": "https://github.com/xuri/excelize", "hyperlink_type": "External", "print_obj": true, "lock_aspect_ratio": false, "locked": false, "positioning": "oneCell"}`); err != nil {
//	        fmt.Println(err)
//	    }
//	    if err := f.SaveAs("Book1.xlsx"); err != nil {
//	        fmt.Println(err)
//	    }
//	}
//
// The optional parameter "autofit" specifies if you make image size auto-fits the
// cell, the default value of that is 'false'.
//
// The optional parameter "hyperlink" specifies the hyperlink of the image.
//
// The optional parameter "hyperlink_type" defines two types of
// hyperlink "External" for website or "Location" for moving to one of the
// cells in this workbook. When the "hyperlink_type" is "Location",
// coordinates need to start with "#".
//
// The optional parameter "positioning" defines two types of the position of an
// image in an Excel spreadsheet, "oneCell" (Move but don't size with
// cells) or "absolute" (Don't move or size with cells). If you don't set this
// parameter, the default positioning is move and size with cells.
//
// The optional parameter "print_obj" indicates whether the image is printed
// when the worksheet is printed, the default value of that is 'true'.
//
// The optional parameter "lock_aspect_ratio" indicates whether lock aspect
// ratio for the image, the default value of that is 'false'.
//
// The optional parameter "locked" indicates whether lock the image. Locking
// an object has no effect unless the sheet is protected.
//
// The optional parameter "x_offset" specifies the horizontal offset of the
// image with the cell, the default value of that is 0.
//
// The optional parameter "x_scale" specifies the horizontal scale of images,
// the default value of that is 1.0 which presents 100%.
//
// The optional parameter "y_offset" specifies the vertical offset of the
// image with the cell, the default value of that is 0.
//
// The optional parameter "y_scale" specifies the vertical scale of images,
// the default value of that is 1.0 which presents 100%.
func (f *File) AddPicture(sheet, cell, picture, format string) error {
	var err error
	// Check picture exists first.
	if _, err = os.Stat(picture); os.IsNotExist(err) {
		return err
	}
	ext, ok := supportedImageTypes[path.Ext(picture)]
	if !ok {
		return ErrImgExt
	}
	file, _ := os.ReadFile(filepath.Clean(picture))
	_, name := filepath.Split(picture)
	return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
}

// AddPictureFromBytes provides the method to add picture in a sheet by given
// picture format set (such as offset, scale, aspect ratio setting and print
// settings), file base name, extension name and file bytes. For example:
//
//	package main
//
//	import (
//	    "fmt"
//	    _ "image/jpeg"
//	    "os"
//
//	    "github.com/xuri/excelize/v2"
//	)
//
//	func main() {
//	    f := excelize.NewFile()
//
//	    file, err := os.ReadFile("image.jpg")
//	    if err != nil {
//	        fmt.Println(err)
//	    }
//	    if err := f.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file); err != nil {
//	        fmt.Println(err)
//	    }
//	    if err := f.SaveAs("Book1.xlsx"); err != nil {
//	        fmt.Println(err)
//	    }
//	}
func (f *File) AddPictureFromBytes(sheet, cell, opts, name, extension string, file []byte) error {
	var drawingHyperlinkRID int
	var hyperlinkType string
	ext, ok := supportedImageTypes[extension]
	if !ok {
		return ErrImgExt
	}
	options, err := parsePictureOptions(opts)
	if err != nil {
		return err
	}
	img, _, err := image.DecodeConfig(bytes.NewReader(file))
	if err != nil {
		return err
	}
	// Read sheet data.
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return err
	}
	ws.Lock()
	// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
	drawingID := f.countDrawings() + 1
	drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
	drawingID, drawingXML = f.prepareDrawing(ws, drawingID, sheet, drawingXML)
	drawingRels := "xl/drawings/_rels/drawing" + strconv.Itoa(drawingID) + ".xml.rels"
	mediaStr := ".." + strings.TrimPrefix(f.addMedia(file, ext), "xl")
	drawingRID := f.addRels(drawingRels, SourceRelationshipImage, mediaStr, hyperlinkType)
	// Add picture with hyperlink.
	if options.Hyperlink != "" && options.HyperlinkType != "" {
		if options.HyperlinkType == "External" {
			hyperlinkType = options.HyperlinkType
		}
		drawingHyperlinkRID = f.addRels(drawingRels, SourceRelationshipHyperLink, options.Hyperlink, hyperlinkType)
	}
	ws.Unlock()
	err = f.addDrawingPicture(sheet, drawingXML, cell, name, ext, drawingRID, drawingHyperlinkRID, img, options)
	if err != nil {
		return err
	}
	if err = f.addContentTypePart(drawingID, "drawings"); err != nil {
		return err
	}
	f.addSheetNameSpace(sheet, SourceRelationship)
	return err
}

// deleteSheetRelationships provides a function to delete relationships in
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) deleteSheetRelationships(sheet, rID string) {
	name, ok := f.getSheetXMLPath(sheet)
	if !ok {
		name = strings.ToLower(sheet) + ".xml"
	}
	rels := "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
	sheetRels, _ := f.relsReader(rels)
	if sheetRels == nil {
		sheetRels = &xlsxRelationships{}
	}
	sheetRels.Lock()
	defer sheetRels.Unlock()
	for k, v := range sheetRels.Relationships {
		if v.ID == rID {
			sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
		}
	}
	f.Relationships.Store(rels, sheetRels)
}

// addSheetLegacyDrawing provides a function to add legacy drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
	ws, _ := f.workSheetReader(sheet)
	ws.LegacyDrawing = &xlsxLegacyDrawing{
		RID: "rId" + strconv.Itoa(rID),
	}
}

// addSheetDrawing provides a function to add drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetDrawing(sheet string, rID int) {
	ws, _ := f.workSheetReader(sheet)
	ws.Drawing = &xlsxDrawing{
		RID: "rId" + strconv.Itoa(rID),
	}
}

// addSheetPicture provides a function to add picture element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetPicture(sheet string, rID int) error {
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return err
	}
	ws.Picture = &xlsxPicture{
		RID: "rId" + strconv.Itoa(rID),
	}
	return err
}

// countDrawings provides a function to get drawing files count storage in the
// folder xl/drawings.
func (f *File) countDrawings() (count int) {
	f.Pkg.Range(func(k, v interface{}) bool {
		if strings.Contains(k.(string), "xl/drawings/drawing") {
			count++
		}
		return true
	})
	f.Drawings.Range(func(rel, value interface{}) bool {
		if strings.Contains(rel.(string), "xl/drawings/drawing") {
			count++
		}
		return true
	})
	return
}

// addDrawingPicture provides a function to add picture by given sheet,
// drawingXML, cell, file name, width, height relationship index and format
// sets.
func (f *File) addDrawingPicture(sheet, drawingXML, cell, file, ext string, rID, hyperlinkRID int, img image.Config, opts *pictureOptions) error {
	col, row, err := CellNameToCoordinates(cell)
	if err != nil {
		return err
	}
	width, height := img.Width, img.Height
	if opts.Autofit {
		width, height, col, row, err = f.drawingResize(sheet, cell, float64(width), float64(height), opts)
		if err != nil {
			return err
		}
	} else {
		width = int(float64(width) * opts.XScale)
		height = int(float64(height) * opts.YScale)
	}
	col--
	row--
	colStart, rowStart, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, opts.OffsetX, opts.OffsetY, width, height)
	content, cNvPrID, err := f.drawingParser(drawingXML)
	if err != nil {
		return err
	}
	twoCellAnchor := xdrCellAnchor{}
	twoCellAnchor.EditAs = opts.Positioning
	from := xlsxFrom{}
	from.Col = colStart
	from.ColOff = opts.OffsetX * EMU
	from.Row = rowStart
	from.RowOff = opts.OffsetY * EMU
	to := xlsxTo{}
	to.Col = colEnd
	to.ColOff = x2 * EMU
	to.Row = rowEnd
	to.RowOff = y2 * EMU
	twoCellAnchor.From = &from
	twoCellAnchor.To = &to
	pic := xlsxPic{}
	pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = opts.NoChangeAspect
	pic.NvPicPr.CNvPr.ID = cNvPrID
	pic.NvPicPr.CNvPr.Descr = file
	pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
	if hyperlinkRID != 0 {
		pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
			R:   SourceRelationship.Value,
			RID: "rId" + strconv.Itoa(hyperlinkRID),
		}
	}
	pic.BlipFill.Blip.R = SourceRelationship.Value
	pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
	if ext == ".svg" {
		pic.BlipFill.Blip.ExtList = &xlsxEGOfficeArtExtensionList{
			Ext: []xlsxCTOfficeArtExtension{
				{
					URI: ExtURISVG,
					SVGBlip: xlsxCTSVGBlip{
						XMLNSaAVG: NameSpaceDrawing2016SVG.Value,
						Embed:     pic.BlipFill.Blip.Embed,
					},
				},
			},
		}
	}
	pic.SpPr.PrstGeom.Prst = "rect"

	twoCellAnchor.Pic = &pic
	twoCellAnchor.ClientData = &xdrClientData{
		FLocksWithSheet:  opts.FLocksWithSheet,
		FPrintsWithSheet: opts.FPrintsWithSheet,
	}
	content.Lock()
	defer content.Unlock()
	content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
	f.Drawings.Store(drawingXML, content)
	return err
}

// countMedia provides a function to get media files count storage in the
// folder xl/media/image.
func (f *File) countMedia() int {
	count := 0
	f.Pkg.Range(func(k, v interface{}) bool {
		if strings.Contains(k.(string), "xl/media/image") {
			count++
		}
		return true
	})
	return count
}

// addMedia provides a function to add a picture into folder xl/media/image by
// given file and extension name. Duplicate images are only actually stored once
// and drawings that use it will reference the same image.
func (f *File) addMedia(file []byte, ext string) string {
	count := f.countMedia()
	var name string
	f.Pkg.Range(func(k, existing interface{}) bool {
		if !strings.HasPrefix(k.(string), "xl/media/image") {
			return true
		}
		if bytes.Equal(file, existing.([]byte)) {
			name = k.(string)
			return false
		}
		return true
	})
	if name != "" {
		return name
	}
	media := "xl/media/image" + strconv.Itoa(count+1) + ext
	f.Pkg.Store(media, file)
	return media
}

// setContentTypePartImageExtensions provides a function to set the content
// type for relationship parts and the Main Document part.
func (f *File) setContentTypePartImageExtensions() error {
	imageTypes := map[string]string{
		"jpeg": "image/", "png": "image/", "gif": "image/", "svg": "image/", "tiff": "image/",
		"emf": "image/x-", "wmf": "image/x-", "emz": "image/x-", "wmz": "image/x-",
	}
	content, err := f.contentTypesReader()
	if err != nil {
		return err
	}
	content.Lock()
	defer content.Unlock()
	for _, file := range content.Defaults {
		delete(imageTypes, file.Extension)
	}
	for extension, prefix := range imageTypes {
		content.Defaults = append(content.Defaults, xlsxDefault{
			Extension:   extension,
			ContentType: prefix + extension,
		})
	}
	return err
}

// setContentTypePartVMLExtensions provides a function to set the content type
// for relationship parts and the Main Document part.
func (f *File) setContentTypePartVMLExtensions() error {
	var vml bool
	content, err := f.contentTypesReader()
	if err != nil {
		return err
	}
	content.Lock()
	defer content.Unlock()
	for _, v := range content.Defaults {
		if v.Extension == "vml" {
			vml = true
		}
	}
	if !vml {
		content.Defaults = append(content.Defaults, xlsxDefault{
			Extension:   "vml",
			ContentType: ContentTypeVML,
		})
	}
	return err
}

// addContentTypePart provides a function to add content type part
// relationships in the file [Content_Types].xml by given index.
func (f *File) addContentTypePart(index int, contentType string) error {
	setContentType := map[string]func() error{
		"comments": f.setContentTypePartVMLExtensions,
		"drawings": f.setContentTypePartImageExtensions,
	}
	partNames := map[string]string{
		"chart":         "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
		"chartsheet":    "/xl/chartsheets/sheet" + strconv.Itoa(index) + ".xml",
		"comments":      "/xl/comments" + strconv.Itoa(index) + ".xml",
		"drawings":      "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
		"table":         "/xl/tables/table" + strconv.Itoa(index) + ".xml",
		"pivotTable":    "/xl/pivotTables/pivotTable" + strconv.Itoa(index) + ".xml",
		"pivotCache":    "/xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(index) + ".xml",
		"sharedStrings": "/xl/sharedStrings.xml",
	}
	contentTypes := map[string]string{
		"chart":         ContentTypeDrawingML,
		"chartsheet":    ContentTypeSpreadSheetMLChartsheet,
		"comments":      ContentTypeSpreadSheetMLComments,
		"drawings":      ContentTypeDrawing,
		"table":         ContentTypeSpreadSheetMLTable,
		"pivotTable":    ContentTypeSpreadSheetMLPivotTable,
		"pivotCache":    ContentTypeSpreadSheetMLPivotCacheDefinition,
		"sharedStrings": ContentTypeSpreadSheetMLSharedStrings,
	}
	s, ok := setContentType[contentType]
	if ok {
		if err := s(); err != nil {
			return err
		}
	}
	content, err := f.contentTypesReader()
	if err != nil {
		return err
	}
	content.Lock()
	defer content.Unlock()
	for _, v := range content.Overrides {
		if v.PartName == partNames[contentType] {
			return err
		}
	}
	content.Overrides = append(content.Overrides, xlsxOverride{
		PartName:    partNames[contentType],
		ContentType: contentTypes[contentType],
	})
	return err
}

// getSheetRelationshipsTargetByID provides a function to get Target attribute
// value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
	name, ok := f.getSheetXMLPath(sheet)
	if !ok {
		name = strings.ToLower(sheet) + ".xml"
	}
	rels := "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
	sheetRels, _ := f.relsReader(rels)
	if sheetRels == nil {
		sheetRels = &xlsxRelationships{}
	}
	sheetRels.Lock()
	defer sheetRels.Unlock()
	for _, v := range sheetRels.Relationships {
		if v.ID == rID {
			return v.Target
		}
	}
	return ""
}

// GetPicture provides a function to get picture base name and raw content
// embed in spreadsheet by given worksheet and cell name. This function
// returns the file name in spreadsheet and file contents as []byte data
// types. This function is concurrency safe. For example:
//
//	f, err := excelize.OpenFile("Book1.xlsx")
//	if err != nil {
//	    fmt.Println(err)
//	    return
//	}
//	defer func() {
//	    if err := f.Close(); err != nil {
//	        fmt.Println(err)
//	    }
//	}()
//	file, raw, err := f.GetPicture("Sheet1", "A2")
//	if err != nil {
//	    fmt.Println(err)
//	    return
//	}
//	if err := os.WriteFile(file, raw, 0644); err != nil {
//	    fmt.Println(err)
//	}
func (f *File) GetPicture(sheet, cell string) (string, []byte, error) {
	col, row, err := CellNameToCoordinates(cell)
	if err != nil {
		return "", nil, err
	}
	col--
	row--
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return "", nil, err
	}
	if ws.Drawing == nil {
		return "", nil, err
	}
	target := f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID)
	drawingXML := strings.ReplaceAll(target, "..", "xl")
	drawingRelationships := strings.ReplaceAll(
		strings.ReplaceAll(target, "../drawings", "xl/drawings/_rels"), ".xml", ".xml.rels")

	return f.getPicture(row, col, drawingXML, drawingRelationships)
}

// DeletePicture provides a function to delete charts in spreadsheet by given
// worksheet name and cell reference. Note that the image file won't be deleted
// from the document currently.
func (f *File) DeletePicture(sheet, cell string) error {
	col, row, err := CellNameToCoordinates(cell)
	if err != nil {
		return err
	}
	col--
	row--
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return err
	}
	if ws.Drawing == nil {
		return err
	}
	drawingXML := strings.ReplaceAll(f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID), "..", "xl")
	return f.deleteDrawing(col, row, drawingXML, "Pic")
}

// getPicture provides a function to get picture base name and raw content
// embed in spreadsheet by given coordinates and drawing relationships.
func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string) (ret string, buf []byte, err error) {
	var (
		wsDr            *xlsxWsDr
		ok              bool
		deWsDr          *decodeWsDr
		drawRel         *xlsxRelationship
		deTwoCellAnchor *decodeTwoCellAnchor
	)

	if wsDr, _, err = f.drawingParser(drawingXML); err != nil {
		return
	}
	if ret, buf = f.getPictureFromWsDr(row, col, drawingRelationships, wsDr); len(buf) > 0 {
		return
	}
	deWsDr = new(decodeWsDr)
	if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(drawingXML)))).
		Decode(deWsDr); err != nil && err != io.EOF {
		return
	}
	err = nil
	for _, anchor := range deWsDr.TwoCellAnchor {
		deTwoCellAnchor = new(decodeTwoCellAnchor)
		if err = f.xmlNewDecoder(strings.NewReader("<decodeTwoCellAnchor>" + anchor.Content + "</decodeTwoCellAnchor>")).
			Decode(deTwoCellAnchor); err != nil && err != io.EOF {
			return
		}
		if err = nil; deTwoCellAnchor.From != nil && deTwoCellAnchor.Pic != nil {
			if deTwoCellAnchor.From.Col == col && deTwoCellAnchor.From.Row == row {
				drawRel = f.getDrawingRelationships(drawingRelationships, deTwoCellAnchor.Pic.BlipFill.Blip.Embed)
				if _, ok = supportedImageTypes[filepath.Ext(drawRel.Target)]; ok {
					ret = filepath.Base(drawRel.Target)
					if buffer, _ := f.Pkg.Load(strings.ReplaceAll(drawRel.Target, "..", "xl")); buffer != nil {
						buf = buffer.([]byte)
					}
					return
				}
			}
		}
	}
	return
}

// getPictureFromWsDr provides a function to get picture base name and raw
// content in worksheet drawing by given coordinates and drawing
// relationships.
func (f *File) getPictureFromWsDr(row, col int, drawingRelationships string, wsDr *xlsxWsDr) (ret string, buf []byte) {
	var (
		ok      bool
		anchor  *xdrCellAnchor
		drawRel *xlsxRelationship
	)
	wsDr.Lock()
	defer wsDr.Unlock()
	for _, anchor = range wsDr.TwoCellAnchor {
		if anchor.From != nil && anchor.Pic != nil {
			if anchor.From.Col == col && anchor.From.Row == row {
				if drawRel = f.getDrawingRelationships(drawingRelationships,
					anchor.Pic.BlipFill.Blip.Embed); drawRel != nil {
					if _, ok = supportedImageTypes[filepath.Ext(drawRel.Target)]; ok {
						ret = filepath.Base(drawRel.Target)
						if buffer, _ := f.Pkg.Load(strings.ReplaceAll(drawRel.Target, "..", "xl")); buffer != nil {
							buf = buffer.([]byte)
						}
						return
					}
				}
			}
		}
	}
	return
}

// getDrawingRelationships provides a function to get drawing relationships
// from xl/drawings/_rels/drawing%s.xml.rels by given file name and
// relationship ID.
func (f *File) getDrawingRelationships(rels, rID string) *xlsxRelationship {
	if drawingRels, _ := f.relsReader(rels); drawingRels != nil {
		drawingRels.Lock()
		defer drawingRels.Unlock()
		for _, v := range drawingRels.Relationships {
			if v.ID == rID {
				return &v
			}
		}
	}
	return nil
}

// drawingsWriter provides a function to save xl/drawings/drawing%d.xml after
// serialize structure.
func (f *File) drawingsWriter() {
	f.Drawings.Range(func(path, d interface{}) bool {
		if d != nil {
			v, _ := xml.Marshal(d.(*xlsxWsDr))
			f.saveFileList(path.(string), v)
		}
		return true
	})
}

// drawingResize calculate the height and width after resizing.
func (f *File) drawingResize(sheet, cell string, width, height float64, opts *pictureOptions) (w, h, c, r int, err error) {
	var mergeCells []MergeCell
	mergeCells, err = f.GetMergeCells(sheet)
	if err != nil {
		return
	}
	var rng []int
	var inMergeCell bool
	if c, r, err = CellNameToCoordinates(cell); err != nil {
		return
	}
	cellWidth, cellHeight := f.getColWidth(sheet, c), f.getRowHeight(sheet, r)
	for _, mergeCell := range mergeCells {
		if inMergeCell {
			continue
		}
		if inMergeCell, err = f.checkCellInRangeRef(cell, mergeCell[0]); err != nil {
			return
		}
		if inMergeCell {
			rng, _ = cellRefsToCoordinates(mergeCell.GetStartAxis(), mergeCell.GetEndAxis())
			_ = sortCoordinates(rng)
		}
	}
	if inMergeCell {
		cellWidth, cellHeight = 0, 0
		c, r = rng[0], rng[1]
		for col := rng[0]; col <= rng[2]; col++ {
			cellWidth += f.getColWidth(sheet, col)
		}
		for row := rng[1]; row <= rng[3]; row++ {
			cellHeight += f.getRowHeight(sheet, row)
		}
	}
	if float64(cellWidth) < width {
		asp := float64(cellWidth) / width
		width, height = float64(cellWidth), height*asp
	}
	if float64(cellHeight) < height {
		asp := float64(cellHeight) / height
		height, width = float64(cellHeight), width*asp
	}
	width, height = width-float64(opts.OffsetX), height-float64(opts.OffsetY)
	w, h = int(width*opts.XScale), int(height*opts.YScale)
	return
}


text:
Simple web interface for whois lookup

Simply displays output of [whois gem](https://github.com/weppos/whois) via HTTP.

## Environment variables

| Key | Value | Description |
|-----|-------|-------------|
| `ENFORCE_HTTPS` | true OR blank | Enforces HTTPS on Production or not |

## Deployment (on Heroku)

```sh
git clone git@github.com:wktk/web-whois.git
cd web-whois
heroku create
git push heroku master
```

## Deployment (local)

```sh
git clone git@github.com:wktk/web-whois.git
cd web-whois
bundle install
bundle exec rackup
```

## License

See `MIT-LICENSE`


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Smith & Sowerby, Engl. Bot. 27: tab. 1912 (1808)

#### Original name
Lichen fragrans Sm.

### Remarks
null


text:
package co.phoenixlab.discord.api.entities;

import co.phoenixlab.discord.api.entities.channel.DmChannel;
import co.phoenixlab.discord.api.entities.guild.Presence;
import co.phoenixlab.discord.api.entities.guild.UnavailableGuild;
import co.phoenixlab.discord.api.entities.user.SelfUser;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ReadyMessage {

    private int v;
    private Presence[] presences;
    private UnavailableGuild[] guilds;
    private String sessionId;
    private DmChannel[] privateChannels;
    private SelfUser user;
    private int heartbeatInterval;
    @SerializedName("_trace")
    private String[] serverTrace;

}


text:
'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _utilsMdlUpgrade = require('./utils/mdlUpgrade');

var _utilsMdlUpgrade2 = _interopRequireDefault(_utilsMdlUpgrade);

var Tooltip = (function (_React$Component) {
    _inherits(Tooltip, _React$Component);

    function Tooltip() {
        _classCallCheck(this, Tooltip);

        _React$Component.apply(this, arguments);
    }

    Tooltip.prototype.render = function render() {
        var _props = this.props;
        var label = _props.label;
        var large = _props.large;
        var children = _props.children;

        var otherProps = _objectWithoutProperties(_props, ['label', 'large', 'children']);

        var id = Math.random().toString(36).substr(2);

        if (typeof label === 'string') {
            label = _react2['default'].createElement(
                'span',
                null,
                label
            );
        }

        var element;
        if (typeof children === 'string') {
            element = _react2['default'].createElement(
                'span',
                null,
                children
            );
        } else {
            element = _react2['default'].Children.only(this.props.children);
        }

        return _react2['default'].createElement(
            'div',
            _extends({ style: { display: 'inline-block' } }, otherProps),
            _react2['default'].cloneElement(element, {
                id: id
            }),
            _react2['default'].cloneElement(label, {
                htmlFor: id,
                className: _classnames2['default']('mdl-tooltip', { 'mdl-tooltip--large': large })
            })
        );
    };

    _createClass(Tooltip, null, [{
        key: 'propTypes',
        value: {
            children: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.string]).isRequired,
            label: _react.PropTypes.oneOfType([_react.PropTypes.element, _react.PropTypes.string]).isRequired,
            large: _react.PropTypes.bool
        },
        enumerable: true
    }]);

    return Tooltip;
})(_react2['default'].Component);

exports['default'] = _utilsMdlUpgrade2['default'](Tooltip);
module.exports = exports['default'];


text:
#import "EC2GetConsoleOutputRequestMarshaller.h"

@implementation EC2GetConsoleOutputRequestMarshaller

+(AmazonServiceRequest *)createRequest:(EC2GetConsoleOutputRequest *)getConsoleOutputRequest
{
    AmazonServiceRequest *request = [[EC2Request alloc] init];

    [request setParameterValue:@"GetConsoleOutput"           forKey:@"Action"];
    [request setParameterValue:@"2011-12-15"   forKey:@"Version"];

    [request setDelegate:[getConsoleOutputRequest delegate]];
    [request setCredentials:[getConsoleOutputRequest credentials]];
    [request setEndpoint:[getConsoleOutputRequest requestEndpoint]];
    [request setRequestTag:[getConsoleOutputRequest requestTag]];

    if (getConsoleOutputRequest != nil) {
        if (getConsoleOutputRequest.instanceId != nil) {
            [request setParameterValue:[NSString stringWithFormat:@"%@", getConsoleOutputRequest.instanceId] forKey:[NSString stringWithFormat:@"%@", @"InstanceId"]];
        }
    }

    return [request autorelease];
}

@end


text:
import React, { Component } from 'react'
import CardList from '../List/CardList'

export default class Folder extends Component {
  constructor(props) {
    super(props)
    this.state = {name: this.props.name}
  }
  changeName(evt){
      evt.preventDefault()
      this.props.changeName(evt.target.innerHTML)
  }
  moveFromFolder(evt){
      evt.preventDefault()
      evt.stopPropagation()
      this.props.moveFromFolder()
      console.log("test")
  }
  onDragOver(evt){
        evt.preventDefault()
        evt.stopPropagation()
  }
  render() {
    var name
    var data
    if (this.props.data.type == "folder"){
        name = (

                    {this.state.name}

)
        data = this.props.data.data
    }else{
        name = (
{this.props.name}
)
        data = this.props.data
    }

    return (

                {name}
                <CardList   showAdd ={this.props.showAdd}
                            canDelete= {this.props.canDelete}
                            data = {data}
                            onDelete = {this.props.onDelete}
                            cardDragOver = {this.props.cardDragOver}
                            cardDragStart = {this.props.cardDragStart}
                            cardRightClick = {this.props.cardRightClick}
                            dropCard = {this.props.dropCard}
                            onUndelete = {this.props.onUndelete}
                            openFolder = {this.props.openFolder}
                            moveToFolder = {this.props.moveToFolder}/>

    )
  }
}


text:
"""
This is one of the Kolibri core components, the abstract layer of all contents.
To access it, please use the public APIs in api.py

The ONLY public object is ContentNode
"""
from __future__ import print_function

import uuid

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from mptt.models import MPTTModel, TreeForeignKey

from .constants import content_kinds, extensions, presets
from .content_db_router import get_active_content_database
from .utils import paths

class UUIDField(models.CharField):
    """
    Adaptation of Django's UUIDField, but with 32-char hex representation as Python representation rather than a UUID instance.
    """

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 32
        super(UUIDField, self).__init__(*args, **kwargs)

    def prepare_value(self, value):
        if isinstance(value, uuid.UUID):
            return value.hex
        return value

    def deconstruct(self):
        name, path, args, kwargs = super(UUIDField, self).deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

    def get_internal_type(self):
        return "UUIDField"

    def get_db_prep_value(self, value, connection, prepared=False):
        if value is None:
            return None
        if not isinstance(value, uuid.UUID):
            try:
                value = uuid.UUID(value)
            except AttributeError:
                raise TypeError(self.error_messages['invalid'] % {'value': value})
        return value.hex

    def from_db_value(self, value, expression, connection, context):
        return self.to_python(value)

    def to_python(self, value):
        if isinstance(value, uuid.UUID):
            return value.hex
        return value

class ContentQuerySet(models.QuerySet):
    """
    Ensure proper database routing happens even when queryset is evaluated lazily outside of `using_content_database`.
    """
    def __init__(self, *args, **kwargs):
        kwargs["using"] = kwargs.get("using", None) or get_active_content_database(return_none_if_not_set=True)
        super(ContentQuerySet, self).__init__(*args, **kwargs)

class ContentDatabaseModel(models.Model):
    """
    All models that exist in content databases (rather than in the default database) should inherit from this class.
    """
    class Meta:
        abstract = True

@python_2_unicode_compatible
class ContentTag(ContentDatabaseModel):
    id = UUIDField(primary_key=True)
    tag_name = models.CharField(max_length=30, blank=True)

    objects = ContentQuerySet.as_manager()

    def __str__(self):
        return self.tag_name

@python_2_unicode_compatible
class ContentNode(MPTTModel, ContentDatabaseModel):
    """
    The top layer of the contentDB schema, defines the most common properties that are shared across all different contents.
    Things it can represent are, for example, video, exercise, audio or document...
    """
    id = UUIDField(primary_key=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
    license = models.ForeignKey('License', null=True, blank=True)
    has_prerequisite = models.ManyToManyField('self', related_name='prerequisite_for', symmetrical=False, blank=True)
    related = models.ManyToManyField('self', symmetrical=True, blank=True)
    tags = models.ManyToManyField(ContentTag, symmetrical=False, related_name='tagged_content', blank=True)

    title = models.CharField(max_length=200)

    # the content_id is used for tracking a user's interaction with a piece of
    # content, in the face of possibly many copies of that content. When a user
    # interacts with a piece of content, all substantially similar pieces of
    # content should be marked as such as well. We track these "substantially
    # similar" types of content by having them have the same content_id.
    content_id = UUIDField()

    description = models.CharField(max_length=400, blank=True, null=True)
    sort_order = models.FloatField(blank=True, null=True)
    license_owner = models.CharField(max_length=200, blank=True)
    author = models.CharField(max_length=200, blank=True)
    kind = models.CharField(max_length=200, choices=content_kinds.choices, blank=True)
    available = models.BooleanField(default=False)
    stemmed_metaphone = models.CharField(max_length=1800, blank=True)  # for fuzzy search in title and description

    objects = ContentQuerySet.as_manager()

    def __str__(self):
        return self.title

@python_2_unicode_compatible
class Language(ContentDatabaseModel):
    lang_code = models.CharField(max_length=2, db_index=True)
    lang_subcode = models.CharField(max_length=2, db_index=True)

    objects = ContentQuerySet.as_manager()

    def __str__(self):
        return self.lang_code

@python_2_unicode_compatible
class File(ContentDatabaseModel):
    """
    The bottom layer of the contentDB schema, defines the basic building brick for content.
    Things it can represent are, for example, mp4, avi, mov, html, css, jpeg, pdf, mp3...
    """
    id = UUIDField(primary_key=True)
    checksum = models.CharField(max_length=400, blank=True)
    extension = models.CharField(max_length=40, choices=extensions.choices, blank=True)
    available = models.BooleanField(default=False)
    file_size = models.IntegerField(blank=True, null=True)
    contentnode = models.ForeignKey(ContentNode, related_name='files', blank=True, null=True)
    preset = models.CharField(max_length=150, choices=presets.choices, blank=True)
    lang = models.ForeignKey(Language, blank=True, null=True)
    supplementary = models.BooleanField(default=False)
    thumbnail = models.BooleanField(default=False)
    priority = models.IntegerField(blank=True, null=True)

    objects = ContentQuerySet.as_manager()

    class Meta:
        ordering = ["priority"]

    class Admin:
        pass

    def __str__(self):
        return '{checksum}{extension}'.format(checksum=self.checksum, extension='.' + self.extension)

    def get_filename(self):
        return "{}.{}".format(self.checksum, self.extension)

    def get_storage_url(self):
        """
        Return a url for the client side to retrieve the content file.
        The same url will also be exposed by the file serializer.
        """
        if self.available:
            return paths.get_content_storage_file_url(filename=self.get_filename(), baseurl="/")
        else:
            return None

@python_2_unicode_compatible
class License(ContentDatabaseModel):
    """
    Normalize the license of ContentNode model
    """
    license_name = models.CharField(max_length=50)

    objects = ContentQuerySet.as_manager()

    def __str__(self):
        return self.license_name

@python_2_unicode_compatible
class ChannelMetadataAbstractBase(models.Model):
    """
    Holds metadata about all existing content databases that exist locally.
    """
    id = UUIDField(primary_key=True)
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=400, blank=True)
    author = models.CharField(max_length=400, blank=True)
    version = models.IntegerField(default=0)
    thumbnail = models.TextField(blank=True)
    root_pk = UUIDField()

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class ChannelMetadata(ChannelMetadataAbstractBase, ContentDatabaseModel):
    """
    This class stores the channel metadata within the content database itself.
    """

    objects = ContentQuerySet.as_manager()

class ChannelMetadataCache(ChannelMetadataAbstractBase):
    """
    This class stores the channel metadata cached/denormed into the primary database.
    """

    class Admin:
        pass


text:
package org.jetbrains.idea.svn;

import com.intellij.openapi.vcs.EditFileProvider;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.idea.svn.api.Revision;
import org.jetbrains.idea.svn.api.Target;
import org.jetbrains.idea.svn.properties.PropertyClient;
import org.jetbrains.idea.svn.properties.PropertyValue;

import java.io.File;

import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile;

public class SvnEditFileProvider implements EditFileProvider {
  private final SvnVcs myVCS;

  public SvnEditFileProvider(SvnVcs vcs) {
    myVCS = vcs;
  }

  public void editFiles(VirtualFile[] files) throws VcsException {
    File[] ioFiles = new File[files.length];

    for (int i = 0; i < files.length; i++) {
      ioFiles[i] = virtualToIoFile(files[i]);

      PropertyClient client = myVCS.getFactory(ioFiles[i]).createPropertyClient();
      PropertyValue property = client.getProperty(Target.on(ioFiles[i], Revision.WORKING), SvnPropertyKeys.SVN_NEEDS_LOCK,
                                                  false, Revision.WORKING);

      if (property == null) {
        throw new VcsException(SvnBundle.message("exception.text.file.miss.svn", ioFiles[i].getName()));
      }
    }
    SvnUtil.doLockFiles(myVCS.getProject(), myVCS, ioFiles);
  }

  public String getRequestText() {
    return SvnBundle.message("confirmation.text.edit.file");
  }
}


text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NotServingRegionException;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableNotDisabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.executor.EventHandler;
import org.apache.hadoop.hbase.executor.ExecutorService;
import org.apache.hadoop.hbase.executor.EventHandler.EventType;
import org.apache.hadoop.hbase.master.AssignmentManager;
import org.apache.hadoop.hbase.master.MasterServices;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Class to test HBaseAdmin.
 * Spins up the minicluster once at test start and then takes it down afterward.
 * Add any testing of HBaseAdmin functionality here.
 */
public class TestAdmin {
  final Log LOG = LogFactory.getLog(getClass());
  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private HBaseAdmin admin;

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100);
    TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250);
    TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6);
    TEST_UTIL.startMiniCluster(3);
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  @Before
  public void setUp() throws Exception {
    this.admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
  }

  @Test
  public void testDisableAndEnableTable() throws IOException {
    final byte [] row = Bytes.toBytes("row");
    final byte [] qualifier = Bytes.toBytes("qualifier");
    final byte [] value = Bytes.toBytes("value");
    final byte [] table = Bytes.toBytes("testDisableAndEnableTable");
    HTable ht = TEST_UTIL.createTable(table, HConstants.CATALOG_FAMILY);
    Put put = new Put(row);
    put.add(HConstants.CATALOG_FAMILY, qualifier, value);
    ht.put(put);
    Get get = new Get(row);
    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
    ht.get(get);

    this.admin.disableTable(table);

    // Test that table is disabled
    get = new Get(row);
    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
    boolean ok = false;
    try {
      ht.get(get);
    } catch (NotServingRegionException e) {
      ok = true;
    } catch (RetriesExhaustedException e) {
      ok = true;
    }
    assertTrue(ok);
    this.admin.enableTable(table);

    // Test that table is enabled
    try {
      ht.get(get);
    } catch (RetriesExhaustedException e) {
      ok = false;
    }
    assertTrue(ok);
  }

  @Test
  public void testCreateTable() throws IOException {
    HTableDescriptor [] tables = admin.listTables();
    int numTables = tables.length;
    TEST_UTIL.createTable(Bytes.toBytes("testCreateTable"),
      HConstants.CATALOG_FAMILY);
    tables = this.admin.listTables();
    assertEquals(numTables + 1, tables.length);
  }

  @Test
  public void testGetTableDescriptor() throws IOException {
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HColumnDescriptor fam2 = new HColumnDescriptor("fam2");
    HColumnDescriptor fam3 = new HColumnDescriptor("fam3");
    HTableDescriptor htd = new HTableDescriptor("myTestTable");
    htd.addFamily(fam1);
    htd.addFamily(fam2);
    htd.addFamily(fam3);
    this.admin.createTable(htd);
    HTable table = new HTable(TEST_UTIL.getConfiguration(), "myTestTable");
    HTableDescriptor confirmedHtd = table.getTableDescriptor();
    assertEquals(htd.compareTo(confirmedHtd), 0);
  }

  /**
   * Verify schema modification takes.
   * @throws IOException
   */
  @Test
  public void testChangeTableSchema() throws IOException {
    final byte [] tableName = Bytes.toBytes("changeTableSchema");
    HTableDescriptor [] tables = admin.listTables();
    int numTables = tables.length;
    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY);
    tables = this.admin.listTables();
    assertEquals(numTables + 1, tables.length);

    // FIRST, do htabledescriptor changes.
    HTableDescriptor htd = this.admin.getTableDescriptor(tableName);
    // Make a copy and assert copy is good.
    HTableDescriptor copy = new HTableDescriptor(htd);
    assertTrue(htd.equals(copy));
    // Now amend the copy. Introduce differences.
    long newFlushSize = htd.getMemStoreFlushSize() / 2;
    copy.setMemStoreFlushSize(newFlushSize);
    final String key = "anyoldkey";
    assertTrue(htd.getValue(key) == null);
    copy.setValue(key, key);
    boolean expectedException = false;
    try {
      this.admin.modifyTable(tableName, copy);
    } catch (TableNotDisabledException re) {
      expectedException = true;
    }
    assertTrue(expectedException);
    this.admin.disableTable(tableName);
    assertTrue(this.admin.isTableDisabled(tableName));
    modifyTable(tableName, copy);
    HTableDescriptor modifiedHtd = this.admin.getTableDescriptor(tableName);
    // Assert returned modifiedhcd is same as the copy.
    assertFalse(htd.equals(modifiedHtd));
    assertTrue(copy.equals(modifiedHtd));
    assertEquals(newFlushSize, modifiedHtd.getMemStoreFlushSize());
    assertEquals(key, modifiedHtd.getValue(key));

    // Reenable table to test it fails if not disabled.
    this.admin.enableTable(tableName);
    assertFalse(this.admin.isTableDisabled(tableName));

    // Now work on column family changes.
    int countOfFamilies = modifiedHtd.getFamilies().size();
    assertTrue(countOfFamilies > 0);
    HColumnDescriptor hcd = modifiedHtd.getFamilies().iterator().next();
    int maxversions = hcd.getMaxVersions();
    final int newMaxVersions = maxversions + 1;
    hcd.setMaxVersions(newMaxVersions);
    final byte [] hcdName = hcd.getName();
    expectedException = false;
    try {
      this.admin.modifyColumn(tableName, hcd);
    } catch (TableNotDisabledException re) {
      expectedException = true;
    }
    assertTrue(expectedException);
    this.admin.disableTable(tableName);
    assertTrue(this.admin.isTableDisabled(tableName));
    // Modify Column is synchronous
    this.admin.modifyColumn(tableName, hcd);
    modifiedHtd = this.admin.getTableDescriptor(tableName);
    HColumnDescriptor modifiedHcd = modifiedHtd.getFamily(hcdName);
    assertEquals(newMaxVersions, modifiedHcd.getMaxVersions());

    // Try adding a column
    // Reenable table to test it fails if not disabled.
    this.admin.enableTable(tableName);
    assertFalse(this.admin.isTableDisabled(tableName));
    final String xtracolName = "xtracol";
    HColumnDescriptor xtracol = new HColumnDescriptor(xtracolName);
    xtracol.setValue(xtracolName, xtracolName);
    try {
      this.admin.addColumn(tableName, xtracol);
    } catch (TableNotDisabledException re) {
      expectedException = true;
    }
    assertTrue(expectedException);
    this.admin.disableTable(tableName);
    assertTrue(this.admin.isTableDisabled(tableName));
    this.admin.addColumn(tableName, xtracol);
    modifiedHtd = this.admin.getTableDescriptor(tableName);
    hcd = modifiedHtd.getFamily(xtracol.getName());
    assertTrue(hcd != null);
    assertTrue(hcd.getValue(xtracolName).equals(xtracolName));

    // Delete the just-added column.
    this.admin.deleteColumn(tableName, xtracol.getName());
    modifiedHtd = this.admin.getTableDescriptor(tableName);
    hcd = modifiedHtd.getFamily(xtracol.getName());
    assertTrue(hcd == null);

    // Delete the table
    this.admin.deleteTable(tableName);
    this.admin.listTables();
    assertFalse(this.admin.tableExists(tableName));
  }

  /**
   * Modify table is async so wait on completion of the table operation in master.
   * @param tableName
   * @param htd
   * @throws IOException
   */
  private void modifyTable(final byte [] tableName, final HTableDescriptor htd)
  throws IOException {
    MasterServices services = TEST_UTIL.getMiniHBaseCluster().getMaster();
    ExecutorService executor = services.getExecutorService();
    AtomicBoolean done = new AtomicBoolean(false);
    executor.registerListener(EventType.C_M_MODIFY_TABLE, new DoneListener(done));
    this.admin.modifyTable(tableName, htd);
    while (!done.get()) {
      synchronized (done) {
        try {
          done.wait(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
    executor.unregisterListener(EventType.C_M_MODIFY_TABLE);
  }

  /**
   * Listens for when an event is done in Master.
   */
  static class DoneListener implements EventHandler.EventHandlerListener {
    private final AtomicBoolean done;

    DoneListener(final AtomicBoolean done) {
      super();
      this.done = done;
    }

    @Override
    public void afterProcess(EventHandler event) {
      this.done.set(true);
      synchronized (this.done) {
        // Wake anyone waiting on this value to change.
        this.done.notifyAll();
      }
    }

    @Override
    public void beforeProcess(EventHandler event) {
      // continue
    }
  }

  protected void verifyRoundRobinDistribution(HTable ht, int expectedRegions) throws IOException {
    MasterServices services = TEST_UTIL.getMiniHBaseCluster().getMaster();
    AssignmentManager am = services.getAssignmentManager();
    Map<HRegionInfo,HServerAddress> regions = ht.getRegionsInfo();
    for (HRegionInfo regionInfo : regions.keySet()) {
      try {
        am.waitForAssignment(regionInfo);
      } catch (InterruptedException e) {
        LOG.info("Interrupted waiting for region to be assigned during " +
            "create table call", e);
        Thread.currentThread().interrupt();
        return;
      }
    }
    int numRS = ht.getCurrentNrHRS();
    regions = ht.getRegionsInfo();
    Map<HServerAddress, List<HRegionInfo>> server2Regions = new HashMap<HServerAddress, List<HRegionInfo>>();
    for (Map.Entry<HRegionInfo,HServerAddress> entry : regions.entrySet()) {
      HServerAddress server = entry.getValue();
      List<HRegionInfo> regs = server2Regions.get(server);
      if (regs == null) {
        regs = new ArrayList<HRegionInfo>();
        server2Regions.put(server, regs);
      }
      regs.add(entry.getKey());
    }
    float average = (float) expectedRegions/numRS;
    int min = (int)Math.floor(average);
    int max = (int)Math.ceil(average);
    for (List<HRegionInfo> regionList : server2Regions.values()) {
      assertTrue(regionList.size() == min || regionList.size() == max);
    }
  }

  @Test
  public void testCreateTableWithRegions() throws IOException, InterruptedException {

    byte[] tableName = Bytes.toBytes("testCreateTableWithRegions");

    byte [][] splitKeys = {
        new byte [] { 1, 1, 1 },
        new byte [] { 2, 2, 2 },
        new byte [] { 3, 3, 3 },
        new byte [] { 4, 4, 4 },
        new byte [] { 5, 5, 5 },
        new byte [] { 6, 6, 6 },
        new byte [] { 7, 7, 7 },
        new byte [] { 8, 8, 8 },
        new byte [] { 9, 9, 9 },
    };
    int expectedRegions = splitKeys.length + 1;

    HTableDescriptor desc = new HTableDescriptor(tableName);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin.createTable(desc, splitKeys);

    HTable ht = new HTable(TEST_UTIL.getConfiguration(), tableName);
    Map<HRegionInfo,HServerAddress> regions = ht.getRegionsInfo();
    assertEquals("Tried to create " + expectedRegions + " regions " +
        "but only found " + regions.size(),
        expectedRegions, regions.size());
    System.err.println("Found " + regions.size() + " regions");

    Iterator<HRegionInfo> hris = regions.keySet().iterator();
    HRegionInfo hri = hris.next();
    assertTrue(hri.getStartKey() == null || hri.getStartKey().length == 0);
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[0]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[0]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[1]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[1]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[2]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[2]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[3]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[3]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[4]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[4]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[5]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[5]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[6]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[6]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[7]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[7]));
    assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[8]));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[8]));
    assertTrue(hri.getEndKey() == null || hri.getEndKey().length == 0);

    verifyRoundRobinDistribution(ht, expectedRegions);

    // Now test using start/end with a number of regions

    // Use 80 bit numbers to make sure we aren't limited
    byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
    byte [] endKey =   { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };

    // Splitting into 10 regions, we expect (null,1) ... (9, null)
    // with (1,2) (2,3) (3,4) (4,5) (5,6) (6,7) (7,8) (8,9) in the middle

    expectedRegions = 10;

    byte [] TABLE_2 = Bytes.add(tableName, Bytes.toBytes("_2"));

    desc = new HTableDescriptor(TABLE_2);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
    admin.createTable(desc, startKey, endKey, expectedRegions);

    ht = new HTable(TEST_UTIL.getConfiguration(), TABLE_2);
    regions = ht.getRegionsInfo();
    assertEquals("Tried to create " + expectedRegions + " regions " +
        "but only found " + regions.size(),
        expectedRegions, regions.size());
    System.err.println("Found " + regions.size() + " regions");

    hris = regions.keySet().iterator();
    hri = hris.next();
    assertTrue(hri.getStartKey() == null || hri.getStartKey().length == 0);
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {1,1,1,1,1,1,1,1,1,1}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {1,1,1,1,1,1,1,1,1,1}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {2,2,2,2,2,2,2,2,2,2}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {2,2,2,2,2,2,2,2,2,2}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {3,3,3,3,3,3,3,3,3,3}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {3,3,3,3,3,3,3,3,3,3}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {4,4,4,4,4,4,4,4,4,4}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {4,4,4,4,4,4,4,4,4,4}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {5,5,5,5,5,5,5,5,5,5}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {5,5,5,5,5,5,5,5,5,5}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {6,6,6,6,6,6,6,6,6,6}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {6,6,6,6,6,6,6,6,6,6}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {7,7,7,7,7,7,7,7,7,7}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {7,7,7,7,7,7,7,7,7,7}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {8,8,8,8,8,8,8,8,8,8}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {8,8,8,8,8,8,8,8,8,8}));
    assertTrue(Bytes.equals(hri.getEndKey(), new byte [] {9,9,9,9,9,9,9,9,9,9}));
    hri = hris.next();
    assertTrue(Bytes.equals(hri.getStartKey(), new byte [] {9,9,9,9,9,9,9,9,9,9}));
    assertTrue(hri.getEndKey() == null || hri.getEndKey().length == 0);

    verifyRoundRobinDistribution(ht, expectedRegions);

    // Try once more with something that divides into something infinite

    startKey = new byte [] { 0, 0, 0, 0, 0, 0 };
    endKey = new byte [] { 1, 0, 0, 0, 0, 0 };

    expectedRegions = 5;

    byte [] TABLE_3 = Bytes.add(tableName, Bytes.toBytes("_3"));

    desc = new HTableDescriptor(TABLE_3);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
    admin.createTable(desc, startKey, endKey, expectedRegions);

    ht = new HTable(TEST_UTIL.getConfiguration(), TABLE_3);
    regions = ht.getRegionsInfo();
    assertEquals("Tried to create " + expectedRegions + " regions " +
        "but only found " + regions.size(),
        expectedRegions, regions.size());
    System.err.println("Found " + regions.size() + " regions");

    verifyRoundRobinDistribution(ht, expectedRegions);

    // Try an invalid case where there are duplicate split keys
    splitKeys = new byte [][] {
        new byte [] { 1, 1, 1 },
        new byte [] { 2, 2, 2 },
        new byte [] { 3, 3, 3 },
        new byte [] { 2, 2, 2 }
    };

    byte [] TABLE_4 = Bytes.add(tableName, Bytes.toBytes("_4"));
    desc = new HTableDescriptor(TABLE_4);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin = new HBaseAdmin(TEST_UTIL.getConfiguration());
    try {
      admin.createTable(desc, splitKeys);
      assertTrue("Should not be able to create this table because of " +
          "duplicate split keys", false);
    } catch(IllegalArgumentException iae) {
      // Expected
    }
  }

  @Test
  public void testTableExist() throws IOException {
    final byte [] table = Bytes.toBytes("testTableExist");
    boolean exist = false;
    exist = this.admin.tableExists(table);
    assertEquals(false, exist);
    TEST_UTIL.createTable(table, HConstants.CATALOG_FAMILY);
    exist = this.admin.tableExists(table);
    assertEquals(true, exist);
  }

  /**
   * Tests forcing split from client and having scanners successfully ride over split.
   * @throws Exception
   * @throws IOException
   */
  @Test
  public void testForceSplit() throws Exception {
      splitTest(null);
      splitTest(Bytes.toBytes("pwn"));
    }

  void splitTest(byte[] splitPoint) throws Exception {
    byte [] familyName = HConstants.CATALOG_FAMILY;
    byte [] tableName = Bytes.toBytes("testForceSplit");
    assertFalse(admin.tableExists(tableName));
    final HTable table = TEST_UTIL.createTable(tableName, familyName);
    try {
      byte[] k = new byte[3];
      int rowCount = 0;
      for (byte b1 = 'a'; b1 < 'z'; b1++) {
        for (byte b2 = 'a'; b2 < 'z'; b2++) {
          for (byte b3 = 'a'; b3 < 'z'; b3++) {
            k[0] = b1;
            k[1] = b2;
            k[2] = b3;
            Put put = new Put(k);
            put.add(familyName, new byte[0], k);
            table.put(put);
            rowCount++;
          }
        }
      }

      // get the initial layout (should just be one region)
      Map<HRegionInfo,HServerAddress> m = table.getRegionsInfo();
      System.out.println("Initial regions (" + m.size() + "): " + m);
      assertTrue(m.size() == 1);

      // Verify row count
      Scan scan = new Scan();
      ResultScanner scanner = table.getScanner(scan);
      int rows = 0;
      for(@SuppressWarnings("unused") Result result : scanner) {
        rows++;
      }
      scanner.close();
      assertEquals(rowCount, rows);

      // Have an outstanding scan going on to make sure we can scan over splits.
      scan = new Scan();
      scanner = table.getScanner(scan);
      // Scan first row so we are into first region before split happens.
      scanner.next();

      final AtomicInteger count = new AtomicInteger(0);
      Thread t = new Thread("CheckForSplit") {
        public void run() {
          for (int i = 0; i < 20; i++) {
            try {
              sleep(1000);
            } catch (InterruptedException e) {
              continue;
            }
            // check again    table = new HTable(conf, tableName);
            Map<HRegionInfo, HServerAddress> regions = null;
            try {
              regions = table.getRegionsInfo();
            } catch (IOException e) {
              e.printStackTrace();
            }
            if (regions == null) continue;
            count.set(regions.size());
            if (count.get() >= 2) break;
            LOG.debug("Cycle waiting on split");
          }
        }
      };
      t.start();
      // Split the table
      this.admin.split(tableName, splitPoint);
      t.join();

      // Verify row count
      rows = 1; // We counted one row above.
      for (@SuppressWarnings("unused") Result result : scanner) {
        rows++;
        if (rows > rowCount) {
          scanner.close();
          assertTrue("Scanned more than expected (" + rowCount + ")", false);
        }
      }
      scanner.close();
      assertEquals(rowCount, rows);

      if (splitPoint != null) {
        // make sure the split point matches our explicit configuration
        Map<HRegionInfo, HServerAddress> regions = null;
        try {
          regions = table.getRegionsInfo();
        } catch (IOException e) {
          e.printStackTrace();
        }
        assertEquals(2, regions.size());
        HRegionInfo[] r = regions.keySet().toArray(new HRegionInfo[0]);
        assertEquals(Bytes.toString(splitPoint),
            Bytes.toString(r[0].getEndKey()));
        assertEquals(Bytes.toString(splitPoint),
            Bytes.toString(r[1].getStartKey()));
        LOG.debug("Properly split on " + Bytes.toString(splitPoint));
      }
    } finally {
      TEST_UTIL.deleteTable(tableName);
    }
  }

  /**
   * HADOOP-2156
   * @throws IOException
   */
  @Test (expected=IllegalArgumentException.class)
  public void testEmptyHHTableDescriptor() throws IOException {
    this.admin.createTable(new HTableDescriptor());
  }

  @Test
  public void testEnableDisableAddColumnDeleteColumn() throws Exception {
    byte [] tableName = Bytes.toBytes("testMasterAdmin");
    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY);
    this.admin.disableTable(tableName);
    try {
      new HTable(TEST_UTIL.getConfiguration(), tableName);
    } catch (org.apache.hadoop.hbase.client.RegionOfflineException e) {
      // Expected
    }
    this.admin.addColumn(tableName, new HColumnDescriptor("col2"));
    this.admin.enableTable(tableName);
    try {
      this.admin.deleteColumn(tableName, Bytes.toBytes("col2"));
    } catch(TableNotDisabledException e) {
      // Expected
    }
    this.admin.disableTable(tableName);
    this.admin.deleteColumn(tableName, Bytes.toBytes("col2"));
    this.admin.deleteTable(tableName);
  }

  @Test
  public void testCreateBadTables() throws IOException {
    String msg = null;
    try {
      this.admin.createTable(HTableDescriptor.ROOT_TABLEDESC);
    } catch (IllegalArgumentException e) {
      msg = e.toString();
    }
    assertTrue("Unexcepted exception message " + msg, msg != null &&
      msg.startsWith(IllegalArgumentException.class.getName()) &&
      msg.contains(HTableDescriptor.ROOT_TABLEDESC.getNameAsString()));
    msg = null;
    try {
      this.admin.createTable(HTableDescriptor.META_TABLEDESC);
    } catch(IllegalArgumentException e) {
      msg = e.toString();
    }
    assertTrue("Unexcepted exception message " + msg, msg != null &&
      msg.startsWith(IllegalArgumentException.class.getName()) &&
      msg.contains(HTableDescriptor.META_TABLEDESC.getNameAsString()));

    // Now try and do concurrent creation with a bunch of threads.
    final HTableDescriptor threadDesc =
      new HTableDescriptor("threaded_testCreateBadTables");
    threadDesc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    int count = 10;
    Thread [] threads = new Thread [count];
    final AtomicInteger successes = new AtomicInteger(0);
    final AtomicInteger failures = new AtomicInteger(0);
    final HBaseAdmin localAdmin = this.admin;
    for (int i = 0; i < count; i++) {
      threads[i] = new Thread(Integer.toString(i)) {
        @Override
        public void run() {
          try {
            localAdmin.createTable(threadDesc);
            successes.incrementAndGet();
          } catch (TableExistsException e) {
            failures.incrementAndGet();
          } catch (IOException e) {
            throw new RuntimeException("Failed threaded create" + getName(), e);
          }
        }
      };
    }
    for (int i = 0; i < count; i++) {
      threads[i].start();
    }
    for (int i = 0; i < count; i++) {
      while(threads[i].isAlive()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // continue
        }
      }
    }
    // All threads are now dead.  Count up how many tables were created and
    // how many failed w/ appropriate exception.
    assertEquals(1, successes.get());
    assertEquals(count - 1, failures.get());
  }

  /**
   * Test for hadoop-1581 'HBASE: Unopenable tablename bug'.
   * @throws Exception
   */
  @Test
  public void testTableNameClash() throws Exception {
    String name = "testTableNameClash";
    admin.createTable(new HTableDescriptor(name + "SOMEUPPERCASE"));
    admin.createTable(new HTableDescriptor(name));
    // Before fix, below would fail throwing a NoServerForRegionException.
    new HTable(TEST_UTIL.getConfiguration(), name);
  }

  /**
   * Test read only tables
   * @throws Exception
   */
  @Test
  public void testReadOnlyTable() throws Exception {
    byte [] name = Bytes.toBytes("testReadOnlyTable");
    HTable table = TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
    byte[] value = Bytes.toBytes("somedata");
    // This used to use an empty row... That must have been a bug
    Put put = new Put(value);
    put.add(HConstants.CATALOG_FAMILY, HConstants.CATALOG_FAMILY, value);
    table.put(put);
  }

  /**
   * Test that user table names can contain '-' and '.' so long as they do not
   * start with same. HBASE-771
   * @throws IOException
   */
  @Test
  public void testTableNames() throws IOException {
    byte[][] illegalNames = new byte[][] {
        Bytes.toBytes("-bad"),
        Bytes.toBytes(".bad"),
        HConstants.ROOT_TABLE_NAME,
        HConstants.META_TABLE_NAME
    };
    for (int i = 0; i < illegalNames.length; i++) {
      try {
        new HTableDescriptor(illegalNames[i]);
        throw new IOException("Did not detect '" +
          Bytes.toString(illegalNames[i]) + "' as an illegal user table name");
      } catch (IllegalArgumentException e) {
        // expected
      }
    }
    byte[] legalName = Bytes.toBytes("g-oo.d");
    try {
      new HTableDescriptor(legalName);
    } catch (IllegalArgumentException e) {
      throw new IOException("Legal user table name: '" +
        Bytes.toString(legalName) + "' caused IllegalArgumentException: " +
        e.getMessage());
    }
  }

  /**
   * For HADOOP-2579
   * @throws IOException
   */
  @Test (expected=TableExistsException.class)
  public void testTableNotFoundExceptionWithATable() throws IOException {
    final byte [] name = Bytes.toBytes("testTableNotFoundExceptionWithATable");
    TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
    TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
  }

  /**
   * For HADOOP-2579
   * @throws IOException
   */
  @Test (expected=TableNotFoundException.class)
  public void testTableNotFoundExceptionWithoutAnyTables() throws IOException {
    new HTable(TEST_UTIL.getConfiguration(),
        "testTableNotFoundExceptionWithoutAnyTables");
  }

  @Test
  public void testHundredsOfTable() throws IOException{
    final int times = 100;
    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
    HColumnDescriptor fam2 = new HColumnDescriptor("fam2");
    HColumnDescriptor fam3 = new HColumnDescriptor("fam3");

    for(int i = 0; i < times; i++) {
      HTableDescriptor htd = new HTableDescriptor("table"+i);
      htd.addFamily(fam1);
      htd.addFamily(fam2);
      htd.addFamily(fam3);
      this.admin.createTable(htd);
    }

    for(int i = 0; i < times; i++) {
      String tableName = "table"+i;
      this.admin.disableTable(tableName);
      byte [] tableNameBytes = Bytes.toBytes(tableName);
      assertTrue(this.admin.isTableDisabled(tableNameBytes));
      this.admin.enableTable(tableName);
      assertFalse(this.admin.isTableDisabled(tableNameBytes));
      this.admin.disableTable(tableName);
      assertTrue(this.admin.isTableDisabled(tableNameBytes));
      this.admin.deleteTable(tableName);
    }
  }
}


text:
package com.dtar.android.viewpagerexample;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Find the view pager that will allow the user to swipe between fragments.
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        // Create an adapter that knows which fragment should be shown on each page.
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager());

        // Set the adapter onto the view pager.
        viewPager.setAdapter(adapter);
    }
}


text:
module SimpleCredomaticPaycon
  class Configuration
    attr_accessor :show_trace

    def initialize
      @show_trace = false
    end

  end
end


text:
package jace.cheat;

import jace.Emulator;
import jace.EmulatorUILogic;
import jace.config.ConfigurableField;
import jace.core.Computer;
import jace.core.RAM;
import jace.core.RAMEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.input.MouseButton;

public class MontezumasRevengeCheats extends Cheats {

    @ConfigurableField(category = "Hack", name = "Repulsive", defaultValue = "false", description = "YOU STINK!")
    public static boolean repulsiveHack = false;

    @ConfigurableField(category = "Hack", name = "Feather Fall", defaultValue = "false", description = "Falling will not result in death")
    public static boolean featherFall = false;

    @ConfigurableField(category = "Hack", name = "Moon Jump", defaultValue = "false", description = "Wheeee!")
    public static boolean moonJump = false;

    @ConfigurableField(category = "Hack", name = "Infinite Lives", defaultValue = "false", description = "Game on!")
    public static boolean infiniteLives = false;

    @ConfigurableField(category = "Hack", name = "Score hack", defaultValue = "false", description = "Change the score")
    public static boolean scoreHack = false;

    @ConfigurableField(category = "Hack", name = "Snake Charmer", defaultValue = "false", description = "Disable collision detection with enemies")
    public static boolean snakeCharmer = false;

    @ConfigurableField(category = "Hack", name = "Teleport", defaultValue = "false", description = "Click to teleport!")
    public static boolean mouseHack = false;

    @ConfigurableField(category = "Hack", name = "Safe Passage", defaultValue = "false", description = "Deadly floors and doors disabled!")
    public static boolean safePassage = false;

    public static int X_MAX = 80;
    public static int Y_MAX = 160;
    public static int MAX_VEL = 4;
    public static int MOON_JUMP_VELOCITY = -14;
    public static int ROOM_LEVEL = 0x0d1;
    public static int LIVES = 0x0e0;
    public static int SCORE = 0x0e8;
    public static int SCORE_END = 0x0ea;
    public static int FLOOR_TIMER = 0x030a;
    public static int HAZARD_TIMER = 0x030b;
    public static int HAZARD_FLAG = 0x030f;
    public static int PLAYER_X = 0x01508;
    public static int PLAYER_Y = 0x01510;
    public static int Y_VELOCITY = 0x01550;
    public static int CHAR_STATE = 0x01570;

    public static int lastX = 0;

    public MontezumasRevengeCheats(Computer computer) {
        super(computer);
    }

    double mouseX;
    double mouseY;
    EventHandler<javafx.scene.input.MouseEvent> listener = (event) -> {
        Node source = (Node) event.getSource();
        mouseX = event.getSceneX() / source.getBoundsInLocal().getWidth();
        mouseY = event.getSceneY() / source.getBoundsInLocal().getHeight();
        if (event.isPrimaryButtonDown()) {
            mouseClicked(event.getButton());
        }
    };

    @Override
    public void registerListeners() {
        RAM memory = Emulator.getComputer().memory;
        if (repulsiveHack) {
            addCheat(RAMEvent.TYPE.WRITE, this::repulsiveBehavior, 0x1508, 0x1518);
        }

        if (featherFall) {
            addCheat(RAMEvent.TYPE.WRITE, this::featherFallBehavior, PLAYER_Y);
            // Bypass the part that realizes you should die when you hit the floor
            bypassCode(0x6bb3, 0x6bb4);
        }

        if (moonJump) {
            addCheat(RAMEvent.TYPE.WRITE, this::moonJumpBehavior, Y_VELOCITY);
        }

        if (infiniteLives) {
            forceValue(11, LIVES);
        }

        if (safePassage) {
            //blank out pattern for floors/doors
            for (int addr = 0x0b54; addr <= 0xb5f; addr++) {
                memory.write(addr, (byte) 0, false, false);
                memory.write(addr + 0x0400, (byte) 0, false, false);
            }
            memory.write(0x0b50, (byte) 0b11010111, false, false);
            memory.write(0x0b51, (byte) 0b00010000, false, false);
            memory.write(0x0b52, (byte) 0b10001000, false, false);
            memory.write(0x0b53, (byte) 0b10101010, false, false);
            memory.write(0x0f50, (byte) 0b10101110, false, false);
            memory.write(0x0f51, (byte) 0b00001000, false, false);
            memory.write(0x0f52, (byte) 0b10000100, false, false);
            memory.write(0x0f53, (byte) 0b11010101, false, false);
            forceValue(32, FLOOR_TIMER);
            forceValue(32, HAZARD_TIMER);
            forceValue(1, HAZARD_FLAG);
        }

        if (scoreHack) {
            // Score: 900913
            forceValue(0x90, SCORE);
            forceValue(0x09, SCORE + 1);
            forceValue(0x13, SCORE + 2);
        }

        if (snakeCharmer) {
            // Skip the code that determines you're touching an enemy
            bypassCode(0x07963, 0x07964);
        }
        if (mouseHack) {
            EmulatorUILogic.addMouseListener(listener);
        }
    }

    @Override
    protected void unregisterListeners() {
        super.unregisterListeners();
        EmulatorUILogic.removeMouseListener(listener);
    }

    private void repulsiveBehavior(RAMEvent e) {
        int playerX = computer.getMemory().readRaw(PLAYER_X);
        int playerY = computer.getMemory().readRaw(PLAYER_Y);
        for (int num = 7; num > 0; num--) {
            int monsterX = computer.getMemory().readRaw(PLAYER_X + num);
            int monsterY = computer.getMemory().readRaw(PLAYER_Y + num);
            if (monsterX != 0 && monsterY != 0) {
                if (Math.abs(monsterY - playerY) < 19) {
                    if (Math.abs(monsterX - playerX) < 7) {
                        int movement = Math.max(1, Math.abs(lastX - playerX));
                        if (monsterX > playerX) {
                            monsterX += movement;
                        } else {
                            monsterX -= movement;
                            if (monsterX <= 0) {
                                monsterX = 80;
                            }
                        }
                        computer.getMemory().write(PLAYER_X + num, (byte) monsterX, false, false);
                    }
                }
            }
        }
        lastX = playerX;
    }

    private void featherFallBehavior(RAMEvent yCoordChangeEvent) {
        if (yCoordChangeEvent.getNewValue() != yCoordChangeEvent.getOldValue()) {
            int yVel = computer.getMemory().readRaw(Y_VELOCITY);
            if (yVel > MAX_VEL) {
                computer.getMemory().write(Y_VELOCITY, (byte) MAX_VEL, false, false);
            }
        }
    }

    private void moonJumpBehavior(RAMEvent velocityChangeEvent) {
        if (inStartingSequence()) {
            return;
        }
        if (velocityChangeEvent.getNewValue() < 0
                && velocityChangeEvent.getNewValue() < velocityChangeEvent.getOldValue()) {
            velocityChangeEvent.setNewValue(MOON_JUMP_VELOCITY);
        }
    }

    private boolean inStartingSequence() {
        int roomLevel = computer.getMemory().readRaw(ROOM_LEVEL);
        return roomLevel == -1;
    }

    @Override
    public String getName() {
        return "Montezuma's Revenge";
    }

    @Override
    protected String getDeviceName() {
        return "Montezuma's Revenge";
    }

    @Override
    public void tick() {
    }

    private void mouseClicked(MouseButton button) {
        byte newX = (byte) (mouseX * X_MAX);
        byte newY = (byte) (mouseY * Y_MAX);
        computer.memory.write(PLAYER_X, newX, false, false);
        computer.memory.write(PLAYER_Y, newY, false, false);
    }
}


text:
document.addEventListener("deviceready", onDeviceReady_NET, false);

function onDeviceReady_NET(){

	module("NetworkInfo");

	asyncTest("net_001:type", function() {
		var netstate = navigator.connection.type;
		ok(true, "Network type : " + netstate);
		start();
	});

}