text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using SharpLib.Audio.Utils;

namespace SharpLib.Audio.Midi
{
    internal class MidiFile
    {
        #region Ïîëÿ

        private readonly ushort deltaTicksPerQuarterNote;

        private readonly MidiEventCollection events;

        private readonly ushort fileFormat;

        private readonly bool strictChecking;

        #endregion

        #region Ñâîéñòâà

        public int FileFormat
        {
            get { return fileFormat; }
        }

        public MidiEventCollection Events
        {
            get { return events; }
        }

        public int Tracks
        {
            get { return events.Tracks; }
        }

        public int DeltaTicksPerQuarterNote
        {
            get { return deltaTicksPerQuarterNote; }
        }

        #endregion

        #region Êîíñòðóêòîð

        public MidiFile(string filename)
            : this(filename, true)
        {
        }

        public MidiFile(string filename, bool strictChecking)
        {
            this.strictChecking = strictChecking;

            var br = new BinaryReader(File.OpenRead(filename));
            using (br)
            {
                string chunkHeader = Encoding.UTF8.GetString(br.ReadBytes(4));
                if (chunkHeader != "MThd")
                {
                    throw new FormatException("Not a MIDI file - header chunk missing");
                }
                uint chunkSize = SwapUInt32(br.ReadUInt32());

                if (chunkSize != 6)
                {
                    throw new FormatException("Unexpected header chunk length");
                }

                fileFormat = SwapUInt16(br.ReadUInt16());
                int tracks = SwapUInt16(br.ReadUInt16());
                deltaTicksPerQuarterNote = SwapUInt16(br.ReadUInt16());

                events = new MidiEventCollection((fileFormat == 0) ? 0 : 1, deltaTicksPerQuarterNote);
                for (int n = 0; n < tracks; n++)
                {
                    events.AddTrack();
                }

                long absoluteTime = 0;

                for (int track = 0; track < tracks; track++)
                {
                    if (fileFormat == 1)
                    {
                        absoluteTime = 0;
                    }
                    chunkHeader = Encoding.UTF8.GetString(br.ReadBytes(4));
                    if (chunkHeader != "MTrk")
                    {
                        throw new FormatException("Invalid chunk header");
                    }
                    chunkSize = SwapUInt32(br.ReadUInt32());

                    long startPos = br.BaseStream.Position;
                    MidiEvent me = null;
                    var outstandingNoteOns = new List<NoteOnEvent>();
                    while (br.BaseStream.Position < startPos + chunkSize)
                    {
                        me = MidiEvent.ReadNextEvent(br, me);
                        absoluteTime += me.DeltaTime;
                        me.AbsoluteTime = absoluteTime;
                        events[track].Add(me);
                        if (me.CommandCode == MidiCommandCode.NoteOn)
                        {
                            NoteEvent ne = (NoteEvent)me;
                            if (ne.Velocity > 0)
                            {
                                outstandingNoteOns.Add((NoteOnEvent)ne);
                            }
                            else
                            {
                                FindNoteOn(ne, outstandingNoteOns);
                            }
                        }
                        else if (me.CommandCode == MidiCommandCode.NoteOff)
                        {
                            FindNoteOn((NoteEvent)me, outstandingNoteOns);
                        }
                        else if (me.CommandCode == MidiCommandCode.MetaEvent)
                        {
                            MetaEvent metaEvent = (MetaEvent)me;
                            if (metaEvent.MetaEventType == MetaEventType.EndTrack)
                            {
                                if (strictChecking)
                                {
                                    if (br.BaseStream.Position < startPos + chunkSize)
                                    {
                                        throw new FormatException(String.Format("End Track event was not the last MIDI event on track {0}", track));
                                    }
                                }
                            }
                        }
                    }
                    if (outstandingNoteOns.Count > 0)
                    {
                        if (strictChecking)
                        {
                            throw new FormatException(String.Format("Note ons without note offs {0} (file format {1})", outstandingNoteOns.Count, fileFormat));
                        }
                    }
                    if (br.BaseStream.Position != startPos + chunkSize)
                    {
                        throw new FormatException(String.Format("Read too far {0}+{1}!={2}", chunkSize, startPos, br.BaseStream.Position));
                    }
                }
            }
        }

        #endregion

        #region Ìåòîäû

        private void FindNoteOn(NoteEvent offEvent, List<NoteOnEvent> outstandingNoteOns)
        {
            bool found = false;
            foreach (NoteOnEvent noteOnEvent in outstandingNoteOns)
            {
                if ((noteOnEvent.Channel == offEvent.Channel) && (noteOnEvent.NoteNumber == offEvent.NoteNumber))
                {
                    noteOnEvent.OffEvent = offEvent;
                    outstandingNoteOns.Remove(noteOnEvent);
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                if (strictChecking)
                {
                    throw new FormatException(String.Format("Got an off without an on {0}", offEvent));
                }
            }
        }

        private static uint SwapUInt32(uint i)
        {
            return ((i & 0xFF000000) >> 24) | ((i & 0x00FF0000) >> 8) | ((i & 0x0000FF00) << 8) | ((i & 0x000000FF) << 24);
        }

        private static ushort SwapUInt16(ushort i)
        {
            return (ushort)(((i & 0xFF00) >> 8) | ((i & 0x00FF) << 8));
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendFormat("Format {0}, Tracks {1}, Delta Ticks Per Quarter Note {2}\r\n",
                fileFormat, Tracks, deltaTicksPerQuarterNote);
            for (int n = 0; n < Tracks; n++)
            {
                foreach (MidiEvent midiEvent in events[n])
                {
                    sb.AppendFormat("{0}\r\n", midiEvent);
                }
            }
            return sb.ToString();
        }

        public static void Export(string filename, MidiEventCollection events)
        {
            if (events.MidiFileType == 0 && events.Tracks > 1)
            {
                throw new ArgumentException("Can't export more than one track to a type 0 file");
            }
            using (var writer = new BinaryWriter(File.Create(filename)))
            {
                writer.Write(Encoding.UTF8.GetBytes("MThd"));
                writer.Write(SwapUInt32(6));
                writer.Write(SwapUInt16((ushort)events.MidiFileType));
                writer.Write(SwapUInt16((ushort)events.Tracks));
                writer.Write(SwapUInt16((ushort)events.DeltaTicksPerQuarterNote));

                for (int track = 0; track < events.Tracks; track++)
                {
                    IList<MidiEvent> eventList = events[track];

                    writer.Write(Encoding.UTF8.GetBytes("MTrk"));
                    long trackSizePosition = writer.BaseStream.Position;
                    writer.Write(SwapUInt32(0));

                    long absoluteTime = events.StartAbsoluteTime;

                    MergeSort.Sort(eventList, new MidiEventComparer());
                    if (eventList.Count > 0)
                    {
                        System.Diagnostics.Debug.Assert(MidiEvent.IsEndTrack(eventList[eventList.Count - 1]), "Exporting a track with a missing end track");
                    }
                    foreach (MidiEvent midiEvent in eventList)
                    {
                        midiEvent.Export(ref absoluteTime, writer);
                    }

                    uint trackChunkLength = (uint)(writer.BaseStream.Position - trackSizePosition) - 4;
                    writer.BaseStream.Position = trackSizePosition;
                    writer.Write(SwapUInt32(trackChunkLength));
                    writer.BaseStream.Position += trackChunkLength;
                }
            }
        }

        #endregion
    }
}


text:
Changelog
=========

1.9.5
-----
    - Added ``aleph.getISSNsXML()``.
    - Lincese changed to MIT.

1.9.4
-----
    - Fixed bug in parsing of the AlephRecord.

1.9.3
-----
    - Added support of the e-periodics.
    - Fixed few bugs.

1.9.0 - 1.9.2
-------------
    - Structure SemanticInfo redefined as requested in #54.
    - Fixed bugs in test subsystem, which showed when tested on new machine without envvars used on my PC.
    - Added new property SemanticInfo.acquisitionFields, which holds signs from acq.
    - Fixed #57: Bug in GenericQuery.
    - Fixed few more bugs in tests.
    - Removed ``sudo`` requirement from integration tests.

1.8.0 - 1.8.11
--------------
    - Removed old robot tests and added alternatives in pytest. More will come.
    - Added tests of conversion functions for ``EPublication`` and ``SemanticInfo``.
    - Removed ``marcxml.py`` (#45), which was moved into standalone module [marcxml_parser](https://github.com/edeposit/marcxml_parser).
    - Module refactored to work with ``marcxml.py``, which brings many improvements.
    - Implemented #46: ``convertor.py`` removed, functions moved to static methods and standalone submodule (see ``doc_number.py``).
    - Updated documentation.
    - README.rst updated.
    - Fixed small bug in MANIFEST.in.
    - ISBN is now discriminated to valid and INVALID. See ``EPublication.invalid_ISBN``.
    - External URL is now voluntary in export structure.
    - Fixed #50 - problem with checking for czech ISBN.
    - Fixed jstavel/edeposit#339 - problem with multiple PJM subfields.
    - Insignificant improvements.
    - Implemented parsing of ``.id_number`` to ``EPublication`` structure.
    - Added annotation field ``.anotace`` to ``EPublication`` structure.
    - ``EPublication.anotace`` field is now used in export.
    - Small improvements of export.py code.
    - Added prefix to ``epub.annotation`` to export. This was required by mrs. Svobodová.
    - Fixed bug in counting max. allowed lenght of annotation.

1.7.0 - 1.7.4
-------------
    - isbn.py is no longer part of the edeposit.amqp.aleph, but `standalone module <https://github.com/edeposit/isbn_validator>`_.
    - Small syntax improvements in ISBN module.
    - Improved parsing of `summaryRecordSysNumber` in SemanticInfo submodule.
    - Fixed paths in ``run_tests.sh``.
    - Added new items to ``SemanticInfo`` structure (``.isClosed``, ``.summaryRecordSysNumber``, ``.parsedSummaryRecordSysNumber``).
    - Added new query ``ICZQuery``.
    - Fixed #41 - case of deleted record with stub left after deletion.
    - Implemented #43 - new attributes to SemanticInfo.
    - Removed ``_remove_hairs()`` function, which is now in stanalone package.
    - Added dependency to ``remove_hairs`` standalone package.

1.6.0 - 1.6.5
-------------
    - Added new fields to SemanticInfo structure.
    - Fixed few bugs in aleph.py.
    - Fixed bugs, old code, small improvements.
    - aleph.py: Added new function downloadRecords().
    - aleph.py: Added four new functions: getISBNsXML(), getAuthorsBooksXML(), getPublishersBooksXML() and getBooksTitleIDs().
    - aleph.py: Refactored few unnecessarily long variables.
    - convertor.py: Added new function getDocNumber().
    - __init__.py switched to use aleph.downloadRecord().
    - Fixed #27 - parsing of internal url field.
    - convertor.py refactored slightly, fixed few little bugs.
    - Added different way of tracking SemanticInfo.hasISBNAgencyFields.
    - Fixed bug in convertor.py.
    - ``reactToAMQPMessage()`` parameters modified.

1.5.0 - 1.5.9
-------------
    - Fixed bug in marcxml.py.
    - Added more detections to convertor.py / toSemanticInfo().
    - marcxml.py changed and fixed. It can now convert MARC XML <-> OAI without any problems, just by changing .oai_marc property.
    - Fixed bug in ISBN submodule.
    - Added detection of ``ISBNQuery`` in ``ISBNValidationRequest``.
    - Updated setup.py to new version of dhtmlparser.
    - Fixed bug in deserialization of semanticinfo.
    - Added tracking of export progress.
    - Added new Query class - DocumentQuery.
    - Documentation cleaned.
    - Added documentation for convertor.
    - Fixed bug in unittests.
    - Queries to test base are now handled by OAI API, which has access.
    - Export is working.

1.4.0 - 1.4.9
-------------
    - API change in reactToAMQPmessage(), which now takes just two parameters and returns values, instead of calling callbacks.
    - Documentation updated and made useful.
    - Documentation of export.py updated.
    - Assertions in export.py are now annotated (useful for debugging).
    - Version of package and documentation is now automatically parsed from this file.
    - Documentation of the whole package updated.
    - Fixed bugs in MARC XML parser and Aleph lowlevel API.
    - Added ``run_tests.sh``.
    - Added TitleQuery.
    - Fixed bug in export script.
    - Changelog made more compact.
    - Fixed bug #23 in _removeSpecialCharacters().
    - Fixed export bugs (see #21 and #22).
    - Fixed reported bugs in export script.
    - Fixed bug in ISBN submodule.
    - Added unicode support to settings.py.

1.3.0
-----
    - Serializers removed from convertors.py. (De)serialization will be handled in edeposit.amqp, because other packages also uses it.

1.2.0 - 1.2.5
-------------
    - Fixed bug with package installation, when the package couldn't find README.rst.
    - User defined JSON configuration is now supported.
    - Documentation is now even for settings.py's attributes.
    - Documentation is now generated automatically everytime the package is generated.
    - Tests and HTML help is now included in PYPI package.
    - All source files are now documented with google style docstrings.
    - Added experimental export support.

1.1.0
-----
    - Project released at PYPI.

1.0 (unreleased)
----------------
    - Communication with Aleph is now working.

0.1-dev (unreleased)
--------------------
    - Package created using templer.

redpajama_set_name: RedPajamaGithub


text:
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.

// ====================================================
// GraphQL query operation: OnboardingUserInfoQuery
// ====================================================

export interface OnboardingUserInfoQuery_me {
  __typename: "Me";
  slug: string | null;
}

export interface OnboardingUserInfoQuery {
  /**
   * The current logged in user
   */
  me: OnboardingUserInfoQuery_me | null;
}


text:
window.package("zetaret.global.packages.protoss.protoss").IProtoSS = {
	toInterface: [Object, Object],
	stringPattern: [String, String, Number],
	getSuperCls: [String, Object, String],
	resolveCls: [Object, Object, String],
	resolveHeaders: [Object, String, Boolean]
};


text:
package org.saburto.seq.agent;

import java.lang.instrument.Instrumentation;

import org.saburto.seq.agent.transformer.CallTraceTransformer;

public class Agent {

public static void premain(String agentArgs, Instrumentation inst) {

        // registers the transformer
		inst.addTransformer(new CallTraceTransformer());
    }

}


text:
#ifndef __DS3_UTILS__
#define __DS3_UTILS__

#ifdef __cplusplus
extern "C" {
#endif

void         ds3_log_message(const ds3_log* log, ds3_log_lvl lvl, const char* message, ...);
size_t       ds3_load_buffer(void* buffer, size_t size, size_t nmemb, void* user_data);
ds3_error*   ds3_create_error(ds3_error_code code, const char * message);

#ifdef __cplusplus
}
#endif

#endif


text:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define LIM 500

typedef struct _p_node{
	int prime;
	struct _p_node *next;
}prime;
/*create linked list for prime numbers*/

prime *p_list;
/*create global linked list*/

void init(prime *plist){
	int target;
	prime *cur = (prime*)malloc(sizeof(prime));

	plist->prime = 2;
	plist->next = cur;
	/*init first node! plist is the head node!*/

	cur->prime = 3;
	cur->next = NULL;
	/*init second node for I will not touch headnode*/

	target = cur->prime+1;
	/*to find next prime, val of target is 1 greater than cur->prime*/

	while(target < LIM){
	/*while val of current prime is less than LIM*/

		cur = plist;
		/*we want to scan from the beginning*/

		while(cur->next != NULL){
		/*while there is node remaining*/

			if(target%cur->prime ==0) break;
			/*if val of target can be divided by any prime, it is not prime, so break the loop*/

			else cur = cur->next;
			/*if it is not divisible, keep proceed.*/
		}
		if(cur->next != NULL){
			target++;
		}
		/*if target is divisible, increase target by 1 and repeat.
		  NOTE : the cur->next should not be NULL and divisible at the same time.
		  		  All composite number is multiple of primes.*/
		else{
			prime *next_node = (prime*)malloc(sizeof(prime));
			next_node->prime = target;
			next_node->next = NULL;
			cur->next = next_node;
			target++;
		}
		/*if the target is not divisible by any of prime numbers in list,
		  make new node, and save val of target into the node and make it next node of current node*/
	}
}
int classify(int determine){
	prime *temp = p_list;
	/*we never move p_list because there is no way to come back to original head node if head node is moved*/
	int ret;
	while(temp->prime < determine){
		temp = temp->next;
	}/*move the node until prime is larger or equal to determine*/

	if(temp->prime == determine){
		printf("%d is indeed Prime!\n",determine);
	}else{
		printf("%d is not a PrImE number!\n",determine);
	}
	/*if found exact match, print yes, else no*/

	printf("wanna try again? Type 0 to exit, 1 to retry ");
	scanf("%d", &ret);
	assert(ret==0 || ret ==1);
	return ret;
}
void CLEAR(){
	while(p_list->next != NULL){
		prime *del = p_list;
		p_list = p_list->next;
		free(del);
	}
	free(p_list);
}/*freeing all the linked list created at the end of program*/

int main(){
	p_list = (prime*) malloc(sizeof(prime));
	init(p_list);

	int exit = 1;
	int determine;

	while(exit){
		printf("Please type number to classfy(1 < x < %d)", LIM);
		scanf("%d", &determine);
		assert(determine<=500);
		exit = classify(determine);
	}

	CLEAR();
	return 0;
}


text:
ENV['RACK_ENV'] ||= 'development'

require 'bundler'
Bundler.require :default, ENV['RACK_ENV'].to_sym

require 'sinatra/base'
require 'rack-flash'
require 'dm-postgres-adapter'

# HELPERS
require './helpers/excel_parser'
require './helpers/file_uploader'

# MODELS
require './models/vip_client.rb'

include FileUploader

class LaMareta < Sinatra::Base

  enable :sessions
  use Rack::Flash

  configure :development, :test do
    DataMapper.setup(:default, 'postgres://postgres@localhost/usersmareta')
    DataMapper.finalize.auto_upgrade!
  end

  configure :production do
    DataMapper.setup(:default, ENV['DATABASE_URL'])
    DataMapper.finalize.auto_upgrade!
  end

  get '/' do
    erb :upload
  end

  post '/upload' do
    filename = create_file(params['birthdayFile'][:filename])

    write_file(filename, params['birthdayFile'][:tempfile])

    clients_list = ExcelParser.parse(filename)

    VipClient.insert_into_database(clients_list)
    flash[:notice] = "Your database has been updated succesfully"
    redirect '/'
  end

  get '/uploaded' do
    erb :uploaded_file
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Persoonia 13(3): 282 (1987)

#### Original name
Sagenoma viride Stolk & G.F. Orr, 1974

### Remarks
null


text:
===============

##### Note

An updated version of CelerFT can be found at this link https://github.com/adminastoolsmith/CelerFT. This version supports
resuming a file upload and is written as a module.

#### Description

CelerFT is a file upload tool that allows you to upload up to 5 files at a time. CelerFT allows you to upload
large files i.e serveral gigabytes in size to a backend web server.

The CelerFT user interface is based on Javascript, the HTML5 File API, Web Workers, and XMLHTTPRequest Level 2.

The CelerFT backend web server is based on Node.js with Express.js.

##### Dependencies

CelerFT requires JQuery and the SparkMD5 library. The Node.js server requires the fs-extra, formidable, crypto,
express and path modules.


text:
regenerate:
	go install github.com/gogo/protobuf/protoc-gen-combo
	go install github.com/gogo/protobuf/protoc-gen-gogo
	protoc-gen-combo --version="3.0.0" --gogo_out=\
	Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types,\
	Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,\
	Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,\
	Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,\
	Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types:. \
	--proto_path=../../../../../:../../protobuf/:. types.proto
	find combos -type d -not -name combos -exec cp types_test.go.in {}/types_test.go \;


text:
class Sshfs < Formula
  desc "File system client based on SSH File Transfer Protocol"
  homepage "https://github.com/libfuse/sshfs"
  url "https://github.com/libfuse/sshfs/archive/sshfs-3.7.2.tar.gz"
  sha256 "8a9b0d980e9d34d0d18eacb9e1ca77fc499d1cf70b3674cc3e02f3eafad8ab14"
  license any_of: ["LGPL-2.1-only", "GPL-2.0-only"]

  bottle do
    sha256 x86_64_linux: "1fcf1f7994d56b8fac40224364d2b554084a4fde6fb07a8c4323d0e5957c92bb"
  end

  depends_on "meson" => :build
  depends_on "ninja" => :build
  depends_on "pkg-config" => :build
  depends_on "glib"

  on_macos do
    disable! date: "2021-04-08", because: "requires closed-source macFUSE"
  end

  on_linux do
    depends_on "libfuse"
  end

  def install
    mkdir "build" do
      system "meson", ".."
      system "meson", "configure", "--prefix", prefix
      system "ninja", "--verbose"
      system "ninja", "install", "--verbose"
    end
  end

  def caveats
    on_macos do
      <<~EOS
        The reasons for disabling this formula can be found here:
          https://github.com/Homebrew/homebrew-core/pull/64491

        An external tap may provide a replacement formula. See:
          https://docs.brew.sh/Interesting-Taps-and-Forks
      EOS
    end
  end

  test do
    system "#{bin}/sshfs", "--version"
  end
end


text:
import Component from 'ember-component';
import layout from './template';
import computed from 'ember-computed';
import box from 'ember-primer/utils/box-expression';
const { keys } = Object;
const Container =  Component.extend({
  tagName: '',

  layout,

  xScale: null,

  yScale: null,

  width: null,

  height: null,

  margin: '0',
  padding: '0',

  cursorPosition: [0, 0],

  xCursor: -1,
  yCursor: -1,

  localizedXScale: computed('xScale', 'rect', {
    get() {
      let { xScale, rect } = this.getProperties('xScale', 'rect');
      return xScale.copy().range([0, rect.width]);
    }
  }),

  localizedYScale: computed('yScale', 'rect', {
    get() {
      let { yScale, rect } = this.getProperties('yScale', 'rect');
      return yScale.copy().range([rect.height, 0]);
    }
  }),

  rect: computed('width', 'height', 'margin', {
    get() {
      let outerHeight = this.get('height') || 10;
      let outerWidth = this.get('width') || 10;
      let margin = box(this.get('margin'));
      // let padding = box(this.get('padding'));

      // let innerWidth = outerWidth - margin.left - margin.right;
      // let innerHeight = outerHeight - margin.top - margin.bottom;
      // let width = innerWidth - padding.left - padding.right;
      // let height = innerHeight - padding.top - padding.bottom;

      // let rect = {
      //   padding,
      //   margin,
      //   outerWidth, outerHeight,
      //   innerWidth, innerHeight,
      //   width, height,
      //   top: margin.top + padding.top,
      //   left: margin.left + padding.left
      //   // right: margin.left + padding.left,
      // };

      // // let height = this.get('height') || 10;
      // // let width = this.get('width') || 10;
      // // let margin = box(this.get('margin'));
      // // let padding = box(this.get('padding'));

      let innerWidth = outerWidth - margin.left - margin.right;
      let innerHeight = outerHeight - margin.top - margin.bottom;

      let rect = {
        margin,
        top: margin.top,
        left: margin.left,
        bottom: innerHeight - margin.top,
        right: innerWidth - margin.right,
        outerWidth,
        outerHeight,
        innerWidth,
        innerHeight,

        // Dupes
        height: innerHeight,
        width: innerWidth
      };

      keys(rect).forEach((key) => {
        if (rect[key] < 0) {
          rect[key] = 0;
        }
      });

      return rect;
    }
  }),

  actions: {
    updateCursorPosition([xValue, yValue], [xCursor, yCursor]) {
      this.sendAction('update-cursor-position', [xValue, yValue], [xCursor, yCursor]);

      // this.setProperties({ cursorPosition: [xCursor, yCursor] });
      // this.sendAction('_cursorChangedPosition', [xValue, yValue], [xCursor, yCursor]);
    }
  }
});

Container.reopenClass({
  positionalParams: ['xScale', 'yScale']
});

export default Container;


text: $(function(){$(".hospitality_id input[type=select]").click(function(){alert("clicked!")})});


text:
一个Tornado web应用存在一个或者多个RequestHandler之类,一个Application对象(负责路由到特定Handler),和一个main函数来启动server。

一个最小化的HelloWolrd示例其代码如下:

	from tornado.ioloop import IOLoop
	from tornado.web import RequestHandler, Application, url

	class HelloHandler(RequestHandler):
	    def get(self):
	        self.write("Hello, world")

	def make_app():
	    return Application([
	        url(r"/", HelloHandler),
	        ])

	def main():
	    app = make_app()
	    app.listen(8888)
	    IOLoop.current().start()

## Application对象

Application对象是可靠的全局配置,包括了路由表(映射所有的RequestHandler)。

路由表是一个URLSpec对象的数组,每一个对象都至少包含一个正则表达式和一个handler类。排序事项,第一匹配原则是被使用的。如果正则表达式包含捕获groups,这些groups是路径参数而且将传递给Handler的HTTP方法。如果一个字典传递作为URLSpec的第三个元素,它将提供初始化参数(这些参数将传递给RequestHandler.initialize)。最后,URLSpec有一个名称,这会被RequestHandler.reverse_url所使用。

例如,在如下不完整代码,根路径`/`将映射到MainHandler和 /story/(允许传递数量)将会映射到StoryHandler。数量将被作为字符串传递给StoryHandler.get。

	class MainHandler(RequestHandler):
	    def get(self):
	        self.write('link to story 1' %
	                   self.reverse_url("story", "1"))

	class StoryHandler(RequestHandler):
	    def initialize(self, db):
	        self.db = db

	    def get(self, story_id):
	        self.write("this is story %s" % story_id)

	app = Application([
	    url(r"/", MainHandler),
	    url(r"/story/([0-9]+)", StoryHandler, dict(db=db), name="story")
	    ])

Application构造函数需要传递许多关键参数,以便是用来自定义应用的行为以及启动可选的特性,查看[`Application.settings`](http://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings)已了解更多。


text:
import os
from skimage._build import cython

base_path = os.path.abspath(os.path.dirname(__file__))

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs

    config = Configuration('segmentation', parent_package, top_path)

    cython(['_felzenszwalb_cy.pyx'], working_path=base_path)
    config.add_extension('_felzenszwalb_cy', sources=['_felzenszwalb_cy.c'],
                         include_dirs=[get_numpy_include_dirs()])
    cython(['_quickshift_cy.pyx'], working_path=base_path)
    config.add_extension('_quickshift_cy', sources=['_quickshift_cy.c'],
                         include_dirs=[get_numpy_include_dirs()])
    cython(['_slic.pyx'], working_path=base_path)
    config.add_extension('_slic', sources=['_slic.c'],
                         include_dirs=[get_numpy_include_dirs()])

    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(maintainer='scikit-image Developers',
          maintainer_email='scikit-image@googlegroups.com',
          description='Segmentation Algorithms',
          url='https://github.com/scikit-image/scikit-image',
          license='SciPy License (BSD Style)',
          **(configuration(top_path='').todict())
          )


text:
require 'spec_helper'

describe Projects::Registry::TagsController do
  let(:user)    { create(:user) }
  let(:project) { create(:empty_project, :private) }

  before do
    sign_in(user)
    stub_container_registry_config(enabled: true)
  end

  context 'when user has access to registry' do
    before do
      project.add_developer(user)
    end

    describe 'POST destroy' do
      context 'when there is matching tag present' do
        before do
          stub_container_registry_tags(repository: /image/, tags: %w[rc1 test.])
        end

        let(:repository) do
          create(:container_repository, name: 'image', project: project)
        end

        it 'makes it possible to delete regular tag' do
          expect_any_instance_of(ContainerRegistry::Tag).to receive(:delete)

          destroy_tag('rc1')
        end

        it 'makes it possible to delete a tag that ends with a dot' do
          expect_any_instance_of(ContainerRegistry::Tag).to receive(:delete)

          destroy_tag('test.')
        end
      end
    end
  end

  def destroy_tag(name)
    post :destroy, namespace_id: project.namespace,
                   project_id: project,
                   repository_id: repository,
                   id: name
  end
end


text:
This is the source for the website of rphradio.net.

It contains all the necessary files/js/flatfiles that is needed to power the website. compile it using [Hugo](http://gohugo.io).

-------------------

**Non-Stop Channel Addresses**

Below are the addresses that you may use when you connect to the broadcast. the streams run on top of IceCast2 audio server.

```
http://rphradio.net:8000/mpd.mp3 Channel 1 - All Songs Mix
http://rphradio.net:8000/mpd2.mp3 Channel 2 - Acoustic Jam
http://rphradio.net:8000/mpd3.mp3 Channel 3 - Easy Rock
http://rphradio.net:8000/mpd4.mp3 Channel 4 - Pure Love Songs
http://rphradio.net:8000/mpd5.mp3 Channel 5 - Foreign Mix
http://rphradio.net:8000/mpd6.mp3 Channel 6 - OPM Mix
http://rphradio.net:8000/mpd7.mp3 Channel 7 - OPM Alternatives
http://rphradio.net:8000/mpd8.mp3 Channel 8 - OPM Rock Oldies
```
---------------------

**Live Channel Addresses and Credentials**

```
http://rphradio.net:8000/live.mp3
http://rphradio.net:8000/test.mp3
```

---------------------

**Credentials and format accepted**

```

Type:	Icecast2
Host:	rphradio.net
Mount:	/live.mp3 <--make sure to include the "/"
port:	8000
Login:	source
password:	livepass
Bitrate:	128 kbps
Format:	mp3
Channels:	Stereo

```

Just change the live channel part if you will broadcast to other channels (i.e test to live etc.) note that you cannot stream on non-stop music channels.


text:
namespace A2O {

enum class ManeuverStatus{
  STARTUP = -2,
  ERROR = -1,
  READY = 0,
  RUNNING = 1,
  COMPLETE = 2
};

namespace MANEUVER {
  const static std::string HALT = "Halt";
  const static std::string GET_READY = "GetReady";
  const static std::string IS_READY = "IsReady";
  const static std::string DRIVE_VIRTUAL_LANE = "DriveVirtualLane";
  const static std::string DRIVE_WAY_POINTS = "DriveWayPoints";
  const static std::string DRIVE_WAY_POINTS_STRAIGHT = "DriveWayPointsStraight";
  const static std::string FOLLOW_LANE = "FollowLane";
  const static std::string ONE_METER = "OneMeter";
  const static std::string CALIBRATION = "Calibration";
  const static std::string SENDSTATUS_TO_JURY = "SendStatusToJury";
}
}


text:
Here is the protocol for the BliepProject.

Notice! This is not the diep.io protocol.

## Clientbound Packets (server -> client)

### Packet 0: Handshake Request
This packet is sent to the player immediately after they connect.
If player does not respond with packet 1 within 10 seconds of sending this packet,
they will be kicked.

| Bytes | Data Type | Description |
|-------|-----------|-------------|
| 0     | uint8     | Packet Id   |
| 1     | uint16    | World Size  |

### Packet 20: Init Player(s)
This packet is sent to the client when a new tank(s) enters the players viewing
range or the player presses play. The client stores the information sent in this
packet as information such as a tank's nickname or tank type will no longer be
sent to the player for that tank.

| Bytes | Data Type    | Description          |
|-------|--------------|----------------------|
| 0     | uint8        | Packet Id            |
| 1     | uint8        | Player Count         |
| 2-?   | Player Data  | Data for all players |
#### Player Data
| Data Type | Description                  |
|-----------|------------------------------|
| uint32    | Player's Id (0=you)          |
| uint16    | Player's Nickname (charcode) |
| uint16    | Marks End of Nick (always 0) |
| uint32    | Player's Score               |
| uint8     | Tank Type Id                 |

### Packet 21: Forget Player(s)
This is packet is sent to the client when a player disconnects and must be
removed from the canvas.

| Bytes | Data Type | Description  |
|-------|-----------|--------------|
| 0     | uint8     | Packet Id    |
| 1     | uint8     | Player Count |
| 2-?   | uint32    | Player's Id  |

### Packet 25: Update Player(s) Score, Position, Bullets
This packet is sent to the client 30 times per second. It contains the new score
and position/rotation of the player and other players in the viewing range and
the players bullets location.
UPDATE: This packet is no longer being used for bullets, instead see packet 35.

| Bytes | Data Type          | Description          |
|-------|--------------------|----------------------|
| 0     | uint8              | Packet Id            |
| 1     | uint8              | Player Count         |
| 2-?   | Player Update Data | New data for players |
#### Player Update Data
| Data Type   | Description              |
|-------------|--------------------------|
| uint32      | Player's Id (0=you)      |
| uint32      | Player's Score           |
| int32       | Player's Position X      |
| int32       | Player's Position Y      |
| uint16      | Player's Rotation (!you) |
| uint8       | Player's Bullet Count    |
| Bullet Data | Data for Player's Bullet |
#### Bullet Data
| Data Type | Description         |
|-----------|---------------------|
| uint8     | Bullet Type Id      |
| int32     | Bullet's Position X |
| int32     | Bullet's Position Y |

### Packet 30: Add Food
This packet is sent to the client when new food is spawned in.

| Bytes | Data Type | Description       |
|-------|-----------|-------------------|
| 0     | uint8     | Packet Id         |
| 1     | uint16    | Food Count        |
| 2-?   | Food Data | Data for all food |
#### Food Data
| Data Type | Description     |
|-----------|-----------------|
| uint8     | Food Type Id    |
| int32     | Food Position X |
| int32     | Food Position Y |

### Packet 35: Spawn Player Bullet(s)
This packet is sent to the client after packet 25 if there are any bullets which
are unknown to the client, fired by the client's known players. The packet is
only sent once for each bullet, but contains lots of information to aid the
client in locally calculating and rendering bullets and their movement.

| Bytes | Data Type    | Description             |
|-------|--------------|-------------------------|
| 0     | uint8        | Packet Id               |
| 1     | uint16       | Server Time (part 1)    |
| 3     | uint32       | Server Time (part 2)    |
| 7     | uint8        | Bullet Count            |
| 7-?   | Bullet Data2 | Bullet Data             |
#### Bullet Data2
| uint32  | Owner's Id (0=yours)    |
| uint8   | Bullet Type Id          |
| float32 | Bullet Speed            |
| uint16  | Bullet Aim Angle        |
| int32   | Bullet Start Position X |
| int32   | Bullet Stop Position Y  |
| uint16  | Bullet Life             |

## Serverbound Packets (client -> server)

### Packet 1: Handshake
This packet is sent after receiving packet 0 from server.

| Bytes | Data Type | Description      |
|-------|-----------|------------------|
| 0     | uint8     | Packet Id        |
| 1     | uint8     | Protocol Version |

### Packet 2: Heartbeat
This packet is sent every second to keep the connection alive.

| Bytes | Data Type | Description |
|-------|-----------|-------------|
| 0     | uint8     | Packet Id   |

### Packet 10: Set Nickname & Play
This packet is sent when the player presses enter on the menu screen to play.

| Bytes | Data Type | Description                  |
|-------|-----------|------------------------------|
| 0     | uint8     | Packet Id                    |
| 1-?   | uint16    | Player's Nickname (charcode) |
| ?     | uint16    | Marks End of Nick (always 0) |

### Packet 50: Mouse Move
This packet is sent when the player moves their mouse.

| Bytes | Data Type | Description            |
|-------|-----------|------------------------|
| 0     | uint8     | Packet Id              |
| 1     | uint16    | Mouse angle in Degrees |

### Packet 51: Movement key press
This packet is sent when a WASD key is pressed or released.

| Bytes | Data Type | Description |
|-------|-----------|-------------|
| 0     | uint8     | Packet Id   |
| 1     | uint8     | W Key State |
| 2     | uint8     | A Key State |
| 3     | uint8     | S Key State |
| 4     | uint8     | D Key State |

### Packet 52: Fire Bullet
This packet is sent when the tanks needs to start or stop firing bullets.

| Bytes | Data Type | Description  |
|-------|-----------|--------------|
| 0     | uint8     | Packet Id    |
| 1     | uint8     | Fire Bullets |


text:
package jp.ijufumi.sample.twitter.domain.dao;

import jp.ijufumi.sample.twitter.domain.entity.TCampaignResult;
import org.seasar.doma.Dao;
import org.seasar.doma.Insert;
import org.seasar.doma.Select;
import org.seasar.doma.Update;
import org.seasar.doma.boot.ConfigAutowireable;
import org.seasar.doma.jdbc.Result;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@ConfigAutowireable
@Dao
public interface CampaignResultDao {
    @Select
    List<TCampaignResult> selectAll(int campaignId);

    @Select
    Optional<TCampaignResult> selectById(int campaignId, long twitterId);

    @Transactional
    @Insert
    Result<TCampaignResult> insert(TCampaignResult result);

    @Transactional
    @Update
    Result<TCampaignResult> update(TCampaignResult result);
}


text:
namespace Math{

	class Vector3D{

	public:
		float x;

		float y;

		float z;

	public:
	    inline Vector3D();

	    inline Vector3D(const Vector3D & copy);

		inline Vector3D(float  xx, float  yy, float  zz);

		inline ~Vector3D();

		inline void add(const Vector3D & vector);
		inline void subtract(const Vector3D & vector);
		inline void multiply(const Vector3D & vector);
		inline void divide(const Vector3D & vector);

		inline bool operator==(const Vector3D & vector);
		inline bool operator!=(const Vector3D & vector);

		inline const Vector3D operator+(const Vector3D & vector) const;
		inline Vector3D& operator+=(const Vector3D & vector);

		inline const Vector3D operator-(const Vector3D & vector) const;
		inline Vector3D& operator-=(const Vector3D & vector);

		inline const Vector3D operator*(const Vector3D & vector) const;
		inline Vector3D& operator*=(const Vector3D & vector);

		inline const Vector3D operator/(const Vector3D & vector) const;
		inline Vector3D& operator/=(const Vector3D & vector);

	public:
		inline void scale(float scalar);
		inline void scale(const Vector3D & vector);

		float length()const;
		float lengthSquared()const;
		float distance(const Vector3D & vector) const;
		float distanceSquared(const Vector3D & vector) const;
		Vector3D crossProduct(const Vector3D & vector) const;

		void normalize();
		Vector3D getNormalized()const;

		friend std::ostream& operator<<(std::ostream& stream, const Vector3D & vector);

	};

	inline const Vector3D operator*(float scalar, const Vector3D & right);
	inline const Vector3D operator*(const Vector3D & left, float scalar);
#include "Vector3D.inl"
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <policyArea>
      <name>Taxation</name>
    </policyArea>
    <committeeReports />
    <sponsors>
      <item>
        <party>R</party>
        <bioguideId>C001035</bioguideId>
        <firstName>SUSAN</firstName>
        <byRequestType />
        <identifiers>
          <gpoId>8291</gpoId>
          <lisID>1541</lisID>
          <bioguideId>C001035</bioguideId>
        </identifiers>
        <middleName>MARGARET</middleName>
        <lastName>COLLINS</lastName>
        <state>ME</state>
        <fullName>Sen. Collins, Susan M. [R-ME]</fullName>
      </item>
    </sponsors>
    <relatedBills />
    <version>1.0.0</version>
    <recordedVotes />
    <createDate>2017-09-08T10:26:41Z</createDate>
    <billType>S</billType>
    <title>Forty Hours Is Full Time Act of 2017</title>
    <notes />
    <congress>115</congress>
    <latestAction>
      <links />
      <actionDate>2017-09-07</actionDate>
      <text>Read twice and referred to the Committee on Finance.</text>
    </latestAction>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Employee benefits and pensions</name>
          </item>
          <item>
            <name>Health care costs and insurance</name>
          </item>
          <item>
            <name>Health care coverage and access</name>
          </item>
          <item>
            <name>Sales and excise taxes</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Taxation</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <cosponsors>
      <item>
        <party>D</party>
        <bioguideId>D000607</bioguideId>
        <firstName>Joe</firstName>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <gpoId>7941</gpoId>
          <bioguideId>D000607</bioguideId>
          <lisID>1850</lisID>
        </identifiers>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName />
        <sponsorshipDate>2017-09-07</sponsorshipDate>
        <lastName>Donnelly</lastName>
        <state>IN</state>
        <fullName>Sen. Donnelly, Joe [D-IN]</fullName>
      </item>
      <item>
        <party>R</party>
        <bioguideId>Y000064</bioguideId>
        <firstName>Todd</firstName>
        <sponsorshipWithdrawnDate />
        <identifiers>
          <lisID>2019</lisID>
          <bioguideId>Y000064</bioguideId>
          <gpoId>7948</gpoId>
        </identifiers>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <middleName>C.</middleName>
        <sponsorshipDate>2017-09-14</sponsorshipDate>
        <lastName>Young</lastName>
        <state>IN</state>
        <fullName>Sen. Young, Todd C. [R-IN]</fullName>
      </item>
    </cosponsors>
    <originChamber>Senate</originChamber>
    <updateDate>2017-09-21T04:31:11Z</updateDate>
    <laws />
    <actions>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
      <item>
        <actionDate>2017-09-07</actionDate>
        <committee>
          <systemCode>ssfi00</systemCode>
          <name>Finance Committee</name>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Finance.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <committee />
        <actionDate>2017-09-07</actionDate>
        <links />
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <text>Introduced in Senate</text>
        <type>IntroReferral</type>
        <actionCode>10000</actionCode>
      </item>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
    </actions>
    <cboCostEstimates />
    <committees>
      <billCommittees>
        <item>
          <systemCode>ssfi00</systemCode>
          <type>Standing</type>
          <activities>
            <item>
              <date>2017-09-07T21:00:49Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <subcommittees />
          <chamber>Senate</chamber>
          <name>Finance Committee</name>
        </item>
      </billCommittees>
    </committees>
    <billNumber>1782</billNumber>
    <amendments />
    <summaries>
      <billSummaries>
        <item>
          <actionDesc>Introduced in Senate</actionDesc>
          <lastSummaryUpdateDate>2017-09-18T15:02:37Z</lastSummaryUpdateDate>
          <versionCode>00</versionCode>
          <actionDate>2017-09-07</actionDate>
          <name>Introduced in Senate</name>
          <text><![CDATA[
Forty Hours is Full Time Act of 2017

 This bill amends the Internal Revenue Code, with respect to the employer mandate to provide health care coverage, to: (1) modify the formula for calculating the number of full-time employees employed by an applicable large employer subject to the mandate; and (2) define a "full-time employee" as an employee who is employed on average at least 40 hours per week (currently, 30 hours).
]]></text>
          <updateDate>2017-09-07T04:00:00Z</updateDate>
        </item>
      </billSummaries>
    </summaries>
    <introducedDate>2017-09-07</introducedDate>
    <calendarNumbers />
    <titles>
      <item>
        <chamberName />
        <chamberCode />
        <titleType>Short Titles as Introduced</titleType>
        <parentTitleType />
        <title>Forty Hours Is Full Time Act of 2017</title>
      </item>
      <item>
        <chamberName />
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <parentTitleType />
        <title>A bill to amend the Internal Revenue Code of 1986 to modify the definition of full-time employee for purposes of the employer mandate in the Patient Protection and Affordable Care Act.</title>
      </item>
      <item>
        <chamberName />
        <chamberCode />
        <titleType>Display Title</titleType>
        <parentTitleType />
        <title>Forty Hours Is Full Time Act of 2017</title>
      </item>
      <item>
        <chamberName />
        <chamberCode />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <parentTitleType />
        <title>Forty Hours Is Full Time Act of 2017</title>
      </item>
    </titles>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
package oasis.names.tc.ebxml_regrep.xsd.query._3;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="StringFilterType")
public class StringFilterType extends SimpleFilterType
{

  @XmlAttribute(name="value", required=true)
  protected String value;

  public String getValue()
  {
    return this.value;
  }

  public void setValue(String value)
  {
    this.value = value;
  }
}


text:
<?php

namespace FormAl\Elements;

use FormAl\ElementBase;

/**
 * Class Title
 *
 * @package FormAl\Elements
 */
class Title extends ElementBase
{
    /** @var string */
    public $value = null;
    /** @var bool */
    public $fullWidth = true;
    /** @var bool */
    public $markForExport = false;
    /** @var string */
    public $text = "You need to set this title with using ->setText()";

    /**
     * @return bool
     */
    public function isClicked()
    {
        $updateArray = $this->getFormAl()->updatedValues();
        $name = md5($this->getName());

        return isset($updateArray[$name]);
    }

    /**
     * @param string $text
     */
    public function setText($text)
    {
        $this->text = $text;
    }

    /**
     * @return string
     */
    public function render()
    {
        return "<h2>" . $this->text . "</h2>";
    }
}


text:
require 'spec_helper'

describe Foodie do
  it 'should have a version number' do
    Foodie::VERSION.should_not be_nil
  end

  it 'milk is delicious' do
    Foodie::Food.portray("milk").should eql("delicious")
  end

  it 'egg is gross' do
    Foodie::Food.portray("egg").should eql("gross")
  end

  it 'egg pluralize eggs' do
    Foodie::Food.pluralize("egg").should eql("eggs")
  end
end


text:
<?php

/**
 * Represents schema management object for MySQL
 *
 * @package framework
 * @subpackage model
 */
class MySQLSchemaManager extends DBSchemaManager {

	/**
	 * Identifier for this schema, used for configuring schema-specific table
	 * creation options
	 */
	const ID = 'MySQL';

	public function createTable($table, $fields = null, $indexes = null, $options = null, $advancedOptions = null) {
		$fieldSchemas = $indexSchemas = "";

		if (!empty($options[self::ID])) {
			$addOptions = $options[self::ID];
		} elseif (!empty($options[get_class($this)])) {
			Deprecation::notice(
				'3.2',
				'Use MySQLSchemaManager::ID for referencing mysql-specific table creation options'
			);
			$addOptions = $options[get_class($this)];
		} elseif (!empty($options[get_parent_class($this)])) {
			Deprecation::notice(
				'3.2',
				'Use MySQLSchemaManager::ID for referencing mysql-specific table creation options'
			);
			$addOptions = $options[get_parent_class($this)];
		} else {
			$addOptions = "ENGINE=InnoDB";
		}

		if (!isset($fields['ID'])) {
			$fields['ID'] = "int(11) not null auto_increment";
		}
		if ($fields) {
			foreach ($fields as $k => $v)
				$fieldSchemas .= "\"$k\" $v,\n";
		}
		if ($indexes) {
			foreach ($indexes as $k => $v) {
				$indexSchemas .= $this->getIndexSqlDefinition($k, $v) . ",\n";
			}
		}

		// Switch to "CREATE TEMPORARY TABLE" for temporary tables
		$temporary = empty($options['temporary'])
				? ""
				: "TEMPORARY";

		$this->query("CREATE $temporary TABLE \"$table\" (
				$fieldSchemas
				$indexSchemas
				primary key (ID)
			) {$addOptions}");

		return $table;
	}

	public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null,
		$alteredIndexes = null, $alteredOptions = null, $advancedOptions = null
	) {
		if ($this->isView($tableName)) {
			$this->alterationMessage(
				sprintf("Table %s not changed as it is a view", $tableName),
				"changed"
			);
			return;
		}
		$alterList = array();

		if ($newFields) {
			foreach ($newFields as $k => $v) {
				$alterList[] .= "ADD \"$k\" $v";
			}
		}
		if ($newIndexes) {
			foreach ($newIndexes as $k => $v) {
				$alterList[] .= "ADD " . $this->getIndexSqlDefinition($k, $v);
			}
		}
		if ($alteredFields) {
			foreach ($alteredFields as $k => $v) {
				$alterList[] .= "CHANGE \"$k\" \"$k\" $v";
			}
		}
		if ($alteredIndexes) {
			foreach ($alteredIndexes as $k => $v) {
				$alterList[] .= "DROP INDEX \"$k\"";
				$alterList[] .= "ADD " . $this->getIndexSqlDefinition($k, $v);
			}
		}

		if ($alteredOptions && isset($alteredOptions[get_class($this)])) {
			$indexList = $this->indexList($tableName);
			$skip = false;
			foreach ($indexList as $index) {
				if ($index['type'] === 'fulltext') {
					$skip = true;
					break;
				}
			}
			if ($skip) {
				$this->alterationMessage(
					sprintf(
						"Table %s options not changed to %s due to fulltextsearch index",
						$tableName,
						$alteredOptions[get_class($this)]
					),
					"changed"
				);
			} else {
				$this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[get_class($this)]));
				$this->alterationMessage(
					sprintf("Table %s options changed: %s", $tableName, $alteredOptions[get_class($this)]),
					"changed"
				);
			}
		}

		$alterations = implode(",\n", $alterList);
		$this->query("ALTER TABLE \"$tableName\" $alterations");
	}

	public function isView($tableName) {
		$info = $this->query("SHOW /*!50002 FULL*/ TABLES LIKE '$tableName'")->record();
		return $info && strtoupper($info['Table_type']) == 'VIEW';
	}

	public function renameTable($oldTableName, $newTableName) {
		$this->query("ALTER TABLE \"$oldTableName\" RENAME \"$newTableName\"");
	}

	public function checkAndRepairTable($tableName) {
		// If running PDO and not in emulated mode, check table will fail
		if($this->database->getConnector() instanceof PDOConnector && !PDOConnector::is_emulate_prepare()) {
			$this->alterationMessage('CHECK TABLE command disabled for PDO in native mode', 'notice');
			return true;
		}

		// Perform check
		if (!$this->runTableCheckCommand("CHECK TABLE \"$tableName\"")) {
			if ($this->runTableCheckCommand("CHECK TABLE \"" . strtolower($tableName) . "\"")) {
				$this->alterationMessage(
					"Table $tableName: renamed from lowercase",
					"repaired"
				);
				return $this->renameTable(strtolower($tableName), $tableName);
			}

			$this->alterationMessage(
				"Table $tableName: repaired",
				"repaired"
			);
			return $this->runTableCheckCommand("REPAIR TABLE \"$tableName\" USE_FRM");
		} else {
			return true;
		}
	}

	/**
	 * Helper function used by checkAndRepairTable.
	 * @param string $sql Query to run.
	 * @return boolean Returns if the query returns a successful result.
	 */
	protected function runTableCheckCommand($sql) {
		$testResults = $this->query($sql);
		foreach ($testResults as $testRecord) {
			if (strtolower($testRecord['Msg_text']) != 'ok') {
				return false;
			}
		}
		return true;
	}

	public function hasTable($table) {
		// MySQLi doesn't like parameterised queries for some queries
		$sqlTable = $this->database->quoteString($table);
		return (bool) ($this->query("SHOW TABLES LIKE $sqlTable")->value());
	}

	public function createField($tableName, $fieldName, $fieldSpec) {
		$this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec");
	}

	public function databaseList() {
		return $this->query("SHOW DATABASES")->column();
	}

	public function databaseExists($name) {
		// MySQLi doesn't like parameterised queries for some queries
		$sqlName = $this->database->quoteString($name);
		return !!($this->query("SHOW DATABASES LIKE $sqlName")->value());
	}

	public function createDatabase($name) {
		$this->query("CREATE DATABASE \"$name\" DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci");
	}

	public function dropDatabase($name) {
		$this->query("DROP DATABASE \"$name\"");
	}

	/**
	 * Change the database type of the given field.
	 * @param string $tableName The name of the tbale the field is in.
	 * @param string $fieldName The name of the field to change.
	 * @param string $fieldSpec The new field specification
	 */
	public function alterField($tableName, $fieldName, $fieldSpec) {
		$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
	}

	/**
	 * Change the database column name of the given field.
	 *
	 * @param string $tableName The name of the tbale the field is in.
	 * @param string $oldName The name of the field to change.
	 * @param string $newName The new name of the field
	 */
	public function renameField($tableName, $oldName, $newName) {
		$fieldList = $this->fieldList($tableName);
		if (array_key_exists($oldName, $fieldList)) {
			$this->query("ALTER TABLE \"$tableName\" CHANGE \"$oldName\" \"$newName\" " . $fieldList[$oldName]);
		}
	}

	protected static $_cache_collation_info = array();

	public function fieldList($table) {
		$fields = $this->query("SHOW FULL FIELDS IN \"$table\"");
		foreach ($fields as $field) {

			// ensure that '' is converted to \' in field specification (mostly for the benefit of ENUM values)
			$fieldSpec = str_replace('\'\'', '\\\'', $field['Type']);
			if (!$field['Null'] || $field['Null'] == 'NO') {
				$fieldSpec .= ' not null';
			}

			if ($field['Collation'] && $field['Collation'] != 'NULL') {
				// Cache collation info to cut down on database traffic
				if (!isset(self::$_cache_collation_info[$field['Collation']])) {
					self::$_cache_collation_info[$field['Collation']]
						= $this->query("SHOW COLLATION LIKE '{$field['Collation']}'")->record();
				}
				$collInfo = self::$_cache_collation_info[$field['Collation']];
				$fieldSpec .= " character set $collInfo[Charset] collate $field[Collation]";
			}

			if ($field['Default'] || $field['Default'] === "0") {
				$fieldSpec .= " default " . $this->database->quoteString($field['Default']);
			}
			if ($field['Extra']) $fieldSpec .= " " . $field['Extra'];

			$fieldList[$field['Field']] = $fieldSpec;
		}
		return $fieldList;
	}

	/**
	 * Create an index on a table.
	 *
	 * @param string $tableName The name of the table.
	 * @param string $indexName The name of the index.
	 * @param string $indexSpec The specification of the index, see {@link SS_Database::requireIndex()} for more
	 *                          details.
	 */
	public function createIndex($tableName, $indexName, $indexSpec) {
		$this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec));
	}

	/**
	 * Generate SQL suitable for creating this index
	 *
	 * @param string $indexName
	 * @param string|array $indexSpec See {@link requireTable()} for details
	 * @return string MySQL compatible ALTER TABLE syntax
	 */
	protected function getIndexSqlDefinition($indexName, $indexSpec) {
		$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
		if ($indexSpec['type'] == 'using') {
			return "index \"$indexName\" using ({$indexSpec['value']})";
		} else {
			return "{$indexSpec['type']} \"$indexName\" ({$indexSpec['value']})";
		}
	}

	public function alterIndex($tableName, $indexName, $indexSpec) {
		$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
		$this->query("ALTER TABLE \"$tableName\" DROP INDEX \"$indexName\"");
		$this->query("ALTER TABLE \"$tableName\" ADD {$indexSpec['type']} \"$indexName\" {$indexSpec['value']}");
	}

	protected function indexKey($table, $index, $spec) {
		// MySQL simply uses the same index name as SilverStripe does internally
		return $index;
	}

	public function indexList($table) {
		$indexes = $this->query("SHOW INDEXES IN \"$table\"");
		$groupedIndexes = array();
		$indexList = array();

		foreach ($indexes as $index) {
			$groupedIndexes[$index['Key_name']]['fields'][$index['Seq_in_index']] = $index['Column_name'];

			if ($index['Index_type'] == 'FULLTEXT') {
				$groupedIndexes[$index['Key_name']]['type'] = 'fulltext';
			} else if (!$index['Non_unique']) {
				$groupedIndexes[$index['Key_name']]['type'] = 'unique';
			} else if ($index['Index_type'] == 'HASH') {
				$groupedIndexes[$index['Key_name']]['type'] = 'hash';
			} else if ($index['Index_type'] == 'RTREE') {
				$groupedIndexes[$index['Key_name']]['type'] = 'rtree';
			} else {
				$groupedIndexes[$index['Key_name']]['type'] = 'index';
			}
		}

		if ($groupedIndexes) {
			foreach ($groupedIndexes as $index => $details) {
				ksort($details['fields']);
				$indexList[$index] = $this->parseIndexSpec($index, array(
					'name' => $index,
					'value' => $this->implodeColumnList($details['fields']),
					'type' => $details['type']
				));
			}
		}

		return $indexList;
	}

	public function tableList() {
		$tables = array();
		foreach ($this->query("SHOW TABLES") as $record) {
			$table = reset($record);
			$tables[strtolower($table)] = $table;
		}
		return $tables;
	}

	public function enumValuesForField($tableName, $fieldName) {
		// Get the enum of all page types from the SiteTree table
		$classnameinfo = $this->query("DESCRIBE \"$tableName\" \"$fieldName\"")->first();
		preg_match_all("/'[^,]+'/", $classnameinfo["Type"], $matches);

		$classes = array();
		foreach ($matches[0] as $value) {
			$classes[] = stripslashes(trim($value, "'"));
		}
		return $classes;
	}

	public function dbDataType($type) {
		$values = Array(
			'unsigned integer' => 'UNSIGNED'
		);

		if (isset($values[$type])) return $values[$type];
		else return '';
	}

	/**
	 * Return a boolean type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function boolean($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'tinyint', 'precision'=>1, 'sign'=>'unsigned', 'null'=>'not null',
		//'default'=>$this->default);
		//DB::requireField($this->tableName, $this->name, "tinyint(1) unsigned not null default
		//'{$this->defaultVal}'");
		return 'tinyint(1) unsigned not null' . $this->defaultClause($values);
	}

	/**
	 * Return a date type-formatted string
	 * For MySQL, we simply return the word 'date', no other parameters are necessary
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function date($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'date');
		//DB::requireField($this->tableName, $this->name, "date");
		return 'date';
	}

	/**
	 * Return a decimal type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function decimal($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'decimal', 'precision'=>"$this->wholeSize,$this->decimalSize");
		//DB::requireField($this->tableName, $this->name, "decimal($this->wholeSize,$this->decimalSize)");
		// Avoid empty strings being put in the db
		if ($values['precision'] == '') {
			$precision = 1;
		} else {
			$precision = $values['precision'];
		}

		$defaultValue = '';
		if (isset($values['default']) && is_numeric($values['default'])) {
			$decs = strpos($precision, ',') !== false
					? (int) substr($precision, strpos($precision, ',') + 1)
					: 0;
			$defaultValue = ' default ' . number_format($values['default'], $decs, '.', '');
		}

		return "decimal($precision) not null $defaultValue";
	}

	/**
	 * Return a enum type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function enum($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'enum', 'enums'=>$this->enum, 'character set'=>'utf8', 'collate'=>
		// 'utf8_general_ci', 'default'=>$this->default);
		//DB::requireField($this->tableName, $this->name, "enum('" . implode("','", $this->enum) . "') character set
		// utf8 collate utf8_general_ci default '{$this->default}'");
		$valuesString = implode(",", Convert::raw2sql($values['enums'], true));
		return "enum($valuesString) character set utf8 collate utf8_general_ci" . $this->defaultClause($values);
	}

	/**
	 * Return a set type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function set($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'enum', 'enums'=>$this->enum, 'character set'=>'utf8', 'collate'=>
		// 'utf8_general_ci', 'default'=>$this->default);
		//DB::requireField($this->tableName, $this->name, "enum('" . implode("','", $this->enum) . "') character set
		//utf8 collate utf8_general_ci default '{$this->default}'");
		$valuesString = implode(",", Convert::raw2sql($values['enums'], true));
		return "set($valuesString) character set utf8 collate utf8_general_ci" . $this->defaultClause($values);
	}

	/**
	 * Return a float type-formatted string
	 * For MySQL, we simply return the word 'date', no other parameters are necessary
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function float($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'float');
		//DB::requireField($this->tableName, $this->name, "float");
		return "float not null" . $this->defaultClause($values);
	}

	/**
	 * Return a int type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function int($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'int', 'precision'=>11, 'null'=>'not null', 'default'=>(int)$this->default);
		//DB::requireField($this->tableName, $this->name, "int(11) not null default '{$this->defaultVal}'");
		return "int(11) not null" . $this->defaultClause($values);
	}

	/**
	 * Return a datetime type-formatted string
	 * For MySQL, we simply return the word 'datetime', no other parameters are necessary
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function ss_datetime($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'datetime');
		//DB::requireField($this->tableName, $this->name, $values);
		return 'datetime';
	}

	/**
	 * Return a text type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function text($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'mediumtext', 'character set'=>'utf8', 'collate'=>'utf8_general_ci');
		//DB::requireField($this->tableName, $this->name, "mediumtext character set utf8 collate utf8_general_ci");
		return 'mediumtext character set utf8 collate utf8_general_ci' . $this->defaultClause($values);
	}

	/**
	 * Return a time type-formatted string
	 * For MySQL, we simply return the word 'time', no other parameters are necessary
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function time($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'time');
		//DB::requireField($this->tableName, $this->name, "time");
		return 'time';
	}

	/**
	 * Return a varchar type-formatted string
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function varchar($values) {
		//For reference, this is what typically gets passed to this function:
		//$parts=Array('datatype'=>'varchar', 'precision'=>$this->size, 'character set'=>'utf8', 'collate'=>
		//'utf8_general_ci');
		//DB::requireField($this->tableName, $this->name, "varchar($this->size) character set utf8 collate
		// utf8_general_ci");
		$default = $this->defaultClause($values);
		return "varchar({$values['precision']}) character set utf8 collate utf8_general_ci$default";
	}

	/*
	 * Return the MySQL-proprietary 'Year' datatype
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string
	 */
	public function year($values) {
		return 'year(4)';
	}

	public function IdColumn($asDbValue = false, $hasAutoIncPK = true) {
		return 'int(11) not null auto_increment';
	}

	/**
	 * Parses and escapes the default values for a specification
	 *
	 * @param array $values Contains a tokenised list of info about this data type
	 * @return string Default clause
	 */
	protected function defaultClause($values) {
		if(isset($values['default'])) {
			return ' default ' . $this->database->quoteString($values['default']);
		}
		return '';
	}

}


text:
'use static'

process.env.DEBUG = "w:*";

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
const debug = require('debug')('w:main');
const serveStatic = require('serve-static');
const path = require('path');
const morgan = require('morgan');
const crypto = require('crypto');
const secret = process.env.HMAC_SECRET || Math.random().toString();
const bodyParser = require('body-parser');

const Room = require('./lib/Room.js');

function id(c) {
	return crypto.createHmac('sha256', secret).update(c).digest('hex').substr(0, 10);
}

debug(secret);

app.use(morgan("tiny"));

app.ws('/ws/:room', function (ws, req) {
	console.log(req.params, req.query);

	req.query.name = req.query.name || "GUEST";

	if (!Room.getRoom(req.params.room)) {
		debug('This room doesn\'t exist');
		ws.close();
		return;
	}

	if (!req.query.clientID) {
		debug('Invalid clientID');
		ws.close();
		return;
	}

	let clientHash;
	try {
		clientHash = id(req.query.clientID);
	} catch (err) {
		debug(err);
	}

	debug('Debug %s connected to room %s', clientHash, req.params.room);

	Room.getRoom(req.params.room).connect(clientHash, req.query.name, ws);
});

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

app.post('/create', function (req, res) {
	debug(req.body);
	let room = new Room(id(req.body.clientID), {
		mode: req.body.mode
	});

	res.json({
		roomID: room.id
	});
});

app.use(serveStatic(path.join(__dirname, 'public')));

app.use(function (req, res) {
	res.redirect('/');
});

const port = process.env.PORT || 8080;

app.listen(port, function () {
	debug('Server running on port %d', port);
})


text:
import Sprite from './sprite';
import SpriteSvgAttr from '../attribute/spritesvg';
import ownerDocument from '../document';
import {querySelector, querySelectorAll} from '../selector';
import {sizeToPixel} from '../utils/attribute_value';

// This class only avaliable for browser

const namespace = 'http://www.w3.org/2000/svg';
const setAttribute = Symbol.for('spritejs_setAttribute');
const _root = Symbol('root');

const _updateTextureTask = Symbol('task');

function updateTexture(svgNode, flexible = true) {
  const root = svgNode[_root];
  if(root && root.children[0]) {
    const svg = svgNode.svg;
    const displayRatio = svgNode.layer ? svgNode.layer.displayRatio : 1;
    if(!svg.hasAttribute('data-original-width')) {
      let w = svg.getAttribute('width');
      w = w ? sizeToPixel(w) : 300;
      let h = svg.getAttribute('height');
      h = h ? sizeToPixel(h) : 150;

      if(!svg.hasAttribute('viewBox')) {
        svg.setAttribute('viewBox', `0 0 ${Math.round(w)} ${Math.round(h)}`);
      }
      svg.setAttribute('data-original-width', w);
      svg.setAttribute('data-original-height', h);
    }
    let width = svgNode.attributes.width || Number(svg.getAttribute('data-original-width'));
    let height = svgNode.attributes.height || Number(svg.getAttribute('data-original-height'));
    width *= displayRatio;
    height *= displayRatio;
    if(flexible && svgNode.attributes.flexible) {
      const scale = svgNode.attributes.scale[0];
      width *= scale;
      height *= scale;
      svg.setAttribute('width', width);
      svg.setAttribute('height', height);
      if(width && height && svgNode.textureImage) {
        const imgWidth = svgNode.textureImage.width;
        const imgHeight = svgNode.textureImage.height;
        const boxSize = svgNode.clientSize;
        svgNode.attributes.textureRect = [0, 0, Math.round(boxSize[0] * imgWidth / width), Math.round(boxSize[1] * imgHeight / height)];
      }
    } else if(!svgNode[_updateTextureTask]) {
      svg.setAttribute('width', width);
      svg.setAttribute('height', height);
      svgNode[_updateTextureTask] = Promise.resolve().then(() => {
        delete svgNode[_updateTextureTask];
        const svgText = root.innerHTML;
        const blob = new Blob([svgText], {type: 'image/svg+xml'});
        const textureURL = URL.createObjectURL(blob);
        const img = new Image();
        img.onload = function () {
          if(img.width && img.height) {
            svgNode.attributes[setAttribute]('texture', img);
            if(svgNode.attributes.flexible) {
              svgNode.attributes.textureRect = null;
            }
          } else {
            svgNode.attributes[setAttribute]('texture', null);
          }
        };
        img.src = textureURL;
      });
    }
  }
}

export default class SpriteSvg extends Sprite {
  static Attr = SpriteSvgAttr;

  constructor(attrs = {}) {
    if(typeof attrs === 'string') attrs = {svgText: attrs};
    let {svgText, ..._attrs} = attrs;
    super(_attrs);
    this[_root] = document.createElement('div');
    if(svgText) {
      this[_root].innerHTML = svgText;
      const svg = this[_root].children[0];
      if(svg) svg.setAttribute('xmlns', namespace);
      else {
        // not svg text
        fetch(svgText).then((res) => {
          return res.text();
        }).then((text) => {
          this[_root].innerHTML = text;
          if(!this.observer || this.attributes.flexible) updateTexture(this);
        });
        svgText = null;
      }
    }
    if(!svgText) {
      const svg = document.createElementNS(namespace, 'svg');
      svg.setAttribute('xmlns', namespace);
      this[_root].appendChild(svg);
    }
    // updateTexture(this);

    if(typeof MutationObserver === 'function') {
      const observer = new MutationObserver((mutationsList) => {
        updateTexture(this, false);
      });

      observer.observe(this[_root], {
        attributes: true,
        subtree: true,
        characterData: true,
        childList: true,
      });

      this.observer = observer;
    }
  }

  get children() {
    return [this.svg];
  }

  get childNodes() {
    return [this.svg];
  }

  get svg() {
    if(this[_root]) {
      return this[_root].children[0];
    }
    return null;
  }

  /* override */
  setResolution({width, height}) {
    super.setResolution({width, height});
    updateTexture(this);
  }

  /* override */
  dispatchPointerEvent(event) {
    // 派发事件给 svg 元素,但是目前只支持派发给 svg 根元素,不支持派发给子元素
    const ret = super.dispatchPointerEvent(event);
    if(ret && this.attributes.passEvents && typeof MouseEvent === 'function') {
      const {x, y} = event;
      let [offsetX, offsetY] = this.getOffsetPosition(x, y);
      const originalEvent = event.originalEvent;
      const anchor = this.attributes.anchor;
      const cz = this.clientSize;
      offsetX = (offsetX + anchor[0] * cz[0]) / 2;
      offsetY = (offsetY + anchor[1] * cz[1]) / 2;

      const type = event.type;
      if(type === originalEvent.type) {
        let newEvent = null;
        if(originalEvent instanceof MouseEvent) {
          newEvent = new MouseEvent(type, {
            screenX: offsetX,
            screenY: offsetY,
            clientX: offsetX,
            clientY: offsetY,
            bubbles: originalEvent.bubbles,
            button: originalEvent.button,
            buttons: originalEvent.buttons,
            cancelBubble: originalEvent.cancelBubble,
            cancelable: originalEvent.cancelable,
            currentTarget: originalEvent.currentTarget,
            fromElement: originalEvent.fromElement,
            relatedTarget: originalEvent.relatedTarget,
            returnValue: originalEvent.returnValue,
            srcElement: originalEvent.srcElement,
            target: originalEvent.target,
            toElement: originalEvent.toElement,
            // view: originalEvent.view,
            which: originalEvent.witch,
          });
        } else if(originalEvent instanceof TouchEvent) {
          let originalTouch = null;
          const pointers = originalEvent.changedTouches || [originalEvent];
          for(let i = 0; i < pointers.length; i++) {
            const pointer = pointers[i];
            if(event.identifier === pointer.identifier) {
              originalTouch = pointer;
              break;
            }
          }
          if(originalTouch) {
            const newTouch = new Touch({
              identifier: originalTouch.identifier,
              target: originalTouch.target,
              clientX: offsetX,
              clientY: offsetY,
              screenX: offsetX,
              screenY: offsetY,
              pageX: offsetX,
              pageY: offsetY,
              radiusX: originalTouch.radiusX,
              radiusY: originalTouch.radiusY,
              rotationAngle: originalTouch.rotationAngle,
              force: originalTouch.force});

            newEvent = new TouchEvent(type, {
              cancelable: originalEvent.cancelable,
              bubbles: originalEvent.bubbles,
              composed: originalEvent.composed,
              touches: [newTouch],
              targetTouches: [newTouch],
              changedTouches: [newTouch],
            });
          }
        } else {
          newEvent = originalEvent;
        }
        if(newEvent) this.svg.dispatchEvent(newEvent);
      }
    }
    return ret;
  }

  getElementById(id) {
    return querySelector(`#${id}`, this);
  }

  getElementsByClassName(className) {
    return querySelectorAll(`.${className}`, this);
  }

  getElementsByName(name) {
    return querySelectorAll(`[name="${name}"]`, this);
  }

  getElementsByTagName(tagName) {
    return querySelectorAll(tagName, this);
  }

  querySelector(selector) {
    return querySelector(selector, this);
  }

  querySelectorAll(selector) {
    return querySelectorAll(selector, this);
  }

  /* override */
  onPropertyChange(key, newValue, oldValue) {
    super.onPropertyChange(key, newValue, oldValue);
    if(key === 'flexible') {
      updateTexture(this);
    }
    if(this.attributes.flexible && (key === 'width' || key === 'height' || key === 'scale' || key === 'transform')) {
      updateTexture(this);
    }
  }
}

ownerDocument.registerNode(SpriteSvg, 'spritesvg');