text:
package com.fasterxml.jackson.annotation;

import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * Tests to verify that it is possibly to merge {@link JsonInclude.Value}
 * instances for overrides
 */
public class IncludeTest extends TestBase
{
    private final JsonInclude.Value EMPTY = JsonInclude.Value.empty();

    @JsonInclude(value=JsonInclude.Include.NON_EMPTY, content=JsonInclude.Include.NON_DEFAULT)
    private final static class Bogus { }

    @JsonInclude(value=JsonInclude.Include.CUSTOM, valueFilter=Integer.class,
            content=JsonInclude.Include.CUSTOM, contentFilter=Long.class)
    private final static class Custom { }

    public void testEquality() {
        assertTrue(EMPTY.equals(EMPTY));

        JsonInclude.Value v1 = JsonInclude.Value.construct(Include.NON_ABSENT, null);
        JsonInclude.Value v2 = JsonInclude.Value.construct(Include.NON_ABSENT, null);
        JsonInclude.Value v3 = JsonInclude.Value.construct(Include.NON_ABSENT, Include.NON_EMPTY);

        assertTrue(v1.equals(v2));
        assertTrue(v2.equals(v1));

        assertFalse(v1.equals(v3));
        assertFalse(v3.equals(v1));
        assertFalse(v2.equals(v3));
        assertFalse(v3.equals(v2));
    }

    public void testFromAnnotation()
    {
        JsonInclude ann = Bogus.class.getAnnotation(JsonInclude.class);
        JsonInclude.Value v = JsonInclude.Value.from(ann);
        assertEquals(Include.NON_EMPTY, v.getValueInclusion());
        assertEquals(Include.NON_DEFAULT, v.getContentInclusion());
    }

    public void testFromAnnotationWithCustom()
    {
        JsonInclude ann = Custom.class.getAnnotation(JsonInclude.class);
        JsonInclude.Value v = JsonInclude.Value.from(ann);
        assertEquals(Include.CUSTOM, v.getValueInclusion());
        assertEquals(Include.CUSTOM, v.getContentInclusion());
        assertEquals(Integer.class, v.getValueFilter());
        assertEquals(Long.class, v.getContentFilter());

        assertEquals(
"JsonInclude.Value(value=CUSTOM,content=CUSTOM,valueFilter=java.lang.Integer.class,contentFilter=java.lang.Long.class)",
                v.toString());
    }

    public void testStdOverrides() {
        assertEquals("JsonInclude.Value(value=NON_ABSENT,content=USE_DEFAULTS)",
                JsonInclude.Value.construct(Include.NON_ABSENT, null).toString());
        int x = EMPTY.hashCode();
        if (x == 0) {
            fail();
        }
        assertFalse(EMPTY.equals(null));
        assertFalse(EMPTY.equals(""));
    }

    public void testSimpleMerge()
    {
        JsonInclude.Value empty = JsonInclude.Value.empty();

        assertEquals(Include.USE_DEFAULTS, empty.getValueInclusion());
        assertEquals(Include.USE_DEFAULTS, empty.getContentInclusion());

        JsonInclude.Value v2 = empty.withValueInclusion(Include.NON_ABSENT);

        assertEquals(Include.NON_ABSENT, v2.getValueInclusion());
        assertEquals(Include.USE_DEFAULTS, v2.getContentInclusion());

        JsonInclude.Value v3 = new JsonInclude.Value(Include.NON_EMPTY, Include.ALWAYS,
                null, null);
        assertEquals(Include.NON_EMPTY, v3.getValueInclusion());
        assertEquals(Include.ALWAYS, v3.getContentInclusion());

        // Ok; but then overrides, which should skip 'USE_DEFAULT' overrides
        JsonInclude.Value merged = v3.withOverrides(empty);
        // no overrides with "empty":
        assertEquals(v3.getValueInclusion(), merged.getValueInclusion());
        assertEquals(v3.getContentInclusion(), merged.getContentInclusion());

        // but other values ought to be overridden (value, yes, content, no because it's default)
        merged = JsonInclude.Value.merge(v3, v2);
        assertEquals(v2.getValueInclusion(), merged.getValueInclusion());
        assertEquals(v3.getContentInclusion(), merged.getContentInclusion());

        merged = JsonInclude.Value.mergeAll(empty, v3);
        assertEquals(v3.getValueInclusion(), merged.getValueInclusion());
        assertEquals(v3.getContentInclusion(), merged.getContentInclusion());
    }

    // for [annotations#76]
    public void testContentMerge76()
    {
        JsonInclude.Value v1 = JsonInclude.Value.empty()
                .withContentInclusion(JsonInclude.Include.ALWAYS)
                .withValueInclusion(JsonInclude.Include.NON_ABSENT);
        JsonInclude.Value v2 = JsonInclude.Value.empty()
                .withContentInclusion(JsonInclude.Include.NON_EMPTY)
                .withValueInclusion(JsonInclude.Include.USE_DEFAULTS);

        JsonInclude.Value v12 = v2.withOverrides(v1); // v1 priority
        JsonInclude.Value v21 = v1.withOverrides(v2); // v2 priority

        assertEquals(JsonInclude.Include.ALWAYS, v12.getContentInclusion());
        assertEquals(JsonInclude.Include.NON_ABSENT, v12.getValueInclusion());

        assertEquals(JsonInclude.Include.NON_EMPTY, v21.getContentInclusion());
        assertEquals(JsonInclude.Include.NON_ABSENT, v21.getValueInclusion());
    }

    public void testFilters()
    {
        JsonInclude.Value empty = JsonInclude.Value.empty();
        assertNull(empty.getValueFilter());
        assertNull(empty.getContentFilter());

        // note: filter class choices are arbitrary, just confirming assignments
        JsonInclude.Value v1 = empty.withValueFilter(String.class);
        assertEquals(JsonInclude.Include.CUSTOM, v1.getValueInclusion());
        assertEquals(String.class, v1.getValueFilter());
        assertNull(v1.withValueFilter(null).getValueFilter());
        assertNull(v1.withValueFilter(Void.class).getValueFilter());

        JsonInclude.Value v2 = empty.withContentFilter(Long.class);
        assertEquals(JsonInclude.Include.CUSTOM, v2.getContentInclusion());
        assertEquals(Long.class, v2.getContentFilter());
        assertNull(v2.withContentFilter(null).getContentFilter());
        assertNull(v2.withContentFilter(Void.class).getContentFilter());
    }
}


text:
<tool id="change_sp" name="change_sp" version="1.0">
    <description>Change code name to full species name in fasta or phytab</description>
    <command interpreter="perl">
		change_sp.pl $infile $changefile $outfile
    </command>
    <inputs>
	    <param name="infile" type="data" format="tabular" label="Input File" help="PHYTAB file to alter" />
	    <param name="changefile" type="data" format="tabular" label="Conversion Table" help="Tabular format with column 1=code; column 2=Full species name" />
    </inputs>
    <outputs>
	<data format="tabular" name="outfile" label="${tool.name} on ${on_string}: Out file" />
    </outputs>
    <help>
**What it does**

Many times a dataset will have code names instead of full species names. This will search for a code name and replace with a species name based on a table of input values.

------

**Inputs**

PHYTAB with species codes

------

**Outputs**

PHYTAB with full species names replacing codes
------

**Additional Information**

Please direct questions or comments to ucsb_phylogenetics@lifesci.ucsb.edu or, if you can, enter them on the
osiris_phylogenetics site at bitbucket.org

------

**Citations**

This tool is part of the Osiris Phylogenetics Tool Package for Galaxy. If you make extensive use
of this tool in a publication, please consider citing the following.

Current Osiris Citation is here

http://osiris-phylogenetics.blogspot.com/2012/10/citation.html
    </help>
</tool>

redpajama_set_name: RedPajamaGithub


text:
module Ci
  class RetryPipelineService < ::BaseService
    include Gitlab::OptimisticLocking

    def execute(pipeline)
      unless can?(current_user, :update_pipeline, pipeline)
        raise Gitlab::Access::AccessDeniedError
      end

      pipeline.retryable_builds.find_each do |build|
        next unless can?(current_user, :update_build, build)

        Ci::RetryBuildService.new(project, current_user)
          .reprocess!(build)
      end

      pipeline.builds.latest.skipped.find_each do |skipped|
        retry_optimistic_lock(skipped) { |build| build.process }
      end

      MergeRequests::AddTodoWhenBuildFailsService
        .new(project, current_user)
        .close_all(pipeline)

      pipeline.process!
    end
  end
end


text:
<?php

namespace Simpletools\Cloud\Google\Storage;

use Google\Cloud\Storage\StorageObject;

/*
 * http://googlecloudplatform.github.io/google-cloud-php/#/docs/v0.22.0/storage/storageobject
 */
class File
{
    protected $_fileLocation;
    protected $_isTempFile;
    protected $_fileHandler;
    protected $_isImport =false;

    protected $_fileSettings;
    protected $_client;

    protected $_bucketObject;
    protected $_remoteFile;

    protected $_bodyTouched = false;
    protected $_acl;

    protected $_tmpDir;

    protected $_gzip = false;
    protected $_gzipChunk = 100000;
    protected $_gzipCompressionLevel = 9;

    public function __construct($file,array $meta=[])
    {
        if($file instanceof StorageObject)
        {
            $this->_remoteFile = $file;

            $info = $file->info();

            if(!isset($info['metadata']))
            {
                $info['metadata'] = [];
            }

            $this->_fileSettings = [
                'path'          => 'gs://'.$info['bucket'].'/'.$info['name'],
                'bucket'        => $info['bucket'],
                'key'           => $info['name'],
                'meta'      => [
                    'metadata'      => $info['metadata']
                ]
            ];
        }
        else
        {
            if (strpos($file, 'gs://') === false) {
                throw new \Exception('Please specify your location following the pattern - gs://{bucket}/{file-key}');
            }

            $path = $this->parsePath($file);

            $this->_fileSettings = [
                'path'  => $file,
                'bucket' => $path['bucket'],
                'key' => $path['key'],
                'meta' => $meta
            ];
        }

        $this->_tmpDir = sys_get_temp_dir();
    }

    protected function _getBucket($bucket)
    {
        if($this->_bucketObject) return $this->_bucketObject;

        return $this->_bucketObject = Bucket::get($bucket);
    }

    protected function _initStorageObject()
    {
        if(!$this->_remoteFile)
        {
            $bucket = $this->_getBucket($this->_fileSettings['bucket']);
            $this->_remoteFile = $bucket->object($this->_fileSettings['key']);
        }
    }

    public function tempDir($tempDir)
    {
        if(!is_dir($tempDir))
        {
            throw new \Exception("Provided temp dir doesn't exist",404);
        }

        $this->_tmpDir = $tempDir;
    }

    protected function _createEmptyFile()
    {
        if($this->_fileLocation) return $this->_fileLocation;

        $this->_isTempFile = true;
        return $this->_fileLocation = tempnam($this->_tmpDir,uniqid());
    }

    protected function _download()
    {
        $TMPDIR = sys_get_temp_dir();
        if($this->_tmpDir) putenv('TMPDIR=/' . $this->_tmpDir);

        if(!$this->_fileLocation)
        {
            $this->_initStorageObject();
            $this->_createEmptyFile();

            if(!$this->_remoteFile->exists())
            {
                if($this->_tmpDir) putenv('TMPDIR=/' . $TMPDIR);

                return false;
            }

            try
            {
                $this->_remoteFile->downloadToFile($this->_fileLocation);
            }
            catch(\Exception $e){

                if($this->_tmpDir) putenv('TMPDIR=/' . $TMPDIR);

                //no file found - $e->getCode() = 404
                $this->_remoteFile = null;
                return false;
            }
        }

        if($this->_tmpDir) putenv('TMPDIR=/' . $TMPDIR);

        return true;
    }

		public function importFile($filepath, $flag='a')
		{
			if(!file_exists($filepath))
			{
				throw new \Exception('File '.$filepath.' doesn\'t exists');
			}

			if($this->_fileHandler)
			{
				@fclose($this->_fileHandler);
			}

			if($this->_fileLocation)
			{
				@unlink($this->_fileLocation);
			}

			$this->_fileLocation = $filepath;
			$this->_isTempFile = false;
			$this->_isImport = true;

			$this->_fileHandler = fopen($this->_fileLocation,$flag);
			return $this;
		}

		public function exportFile($filepath)
		{
			$this->_initStorageObject();

			if(!$this->_remoteFile->exists())
			{
				throw new \Exception('File '.$this->_fileSettings['path']. "doesn't exists.");
			}

			if(!$fp= @fopen($filepath,'w'))
			{
				throw new \Exception("Couldn't open a file pointer for this location: ".$filepath);
			}
			fclose($fp);

			$this->_remoteFile->downloadToFile($filepath);
			return $this;
		}

    public function getHandler($flag)
    {
        if($flag!='r')
        {
            $this->_bodyTouched = true;
        }

        if($this->_fileHandler) return $this->_fileHandler;
        $this->_download();
        return $this->_fileHandler = fopen($this->_fileLocation,$flag);
    }

    public function save()
    {
        $bucket = $this->_getBucket($this->_fileSettings['bucket']);
        if($this->_fileHandler) fclose($this->_fileHandler);

        $this->_initStorageObject();
        if(!$this->exists())
        {
            $this->_download();
            $this->_bodyTouched = true;
        }

        if($this->_bodyTouched || $this->_isImport)
        {
            if($this->_gzip)
            {
                $compressed_file_path 	= tempnam($this->_tmpDir,uniqid());
                $compressed_file_h		= gzopen($compressed_file_path,'wb'.$this->_gzipCompressionLevel);

                $original_file_h = fopen($this->_fileLocation,'rb');

                while($content = fread($original_file_h,$this->_gzipChunk))
                {
                    gzwrite($compressed_file_h,$content);
                }

                fclose($original_file_h);
                gzclose($compressed_file_h);

                $beforeGzip = filesize($this->_fileLocation);
                $afterGzip = filesize($compressed_file_path);

                $file_path = $compressed_file_path;

                if($beforeGzip > $afterGzip) {
                    $this->setMeta([
                        'contentEncoding' => 'gzip',
                        'metadata' => [
                            'contentLengthBeforeGzip' => $beforeGzip,
                            'contentLengthAfterGzip' => $afterGzip
                        ]
                    ]);
                }
                else
                {
                    $file_path = $this->_fileLocation;
                    @unlink($compressed_file_path);
                    $compressed_file_path = null;
                }
            }
            else
            {
                $file_path = $this->_fileLocation;
            }

            $settings = [
                "name"      => $this->_fileSettings['key'],
                "metadata"  => $this->_fileSettings['meta']
            ];

            if($this->_acl)
                $settings['predefinedAcl'] = $this->_acl;

            try {
                $this->_remoteFile = $bucket->upload(
                    fopen($file_path, 'rb'),
                    $settings
                );

                if(isset($compressed_file_path))
                    @unlink($compressed_file_path);
            }
            catch(\Exception $e)
            {
                if(isset($compressed_file_path))
                    @unlink($compressed_file_path);

                throw $e;
            }
        }
        else
        {
            $settings = array();

            if($this->_fileSettings['meta'])
                $settings['metadata'] = $this->_fileSettings['meta'];

            if($this->_acl)
                $settings['predefinedAcl'] = $this->_acl;

            $this->_remoteFile->update($settings);
        }
    }

    public function delete()
    {
        $this->_initStorageObject();
        if($this->_remoteFile)
        {
            try {
                $this->_remoteFile->delete();
                return true;
            }
            catch(\Exception $e)
            {
                return false;
            }
        }

        return false;
    }

    public function getName()
    {
        $file = explode('/',$this->_fileSettings['key']);
        return end($file);
    }

    public function getBody()
    {
        $this->_download();
        return file_get_contents($this->_fileLocation);
    }

    public function setBody($body,$flag=null)
    {
        $this->_bodyTouched = true;

        if($flag=='a') {
            $flag = FILE_APPEND;
            $this->_download();
        }
        else {
            $flag = 0; //default file_put_contents flag
            $this->_createEmptyFile();
        }

        if($this->_fileHandler)
        {
            fclose($this->_fileHandler);
            $this->_fileHandler = null;
        }

        if(file_put_contents($this->_fileLocation,$body,$flag)===false)
        {
            throw new \Exception("Can't write to file",401);
        }

        return $this;
    }

    public function appendBody($body)
    {
        $this->setBody($body,'a');
        return $this;
    }

    public function getMeta()
    {
        $this->_initStorageObject();
        if($this->_remoteFile)
        {
            return $this->_remoteFile->info();
        }
        else
        {
            return false;
        }
    }

    public function setMeta(array $metadata)
    {
        $this->_fileSettings['meta'] = $metadata;
        return $this;
    }

    public function exists()
    {
        $this->_initStorageObject();
        return $this->_remoteFile->exists();
    }

    public function __destruct()
    {
        if($this->_fileHandler)
        {
            @fclose($this->_fileHandler);
        }

        if($this->_fileLocation && $this->_isTempFile)
        {
            @unlink($this->_fileLocation);
        }
    }

    public function parsePath($path)
    {
        $path = str_replace('gs://', '', $path);
        $path = explode('/', $path, 2);

        return [
            'bucket' => $path[0],
            'key' => $path[1]
        ];
    }

    public function getUri()
    {
        return $this->_fileSettings['path'];
    }

    public function renameTo($path)
    {
        $this->_initStorageObject();
        if(!$this->exists()) return;

        $meta = $this->parsePath($path);
        $this->_remoteFile->rename($meta['key']);
    }

    public function getUrl()
    {
        $this->_initStorageObject();
        $info = $this->_remoteFile->info();

        return $info['selfLink'];
    }

    /**
     * Get a signed URL referencing the object
     *
     * @param \DateTime $expiry Expiry of the url
     *
     * @return string
     */
    public function getSignedUrl($expiry)
    {
        if(!$expiry instanceof \DateTime) {
            throw new \Exception(sprintf('Expiry must be a DateTime instance, %s given', gettype($expiry)));
        }
        $this->_initStorageObject();
        return $this->_remoteFile->signedUrl($expiry);
    }

    public function getSize()
    {
        if(!$this->exists()) return 0;
        $meta = $this->getMeta();
        return $meta['size'];
    }

    public function makePublic()
    {
        $this->_acl = 'publicRead';
    }

    public function makePrivate()
    {
        $this->_acl = 'private';
    }

    public function gzip($compressionLevel=9,$chunkSize=100000)
    {
        $this->_gzipChunk = $chunkSize;
        $this->_gzipCompressionLevel = $compressionLevel;
        $this->_gzip = true;

        return $this;
    }

    public function gzipOff()
    {
        $this->_gzip = false;

        return $this;
    }

    public function stream()
    {
        $this->_initStorageObject();
        return $this->_remoteFile->downloadAsStream();
    }
}


text:
https://http2.github.io/

https://http2.github.io/faq/

https://http2.github.io/faq/#why-just-one-tcp-connection

## Why just one TCP connection?

With HTTP/1, browsers open between four and eight connections per origin. Since many sites use multiple origins, this could mean that a single page load opens more than thirty connections.

使用HTTP/1,浏览器打开每个源4到8个连接。由于许多站点使用多个源,这可能意味着单个页面加载打开超过三十个连接。

One application opening so many connections simultaneously breaks a lot of the assumptions that TCP was built upon; since each connection will start a flood of data in the response, there's a real risk that buffers in the intervening network will overflow, causing a congestion event and retransmits.

一个应用程序打开这么多连接同时打破了TCP建立的很多假设;因为每个连接将在响应中启动大量数据,所以存在中间网络中的缓冲器将溢出的真实风险,从而导致拥塞事件并重新传输。

Additionally, using so many connections unfairly monopolizes network resources, "stealing" them from other, better-behaved applications (e.g., VoIP).

另外,使用这么多连接不公平地独占网络资源,"窃取"它们与其他更好行为的应用(例如,VoIP)。

https://http2.github.io/faq/#is-it-http20-or-http2

http2

https://http2.github.io/faq/#what-are-the-key-differences-to-http1x

At a high level, HTTP/2:

is binary, instead of textual
is fully multiplexed, instead of ordered and blocking
can therefore use one connection for parallelism
uses header compression to reduce overhead
allows servers to "push" responses proactively into client caches

是二进制,而不是文本

是完全多路复用,而不是有序和阻塞

因此可以使用一个连接用于并行性

使用头压缩来减少开销

允许服务器主动将"响应"推送到客户端缓存中

https://http2.github.io/faq/#whats-the-relationship-with-spdy

HTTP/2 was first discussed when it became apparent that SPDY was gaining traction with implementers (like Mozilla and nginx), and was showing significant improvements over HTTP/1.x.

HTTP / 2首先被讨论,当它变得明显SPDY正在获得与实施者(如Mozilla和nginx)的牵引力,并显示重大改进超过HTTP / 1.x。

After a call for proposals and a selection process, SPDY/2 was chosen as the basis for HTTP/2. Since then, there have been a number of changes, based on discussion in the Working Group and feedback from implementers.

在呼叫建议和选择过程之后,选择SPDY / 2作为HTTP / 2的基础。自那时起,根据工作组的讨论和实施者的反馈,出现了一些变化。

Throughout the process, the core developers of SPDY have been involved in the development of HTTP/2, including both Mike Belshe and Roberto Peon. In February 2015, Google announced its plans to remove support for SPDY in favor of HTTP/2.

在整个过程中,SPDY的核心开发人员参与了HTTP / 2的开发,包括Mike Belshe和Roberto Peon。 2015年2月,Google宣布计划取消对SPDY的支持,赞成HTTP / 2。

http://httparchive.org/

http://httparchive.org/websites.php

http://httparchive.org/interesting.php

http://httparchive.org/trends.php

http://httparchive.org/about.php#bigquery

Google BigQuery

How do I use BigQuery to write custom queries over the data?

The HTTP Archive data dumps are also available in Google BigQuery thanks to Ilya Grigorik. This means you can create your own custom queries like How many resources return Last-Modified and/or ETag values? and What is the distribution of 1st party vs 3rd party resources?. For more information see Ilya's blog post HTTP Archive + BigQuery = Web Performance Answers and video. And checkout all the custom queries shared on BigQueri.es.

http://httparchive.org/downloads.php

https://github.com/HTTPArchive/httparchive

https://github.com/http2/http2-spec/wiki/Implementations

https://github.com/molnarg/node-http2

https://github.com/indutny/node-spdy

https://http2-explained.haxx.se/content/zh/

https://http2-explained.haxx.se/content/zh/part3.html

最初的HTTP 1.1规范提到一个客户端最多只能对同一主机建立两个TCP连接。因此,为了不和规范冲突,一些聪明的网站使用了新的主机名,这样的话,用户就能和网站建立更多的连接,从而降低载入时间。

后来,两个连接的限制被取消了,现在的客户端可以轻松地和每个主机建立6-8个连接。但由于连接的上限依然存在,所以网站还是会用这种技术来提升连接的数量。而随着资源个数的提升(上面章节的图例),网站会需要更多的连接来保证HTTP协议的效率,从而提升载入速度

https://http2-explained.haxx.se/content/zh/part6.html

一个客户端最多能和同一主机建立的TCP连接数量

客户端可以轻松地和每个主机建立6-8个连接

https://http2-explained.haxx.se/content/en/part3.html

Initially the HTTP 1.1 specification stated that a client was allowed to use maximum of two TCP connections for each host.

最初,HTTP 1.1规范规定客户端被允许为每个主机使用最多两个TCP连接.

So, in order to not violate the spec clever sites simply invented new host names and – voilá - you could get more connections to your site and decreased page load times.

所以,为了不违反规范聪明的网站只是发明了新的主机名和 - 瞧 - 你可以获得更多的连接到您的网站,减少页面加载时间。

Over time, that limitation was removed and today clients easily use 6-8 connections per host name but they still have a limit so sites continue to use this technique to bump the number of connections.

随着时间的推移,该限制被删除,今天的客户端轻松地使用每个主机名6-8个连接,但他们仍然有一个限制,所以网站继续使用这种技术,以突破连接的数量。

A Parser-blocking, cross-origin script, http://www.xgqfrms.xyz/, is invoked via document.write.

unescape("%3Cspan id='icon'%3E %3C/span%3E %3Cscript src='" + https_protocol + "www.xgqfrms.xyz' type='text/javascript'%3E %3C/script%3E");

""

%3E %3C
<   >

https://stackoverflow.com/questions/4723213/detect-http-or-https-then-force-https-in-javascript

how to redirect http to https javascript

if (location.protocol != 'https:')
{
    location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}

console.log(location.href);

console.log(window.location.href);

console.log(window.location.href.substring());

console.log(window.location.protocol);
// https:

console.log(window.location.protocol.length);
// 6

最初,HTTP 1.1规范规定客户端被允许为每个主机使用最多两个TCP连接.

随着时间的推移,该限制被删除,今天的客户端轻松地使用每个主机名6-8个连接,但他们仍然有一个限制,所以网站继续使用这种技术(sharding),以突破连接的数量。

使用HTTP/1,浏览器打开每个源4到8个连接

location.href
//

typeof(location.href);
// "string"

location.href.replace()

location.href = location.href.replace("http://", "https://");

ocation.href.substr / location.href.substring

location = location.href.substr(0,4) +""+ location.href.substr(5,250);
location = location.href.substr(0,4) +"s"+ location.href.substr(4,250);

substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。

str.substr(start[, length])

开始索引, 字符数/长度

location = location.href.substring(0,4) +""+ location.href.substring(5,250);
location = location.href.substring(0,4) +"s"+ location.href.substring(4,250);

substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。

str.substring(indexStart[, indexEnd])

开始索引, 结束索引

ECMA-404

http://wiki.geekdream.com/Specification/json-rpc_2.0.html

http://www.jsonrpc.org/specification#error_object

http://wiki.geekdream.com/

https://github.com/bagder/http2-explained

JSON Web Token(JWT) 是一个应用安全通信规范

http://wiki.geekdream.com/Specification/jwt.html

https://tools.ietf.org/html/rfc7519

https://github.com/bagder/http2-explained/blob/master/zh/part3.md

http://wiki.jikexueyuan.com/project/http-2-explained/latency.html

http://wiki.jikexueyuan.com/project/java-socket/udp.html

http://www.cnblogs.com/dreamroute/p/6247726.html

http://blog.csdn.net/sundacheng1989/article/details/28239711

http://blog.csdn.net/sundacheng1989/article/details/52437128

http://www.jianshu.com/p/13e6a943b3f5

http://www.cnblogs.com/panwenbin-logs/p/5655130.html

http://www.importnew.com/20267.html

https://github.com/syq1122/AsynSocketDemoSYQ/

## TCP

https://zh.wikipedia.org/wiki/%E4%BC%A0%E8%BE%93%E6%8E%A7%E5%88%B6%E5%8D%8F%E8%AE%AE

https://en.wikipedia.org/wiki/Transmission_Control_Protocol

## socket


text:
1. [t-algerie](http://www.startupranking.com/t-algerie)
2. [epay.dz](http://www.startupranking.com/epay-dz)
3. [netbeopen](http://www.startupranking.com/netbeopen)
4. [jib.li](http://www.startupranking.com/jib-li)
5. [zarimo](http://www.startupranking.com/zarimo)
6. [studio-lak](http://www.startupranking.com/studio-lak)
7. [mavi-furniture](http://www.startupranking.com/mavi-furniture)
8. [ingeniway](http://www.startupranking.com/ingeniway)
9. [azzreb](http://www.startupranking.com/azzreb)
10. [dzdoctors](http://www.startupranking.com/dzdoctors)


text:
package org.pentaho.platform.pdi.vfs;

import java.io.InputStream;

import junit.framework.Assert;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.junit.Test;
import org.pentaho.platform.pdi.vfs.MetadataToMondrianVfs;

@SuppressWarnings("nls")
public class MetadataToMondrianVfsTest {

  @Test
  public void testVfs() throws Exception {

    ((DefaultFileSystemManager)VFS.getManager()).addProvider("mtm", new MetadataToMondrianVfs());

    FileSystemManager fsManager = VFS.getManager();
    FileObject fobj = fsManager.resolveFile("mtm:src/test/resources/example_olap.xmi");
    StringBuilder buf = new StringBuilder(1000);
    InputStream in = fobj.getContent().getInputStream();
    int n;
    while ((n = in.read()) != -1) {
        buf.append((char) n);
    }
    in.close();
    String results = buf.toString();
    Assert.assertTrue(results.indexOf("<Cube name=\"customer2 Table\">") >= 0);
  }
}


text:
package com.intuso.housemate.client.v1_0.api.object;

import com.intuso.housemate.client.v1_0.api.object.view.ValueBaseView;

/**
 * @param <DATA_TYPE> the type of the value's type
 * @param <VALUE> the type of the value
 */
public interface ValueBase<DATA extends ValueBase.Data,
        DATA_TYPE,
        TYPE extends Type<?>,
        LISTENER extends ValueBase.Listener<? super VALUE>,
        VIEW extends ValueBaseView,
        VALUE extends ValueBase<?, ?, ?, ?, ?, ?>>
        extends Object<DATA, LISTENER, VIEW> {

    String VALUE_ID = "value";

    /**
     * Gets the value's type
     * @return the value's type
     */
    TYPE getType();

    /**
     * Gets the value's value
     * @return the value's value
     */
    DATA_TYPE getValues();

    /**
     *
     * Listener interface for values
     */
    interface Listener<VALUE extends ValueBase<?, ?, ?, ?, ?, ?>> extends Object.Listener {

        /**
         * Notifies that the value of this value object is about to be changed
         * @param value the value object whose value is about to be changed
         */
        void valueChanging(VALUE value);

        /**
         * Notifies that the value of this value object has been changed
         * @param value the value object whose value has just been changed
         */
        void valueChanged(VALUE value);
    }

    /**
     *
     * Data object for a value
     */
    class Data extends Object.Data {

        private static final long serialVersionUID = -1L;

        private String typePath;
        private int minValues;
        private int maxValues;
        private Type.Instances values;

        public Data() {}

        public Data(String objectType, String id, String name, String description, String typePath, int minValues, int maxValues, Type.Instances values) {
            super(objectType, id, name,  description);
            this.typePath = typePath;
            this.minValues = minValues;
            this.maxValues = maxValues;
            this.values = values;
        }

        public String getTypePath() {
            return typePath;
        }

        public void setTypePath(String typePath) {
            this.typePath = typePath;
        }

        public int getMaxValues() {
            return maxValues;
        }

        public void setMaxValues(int maxValues) {
            this.maxValues = maxValues;
        }

        public int getMinValues() {
            return minValues;
        }

        public void setMinValues(int minValues) {
            this.minValues = minValues;
        }

        public Type.Instances getValues() {
            return values;
        }

        public void setValues(Type.Instances values) {
            this.values = values;
        }
    }
}


text:
{% extends 'marketplace/package_detail/packageresource_list.html' %}
{% load django_bootstrap_breadcrumbs %}
{% block title %}Resource {{ object }}{% endblock %}
{% block breadcrumbs %}
    {{ block.super }}
    {% breadcrumb object "packageresource_detail" object.pk %}
{% endblock %}

{% block content %}

    {% include "marketplace/package_detail/package_detail_tabs.html" %}

Resource {{ object }}

     Recommend this resource
    Recommended {{ package.recommendations.count }}x times

        {{ object.markdown|safe }}

{% endblock %}


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

package org.flowable.rest.idm.service.api.group;

import org.flowable.engine.common.api.FlowableObjectNotFoundException;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.rest.idm.service.api.IdmRestResponseFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Frederik Heremans
 * @author Joram Barrez
 */
public class BaseGroupResource {

    @Autowired
    protected IdmRestResponseFactory restResponseFactory;

    @Autowired
    protected IdmIdentityService identityService;

    protected Group getGroupFromRequest(String groupId) {
        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();

        if (group == null) {
            throw new FlowableObjectNotFoundException("Could not find a group with id '" + groupId + "'.", Group.class);
        }
        return group;
    }

}


text:
/**
 * Created by sachg on 2/16/2016.
 */

import {mongoose} from './dbConfig';
import {productsSchema} from './Models/Products/ProductsSchema';
import {addressSchema} from './Models/Address/addressSchema';
import {destinationSchema} from './locationSchema';
var Schema = mongoose.Schema;

var userSchema = new Schema({
    id: Schema.ObjectId,//TODO not sure if this is the right ObjectId
    graphQLID: String,
    age: {type: Number},
    username: {type:String, required: true, unique: true},
    email: {type:String, lowercase: true, required: true},
    password: {type: String, required: true},
    timeCreated: {type:Date, default: Date.now},
    gender: {type: Boolean, default: 0, comment:"defaults to 0 for MALE"},
    photoAlbum: {type:String, required: true},
    name: {
        firstname: String,
        lastname: String
    },
    lastLogin: {type: Date, onUpdate: Date.now},
    address: [addressSchema],
    destination: [destinationSchema],
    products: [productsSchema]
});

userSchema.set('toJson', {getters:true});
module.exports =  userSchema;
let Users = mongoose.model('Users', userSchema);

module.exports = Users;

module.exports.getListOfUsers = ()=> {
    return new Promise((resolve, reject)=>{
        Users.find({}).exec((err,res)=>{
            if(err){
                console.error(err);
                reject(err)
            }
            resolve(res);
        })
    })
};


text:
using GHIElectronics.UAP.Gadgeteer.SocketInterfaces;
using System;
using System.Threading.Tasks;

namespace GHIElectronics.UAP.Gadgeteer.Modules {
	public class CharacterDisplay : Module {
		private static uint[] RowOffsets => new uint[4] { 0x00, 0x40, 0x14, 0x54 };
		private static uint DisplayOnCommand => 0x0C;
		private static uint ClearDisplayCommand => 0x01;
		private static uint CursorHomeCommand => 0x02;
		private static uint SetCursorCommand => 0x80;

		private DigitalIO lcdRS;
		private DigitalIO lcdE;
		private DigitalIO lcdD4;
		private DigitalIO lcdD5;
		private DigitalIO lcdD6;
		private DigitalIO lcdD7;
		private DigitalIO backlight;

		private uint currentRow;

		public override string Name => "CharacterDisplay";
		public override string Manufacturer => "GHI Electronics, LLC";

		protected async override Task Initialize(ISocket parentSocket) {
			this.lcdRS = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Four, false);
			this.lcdE = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Three, false);
			this.lcdD4 = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Five, false);
			this.lcdD5 = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Seven, false);
			this.lcdD6 = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Nine, false);
			this.lcdD7 = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Six, false);
			this.backlight = await parentSocket.CreateDigitalIOAsync(SocketPinNumber.Eight, true);

			this.currentRow = 0;

			this.SendCommand(0x33);
			this.SendCommand(0x32);
			this.SendCommand(CharacterDisplay.DisplayOnCommand);
			this.SendCommand(CharacterDisplay.ClearDisplayCommand);

			Task.Delay(3).Wait();
		}

		public bool BacklightEnabled {
			get {
				return this.backlight.Read();
			}
			set {
				this.backlight.Write(value);
			}
		}

		private void WriteNibble(byte b) {
			this.lcdD7.Write((b & 0x8) != 0);
			this.lcdD6.Write((b & 0x4) != 0);
			this.lcdD5.Write((b & 0x2) != 0);
			this.lcdD4.Write((b & 0x1) != 0);

			this.lcdE.SetHigh();
			this.lcdE.SetLow();

			Task.Delay(1).Wait();
		}

		private void SendCommand(uint command) {
			this.lcdRS.SetLow();

			this.WriteNibble((byte)(command >> 4));
			this.WriteNibble((byte)command);

			Task.Delay(2).Wait();

			this.lcdRS.SetHigh();
		}

		public void Print(string value) {
			for (int i = 0; i < value.Length; i++)
				this.Print(value[i]);
		}

		public void Print(char value) {
			if (value != '\n') {
				this.WriteNibble((byte)(value >> 4));
				this.WriteNibble((byte)value);
			}
			else {
				this.SetCursorPosition((this.currentRow + 1) % 2, 0);
			}
		}

		public void Clear() {
			this.SendCommand(CharacterDisplay.ClearDisplayCommand);

			this.currentRow = 0;

			Task.Delay(2).Wait();
		}

		public void CursorHome() {
			this.SendCommand(CharacterDisplay.CursorHomeCommand);

			this.currentRow = 0;

			Task.Delay(2).Wait();
		}

		public void SetCursorPosition(uint row, uint column) {
			if (column > 15) throw new ArgumentOutOfRangeException(nameof(column), $"{nameof(column)} must be between 0 and 15.");
			if (row > 1) throw new ArgumentOutOfRangeException(nameof(row), $"{nameof(row)} must be between 0 and 1.");

			this.currentRow = row;

            this.SendCommand((byte)(CharacterDisplay.SetCursorCommand | CharacterDisplay.RowOffsets[row] | column));
		}
	}
}


text:
{% extends "base.html" %}

{% load bootstrap3 %}

{% block head_title %}{{owner.get_username}}'s Playlists{% endblock %}

{% block content %}

    {% if owner %}
        {% if user.id == owner.id %}
        Your
        {% else %}
        {{owner.get_username}}'s
        {% endif %}
    {% endif %}
    Playlists

    {% if user.is_authenticated %}
    <form class="form-inline" action="{% url 'playlist:create' user.id %}">
        <button class="btn btn-default" type="submit">{% bootstrap_icon 'plus' %} Create</button>
    </form>
    {% endif %}

{% include 'playlist/snippets/playlist.html' %}
{% endblock %}


text:
import wx
import GlobalVars as gl
import webbrowser
import logging
import http.client
import sys

from MainGUI import MainGUI
from LoginGUI import LoginGUI
from SelfPatchGUI import SelfPatchGUI
from UpdateGUI import UpdateGUI
from FaqDialog import FaqDialog

class Frame(wx.Frame):
    def MakeConnection(self):
        # Создание и проверка соединения, а также проверка версии программы
        try:
            gl.server_conn = http.client.HTTPConnection("translate.lotros.ru")
            gl.server_conn.request("GET", u"/pages/easypatcher.html")
            self.resp = gl.server_conn.getresponse()
            self.respdata = str(self.resp.read()).decode('UTF-8')
            version_start = self.respdata.find('<version>') + 9
            version_end = self.respdata.find('</version>')
            self.onsite_version = self.respdata[version_start:version_end]
        except:
            self.ErrorMessage(
                u"Ошибка подключения к серверу, работа программы не может быть продолжена без интернет-соединения :(")
            sys.exit(0)

        if not self.onsite_version == gl.VERSION:
            self.WarningMessage(
                u"Внимание! Данная версия программы устарела! В целях безопасности использование устаревшей версии невозможно... После нажатия кнопки \"ОК\" Вы будете автоматически перенаправлены на страницу загрузки новой версии! Мы очень стараемся сделать программу лучше с каждым обновлением!\n Спасибо за понимание :) ")
            webbrowser.open("http://translate.lotros.ru/pages/easypatcher.html", new=2)
            sys.exit(0)

    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(768, 576),
                          style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.RESIZE_BOX | wx.MAXIMIZE_BOX))
        self.Centre()
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.panel = wx.Panel(self, -1)
        self.panel.SetBackgroundColour((255, 255, 255))
        bg = wx.Image('bg.jpg', wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
        self.bmp = wx.StaticBitmap(parent=self.panel, bitmap=bg, pos=(0, 0), size=(768, 576))
        self.mainPanel = wx.Panel(self.bmp, pos=(0, 80), size=(768, 430))
        self.mainPanel.SetBackgroundColour((255, 255, 255))
        logging.info(u'Инициализация GUI...')
        self.AddGUI()
        self.Show(True)
        self.MakeConnection()

    def StartGame(self, event):
        # Function - uses path to folder with client_local_English.dat, and starts TurbineLauncher.exe from the same folder
        if gl.cfg["DatPath"] == "NULL":
            self.WarningMessage(u"Укажите путь к папке с игрой!")
            return
        execstr = '"' + str(gl.cfg["DatPath"][:-24]) + 'TurbineLauncher.exe" -nosplash -disablePatch -skiprawdownload'

        try:
            import win32api
            win32api.WinExec(execstr)
        except:
            self.WarningMessage(
                u'Не найден файл TurbineLauncher.exe в папке с .dat файлом... Не можем запустить игру :(')

    def OnClickDatButton(self, event):
        if self.dat_dialogue.ShowModal() == wx.ID_OK:
            self.dat_path = self.dat_dialogue.GetPath()
            gl.cfg['DatPath'] = self.dat_path
            if (len(self.dat_path) <= 85):
                self.dat_filetext.SetLabel(self.dat_path)
            else:
                self.dat_filetext.SetLabel(self.dat_path[:85] + "...")

    def Report(self, event):
        webbrowser.open("http://translate.lotros.ru/bugs/add", new=2)

    def AddGUI(self):
        self.MainGUI = MainGUI(self)
        self.LoginGUI = LoginGUI(self)
        self.SelfPatchGUI = SelfPatchGUI(self)
        self.UpdateGUI = UpdateGUI(self)

        # Logo text
        LogoText = wx.StaticText(self.mainPanel, -1, "LOTRO Patcher: Enchanced edition", (0, 0), (768, -1),
                                 wx.ALIGN_CENTER)
        LogoFont = wx.Font(18, wx.FONTFAMILY_SCRIPT, wx.ITALIC, wx.NORMAL)
        LogoText.SetFont(LogoFont)

        # path to client_local_English.dat file
        self.dat_text = wx.StaticText(self.mainPanel, -1, u"1) Файл данных: ", pos=(20, 50), size=(100, -1));
        self.dat_dialogue = wx.FileDialog(self.mainPanel,
                                          u"Укажите путь до файла \"client_local_English.dat\" в папке с игрой", "", "",
                                          "client_local_English.dat")
        self.dat_filetext = wx.StaticText(self.mainPanel, -1,
                                          u"1) Укажите путь до файла \"client_local_English.dat\" в папке с игрой",
                                          pos=(120, 50), size=(500, -1), style=wx.SIMPLE_BORDER)
        self.dat_path = ""
        self.dat_filetext.SetWindowStyleFlag(wx.SIMPLE_BORDER)
        if not gl.cfg["DatPath"] == "NULL":
            self.dat_path = gl.cfg["DatPath"]
            if (len(gl.cfg["DatPath"]) <= 85):
                self.dat_filetext.SetLabel(gl.cfg["DatPath"])
            else:
                self.dat_filetext.SetLabel(gl.cfg["DatPath"][:85] + "...")
            self.dat_dialogue.SetDirectory(gl.cfg["DatPath"][:-24])

        self.dat_button = wx.Button(self.mainPanel, -1, u"Выбрать файл", pos=(625, 45))
        self.Bind(wx.EVT_BUTTON, self.OnClickDatButton, self.dat_button)

        # Field - choose what to do
        self.what_to_do_text = wx.StaticText(self.mainPanel, -1, u"Что будем делать?", pos=(0, 70), size=(500, -1),
                                             style=wx.ALIGN_CENTER)
        self.what_to_do_text.SetFont(
            wx.Font(19, family=wx.FONTFAMILY_DECORATIVE, weight=wx.FONTWEIGHT_NORMAL, style=wx.NORMAL))

        # Buttons - what to do
        self.login = wx.Button(self.mainPanel, -1, u"2) Войти в систему", pos=(20, 130), size=(220, 25))
        self.update = wx.Button(self.mainPanel, -1, u"3) Скачать новые переводы", pos=(265, 130), size=(220, 25))
        self.translate = wx.Button(self.mainPanel, -1, u"Переводить отдельный фрагмент", pos=(20, 160), size=(220, 25))
        self.bug_report = wx.Button(self.mainPanel, -1, u"Писать сообщение об ошибке", pos=(265, 160), size=(220, 25))
        self.return_back = wx.Button(self.mainPanel, -1, u"Основные настройки", pos=(505, 85), size=(220, 25))

        # Describing gui_panel - panel with main content
        self.gui_panel = wx.Panel(self.mainPanel, -1, pos=(20, 190), size=(465, 240), style=wx.SIMPLE_BORDER)
        self.gui_panel.SetBackgroundColour((255, 255, 255))  # for debug it is useful to change color

        # Describing settings_panel - panel with additional settings
        self.setting_panel = wx.Panel(self.mainPanel, -1, pos=(505, 125), size=(220, 230), style=wx.SIMPLE_BORDER)
        self.setting_panel.SetBackgroundColour((255, 255, 255))  # for debug it is useful to change color

        # Button - start the game
        self.startButton = wx.Button(self.mainPanel, -1, u'Запуск игры', pos=(520, 370), size=(200, 35))
        self.startButton.SetFont(
            wx.Font(19, family=wx.FONTFAMILY_DECORATIVE, weight=wx.FONTWEIGHT_NORMAL, style=wx.NORMAL))

        # Binding buttons to actions - show GUI on gui_panel
        self.Bind(wx.EVT_BUTTON, self.LoginGUI.Start, self.login)
        self.Bind(wx.EVT_BUTTON, self.UpdateGUI.Start, self.update)
        self.Bind(wx.EVT_BUTTON, self.SelfPatchGUI.Start, self.translate)
        self.Bind(wx.EVT_BUTTON, self.Report, self.bug_report)
        self.Bind(wx.EVT_BUTTON, self.MainGUI.Start, self.return_back)
        self.Bind(wx.EVT_BUTTON, self.StartGame, self.startButton)
        self.Bind(wx.wx.EVT_CHAR_HOOK, self.onKeyPress)

        self.MainGUI.Start()

    def onKeyPress(self, event):
        keycode = event.GetKeyCode()
        print keycode
        if keycode == wx.WXK_ESCAPE:
            self.Destroy()
        if keycode == wx.WXK_F1:
            print(u'Нажали F1')
            gl.faq_wnd = FaqDialog(None)
        event.Skip()

    def RemoveGUI(self):
        for child in self.gui_panel.GetChildren():
            child.Destroy()
        for child in self.setting_panel.GetChildren():
            child.Destroy()

    def WarningMessage(self, msg):
        logging.warning(msg)
        dlg = wx.MessageDialog(self, msg, u"Внимание!", wx.OK | wx.ICON_WARNING | wx.STAY_ON_TOP)
        dlg.ShowModal()
        dlg.Destroy()

    def ErrorMessage(self, msg):
        logging.error(msg)
        dlg = wx.MessageDialog(self, msg, u"Ошибка!", wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP)
        print sys.exc_info()[0]
        dlg.ShowModal()
        dlg.Destroy()

    def InformationMessage(self, msg):
        logging.info(msg)
        dlg = wx.MessageDialog(self, msg, u"Уведомление", wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP)
        dlg.ShowModal()
        dlg.Destroy()

    def CriticalMessage(self, msg):
        logging.critical(msg)
        dlg = wx.MessageDialog(self, msg, u"Критическая ошибка!", wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP)
        dlg.ShowModal()
        dlg.Destroy()
        gl.wnd.Destroy()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>mmorpgServer-desktop</groupId>
	<artifactId>mmorpgServer-desktop</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<build>

		<sourceDirectory>src</sourceDirectory>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>11</source>
					<target>11</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>3.0.2</version>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
							<mainClass>pl.mmorpg.protptype.server.desktop.ServerLauncher</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>3.0.1</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>false</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<dependency>
			<groupId>mmorpgServer-core</groupId>
			<artifactId>mmorpgServer-core</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>

		<dependency>
			<groupId>com.badlogicgames.gdx</groupId>
			<artifactId>gdx-backend-lwjgl3</artifactId>
			<version>1.9.9</version>
		</dependency>

		<dependency>
			<groupId>com.badlogicgames.gdx</groupId>
			<artifactId>gdx-platform</artifactId>
			<version>1.9.9</version>
			<classifier>natives-desktop</classifier>
		</dependency>

	</dependencies>
</project>


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.Owin.Security.OAuth.Messages;
using Microsoft.Owin.Security.Provider;

namespace Microsoft.Owin.Security.OAuth
{
    /// <summary>
    /// Provides context information used when processing an OAuth token request.
    /// </summary>
    public class OAuthTokenEndpointContext : EndpointContext<OAuthAuthorizationServerOptions>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthTokenEndpointContext"/> class
        /// </summary>
        /// <param name="context"></param>
        /// <param name="options"></param>
        /// <param name="ticket"></param>
        /// <param name="tokenEndpointRequest"></param>
        public OAuthTokenEndpointContext(
            IOwinContext context,
            OAuthAuthorizationServerOptions options,
            AuthenticationTicket ticket,
            TokenEndpointRequest tokenEndpointRequest)
            : base(context, options)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Identity = ticket.Identity;
            Properties = ticket.Properties;
            TokenEndpointRequest = tokenEndpointRequest;
            AdditionalResponseParameters = new Dictionary<string, object>(StringComparer.Ordinal);
            TokenIssued = Identity != null;
        }

        /// <summary>
        /// Gets the identity of the resource owner.
        /// </summary>
        public ClaimsIdentity Identity { get; private set; }

        /// <summary>
        /// Dictionary containing the state of the authentication session.
        /// </summary>
        public AuthenticationProperties Properties { get; private set; }

        /// <summary>
        /// Gets information about the token endpoint request.
        /// </summary>
        public TokenEndpointRequest TokenEndpointRequest { get; set; }

        /// <summary>
        /// Gets whether or not the token should be issued.
        /// </summary>
        public bool TokenIssued { get; private set; }

        /// <summary>
        /// Enables additional values to be appended to the token response.
        /// </summary>
        public IDictionary<string, object> AdditionalResponseParameters { get; private set; }

        /// <summary>
        /// Issues the token.
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="properties"></param>
        public void Issue(ClaimsIdentity identity, AuthenticationProperties properties)
        {
            Identity = identity;
            Properties = properties;
            TokenIssued = true;
        }
    }
}


text:
namespace pythonic
{

  namespace numpy
  {

    template <class T, size_t N, class I, class F>
    typename std::enable_if<types::is_iterable<I>::value and
                                types::is_iterable<F>::value,
                            types::ndarray<T, 1>>::type
    insert(types::ndarray<T, N> in, I const &indices, F const &data,
           types::none_type axis = __builtin__::None);

    template <class T, size_t N, class I, class F>
    typename std::enable_if<types::is_iterable<I>::value and
                                not types::is_iterable<F>::value,
                            types::ndarray<T, 1>>::type
    insert(types::ndarray<T, N> in, I const &indices, F const &data,
           types::none_type axis = __builtin__::None);

    template <class T, size_t N, class I, class F>
    typename std::enable_if<not types::is_iterable<I>::value and
                                types::is_iterable<F>::value,
                            types::ndarray<T, 1>>::type
    insert(types::ndarray<T, N> in, I const &indices, F const &data,
           types::none_type axis = __builtin__::None);

    template <class T, size_t N, class I, class F>
    typename std::enable_if<not types::is_iterable<I>::value and
                                not types::is_iterable<F>::value,
                            types::ndarray<T, 1>>::type
    insert(types::ndarray<T, N> in, I const &indices, F const &data,
           types::none_type axis = __builtin__::None);

    template <class E, class... Args>
    E insert(E, Args const &...);

    DECLARE_FUNCTOR(pythonic::numpy, insert);
  }
}

#endif


text:
"""
raven.contrib.flask
~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

from __future__ import absolute_import

import sys
import os
import logging

from flask import request
from flask.signals import got_request_exception
from raven.conf import setup_logging
from raven.base import Client
from raven.contrib.flask.utils import get_data_from_request
from raven.handlers.logging import SentryHandler

def make_client(client_cls, app, dsn=None):
    return client_cls(
        dsn=dsn or app.config.get('SENTRY_DSN') or os.environ.get('SENTRY_DSN'),
        include_paths=set(app.config.get('SENTRY_INCLUDE_PATHS', [])) | set([app.import_name]),
        exclude_paths=app.config.get('SENTRY_EXCLUDE_PATHS'),
        servers=app.config.get('SENTRY_SERVERS'),
        name=app.config.get('SENTRY_NAME'),
        public_key=app.config.get('SENTRY_PUBLIC_KEY'),
        secret_key=app.config.get('SENTRY_SECRET_KEY'),
        project=app.config.get('SENTRY_PROJECT'),
        site=app.config.get('SENTRY_SITE_NAME'),
        processors=app.config.get('SENTRY_PROCESSORS'),
        string_max_length=app.config.get('SENTRY_MAX_LENGTH_STRING'),
        list_max_length=app.config.get('SENTRY_MAX_LENGTH_LIST'),
    )

class Sentry(object):
    """
    Flask application for Sentry.

    Look up configuration from ``os.environ['SENTRY_DSN']``::

    >>> sentry = Sentry(app)

    Pass an arbitrary DSN::

    >>> sentry = Sentry(app, dsn='http://public:secret@example.com/1')

    Pass an explicit client::

    >>> sentry = Sentry(app, client=client)

    Automatically configure logging::

    >>> sentry = Sentry(app, logging=True)

    Capture an exception::

    >>> try:
    >>>     1 / 0
    >>> except ZeroDivisionError:
    >>>     sentry.captureException()

    Capture a message::

    >>> sentry.captureMessage('hello, world!')
    """
    def __init__(self, app=None, client=None, client_cls=Client, dsn=None,
                 logging=False, level=logging.NOTSET):
        self.dsn = dsn
        self.logging = logging
        self.client_cls = client_cls
        self.client = client
        self.level = level

        if app:
            self.init_app(app)

    def handle_exception(self, *args, **kwargs):
        if not self.client:
            return

        ignored_exc_type_list = self.app.config.get('RAVEN_IGNORE_EXCEPTIONS', [])
        exc = sys.exc_info()[1]

        if any((isinstance(exc, ignored_exc_type) for ignored_exc_type in ignored_exc_type_list)):
            return

        self.client.captureException(
            exc_info=kwargs.get('exc_info'),
            data=get_data_from_request(request),
            extra={
                'app': self.app,
            },
        )

    def init_app(self, app, dsn=None):
        self.app = app

        if dsn is not None:
            self.dsn = dsn

        if not self.client:
            self.client = make_client(self.client_cls, app, self.dsn)

        if self.logging:
            setup_logging(SentryHandler(self.client, level=self.level))

        got_request_exception.connect(self.handle_exception, sender=app)

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions['sentry'] = self

    def captureException(self, *args, **kwargs):
        assert self.client, 'captureException called before application configured'
        data = kwargs.get('data')
        if data is None:
            try:
                kwargs['data'] = get_data_from_request(request)
            except RuntimeError:
                # app is probably not configured yet
                pass
        return self.client.captureException(*args, **kwargs)

    def captureMessage(self, *args, **kwargs):
        assert self.client, 'captureMessage called before application configured'
        data = kwargs.get('data')
        if data is None:
            try:
                kwargs['data'] = get_data_from_request(request)
            except RuntimeError:
                # app is probably not configured yet
                pass
        return self.client.captureMessage(*args, **kwargs)


text:
/*
 * The Open Geospatial Consortium licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at:
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 */
package com.occamlab.te.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.Permission;
import java.util.List;
import java.util.Map;

public class HttpURLConnectionCopy extends HttpURLConnection {
    HttpURLConnection uc = null;

    public HttpURLConnectionCopy(HttpURLConnection uc) {
        super(null);
        this.uc = uc;
    }

    @Override
    public InputStream getErrorStream() {
        return uc.getErrorStream();
    }

    @Override
    public String getHeaderField(int n) {
        return uc.getHeaderField(n);
    }

    @Override
    public long getHeaderFieldDate(String name, long Default) {
        return uc.getHeaderFieldDate(name, Default);
    }

    @Override
    public String getHeaderFieldKey(int n) {
        return uc.getHeaderFieldKey(n);
    }

    @Override
    public boolean getInstanceFollowRedirects() {
        return uc.getInstanceFollowRedirects();
    }

    @Override
    public Permission getPermission() throws IOException {
        return uc.getPermission();
    }

    @Override
    public String getRequestMethod() {
        return uc.getRequestMethod();
    }

    @Override
    public int getResponseCode() throws IOException {
        return uc.getResponseCode();
    }

    @Override
    public String getResponseMessage() throws IOException {
        return uc.getResponseMessage();
    }

    @Override
    public void setChunkedStreamingMode(int chunklen) {
        uc.setChunkedStreamingMode(chunklen);
    }

    @Override
    public void setFixedLengthStreamingMode(int contentLength) {
        uc.setFixedLengthStreamingMode(contentLength);
    }

    @Override
    public void setInstanceFollowRedirects(boolean followRedirects) {
        uc.setInstanceFollowRedirects(followRedirects);
    }

    @Override
    public void setRequestMethod(String method) throws ProtocolException {
        uc.setRequestMethod(method);
    }

    @Override
    public void addRequestProperty(String key, String value) {
        uc.addRequestProperty(key, value);
    }

    @Override
    public boolean getAllowUserInteraction() {
        return uc.getAllowUserInteraction();
    }

    @Override
    public int getConnectTimeout() {
        return uc.getConnectTimeout();
    }

    @Override
    public Object getContent() throws IOException {
        return uc.getContent();
    }

    @Override
    public Object getContent(@SuppressWarnings("rawtypes") Class[] classes)
            throws IOException {
        return uc.getContent(classes);
    }

    @Override
    public String getContentEncoding() {
        return uc.getContentEncoding();
    }

    @Override
    public int getContentLength() {
        return uc.getContentLength();
    }

    @Override
    public String getContentType() {
        return uc.getContentType();
    }

    @Override
    public long getDate() {
        return uc.getDate();
    }

    @Override
    public boolean getDefaultUseCaches() {
        return uc.getDefaultUseCaches();
    }

    @Override
    public boolean getDoInput() {
        return uc.getDoInput();
    }

    @Override
    public boolean getDoOutput() {
        return uc.getDoOutput();
    }

    @Override
    public long getExpiration() {
        return uc.getExpiration();
    }

    @Override
    public String getHeaderField(String name) {
        return uc.getHeaderField(name);
    }

    @Override
    public int getHeaderFieldInt(String name, int Default) {
        return uc.getHeaderFieldInt(name, Default);
    }

    @Override
    public Map<String, List<String>> getHeaderFields() {
        return uc.getHeaderFields();
    }

    @Override
    public long getIfModifiedSince() {
        return uc.getIfModifiedSince();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return uc.getInputStream();
    }

    @Override
    public long getLastModified() {
        return uc.getLastModified();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return uc.getOutputStream();

    }

    @Override
    public int getReadTimeout() {
        return uc.getReadTimeout();
    }

    @Override
    public Map<String, List<String>> getRequestProperties() {
        return uc.getRequestProperties();
    }

    @Override
    public String getRequestProperty(String key) {
        return uc.getRequestProperty(key);
    }

    @Override
    public URL getURL() {
        return uc.getURL();
    }

    @Override
    public boolean getUseCaches() {
        return uc.getUseCaches();
    }

    @Override
    public void setAllowUserInteraction(boolean allowuserinteraction) {
        uc.setAllowUserInteraction(allowuserinteraction);
    }

    @Override
    public void setConnectTimeout(int timeout) {
        uc.setConnectTimeout(timeout);
    }

    @Override
    public void setDefaultUseCaches(boolean defaultusecaches) {
        uc.setDefaultUseCaches(defaultusecaches);
    }

    @Override
    public void setDoInput(boolean doinput) {
        uc.setDoInput(doinput);
    }

    @Override
    public void setDoOutput(boolean dooutput) {
        uc.setDoOutput(dooutput);
    }

    @Override
    public void setIfModifiedSince(long ifmodifiedsince) {
        uc.setIfModifiedSince(ifmodifiedsince);
    }

    @Override
    public void setReadTimeout(int timeout) {
        uc.setReadTimeout(timeout);
    }

    @Override
    public void setRequestProperty(String key, String value) {
        uc.setRequestProperty(key, value);
    }

    @Override
    public void setUseCaches(boolean usecaches) {
        uc.setUseCaches(usecaches);
    }

    @Override
    public String toString() {
        return uc.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return uc.equals(obj);
    }

    @Override
    public int hashCode() {
        return uc.hashCode();
    }

    @Override
    public void disconnect() {
        uc.disconnect();
    }

    @Override
    public boolean usingProxy() {
        return uc.usingProxy();
    }

    @Override
    public void connect() throws IOException {
        uc.connect();
    }
}


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Azure.Management.WebSites;
using Newtonsoft.Json.Linq;

namespace ARMExplorer.Controllers
{
    public class OperationController : ApiController
    {
        [Authorize]
        public HttpResponseMessage Get(bool hidden = false)
        {
            HyakUtils.CSMUrl = HyakUtils.CSMUrl ?? Utils.GetCSMUrl(Request.RequestUri.Host);

            var watch = new Stopwatch();
            watch.Start();

            var json = (JArray)HyakUtils.GetOperations<WebSiteManagementClient>(hidden).DeepClone();
            json.AddFirst(JObject.FromObject(new
            {
                MethodName = "Delete",
                HttpMethod = "DELETE",
                Url = HyakUtils.CSMUrl + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}"
            }));
            json.AddFirst(JObject.FromObject(new
            {
                MethodName = "Get",
                HttpMethod = "GET",
                Url = HyakUtils.CSMUrl + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}"
            }));
            json.AddFirst(JObject.FromObject(new
            {
                MethodName = "Get",
                HttpMethod = "GET",
                Url = HyakUtils.CSMUrl + "/subscriptions/{subscriptionId}/resourceGroups"
            }));
            json.AddFirst(JObject.FromObject(new
            {
                MethodName = "Get",
                HttpMethod = "GET",
                Url = HyakUtils.CSMUrl + "/subscriptions"
            }));
            json.AddFirst(JObject.FromObject(new
            {
                MethodName = "Get",
                HttpMethod = "GET",
                Url = HyakUtils.CSMUrl + "/subscriptions/{subscriptionId}"
            }));
            watch.Stop();
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
            response.Headers.Add(Utils.X_MS_Ellapsed, watch.ElapsedMilliseconds + "ms");
            return response;
        }

        [Authorize]
        public async Task<HttpResponseMessage> Invoke(OperationInfo info)
        {
            HyakUtils.CSMUrl = HyakUtils.CSMUrl ?? Utils.GetCSMUrl(Request.RequestUri.Host);

            using (var client = GetClient(Utils.GetCSMUrl(Request.RequestUri.Host)))
            {
                var apiVersion = Utils.GetApiVersion(info.Url);
                var request = new HttpRequestMessage(new System.Net.Http.HttpMethod(info.HttpMethod), info.Url + "?api-version=" + apiVersion);
                if (info.RequestBody != null)
                {
                    request.Content = new StringContent(info.RequestBody.ToString(), Encoding.UTF8, "application/json");
                }

                return await Utils.Execute(client.SendAsync(request));
            }
        }

        private HttpClient GetClient(string baseUri)
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(baseUri);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                Request.Headers.GetValues(Utils.X_MS_OAUTH_TOKEN).FirstOrDefault());
            client.DefaultRequestHeaders.Add("User-Agent", Request.RequestUri.Host);
            return client;
        }
    }
}


text:
package definitions

type PresenceEvent struct {
	AllowSeeMyPresence  bool   `json:"allowSeeMyPresence,omitempty"`
	DndStatus           string `json:"dndStatus,omitempty"`
	ExtensionId         string `json:"extensionId,omitempty"`
	PickUpCallsOnHold   bool   `json:"pickUpCallsOnHold,omitempty"`
	PresenceStatus      string `json:"presenceStatus,omitempty"`
	RingOnMonitoredCall bool   `json:"ringOnMonitoredCall,omitempty"`
	Sequence            int    `json:"sequence,omitempty"`
	TelephonyStatus     string `json:"telephonyStatus,omitempty"`
	TerminationType     string `json:"terminationType,omitempty"`
	UserStatus          string `json:"userStatus,omitempty"`
}


text:
"""Handling surfaces."""
import os
import re
from pathlib import Path
from collections import defaultdict

import numpy as np
import nibabel as nb

from nipype.utils.filemanip import fname_presuffix
from nipype.interfaces.base import (
    BaseInterfaceInputSpec,
    TraitedSpec,
    DynamicTraitedSpec,
    SimpleInterface,
    CommandLine,
    CommandLineInputSpec,
    File,
    traits,
    isdefined,
    InputMultiPath,
    OutputMultiPath,
    Undefined,
)

SECONDARY_ANAT_STRUC = {
    "smoothwm": "GrayWhite",
    "pial": "Pial",
    "midthickness": "GrayMid",
}

class _NormalizeSurfInputSpec(BaseInterfaceInputSpec):
    in_file = File(mandatory=True, exists=True, desc="Freesurfer-generated GIFTI file")
    transform_file = File(exists=True, desc="FSL or LTA affine transform file")

class _NormalizeSurfOutputSpec(TraitedSpec):
    out_file = File(desc="output file with re-centered GIFTI coordinates")

class NormalizeSurf(SimpleInterface):
    """
    Normalize a FreeSurfer-generated GIFTI image.

    FreeSurfer includes an offset to the center of the brain volume that is not
    respected by all software packages.
    Normalization involves adding this offset to the coordinates of all
    vertices, and zeroing out that offset, to ensure consistent behavior
    across software packages.
    In particular, this normalization is consistent with the Human Connectome
    Project pipeline (see `AlgorithmSurfaceApplyAffine`_ and
    `FreeSurfer2CaretConvertAndRegisterNonlinear`_), although the the HCP
    may not zero out the offset.

    GIFTI files with ``midthickness``/``graymid`` in the name are also updated
    to include the following metadata entries::

        {
            AnatomicalStructureSecondary: MidThickness,
            GeometricType: Anatomical
        }

    This interface is intended to be applied uniformly to GIFTI surface files
    generated from the ``?h.white``/``?h.smoothwm`` and ``?h.pial`` surfaces,
    as well as externally-generated ``?h.midthickness``/``?h.graymid`` files.
    In principle, this should apply safely to any other surface, although it is
    less relevant to surfaces that don't describe an anatomical structure.

    .. _AlgorithmSurfaceApplyAffine: https://github.com/Washington-University/workbench\
/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91

    .. _FreeSurfer2CaretConvertAndRegisterNonlinear: https://github.com/Washington-University/\
Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh\
#L147-154

    """

    input_spec = _NormalizeSurfInputSpec
    output_spec = _NormalizeSurfOutputSpec

    def _run_interface(self, runtime):
        transform_file = self.inputs.transform_file
        if not isdefined(transform_file):
            transform_file = None
        self._results["out_file"] = normalize_surfs(
            self.inputs.in_file, transform_file, newpath=runtime.cwd
        )
        return runtime

class _Path2BIDSInputSpec(BaseInterfaceInputSpec):
    in_file = File(mandatory=True, desc="input GIFTI file")

class _Path2BIDSOutputSpec(DynamicTraitedSpec):
    extension = traits.Str()

class Path2BIDS(SimpleInterface):
    """
    Extract BIDS entities from paths using a pattern.

    Default pattern is given for Gifti surfaces.

    >>> Path2BIDS(in_file='_fix_surfs0/rh.pial.surf.gii').run().outputs
    <BLANKLINE>
    extension = .surf.gii
    hemi = R
    suffix = pial
    <BLANKLINE>

    >>> Path2BIDS(in_file='_fix_surfs0/rh.pial.gii').run().outputs
    <BLANKLINE>
    extension = .gii
    hemi = R
    suffix = pial
    <BLANKLINE>

    >>> Path2BIDS(in_file='_fix_surfs0/rh.smoothwm_converted.gii').run().outputs
    <BLANKLINE>
    extension = .gii
    hemi = R
    suffix = smoothwm
    <BLANKLINE>

    >>> Path2BIDS(in_file='_fix_surfs0/rh.smoothwm_converted.func.gii').run().outputs
    <BLANKLINE>
    extension = .func.gii
    hemi = R
    suffix = smoothwm
    <BLANKLINE>

    """

    input_spec = _Path2BIDSInputSpec
    output_spec = _Path2BIDSOutputSpec
    _pattern = re.compile(
        r"(?P<hemi>[lr])h.(?P<suffix>(wm|smoothwm|pial|midthickness|"
        r"inflated|vinflated|sphere|flat))[\w\d_-]*(?P<extprefix>\.\w+)?"
    )
    _excluded = ("extprefix",)

    def __init__(self, pattern=None, **inputs):
        """Initialize the interface."""
        super().__init__(**inputs)
        if pattern:
            self._pattern = re.compile(pattern)

    def _outputs(self):
        outputs = self.output_spec()
        outputs.trait_set(
            trait_change_notify=False,
            **{
                entity: Undefined
                for entity in self._pattern.groupindex.keys()
                if entity not in self._excluded
            },
        )
        return outputs

    def _run_interface(self, runtime):
        in_file = Path(self.inputs.in_file)
        extension = "".join(in_file.suffixes[-((in_file.suffixes[-1] == ".gz") + 1):])
        info = self._pattern.match(in_file.name[: -len(extension)]).groupdict()
        self._results["extension"] = f"{info.pop('extprefix', None) or ''}{extension}"
        self._results.update(info)
        if "hemi" in self._results:
            self._results["hemi"] = self._results["hemi"].upper()
        return runtime

class _GiftiNameSourceInputSpec(BaseInterfaceInputSpec):
    in_file = File(mandatory=True, exists=True, desc="input GIFTI file")
    pattern = traits.Str(
        mandatory=True, desc='input file name pattern (must capture named group "LR")'
    )
    template = traits.Str(mandatory=True, desc="output file name template")
    template_kwargs = traits.Dict(desc="additional template keyword value pairs")

class _GiftiNameSourceOutputSpec(TraitedSpec):
    out_name = traits.Str(desc="(partial) filename formatted according to template")

class GiftiNameSource(SimpleInterface):
    r"""
    Construct a new filename for a GIFTI file.

    Construct a new filename based on an input filename, a matching pattern,
    and a related template, with optionally additional keywords.

    This interface is intended for use with GIFTI files, to generate names
    conforming to Section 9.0 of the `GIFTI Standard`_.

    Patterns are expected to have named groups, including one named "LR" that
    matches "l" or "r".
    These groups must correspond to named format elements in the template.

    .. testsetup::

       >>> open('lh.pial.gii', 'w').close()
       >>> open('rh.fsaverage.gii', 'w').close()

    Examples
    --------
    >>> surf_namer = GiftiNameSource()
    >>> surf_namer.inputs.pattern = r'(?P<LR>[lr])h.(?P<surf>\w+).gii'
    >>> surf_namer.inputs.template = r'{surf}.{LR}.surf'
    >>> surf_namer.inputs.in_file = 'lh.pial.gii'
    >>> res = surf_namer.run()
    >>> res.outputs.out_name
    'pial.L.surf'

    >>> func_namer = GiftiNameSource()
    >>> func_namer.inputs.pattern = r'(?P<LR>[lr])h.(?P<space>\w+).gii'
    >>> func_namer.inputs.template = r'space-{space}.{LR}.func'
    >>> func_namer.inputs.in_file = 'rh.fsaverage.gii'
    >>> res = func_namer.run()
    >>> res.outputs.out_name
    'space-fsaverage.R.func'

    >>> namer = GiftiNameSource()
    >>> namer.inputs.pattern = r'(?P<LR>[lr])h.(?P<space>\w+).gii'
    >>> namer.inputs.template = r'space-{space}_density-{density}_hemi-{LR}.func'
    >>> namer.inputs.in_file = 'rh.fsaverage.gii'
    >>> namer.inputs.template_kwargs = {'density': '10k'}
    >>> res = namer.run()
    >>> res.outputs.out_name
    'space-fsaverage_density-10k_hemi-R.func'

    .. testcleanup::

    >>> import os
    >>> os.unlink('lh.pial.gii')
    >>> os.unlink('rh.fsaverage.gii')

    .. _GIFTI Standard: https://www.nitrc.org/frs/download.php/2871/GIFTI_Surface_Format.pdf
    """
    input_spec = _GiftiNameSourceInputSpec
    output_spec = _GiftiNameSourceOutputSpec

    def _run_interface(self, runtime):
        in_format = re.compile(self.inputs.pattern)
        in_file = os.path.basename(self.inputs.in_file)
        info = in_format.match(in_file).groupdict()
        info["LR"] = info["LR"].upper()
        if self.inputs.template_kwargs:
            info.update(self.inputs.template_kwargs)
        filefmt = self.inputs.template
        self._results["out_name"] = filefmt.format(**info)
        return runtime

class _GiftiSetAnatomicalStructureInputSpec(BaseInterfaceInputSpec):
    in_file = File(
        mandatory=True, exists=True, desc='GIFTI file beginning with "lh." or "rh."'
    )

class _GiftiSetAnatomicalStructureOutputSpec(TraitedSpec):
    out_file = File(desc="output file with updated AnatomicalStructurePrimary entry")

class GiftiSetAnatomicalStructure(SimpleInterface):
    """
    Set AnatomicalStructurePrimary attribute of GIFTI image based on filename.

    For files that begin with ``lh.`` or ``rh.``, update the metadata to
    include::

        {
            AnatomicalStructurePrimary: (CortexLeft | CortexRight),
        }

    If ``AnatomicalStructurePrimary`` is already set, this function has no
    effect.

    """

    input_spec = _GiftiSetAnatomicalStructureInputSpec
    output_spec = _GiftiSetAnatomicalStructureOutputSpec

    def _run_interface(self, runtime):
        img = nb.load(self.inputs.in_file)
        if any(nvpair.name == "AnatomicalStruturePrimary" for nvpair in img.meta.data):
            out_file = self.inputs.in_file
        else:
            fname = os.path.basename(self.inputs.in_file)
            if fname[:3] in ("lh.", "rh."):
                asp = "CortexLeft" if fname[0] == "l" else "CortexRight"
            else:
                raise ValueError(
                    "AnatomicalStructurePrimary cannot be derived from filename"
                )
            img.meta.data.insert(
                0, nb.gifti.GiftiNVPairs("AnatomicalStructurePrimary", asp)
            )
            out_file = os.path.join(runtime.cwd, fname)
            img.to_filename(out_file)
        self._results["out_file"] = out_file
        return runtime

class _GiftiToCSVInputSpec(BaseInterfaceInputSpec):
    in_file = File(mandatory=True, exists=True, desc="GIFTI file")
    itk_lps = traits.Bool(False, usedefault=True, desc="flip XY axes")

class _GiftiToCSVOutputSpec(TraitedSpec):
    out_file = File(desc="output csv file")

class GiftiToCSV(SimpleInterface):
    """Converts GIfTI files to CSV to make them ammenable to use with
    ``antsApplyTransformsToPoints``."""

    input_spec = _GiftiToCSVInputSpec
    output_spec = _GiftiToCSVOutputSpec

    def _run_interface(self, runtime):
        gii = nb.load(self.inputs.in_file)
        data = gii.darrays[0].data

        if self.inputs.itk_lps:  # ITK: flip X and Y around 0
            data[:, :2] *= -1

        # antsApplyTransformsToPoints requires 5 cols with headers
        csvdata = np.hstack((data, np.zeros((data.shape[0], 3))))

        out_file = fname_presuffix(
            self.inputs.in_file, newpath=runtime.cwd, use_ext=False, suffix="points.csv"
        )
        np.savetxt(
            out_file,
            csvdata,
            delimiter=",",
            header="x,y,z,t,label,comment",
            fmt=["%.5f"] * 4 + ["%d"] * 2,
        )
        self._results["out_file"] = out_file
        return runtime

class _CSVToGiftiInputSpec(BaseInterfaceInputSpec):
    in_file = File(mandatory=True, exists=True, desc="CSV file")
    gii_file = File(mandatory=True, exists=True, desc="reference GIfTI file")
    itk_lps = traits.Bool(False, usedefault=True, desc="flip XY axes")

class _CSVToGiftiOutputSpec(TraitedSpec):
    out_file = File(desc="output GIfTI file")

class CSVToGifti(SimpleInterface):
    """Converts CSV files back to GIfTI, after moving vertices with
    ``antsApplyTransformToPoints``."""

    input_spec = _CSVToGiftiInputSpec
    output_spec = _CSVToGiftiOutputSpec

    def _run_interface(self, runtime):
        gii = nb.load(self.inputs.gii_file)
        data = np.loadtxt(
            self.inputs.in_file, delimiter=",", skiprows=1, usecols=(0, 1, 2)
        )

        if self.inputs.itk_lps:  # ITK: flip X and Y around 0
            data[:, :2] *= -1

        gii.darrays[0].data = data[:, :3].astype(gii.darrays[0].data.dtype)
        out_file = fname_presuffix(
            self.inputs.gii_file, newpath=runtime.cwd, suffix=".transformed"
        )
        gii.to_filename(out_file)
        self._results["out_file"] = out_file
        return runtime

class _SurfacesToPointCloudInputSpec(BaseInterfaceInputSpec):
    in_files = InputMultiPath(
        File(exists=True), mandatory=True, desc="input GIfTI files"
    )
    out_file = File("pointcloud.ply", usedefault=True, desc="output file name")

class _SurfacesToPointCloudOutputSpec(TraitedSpec):
    out_file = File(desc="output pointcloud in PLY format")

class SurfacesToPointCloud(SimpleInterface):
    """Converts multiple surfaces into a pointcloud with corresponding normals
    to then apply Poisson reconstruction"""

    input_spec = _SurfacesToPointCloudInputSpec
    output_spec = _SurfacesToPointCloudOutputSpec

    def _run_interface(self, runtime):
        from pathlib import Path

        giis = [nb.load(g) for g in self.inputs.in_files]
        vertices = np.vstack([g.darrays[0].data for g in giis])
        norms = np.vstack(
            [vertex_normals(g.darrays[0].data, g.darrays[1].data) for g in giis]
        )
        out_file = Path(self.inputs.out_file).resolve()
        pointcloud2ply(vertices, norms, out_file=out_file)
        self._results["out_file"] = str(out_file)
        return runtime

class _PoissonReconInputSpec(CommandLineInputSpec):
    in_file = File(
        exists=True,
        mandatory=True,
        argstr="--in %s",
        desc="input PLY pointcloud (vertices + normals)",
    )
    out_file = File(
        argstr="--out %s",
        keep_extension=True,
        name_source=["in_file"],
        name_template="%s_avg",
        desc="output PLY triangular mesh",
    )

class _PoissonReconOutputSpec(TraitedSpec):
    out_file = File(exists=True, desc="output PLY triangular mesh")

class PoissonRecon(CommandLine):
    """Runs Poisson Reconstruction on a cloud of points + normals
    given in PLY format.
    See https://github.com/mkazhdan/PoissonRecon
    """

    input_spec = _PoissonReconInputSpec
    output_spec = _PoissonReconOutputSpec
    _cmd = "PoissonRecon"

class _PLYtoGiftiInputSpec(BaseInterfaceInputSpec):
    in_file = File(exists=True, mandatory=True, desc="input PLY file")
    surf_key = traits.Str(mandatory=True, desc="reference GIfTI file")

class _PLYtoGiftiOutputSpec(TraitedSpec):
    out_file = File(desc="output GIfTI file")

class PLYtoGifti(SimpleInterface):
    """Convert surfaces from PLY to GIfTI"""

    input_spec = _PLYtoGiftiInputSpec
    output_spec = _PLYtoGiftiOutputSpec

    def _run_interface(self, runtime):
        from pathlib import Path

        meta = {
            "GeometricType": "Anatomical",
            "VolGeomWidth": "256",
            "VolGeomHeight": "256",
            "VolGeomDepth": "256",
            "VolGeomXsize": "1.0",
            "VolGeomYsize": "1.0",
            "VolGeomZsize": "1.0",
            "VolGeomX_R": "-1.0",
            "VolGeomX_A": "0.0",
            "VolGeomX_S": "0.0",
            "VolGeomY_R": "0.0",
            "VolGeomY_A": "0.0",
            "VolGeomY_S": "-1.0",
            "VolGeomZ_R": "0.0",
            "VolGeomZ_A": "1.0",
            "VolGeomZ_S": "0.0",
            "VolGeomC_R": "0.0",
            "VolGeomC_A": "0.0",
            "VolGeomC_S": "0.0",
        }
        meta["AnatomicalStructurePrimary"] = "Cortex%s" % (
            "Left" if self.inputs.surf_key.startswith("lh") else "Right"
        )
        meta["AnatomicalStructureSecondary"] = SECONDARY_ANAT_STRUC[
            self.inputs.surf_key.split(".")[-1]
        ]
        meta["Name"] = "%s_average.gii" % self.inputs.surf_key

        out_file = Path(runtime.cwd) / meta["Name"]
        out_file = ply2gii(self.inputs.in_file, meta, out_file=out_file)
        self._results["out_file"] = str(out_file)
        return runtime

class _UnzipJoinedSurfacesInputSpec(BaseInterfaceInputSpec):
    in_files = traits.List(
        InputMultiPath(File(exists=True), mandatory=True, desc="input GIfTI files")
    )

class _UnzipJoinedSurfacesOutputSpec(TraitedSpec):
    out_files = traits.List(
        OutputMultiPath(File(exists=True), desc="output pointcloud in PLY format")
    )
    surf_keys = traits.List(traits.Str, desc="surface identifier keys")

class UnzipJoinedSurfaces(SimpleInterface):
    """Unpack surfaces by identifier keys"""

    input_spec = _UnzipJoinedSurfacesInputSpec
    output_spec = _UnzipJoinedSurfacesOutputSpec

    def _run_interface(self, runtime):
        from pathlib import Path

        groups = defaultdict(list)
        in_files = [it for items in self.inputs.in_files for it in items]

        for f in in_files:
            bname = Path(f).name
            groups[bname.split("_")[0]].append(f)

        self._results["out_files"] = [sorted(els) for els in groups.values()]
        self._results["surf_keys"] = list(groups.keys())

        return runtime

def normalize_surfs(in_file, transform_file, newpath=None):
    """
    Re-center GIFTI coordinates to fit align to native T1w space.

    For midthickness surfaces, add MidThickness metadata

    Coordinate update based on:
    https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91
    and
    https://github.com/Washington-University/Pipelines/blob/ae69b9a/PostFreeSurfer/scripts/FreeSurfer2CaretConvertAndRegisterNonlinear.sh#L147
    """

    img = nb.load(in_file)
    transform = load_transform(transform_file)
    pointset = img.get_arrays_from_intent("NIFTI_INTENT_POINTSET")[0]
    coords = pointset.data.T
    c_ras_keys = ("VolGeomC_R", "VolGeomC_A", "VolGeomC_S")
    ras = np.array([[float(pointset.metadata[key])] for key in c_ras_keys])
    ones = np.ones((1, coords.shape[1]), dtype=coords.dtype)
    # Apply C_RAS translation to coordinates, then transform
    pointset.data = transform.dot(np.vstack((coords + ras, ones)))[:3].T.astype(
        coords.dtype
    )

    secondary = nb.gifti.GiftiNVPairs("AnatomicalStructureSecondary", "MidThickness")
    geom_type = nb.gifti.GiftiNVPairs("GeometricType", "Anatomical")
    has_ass = has_geo = False
    for nvpair in pointset.meta.data:
        # Remove C_RAS translation from metadata to avoid double-dipping in FreeSurfer
        if nvpair.name in c_ras_keys:
            nvpair.value = "0.000000"
        # Check for missing metadata
        elif nvpair.name == secondary.name:
            has_ass = True
        elif nvpair.name == geom_type.name:
            has_geo = True
    fname = os.path.basename(in_file)
    # Update metadata for MidThickness/graymid surfaces
    if "midthickness" in fname.lower() or "graymid" in fname.lower():
        if not has_ass:
            pointset.meta.data.insert(1, secondary)
        if not has_geo:
            pointset.meta.data.insert(2, geom_type)

    if newpath is not None:
        newpath = os.getcwd()
    out_file = os.path.join(newpath, fname)
    img.to_filename(out_file)
    return out_file

def load_transform(fname):
    """Load affine transform from file

    Parameters
    ----------
    fname : str or None
        Filename of an LTA or FSL-style MAT transform file.
        If ``None``, return an identity transform

    Returns
    -------
    affine : (4, 4) numpy.ndarray
    """
    if fname is None:
        return np.eye(4)

    if fname.endswith(".mat"):
        return np.loadtxt(fname)
    elif fname.endswith(".lta"):
        with open(fname, "rb") as fobj:
            for line in fobj:
                if line.startswith(b"1 4 4"):
                    break
            lines = fobj.readlines()[:4]
        return np.genfromtxt(lines)

    raise ValueError("Unknown transform type; pass FSL (.mat) or LTA (.lta)")

def vertex_normals(vertices, faces):
    """Calculates the normals of a triangular mesh"""

    def normalize_v3(arr):
        """ Normalize a numpy array of 3 component vectors shape=(n,3) """
        lens = np.sqrt(arr[:, 0] ** 2 + arr[:, 1] ** 2 + arr[:, 2] ** 2)
        arr /= lens[:, np.newaxis]

    tris = vertices[faces]
    facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0])
    normalize_v3(facenorms)

    norm = np.zeros(vertices.shape, dtype=vertices.dtype)
    norm[faces[:, 0]] += facenorms
    norm[faces[:, 1]] += facenorms
    norm[faces[:, 2]] += facenorms
    normalize_v3(norm)
    return norm

def pointcloud2ply(vertices, normals, out_file=None):
    """Converts the file to PLY format"""
    from pathlib import Path
    import pandas as pd
    from pyntcloud import PyntCloud

    df = pd.DataFrame(np.hstack((vertices, normals)))
    df.columns = ["x", "y", "z", "nx", "ny", "nz"]
    cloud = PyntCloud(df)

    if out_file is None:
        out_file = Path("pointcloud.ply").resolve()

    cloud.to_file(str(out_file))
    return out_file

def ply2gii(in_file, metadata, out_file=None):
    """Convert from ply to GIfTI"""
    from pathlib import Path
    from numpy import eye
    from nibabel.gifti import (
        GiftiMetaData,
        GiftiCoordSystem,
        GiftiImage,
        GiftiDataArray,
    )
    from pyntcloud import PyntCloud

    in_file = Path(in_file)
    surf = PyntCloud.from_file(str(in_file))

    # Update centroid metadata
    metadata.update(
        zip(
            ("SurfaceCenterX", "SurfaceCenterY", "SurfaceCenterZ"),
            ["%.4f" % c for c in surf.centroid],
        )
    )

    # Prepare data arrays
    da = (
        GiftiDataArray(
            data=surf.xyz.astype("float32"),
            datatype="NIFTI_TYPE_FLOAT32",
            intent="NIFTI_INTENT_POINTSET",
            meta=GiftiMetaData.from_dict(metadata),
            coordsys=GiftiCoordSystem(xform=eye(4), xformspace=3),
        ),
        GiftiDataArray(
            data=surf.mesh.values,
            datatype="NIFTI_TYPE_INT32",
            intent="NIFTI_INTENT_TRIANGLE",
            coordsys=None,
        ),
    )
    surfgii = GiftiImage(darrays=da)

    if out_file is None:
        out_file = fname_presuffix(
            in_file.name, suffix=".gii", use_ext=False, newpath=str(Path.cwd())
        )

    surfgii.to_filename(str(out_file))
    return out_file

def get_gii_meta(in_file):
    from nibabel import load

    if isinstance(in_file, list):
        in_file = in_file[0]
    gii = load(in_file)
    return gii.darrays[0].meta.metadata


text:
package cz.kamenitxan.jakon.webui.controller

import cz.kamenitxan.jakon.logging.Logger
import cz.kamenitxan.jakon.webui.Context
import spark.{Request, Response}

@Deprecated
abstract class AbstractController extends CustomController {
	val template: String
	val icon: String = "fa-cog"

	def doRender(req: Request, res: Response): Context = {
		try {
			render(req, res)
		} catch {
			case e: Exception => {
				Logger.error("Exception thrown during " + name() + " controller render", e)
				new Context(Map[String, Any](
					"errors" -> List(e.toString)
				), template)
			}
		}
	}
}


text:
var Maopy = function (args) {
	return new MAOPY(args);
};

//基础库
function MAOPY(args) {
	//保存获取的节点
	this.elements = [];
	if (typeof args == 'string') {
		//css模拟
		if (args.indexOf(' ') != -1) {
			var elements = args.split(' ');			//把节点拆开分别保存到数组里
			var childElements = [];					//存放临时节点对象的数组,解决被覆盖的问题
			var node = [];								//用来存放父节点用的
			for (var i = 0; i < elements.length; i ++) {
				if (node.length == 0) node.push(document);		//如果默认没有父节点,就把document放入
				switch (elements[i].charAt(0)) {
					case '#' :
						childElements = [];				//清理掉临时节点,以便父节点失效,子节点有效
						childElements.push(this.getId(elements[i].substring(1)));
						node = childElements;		//保存父节点,因为childElements要清理,所以需要创建node数组
						break;
					case '.' :
						childElements = [];
						for (var j = 0; j < node.length; j ++) {
							var temps = this.getClassName(elements[i].substring(1), node[j]);
							for (var k = 0; k < temps.length; k ++) {
								childElements.push(temps[k]);
							}
						}
						node = childElements;
						break;
					default :
						childElements = [];
						for (var j = 0; j < node.length; j ++) {
							var temps = this.getTagName(elements[i], node[j]);
							for (var k = 0; k < temps.length; k ++) {
								childElements.push(temps[k]);
							}
						}
						node = childElements;
				}
			}
			this.elements = childElements;
		} else {
			//find模拟
			switch (args.charAt(0)) {
				case '#' :
					this.elements.push(this.getId(args.substring(1)));
					break;
				case '.' :
					this.elements = this.getClassName(args.substring(1));
					break;
				default :
					this.elements = this.getTagName(args);
			}
		}
	} else if (typeof args == 'object') {
		if (args != undefined) {    //_this是一个对象,undefined也是一个对象,区别与typeof返回的带单引号的'undefined'
			this.elements[0] = args;
		}
	}
}
//获取ID节点
MAOPY.prototype.getId = function (id) {
	return document.getElementById(id);
};
//获取元素节点数组
MAOPY.prototype.getTagName = function (tag, parentNode) {
	var node = null;
	var temps = [];
	if (parentNode != undefined) {
		node = parentNode;
	} else {
		node = document;
	}
	var tags = node.getElementsByTagName(tag);
	for (var i = 0; i < tags.length; i ++) {
		temps.push(tags[i]);
	}
	return temps;
};
//获取CLASS节点数组
MAOPY.prototype.getClassName = function (className, parentNode) {
	var node = null;
	var temps = [];
	if (parentNode != undefined) {
		node = parentNode;
	} else {
		node = document;
	}
	var all = node.getElementsByTagName('*');
	for (var i = 0; i < all.length; i ++) {
		if (all[i].className == className) {
			temps.push(all[i]);
		}
	}
	return temps;
};
//设置CSS选择器子节点
MAOPY.prototype.find = function (str) {
	var childElements = [];
	for (var i = 0; i < this.elements.length; i ++) {
		switch (str.charAt(0)) {
			case '#' :
				childElements.push(this.getId(str.substring(1)));
				break;
			case '.' :
				var temps = this.getClassName(str.substring(1), this.elements[i]);
				for (var j = 0; j < temps.length; j ++) {
					childElements.push(temps[j]);
				}
				break;
			default :
				var temps = this.getTagName(str, this.elements[i]);
				for (var j = 0; j < temps.length; j ++) {
					childElements.push(temps[j]);
				}
		}
	}
	this.elements = childElements;
	return this;
};
//获取某一个节点,并返回DOM对象
MAOPY.prototype.get = function (num) {
	return this.elements[num];
};
//获取某一个节点,并返回Maopy对象
MAOPY.prototype.eq = function (num) {
	var element = this.elements[num];
	this.elements = [];
	this.elements[0] = element;
	return this;
};
//设置CSS
MAOPY.prototype.css = function (attr, value) {
	for(var i = 0; i < this.elements.length; i++) {
		if(1 == arguments.length) {
			return this.getStyle(this.elements[i], attr);
		}
		this.elements[i].style[attr] = value;
	}
	return this;
};
//添加Class
MAOPY.prototype.addClass = function (className) {
	for (var i = 0; i < this.elements.length; i ++) {
		if (!this.hasClass(this.elements[i], className)) {
			this.elements[i].className += className + ' ';
		}
	}
	return this;
};
//移除Class
MAOPY.prototype.removeClass = function (className) {
	for (var i = 0; i < this.elements.length; i ++) {
		if (this.hasClass(this.elements[i], className)) {
			this.elements[i].className = this.elements[i].className.replace(new RegExp('(\\s|^)' +className +'(\\s|$)'), ' ');
		}
	}
	return this;
};
//添加link或style的CSS规则
MAOPY.prototype.addRule = function (num, selectorText, cssText, position) {
	var sheet = document.styleSheets[num];
	this.insertRule(sheet, selectorText, cssText, position);
	return this;
};
//移除link或style的CSS规则
MAOPY.prototype.removeRule = function (num, index) {
	var sheet = document.styleSheets[num];
	this.deleteRule(sheet, index);
	return this;
};
//设置innerHTML
MAOPY.prototype.html = function (str) {
	for(var i = 0; i < this.elements.length; i++) {
		if(0 == arguments.length) {
			return this.elements[i].innerHTML;
		}
		this.elements[i].innerHTML = str;
	}
	return this;
};
//设置鼠标移入移出方法
MAOPY.prototype.hover = function (over, out) {
	for (var i = 0; i < this.elements.length; i ++) {
		this.elements[i].onmouseover = over;
		this.elements[i].onmouseout = out;
	}
	return this;
};
//设置显示
MAOPY.prototype.show = function () {
	for (var i = 0; i < this.elements.length; i ++) {
		this.elements[i].style.display = 'block';
	}
	return this;
};
//设置隐藏
MAOPY.prototype.hide = function () {
	for (var i = 0; i < this.elements.length; i ++) {
		this.elements[i].style.display = 'none';
	}
	return this;
};
//插件入口
MAOPY.prototype.extend = function (name, fn) {
	MAOPY.prototype[name] = fn;
};


text:
package main

import (
	"sync"
	"fmt"
)

var once sync.Once

type single2 struct{}

var singleInstance2 *single2

func getInstance2() *single2{
	if singleInstance2 == nil{
		once.Do(
			func(){
				fmt.Println("Creating single instance now")
				singleInstance2 = &single2{}
			})
	}else{
		fmt.Println("Single instance already created!")
	}
	return singleInstance2
}