text:
namespace Public.Common.Lib.Logging.AttemptA
{
    public class LoggingImplementation : ILoggingImplementation
    {
        public ILogger DefaultLogger { get; set; }

        public LoggingImplementation(ILogger defaultLogger)
        {
            this.DefaultLogger = defaultLogger;
        }

        public LoggingImplementation()
            : this(DummyLogger.Instance)
        {

        }

        public ILogger GetDefaultLogger()
        {
            return this.DefaultLogger;
        }

        public ILogger GetLogger(ILoggerConfiguration configuration)
        {
            // Ignore configuration.

            var output = this.GetDefaultLogger();
            return output;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Xunit;

namespace Faithlife.Parsing.Tests;

public class CharTests
{
	[Fact]
	public void ConstantShouldFailOnEmpty()
	{
		Parser.Char('a').TryParse("").ShouldFail(0);
	}

	[Fact]
	public void ConstantShouldSucceedOnGoodChar()
	{
		Parser.Char('a').TryParse("a").ShouldSucceed('a', 1);
		Parser.Char('a').TryParse("ab").ShouldSucceed('a', 1);
	}

	[Fact]
	public void ConstantShouldFailOnBadChar()
	{
		Parser.Char('a').TryParse("b").ShouldFail(0);
	}

	[Fact]
	public void PredicateShouldFailOnEmpty()
	{
		Parser.Char(ch => ch is >= 'a' and <= 'z').TryParse("").ShouldFail(0);
	}

	[Fact]
	public void PredicateShouldSucceedOnGoodChar()
	{
		Parser.Char(ch => ch is >= 'a' and <= 'z').TryParse("a").ShouldSucceed('a', 1);
		Parser.Char(ch => ch is >= 'a' and <= 'z').TryParse("ab").ShouldSucceed('a', 1);
		Parser.Char(ch => ch is >= 'a' and <= 'z').TryParse("b").ShouldSucceed('b', 1);
	}

	[Fact]
	public void PredicateShouldFailOnBadChar()
	{
		Parser.Char(ch => ch is >= 'a' and <= 'z').TryParse("1").ShouldFail(0);
	}

	[Fact]
	public void AnyCharShouldFailOnEmpty()
	{
		Parser.AnyChar.TryParse("").ShouldFail(0);
	}

	[Fact]
	public void AnyCharShouldSucceedOnAnyChar()
	{
		Parser.AnyChar.TryParse("a").ShouldSucceed('a', 1);
		Parser.AnyChar.TryParse("1").ShouldSucceed('1', 1);
	}

	[Fact]
	public void AnyCharExceptShouldFailOnEmpty()
	{
		Parser.AnyCharExcept('a').TryParse("").ShouldFail(0);
	}

	[Fact]
	public void AnyCharExceptShouldSucceedOnGoodChar()
	{
		Parser.AnyCharExcept('a').TryParse("b").ShouldSucceed('b', 1);
	}

	[Fact]
	public void AnyCharExceptShouldFailOnBadChar()
	{
		Parser.AnyCharExcept('a').TryParse("a").ShouldFail(0);
		Parser.AnyCharExcept('a').TryParse("ab").ShouldFail(0);
	}
}


text:
If you haven't done this before, please read the [features design](FEATURES_DESIGN.md) article.

It explains the "why"s of the two key design concepts of this app:
* hierarchical configuration with inheritance, merging/overwriting and additivity,
* raw parameters passing

Please also read the usual [contributing guide](https://github.com/egnyte/gitlabform/blob/main/CONTRIBUTING.md) for the basics of how to create PRs,
the expected style of your code etc. - the "general how"s.

This article purpose is to explain "specific how"s - explain what is where in the code and how to add features
by example.

## Structure

### Packages:

* `gitlabform.*` and `gitlabform.processors.*` - contains the main app logic. It provides the CLI, parsing of the parameters,
  uses below two packages to apply the config defined in `config.yml` to the requested set of projects.

* `gitlabform.gitlab.*` - contains the GitLab API client code, grouped mostly by the GitLab API
  [as documented at docs.gitlab.com](https://docs.gitlab.com/ee/api/api_resources.html).

* `gitlabform.configuration.*` - contains the logic for reading the config from YAML file or a string
  (the latter is only for testing) and getting an effective config per GitLab project by merging
  the config on these levels: common, group and project settings.

## Common pattern - multiple inheritance

In many of the above packages we are using _multiple inheritance_.

The basic features are implemented in the "core" class defined in `core.py`. Extensions to it are defined in all other
files as "feature" classes that inherit the "core". Finally, there is an "everything" class that groups them all - it is
defined in the `__init__.py` file.

### gitlabform.* and gitlabform.processors.*

The entry point for running the app is in `run.py` and the main logic is in the `GitLabForm` class.

This code boils down to the `run()` method, which for each project that according to the app parameters
and config should be taken into account, applies the effective config.

The effective config contains what is called the "config sections", which are the YAML keys that can exist under projects
in the config YAML, for example: `deploy_keys`, `secret_variables`, `group_secret_variables` and so on.

Those config sections are processed by the code in the classes inheriting from the `AbstractProcessor` class. This class
should be reused when implementing new functionalities (such as supporting new configuration keys) as it holds the common
logic for skipping the configuration parts and running in dry-run mode. The processors have been grouped into two
packages - `group` where the processors applied to the group settings are implemented and `project` - where processors
executed on the project level are located.

Since v2.2.0 there is a new way of implementing processors - by inheriting form `MultipleEntitiesProcessor` class.
It should be applied for new features which manage 0-N entities of some kind under a group or a project.
See `BadgesProcessor` as an example how to use it.

#### Usage

If you want to **add/change/fix things under an existing config section** then most likely you will need to update
the code in the processor classes (for example, in `BranchesProcessor`).

If you want to **add support for a new config section** (= completely new feature), then you need to:

0. (TODO: expand this sections) Consider writing a new processor using `MultipleEntitiesProcessor` class as a base.
1. Create a new class `group_<new_config_section_name>_processor` (if it applies to the group settings) or
`<new_config_section_name>_processor` (if it applies to project settings) and implement two methods:
    - `_process_configuration` - which does the actual processing by calling the API and applying the changes in GitLab;
    - `_log_changes` - which is optional but recommended to implement; by calling this method the effective changes
    to be applied should be logged (when running in dry-run mode).
2. Add the new processor to `GroupProcessors` in `group > __init__.py` (if group settings processor was created) or
to `ProjectProcessors` in `project > __init__.py`.

### gitlabform.gitlab.*

With the basics for making requests to the GitLab API covered in the `GitLabCore` class in `core.py`, all other code
is simple (most of the time).

Almost all methods in other classes end up calling `self._make_requests_to_api`, which takes care of making the HTTP
GitLab API requests with proper authentication, sometimes pagination, if needed retries & timeouts support, and more.

Sometimes there is some logic in these methods if:
* we only need a specific part of the response from GitLab API - see `GitLabProjects.get_all_projects()` as an example,
* some GitLab APIs need some workarounds for their bugs or documentation inconsistencies, like:
  * some APIs declare in the docs that they accept both "group/project" string OR a project id while in fact only
the latter works - see `GitLabProjects.post_approvals()` as an example,
  * some APIs return invalid HTTP error codes, like 404 instead of 400 - see `GitLabGroupLDAPLinks.add_ldap_group_link`
    as an example.

**Note**: Some of the code here is **NOT used by the GitLabForm app**, but utilized by internal Egnyte
applications that have not yet switched to the more standard `python-gitlab`.

#### Usage

If you want to **add/change/fix code that operates on an existing GitLab API** you should look around
the "feature" classes in this package (for example `GitLabMergeRequests` in `merge_requests.py`).

If you want to **add code that operates on the new GitLab API** you should:

1. create a new `new_gitlab_api_name.py` file in `gitlabform.gitlab` and define a "feature" class there
   that inherits `GitLabCore` (for example: `GitLabApiName`).
2. add the new feature class to the list of classes inherited by the "everything" `GitLab` class
   defined in `__init__.py`.

### gitlabform.configuration.*

**TODO**: describe this part. Especially what an "effective project config" is, because that may not be clear.


text:
<?php

/**
 * This file is part of Gush package.
 *
 * (c) 2013-2014 Luis Cordova <cordoval@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Gush\Tests\Command\PullRequest;

use Gush\Command\PullRequest\PullRequestMilestoneListCommand;
use Gush\Tests\Command\BaseTestCase;

class PullRequestMilestoneListCommandTest extends BaseTestCase
{
    /**
     * @test
     */
    public function lists_pull_requests_associated_milestones()
    {
        $tester = $this->getCommandTester(new PullRequestMilestoneListCommand());
        $tester->execute(['--org' => 'gushphp', '--repo' => 'gush'], ['interactive' => false]);

        $this->assertEquals('version 1.0', trim($tester->getDisplay(true)));
    }
}


text:
<?php

defined('_JEXEC') or die('Restricted access');
?>


text:
package com.asofdate.batch.dao;

import com.asofdate.batch.entity.BatchDefineEntity;

import java.util.List;

/**
 * Created by hzwy23 on 2017/5/24.
 */
public interface BatchDefineDao {
    List findAll(String domainId);

    List<BatchDefineEntity> getRunning(String domainId);

    int add(BatchDefineEntity m);

    String delete(List<BatchDefineEntity> m);

    int update(BatchDefineEntity m);

    int getStatus(String batchId);

    int batchPagging(String batchId, String asOfDate);

    int setStatus(String batchId, int status);

    int updateAsofdate(String asofdate, String batchId);

    int runBatchInit(String batchId);

    int destoryBatch(String batchId, String retMsg, int status);

    int saveHistory(String batchId);

    String getBatchAsOfDate(String batchId);

    BatchDefineEntity findDetailsByBatchId(String batchId);

    void initBatchStatus();
}


text:
<!--

    Copyright (C) 2012 RECIA http://www.recia.fr
    @Author (C) 2012 Maxime Bossard <mxbossard@gmail.com>

    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.

-->
<samlp:LogoutResponse xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
	xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_cbb63e9741259e3f1c98a1ae38ac5ac25889720b32"
	Version="2.0" IssueInstant="2008-06-03T12:59:57Z"
	Destination="https://foodle.feide.no/simplesaml/saml2/sp/SingleLogoutService.php"
	InResponseTo="_72424ea37e28763e351189529639b9c2b150ff37e5">
	<saml:Issuer>https://openidp.feide.no</saml:Issuer>
	<samlp:Status>
		<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success">
		</samlp:StatusCode>
		<samlp:StatusMessage>Successfully logged out from service
			https://openidp.feide.no</samlp:StatusMessage>
	</samlp:Status>
</samlp:LogoutResponse>


text: require 'trajectory/core_ext/hash'


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.openqa.selenium.internal.selenesedriver
</TITLE>

<META NAME="date" CONTENT="2010-02-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.openqa.selenium.internal.selenesedriver

Interface Summary

SeleneseFunction<T>

Class Summary

ClearElement

ClickElement

ElementFunction<T>

ExecuteScript

FindElement

GetCurrentUrl

GetElementAttribute

GetElementText

GetElementValue

GetPageSource

GetTagName

GetTitle

GetUrl

IsElementDisplayed

IsElementEnabled

IsElementSelected

NewSession

QuitSelenium

SendKeys

SetElementSelected

SubmitElement

ToggleElement

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
<!doctype html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
    <!-- build:js js/main.min.js -->
    <script src="js/cplayer.js"></script>
    <script src="js/soundManager.js"></script>
    <script src="js/upgrade.js"></script>
    <script src="js/utils.js"></script>
    <script src="js/drawing.js"></script>
    <script src="js/game.js"></script>
    <script src="js/render.js"></script>
    <script src="js/sprite.js"></script>
    <script src="js/button.js"></script>
    <script src="js/levels/level.js"></script>
    <script src="js/levels/startLevel.js"></script>
    <script src="js/levels/firstLevel.js"></script>
    <script src="js/levels/mainLevel.js"></script>
    <script src="js/error.js"></script>
    <!-- endbuild -->
    <div style="text-align: center;">
        <canvas id="canvas" width="800" height="600" style="border:none;"></canvas>
    </div>
</body>
</html>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var game = new Game(context, canvas.width, canvas.height);
    game.start();
</script>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<TITLE>
	Changes in TIFF v4.0.1
</TITLE>

<BASEFONT SIZE=4>
TIFF CHANGE INFORMATION
<BASEFONT SIZE=3>

Current Version: v4.0.1

Previous Version: v4.0.0

Master Download Site:
download.osgeo.org, directory pub/libtiff

Master HTTP Site:
http://www.simplesystems.org/libtiff/

This document describes the changes made to the software between the
previous and current versions (see above).  If you don't
find something listed here, then it was not done in this timeframe, or
it was not considered important enough to be mentioned.  The following
information is located here:

Major Changes

Changes in the software configuration

Changes in libtiff

Changes in the tools

Changes in the contrib area

MAJOR CHANGES:

 None

CHANGES IN THE SOFTWARE CONFIGURATION:

 --enable-ld-version-script: New configure option to
	enable shared library symbol versioning on ELF-based systems
	(e.g. Linux and FreeBSD) which use the GNU linker.  This
	allows multiple major versions of libtiff to be loaded
	simultaneously into the same application or library without
	conflict, as long as all libtiffs involved are built with
	versioned symbols.  This option is not enabled by default.

 Added libtiff private dependency on -llzma for pkg-config.

CHANGES IN LIBTIFF:

 libtiff/tif_dir.c, libtiff/tif_dirread.c: Extra caution around
        assumption tag fetching is always successful.

 libtiff/tif_jpeg.c: Extra caution for case where sp is NULL.

CHANGES IN THE TOOLS:

 None

CHANGES IN THE CONTRIB AREA:

 None

Last updated $Date: 2016-09-25 20:05:47 $.


text:
#pragma once

namespace pangolin
{

class GlContextInterface
{
public:
    virtual ~GlContextInterface() {}
};

class WindowInterface
{
public:
    virtual ~WindowInterface() {}

    virtual void ToggleFullscreen() = 0;
    virtual void Move(int x, int y) = 0;
    virtual void Resize(unsigned int w, unsigned int h) = 0;
    virtual void MakeCurrent() = 0;
    virtual void ProcessEvents() = 0;
    virtual void SwapBuffers() = 0;
};

}


text:
from KalutServer.Exceptions import *
import KalutServer.conf as myconf
from KalutServer.Room import Room
from random import randint
import threading
import time
import Queue
import select
import socket
import sys
import json
import traceback
import ssl
rooms = dict()
srvsoc = socket.socket()

def soc_router():
    global srvsoc
    srvsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srvsoc.bind((myconf.host, myconf.sock_port))
    srvsoc.listen(5)
    while 1:
        try:
            sslcltsock, addr = srvsoc.accept()
            # sslcltsock = ssl.wrap_socket(cltsock, myconf.keyfile, myconf.certfile, server_side=True)
            data = sslcltsock.recv(1024)
        except:
            print 'Server socket closed.'
            break
        try:
            if data:
                req = json.loads(data)
                print 'Client with name {0} connected, client...'.format(req['name'])
                if int(req['pin']) in rooms.keys() and req['name']:
                    if rooms[req['pin']].status in ('WAITING_FOR_PLAYERS', 'WAITING_FOR_LAST_PLAYER'):
                        sslcltsock.send(json.dumps({'status' : 'ok', 'UID' : str(rooms[req['pin']].game_uid)}))
                        rooms[req['pin']].add_client(sslcltsock, req['name'])
                        if not rooms[req['pin']].running:
                            t = threading.Thread(target=start_room, args=(req['pin'],))
                            t.start()
                    else:
                        sslcltsock.send(json.dumps({'status' : "Room isn't waiting for players."}))
                        sslcltsock.close()
                else:
                    sslcltsock.send(json.dumps({'status' : 'invalid pin.'}))
                    sslcltsock.close()
            else:
                sslcltsock.close()
        except:
            sslcltsock.close()
            print traceback.format_exc()
            break

def start_room(pin):
    room = rooms[pin]
    room.running = True
    print 'starting room with pin of ' + str(pin)
    room.mainloop()

def close_srvsoc():
    global srvsoc
    srvsoc.close()

def are_there_rooms_running():
    '''Returns true of there are no running rooms.'''
    return len(rooms.keys())==0

def start_room_async(pin):
    t = threading.Thread(target=start_room, args=(pin,))
    t.start()

def create_room(uid, pin=0):
    while pin in rooms.keys() or pin==0:
        pin=randint(1000,10000)
    rooms[pin]=Room.Room(pin, uid)
    print 'created room with pin of' + str(pin)
    return pin

def close_room(pin):
    if pin in rooms.keys():
        del rooms[pin]

def close_all_rooms():
    global srvsoc
    for pin, room in rooms.items():
        room.close()
    s = socket.socket()
    s.connect((myconf.host, myconf.sock_port))
    srvsoc.close()
    s.close()


text:
"""A simple test to ensure that the Python wrapper can get xDS config."""

from concurrent.futures import ThreadPoolExecutor
import logging
import os
import queue
import sys
import time
import unittest

from envoy.service.status.v3 import csds_pb2
from envoy.service.status.v3 import csds_pb2_grpc
from google.protobuf import json_format
import grpc
import grpc_csds

_DUMMY_XDS_ADDRESS = 'xds:///foo.bar'
_DUMMY_BOOTSTRAP_FILE = """
{
  \"xds_servers\": [
    {
      \"server_uri\": \"fake:///xds_server\",
      \"channel_creds\": [
        {
          \"type\": \"fake\"
        }
      ],
      \"server_features\": [\"xds_v3\"]
    }
  ],
  \"node\": {
    \"id\": \"python_test_csds\",
    \"cluster\": \"test\",
    \"metadata\": {
      \"foo\": \"bar\"
    },
    \"locality\": {
      \"region\": \"corp\",
      \"zone\": \"svl\",
      \"sub_zone\": \"mp3\"
    }
  }
}\
"""

@unittest.skipIf(sys.version_info[0] < 3,
                 'ProtoBuf descriptor has moved on from Python2')
class TestCsds(unittest.TestCase):

    def setUp(self):
        os.environ['GRPC_XDS_BOOTSTRAP_CONFIG'] = _DUMMY_BOOTSTRAP_FILE
        self._server = grpc.server(ThreadPoolExecutor())
        port = self._server.add_insecure_port('localhost:0')
        grpc_csds.add_csds_servicer(self._server)
        self._server.start()

        self._channel = grpc.insecure_channel('localhost:%s' % port)
        self._stub = csds_pb2_grpc.ClientStatusDiscoveryServiceStub(
            self._channel)

    def tearDown(self):
        self._channel.close()
        self._server.stop(0)
        os.environ.pop('GRPC_XDS_BOOTSTRAP_CONFIG', None)

    def get_xds_config_dump(self):
        return self._stub.FetchClientStatus(csds_pb2.ClientStatusRequest())

    def test_has_node(self):
        resp = self.get_xds_config_dump()
        self.assertEqual(1, len(resp.config))
        self.assertEqual('python_test_csds', resp.config[0].node.id)
        self.assertEqual('test', resp.config[0].node.cluster)

    def test_no_lds_found(self):
        dummy_channel = grpc.insecure_channel(_DUMMY_XDS_ADDRESS)

        # Force the XdsClient to initialize and request a resource
        with self.assertRaises(grpc.RpcError) as rpc_error:
            dummy_channel.unary_unary('')(b'', wait_for_ready=False)
        self.assertEqual(grpc.StatusCode.UNAVAILABLE,
                         rpc_error.exception.code())

        # The resource request will fail with DOES_NOT_EXIST (after 15s)
        while True:
            resp = self.get_xds_config_dump()
            config = json_format.MessageToDict(resp)
            ok = False
            try:
                for xds_config in config["config"][0].get("xdsConfig", []):
                    if "listenerConfig" in xds_config:
                        listener = xds_config["listenerConfig"][
                            "dynamicListeners"][0]
                        if listener['clientStatus'] == 'DOES_NOT_EXIST':
                            ok = True
                            break
                for generic_xds_config in config["config"][0].get(
                        "genericXdsConfigs", []):
                    if "Listener" in generic_xds_config["typeUrl"]:
                        if generic_xds_config[
                                'clientStatus'] == 'DOES_NOT_EXIST':
                            ok = True
                            break
            except KeyError as e:
                logging.debug("Invalid config: %s\n%s: %s", config, type(e), e)
                pass
            if ok:
                break
            time.sleep(1)
        dummy_channel.close()

@unittest.skipIf(sys.version_info[0] < 3,
                 'ProtoBuf descriptor has moved on from Python2')
class TestCsdsStream(TestCsds):

    def get_xds_config_dump(self):
        if not hasattr(self, 'request_queue'):
            request_queue = queue.Queue()
            response_iterator = self._stub.StreamClientStatus(
                iter(request_queue.get, None))
        request_queue.put(csds_pb2.ClientStatusRequest())
        return next(response_iterator)

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    unittest.main(verbosity=2)


text:
    <base href="/">
    <title>Wikisual - Wikipedia Visualized</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="static/css/readable.min.css">

    {% if DEVMODE %}

    {% else %}

    {% endif %}

          <my-app>Loading...</my-app>

  {% if not DEVMODE %}

  {% endif %}


text:
package org.jeecgframework.core.extend.swftools;
import org.jeecgframework.core.util.FileUtils;
public class DocConverter {

	private PDFConverter pdfConverter;
	private SWFConverter swfConverter;

	public DocConverter(PDFConverter pdfConverter, SWFConverter swfConverter) {
		super();
		this.pdfConverter = pdfConverter;
		this.swfConverter = swfConverter;
	}

	public  void convert(String inputFile,String swfFile,String extend){
		this.pdfConverter.convert2PDF(inputFile,extend);
		String pdfFile = FileUtils.getFilePrefix(inputFile)+".pdf";
		this.swfConverter.convert2SWF(pdfFile, swfFile);
	}

	public void convert(String inputFile,String extend){
		this.pdfConverter.convert2PDF(inputFile,extend);
		String pdfFile = FileUtils.getFilePrefix2(inputFile)+".pdf";
		extend=FileUtils.getExtend(pdfFile);
		this.swfConverter.convert2SWF(pdfFile,extend);

	}

}


text:
#!/usr/bin/python

# This is statement is required by the build system to query build info
if __name__ == '__build__':
	raise Exception

'''
double.c from the Redbook examples.
Converted to Python by Jason L. Petrone 6/00

'''

'''
/*
 *  double.c
 *  This is a simple double buffered program.
 *  Pressing the left mouse button rotates the rectangle.
 *  Pressing the middle mouse button stops the rotation.
 */
 '''

import sys

try:
  from OpenGL.GLUT import *
  from OpenGL.GL import *
  from OpenGL.GLU import *
except:
  print '''
ERROR: PyOpenGL not installed properly.
        '''
  sys.exit()

spin = 0.0

def display():
   glClear(GL_COLOR_BUFFER_BIT)
   glPushMatrix()
   glRotatef(spin, 0.0, 0.0, 1.0)
   glColor3f(1.0, 1.0, 1.0)
   glRectf(-25.0, -25.0, 25.0, 25.0)
   glPopMatrix()
   glutSwapBuffers()

def spinDisplay():
   global spin
   spin = spin + 2.0
   if(spin > 360.0):
      spin = spin - 360.0
   glutPostRedisplay()

def init():
   glClearColor(0.0, 0.0, 0.0, 0.0)
   glShadeModel(GL_FLAT)

def reshape(w, h):
   glViewport(0, 0, w, h)
   glMatrixMode(GL_PROJECTION)
   glLoadIdentity()
   glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0)
   glMatrixMode(GL_MODELVIEW)
   glLoadIdentity()

def mouse(button, state, x, y):
   if button == GLUT_LEFT_BUTTON:
       if(state == GLUT_DOWN):
          glutIdleFunc(spinDisplay)
   elif button == GLUT_MIDDLE_BUTTON or button == GLUT_RIGHT_BUTTON:
       if(state == GLUT_DOWN):
           glutIdleFunc(None)

#  Request double buffer display mode.
#  Register mouse input callback functions
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
glutInitWindowSize(250, 250)
glutInitWindowPosition(100, 100)
glutCreateWindow('Double')
init()
glutDisplayFunc(display)
glutReshapeFunc(reshape)
glutMouseFunc(mouse)
glutMainLoop()


text:
package org.apache.maven.plugin.prefix;

import java.util.List;
import org.apache.maven.model.Model;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;

/**
 * Collects settings required to resolve a plugin prefix.
 *
 * @since 3.0
 * @author Benjamin Bentmann
 */
public interface PluginPrefixRequest {

    /**
     * Gets the prefix of the plugin.
     *
     * @return The prefix of the plugin.
     */
    String getPrefix();

    /**
     * Sets the prefix of the plugin.
     *
     * @param prefix The prefix of the plugin.
     * @return This request, never {@code null}.
     */
    PluginPrefixRequest setPrefix(String prefix);

    /**
     * Gets the list of group ids to scan for the plugin prefix.
     *
     * @return The list of group ids to scan for the plugin prefix, never {@code null}.
     */
    List<String> getPluginGroups();

    /**
     * Sets the list of group ids to scan for the plugin prefix.
     *
     * @param pluginGroups The list of group ids to scan for the plugin prefix, may be {@code null}.
     * @return This request, never {@code null}.
     */
    PluginPrefixRequest setPluginGroups(List<String> pluginGroups);

    /**
     * Gets the POM whose build plugins are to be scanned for the prefix.
     *
     * @return The POM whose build plugins are to be scanned for the prefix or {@code null} to only search the plugin
     *         repositories.
     */
    Model getPom();

    /**
     * Sets the POM whose build plugins are to be scanned for the prefix.
     *
     * @param pom The POM whose build plugins are to be scanned for the prefix, may be {@code null} to only search the
     *            plugin repositories.
     * @return This request, never {@code null}.
     */
    PluginPrefixRequest setPom(Model pom);

    /**
     * Gets the remote repositories to use.
     *
     * @return The remote repositories to use, never {@code null}.
     */
    List<RemoteRepository> getRepositories();

    /**
     * Sets the remote repositories to use. Note: When creating a request from a project, be sure to use the
     * plugin repositories and not the regular project repositories.
     *
     * @param repositories The remote repositories to use.
     * @return This request, never {@code null}.
     */
    PluginPrefixRequest setRepositories(List<RemoteRepository> repositories);

    /**
     * Gets the session to use for repository access.
     *
     * @return The repository session or {@code null} if not set.
     */
    RepositorySystemSession getRepositorySession();

    /**
     * Sets the session to use for repository access.
     *
     * @param repositorySession The repository session to use.
     * @return This request, never {@code null}.
     */
    PluginPrefixRequest setRepositorySession(RepositorySystemSession repositorySession);
}


text:
package com.eptcomputing.neo4j.rest

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith

import org.codehaus.jettison.json.{JSONObject, JSONArray}
import org.neo4j.graphdb._

import com.eptcomputing.neo4j.Neo4jServer

@RunWith(classOf[JUnitRunner])
class JsonConverterSpec extends Spec with ShouldMatchers {

  // Helper for converting JSON to Node
  implicit def jsonObjectToNode(json: JSONObject) = new {
    def toNode[T<:Any](operation: Node => T): T = {
      Neo4jServer.exec { neo =>
        operation(Neo4jJsonConverter.jsonToNeo(json, neo, null))
      }
    }
  }

  // Helper for converting Node to JSON
  def serializedNodeWithProperty(property: Object) = Neo4jServer.exec { neo =>
    val node = neo.createNode
    node.setProperty("foo", property)
    Neo4jJsonConverter.neoToJson(node)
  }

  describe("Neo4jJsonConverter") {

    it("should serialize a string property to JSON") {
      val json = serializedNodeWithProperty("test")
      json.getString("foo") should equal("test")
      json.toString should include("\"foo\":\"test\"")
    }

    it("should unserialize a string property from JSON") {
      new JSONObject().put("foo", "test") toNode { node =>
        node.getProperty("foo") should equal("test")
      }
    }

    it("should serialize an integer property to JSON") {
      val json = serializedNodeWithProperty(new java.lang.Integer(42))
      json.getInt("foo") should equal(42)
      json.toString should include("\"foo\":42")
    }

    it("should unserialize an integer property from JSON") {
      new JSONObject().put("foo", 42) toNode { node =>
        node.getProperty("foo") should equal(42)
      }
    }

    it("should serialize a double property to JSON") {
      val json = serializedNodeWithProperty(new java.lang.Double(4.2))
      json.getDouble("foo") should equal(4.2)
      json.toString should include("\"foo\":4.2")
    }

    it("should unserialize a double property from JSON") {
      new JSONObject().put("foo", 4.2) toNode { node =>
        node.getProperty("foo") should equal(4.2)
      }
    }

    it("should serialize an outgoing relationship to JSON") {
      Neo4jServer.exec { neo =>
        val node1 = neo.createNode
        val node2 = neo.createNode
        node1.createRelationshipTo(node2, DynamicRelationshipType.withName("REL"))
        val json = Neo4jJsonConverter.neoToJson(node1)
        json.getJSONObject("_out").getJSONObject("REL").getInt("_end") should equal(node2.getId)
        json.toString should include("\"_out\":{\"REL\":{\"_end\":%d}}".format(node2.getId))
      }
    }

    it("should serialize an incoming relationship to JSON") {
      Neo4jServer.exec { neo =>
        val node1 = neo.createNode
        val node2 = neo.createNode
        node1.createRelationshipTo(node2, DynamicRelationshipType.withName("REL"))
        val json = Neo4jJsonConverter.neoToJson(node2)
        json.getJSONObject("_in").getJSONObject("REL").getInt("_start") should equal(node1.getId)
        json.toString should include("\"_in\":{\"REL\":{\"_start\":%d}}".format(node1.getId))
      }
    }

    it("should serialize several relationships of the same type to a JSON array") {
      Neo4jServer.exec { neo =>
        val node1 = neo.createNode
        val node2 = neo.createNode
        val node3 = neo.createNode
        node1.createRelationshipTo(node2, DynamicRelationshipType.withName("REL"))
        node1.createRelationshipTo(node3, DynamicRelationshipType.withName("REL"))
        val json = Neo4jJsonConverter.neoToJson(node1)
        val arr = json.getJSONObject("_out").getJSONArray("REL")
        Set(arr.getJSONObject(0).getInt("_end"),
            arr.getJSONObject(1).getInt("_end")) should equal(Set(node2.getId, node3.getId))
      }
    }

    it("should serialize relationship properties to JSON") {
      Neo4jServer.exec { neo =>
        val node1 = neo.createNode
        val node2 = neo.createNode
        val rel = node1.createRelationshipTo(node2, DynamicRelationshipType.withName("REL"))
        rel.setProperty("hello", "world")
        val json = Neo4jJsonConverter.neoToJson(node1).getJSONObject("_out").getJSONObject("REL")
        json.getInt("_end") should equal(node2.getId)
        json.getString("hello") should equal("world")
      }
    }

    it("should unserialize a relationship given as just a plain ID") {
      val id = Neo4jServer.exec { _.createNode.getId }
      new JSONObject().put("_out",
        new JSONObject().put("REL", id)
      ) toNode { node =>
        node.getSingleRelationship(DynamicRelationshipType.withName("REL"),
                                   Direction.OUTGOING).getEndNode.getId should equal(id)
      }
    }

    it("should unserialize multiple relationships given as array of IDs") {
      val (id1, id2) = Neo4jServer.exec { neo => (neo.createNode.getId, neo.createNode.getId) }
      new JSONObject().put("_out",
        new JSONObject().put("REL", new JSONArray().put(id1).put(id2))
      ) toNode { node =>
        val iter = node.getRelationships(DynamicRelationshipType.withName("REL"), Direction.OUTGOING).iterator
        Set(iter.next.getEndNode.getId, iter.next.getEndNode.getId) should equal(Set(id1, id2))
      }
    }

    it("should unserialize a relationship given as hash") {
      val id = Neo4jServer.exec { _.createNode.getId }
      new JSONObject().put("_out",
        new JSONObject().put("REL", new JSONObject().put("_end", id))
      ) toNode { node =>
        node.getSingleRelationship(DynamicRelationshipType.withName("REL"),
                                   Direction.OUTGOING).getEndNode.getId should equal(id)
      }
    }

    it("should unserialize a relationship with properties") {
      val id = Neo4jServer.exec { _.createNode.getId }
      new JSONObject().put("_in",
        new JSONObject().put("REL", new JSONObject().put("_start", id).put("foo", "bar"))
      ) toNode { node =>
        val rel = node.getSingleRelationship(DynamicRelationshipType.withName("REL"), Direction.INCOMING)
        rel.getStartNode.getId should equal(id)
        rel.getProperty("foo") should equal("bar")
      }
    }

    it("should unserialize multiple relationships given as array of hashes") {
      val (id1, id2) = Neo4jServer.exec { neo => (neo.createNode.getId, neo.createNode.getId) }
      new JSONObject().put("_in",
        new JSONObject().put("REL", new JSONArray().put(
          new JSONObject().put("_start", id1)
        ).put(
          new JSONObject().put("_start", id2)
        ))
      ) toNode { node =>
        val iter = node.getRelationships(DynamicRelationshipType.withName("REL"), Direction.INCOMING).iterator
        Set(iter.next.getStartNode.getId, iter.next.getStartNode.getId) should equal(Set(id1, id2))
      }
    }
  }
}


text:
require 'spec_helper'
require 'mspec/guards'
require 'mspec/helpers'

RSpec.describe Object, "#cp" do
  before :each do
    @source = tmp("source.txt")
    @copy = tmp("copied.txt")

    @contents = "This is a copy."
    File.open(@source, "w") { |f| f.write @contents }
  end

  after :each do
    File.delete @source if File.exist? @source
    File.delete @copy if File.exist? @copy
  end

  it "copies a file" do
    cp @source, @copy
    data = IO.read(@copy)
    expect(data).to eq(@contents)
    expect(data).to eq(IO.read(@source))
  end
end

RSpec.describe Object, "#touch" do
  before :all do
    @name = tmp("touched.txt")
  end

  after :each do
    File.delete @name if File.exist? @name
  end

  it "creates a file" do
    touch @name
    expect(File.exist?(@name)).to be_truthy
  end

  it "accepts an optional mode argument" do
    touch @name, "wb"
    expect(File.exist?(@name)).to be_truthy
  end

  it "overwrites an existing file" do
    File.open(@name, "w") { |f| f.puts "used" }
    expect(File.size(@name)).to be > 0

    touch @name
    expect(File.size(@name)).to eq(0)
  end

  it "yields the open file if passed a block" do
    touch(@name) { |f| f.write "touching" }
    expect(IO.read(@name)).to eq("touching")
  end
end

RSpec.describe Object, "#touch" do
  before :all do
    @name = tmp("subdir/touched.txt")
  end

  after :each do
    rm_r File.dirname(@name)
  end

  it "creates all the directories in the path to the file" do
    touch @name
    expect(File.exist?(@name)).to be_truthy
  end
end

RSpec.describe Object, "#mkdir_p" do
  before :all do
    @dir1 = tmp("/nested")
    @dir2 = @dir1 + "/directory"
    @paths = [ @dir2, @dir1 ]
  end

  after :each do
    File.delete @dir1 if File.file? @dir1
    @paths.each { |path| Dir.rmdir path if File.directory? path }
  end

  it "creates all the directories in a path" do
    mkdir_p @dir2
    expect(File.directory?(@dir2)).to be_truthy
  end

  it "raises an ArgumentError if a path component is a file" do
    File.open(@dir1, "w") { |f| }
    expect { mkdir_p @dir2 }.to raise_error(ArgumentError)
  end

  it "works if multiple processes try to create the same directory concurrently" do
    original = File.method(:directory?)
    expect(File).to receive(:directory?).at_least(:once) { |dir|
      ret = original.call(dir)
      if !ret and dir == @dir1
        Dir.mkdir(dir) # Simulate race
      end
      ret
    }
    mkdir_p @dir1
    expect(original.call(@dir1)).to be_truthy
  end
end

RSpec.describe Object, "#rm_r" do
  before :all do
    @topdir  = tmp("rm_r_tree")
    @topfile = @topdir + "/file.txt"
    @link    = @topdir + "/file.lnk"
    @socket  = @topdir + "/socket.sck"
    @subdir1 = @topdir + "/subdir1"
    @subdir2 = @subdir1 + "/subdir2"
    @subfile = @subdir1 + "/subfile.txt"
  end

  before :each do
    mkdir_p @subdir2
    touch @topfile
    touch @subfile
  end

  after :each do
    File.delete @link if File.exist? @link or File.symlink? @link
    File.delete @socket if File.exist? @socket
    File.delete @subfile if File.exist? @subfile
    File.delete @topfile if File.exist? @topfile

    Dir.rmdir @subdir2 if File.directory? @subdir2
    Dir.rmdir @subdir1 if File.directory? @subdir1
    Dir.rmdir @topdir if File.directory? @topdir
  end

  it "raises an ArgumentError if the path is not prefixed by MSPEC_RM_PREFIX" do
    expect { rm_r "some_file.txt" }.to raise_error(ArgumentError)
  end

  it "removes a single file" do
    rm_r @subfile
    expect(File.exist?(@subfile)).to be_falsey
  end

  it "removes multiple files" do
    rm_r @topfile, @subfile
    expect(File.exist?(@topfile)).to be_falsey
    expect(File.exist?(@subfile)).to be_falsey
  end

  platform_is_not :windows do
    it "removes a symlink to a file" do
      File.symlink @topfile, @link
      rm_r @link
      expect(File.exist?(@link)).to be_falsey
    end

    it "removes a symlink to a directory" do
      File.symlink @subdir1, @link
      rm_r @link
      expect do
        File.lstat(@link)
      end.to raise_error(Errno::ENOENT)
      expect(File.exist?(@subdir1)).to be_truthy
    end

    it "removes a dangling symlink" do
      File.symlink "non_existent_file", @link
      rm_r @link
      expect do
        File.lstat(@link)
      end.to raise_error(Errno::ENOENT)
    end

    it "removes a socket" do
      require 'socket'
      UNIXServer.new(@socket).close
      rm_r @socket
      expect(File.exist?(@socket)).to be_falsey
    end
  end

  it "removes a single directory" do
    rm_r @subdir2
    expect(File.directory?(@subdir2)).to be_falsey
  end

  it "recursively removes a directory tree" do
    rm_r @topdir
    expect(File.directory?(@topdir)).to be_falsey
  end
end


text:
import sys,csv
# import codecs
from datetime import date,datetime
from pyh import *
page = PyH('JIRA看板')

#默认只打印3列
PRT_COL = 3
NEW_LINE = ''
SPRINT_DATE = '0901'

class Utils():
    def __init__(self):
        self.p = 0;
    def add(self,param):
        self.p += param
        return self.p

utils = Utils()

# def readExcel():
#     '''Read'''
#     filePath = r"/Users/Nicholas/Documents/人员通讯信息——曲健2017.8.1.xlsx"
#     # 打开文件
#     wb = xlrd.open_workbook(filePath)

#     # 打开第一个sheet
#     sheet0 = wb.sheets()[0]
#     v = sheet0.cell(1,1).value

#     print(v)

def ReadFile(filePath,encoding):
    with codecs.open(filePath,"r",encoding) as f:
        return f.read()

def WriteFile(filePath,u,encoding):
    with codecs.open(filePath,"w",encoding) as f:
        f.write(u)

'''''
定义GBK_2_UTF8方法,用于转换文件存储编码
'''
def GBK_2_UTF8(src,dst):
    content = ReadFile(src,encoding='gbk')
    WriteFile(dst,content,encoding='utf_8')

def readCsv():
    srcPath = "/Users/Nicholas/Desktop/JIRA-ETS源数据2017.8.23.csv"
    dstPath = "/Users/Nicholas/Desktop/JIRA-ETS源数据2017.8.23-UT8.csv"
    # GBK_2_UTF8(srcPath,dstPath);

    # 预处理csv
    # 1. 按照类型(story,任务,子任务),parentid排序
    csvFile = open(srcPath, encoding='GBK',mode='r')
    csvData = csv.reader(csvFile, delimiter=',')
    # sort by team, issuetype, parentid
    sortedlist = sorted(csvData, key = lambda x: (x[53],x[4], x[3]))

    csvFile.close()

    # with open(dstPath, "w", newline = '') as f:
    #     fileWriter = csv.writer(f, delimiter=',')
    #     for row in sortedlist:
    #         if (row[0]=='主题') or ('ETS 0901 Sprint' not in row):
    #             continue
    #         fileWriter.writerow(row)
    # f.close()

    # 渲染出html页面和table的引用
    outerTab = renderHTMLTab()
    trLine  = 0

    i = 0
    for row in sortedlist:
        if (row[0]=='主题') or ('ETS 0901 Sprint' not in row):
            continue

        issuename   = row[0]
        issuekey    = row[1]
        issueid     = row[2]
        parentid    = row[3]
        issuetype   = row[4]
        owner       = row[14]
        estimate    = row[35]
        team        = row[53]
        epiclink    = row[57]

        i += 1

        if (i % PRT_COL == 1):
            trLine = outerTab << tr()

        parentRow = 0
        if (issuetype == 'Story') or (issuetype == r'任务'):
            parentRow = findNameByKey(sortedlist, epiclink)
        else:
            parentRow = findNameById(sortedlist, parentid)

        if parentRow is None:
            parentRow = ['','','','','','']

        renderCard(trLine, team, issuetype, issuekey, issuename, \
                    parentRow[4], parentRow[1], parentRow[0], owner, estimate )

        # if (issuetype == 'Story') or (issuetype == r'任务'):
        #     renderStory(trLine,issuename, epiclink)
        # elif (issuetype == r'子任务'):
        #     renderSubTask(trLine, parentid, issuename, owner, estimate)

    page.printOut('abc.html')

def findNameById(list, id):
    for row in list:
        if (row[2] == id):
            return row

def findNameByKey(list, key):
    for row in list:
        if (row[1] == key):
            return row

def renderHTMLTab():
    # 添加头信息
    page.head.addObj(charset)
    page.head.addObj("<style>body { font-family: Arial, Helvetica, sans-serif; font-size:14px; }" \
        + nl \
        # + "table tr td { border:1px solid #0094ff; }</style>")
        + ".bordercls {border:2px solid #212121;} </style>")

    # 添加table
    # 添加table
    outerTab = page << table(width="1300px", style="border-spacing:2px;")
    outerTab << tr() << td(width="300px") + td(width="300px") + td(width="300px") + td(width="300px")

    return outerTab
    # page.printOut('a.html')
    # page.printOut()

def renderCard(outerTab, team, issuetype, issuekey, issuename, parenttype, parentkey, parentname, owner, estimate):

    global NEW_LINE

    if (utils.add(1) % PRT_COL == 1):
        NEW_LINE = outerTab << tr()

    #story
    condition = 0
    tagbgcolor = "#88ca79"

    if (issuetype == r'任务'):
        condition = 1
        tagbgcolor ="#d3b1e2"
    elif (issuetype == r'子任务'):
        condition = 2
        tagbgcolor = "#e6a988"

    cardTab = NEW_LINE << td(width="300px") << table(width="100%", bgcolor=tagbgcolor)
    cardTab << tr() << td(width="70%") + td(width="30%")
    #标题是故事名称
    cardTab << tr() << td(colspan="2", height="50px", align="center", cl="bordercls") << b(showDesc(team, parenttype,parentkey,parentname))

    if condition == 0 :
        cardTab << tr() \
                  << td(rowspan="3", colspan="2", height="150px", align="left", valign="middle", cl="bordercls") \
                    << span(showDesc('', issuetype, issuekey, issuename))

    elif condition == 1 or condition == 2:
        ttr = cardTab << tr()
        ttr << td(rowspan="3", height="150px", cl="bordercls") << span(showDesc('', issuetype, issuekey, issuename))
        ttr << td(height="50px", cl="bordercls") << span(owner)
        cardTab <<  tr() << td(rowspan="2", cl="bordercls") << span(estimate)

# 拼装标题或者卡片描述
def showDesc(team, issuetype, issuekey, issuename):
    if (issuetype is None) or (issuetype == ''):
        return '-~~-'
    elif (team != ''):
        return team +" 团队<br/>[" + issuetype + "][" + issuekey + "]: " + issuename
    else:
        return "[" + issuetype + "][" + issuekey + "]: " + issuename

from jira import JIRA
from jira.resources import *
from jira.resources import Board
from jira.resources import GreenHopperResource
from jira.resources import Sprint

PRJ_ETS = "ETS"
# http://99.48.46.160:8080/rest/greenhopper/1.0/rapidviews/viewsData
JIRA_BOARD_URL="rapidviews/viewsData"
# http://99.48.46.160:8080/rest/greenhopper/1.0/xboard/plan/backlog/data.json?rapidViewId=97&selectedProjectKey=ETS
JIRA_BACKLOG_URL="xboard/plan/backlog/data.json?rapidViewId={boardId}&selectedProjectKey={projectName}"
JIRA_SUBTASK_URL="xboard/issue/details.json?rapidViewId={boardId}&issueIdOrKey={backlogKey}&loadSubtasks=true"

def jira():

    # 渲染出html页面和table的引用
    outerTab = renderHTMLTab()

    myoption1 = {
        "server": "http://99.48.46.160:8080",
        "context_path": "/",
        "rest_path": "api",
        "rest_api_version": "2",
        "agile_rest_path": GreenHopperResource.GREENHOPPER_REST_PATH, #默认的option是GreenHoper
        "agile_rest_api_version": "1.0",
        "verify": True,
        "resilient": True,
        "async": False,
        "client_cert": None,
        "check_update": False,
        "headers": {
            'Cache-Control': 'no-cache',
            'Accept': 'application/json;charset=UTF-8',  # default for REST
            'Content-Type': 'application/json',  # ;charset=UTF-8',
            'X-Atlassian-Token': 'no-check'}}
    jira_greenhopper = JIRA(options=myoption1, basic_auth=('nicholas.qu','****'))

    # myoption2 = {
    #     "server": "http://99.48.46.160:8080",
    #     "context_path": "/",
    #     "rest_path": "api",
    #     "rest_api_version": "2",
    #     "agile_rest_path": 'agile', #GreenHopperResource.AGILE_BASE_REST_PATH 默认的option是GreenHoper
    #     "agile_rest_api_version": "1.0",
    #     "verify": True,
    #     "resilient": True,
    #     "async": False,
    #     "client_cert": None,
    #     "check_update": False,
    #     "headers": {
    #         'Cache-Control': 'no-cache',
    #         'Accept': 'application/json;charset=UTF-8',  # default for REST
    #         'Content-Type': 'application/json',  # ;charset=UTF-8',
    #         'X-Atlassian-Token': 'no-check'}}
    # greenhopper不支持param的条件查询,只能自己过滤
    # jira_api2 = JIRA(options=myoption2, basic_auth=('nicholas.qu','****'))

    boards_json = jira_greenhopper._get_json(JIRA_BOARD_URL, base=GreenHopperResource.AGILE_BASE_URL)

    filtered_boards = []
    for board in boards_json['views']:
        if (board['name'].startswith("ETS-")):
            filtered_boards.append(board)

    for board in filtered_boards:

        board_id = board['id']
        board_name = board['name']

        backlogs_url = JIRA_BACKLOG_URL.replace("{projectName}",PRJ_ETS).replace("{boardId}", str(board_id))
        backlogs_json = jira_greenhopper._get_json(backlogs_url, base=GreenHopperResource.AGILE_BASE_URL)

        # 打印团队
        team = board_name[4:7].replace("团",'').replace("队",'')

        #只取当前sprint的backlog
        backlogids = []
        sprintname = ''
        for sprint in backlogs_json['sprints']:
            if (SPRINT_DATE in sprint['name']):
                backlogids = sprint['issuesIds']
                sprintname = sprint['name']
                break

        print(r'当前正在处理:' + team + '......\n    Sprint['+ sprintname + \
                    '] 共有 ' + str(len(backlogids)) + ' 个backlog' )

        for backlog in backlogs_json['issues']:
            backlogid = backlog['id']
            # 判断是否在sprint里
            if (backlogid not in backlogids):
                continue

            backlogtype   = backlog['typeName']
            backlogkey    = backlog['key']
            backlogname   = backlog['summary']

            parenttype  = 'Epic'
            try:
                parentkey = backlog['epicField']['epicKey']
            except Exception as e:
                parentkey = ''
            try:
                parentname = backlog['epicField']['text']
            except Exception as e:
                parentname = ''

            try:
                owner = backlog['assigneeName']
            except Exception as e:
                owner = ''

            estimate = ''

            # 打印故事或者任务
            renderCard(outerTab, team, backlogtype, backlogkey, backlogname, \
                    parenttype, parentkey, parentname, owner, estimate )

            subtasks_url = JIRA_SUBTASK_URL.replace("{boardId}", str(board_id)).replace("{backlogKey}", backlogkey)
            subtasks_json = jira_greenhopper._get_json(subtasks_url, base=GreenHopperResource.AGILE_BASE_URL)

            backlog_detail_tabs = subtasks_json['tabs']['defaultTabs']
            subtask_tab = backlog_detail_tabs[0]
            for tab in backlog_detail_tabs:
                if (tab['tabId'] == 'SUB_TASKS'):
                    subtask_tab = tab
                    break

            for subtask in tab['subtaskEntries']:
                issuetype   = '子任务'
                issuekey    = subtask['key']
                issuename   = subtask['summary']

                try:
                    owner = subtask['assignee']['name']
                except Exception as e:
                    owner = ''

                estimate = ''

                # 打印子任务
                renderCard(outerTab, team, issuetype, issuekey, issuename, \
                        backlogtype, backlogkey, backlogname, owner, estimate )

    page.printOut('abc.html')

    # myboards = jira_greenhopper.boards(name="ETS-")
    # mysprint  = ''
    # for myboard in myboards:
    #     print(str(myboard.id) + ' ' + myboard.name)
    #     mysprints = jira.sprints(myboard.id)

    #     for loopsprint in mysprints:
    #         if (SPRINT_DATE in loopsprint.name):
    #             mysprint = loopsprint
    #             break;
    # return

    # if mysprint == '':
    #     print(r'' + myboard.name + r' has not['+ SPRINT_DATE + '] sprint!')
    #     return

    # print('正在处理Sprint...' + mysprint.name + " [id=" + str(mysprint.id) + "]")

    # Issue Fields: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial
    # Agile Api: https://docs.atlassian.com/jira-software/REST/cloud/
    #            https://docs.atlassian.com/jira-software/REST/
    # Rest Api: https://docs.atlassian.com/jira/REST/6.4.6/?&_ga=2.163402428.121064973.1503830222-399981431.1503830222#api/2/search-search
    # JQL: https://confluence.atlassian.com/jira/advanced-searching-179442050.html
    # fields: https://confluence.atlassian.com/jira/advanced-searching-179442050.html#AdvancedSearching-fields
    # r_json = jira._get_json("search/?jql=cf[10601]="+ r"开发运营" + " AND sprint=" + str(mysprint.id) + " order by cf[10601], issuetype ")
    # r_json = jira._get_json("search/?jql=sprint=" + str(mysprint.id) + " order by cf[10601], issuetype ")

    # curr_team = ''
    # for myissue in r_json['issues']:

    #     issuename   = xstr(myissue['fields']['summary'])
    #     issuekey    = xstr(myissue['key'])
    #     issueid     = xstr(myissue['id'])
    #     issuetype   = xstr(myissue['fields']['issuetype']['name'])

    #     try:
    #         parentid = xstr(myissue['fields']['parent']['id'])
    #     except Exception as e:
    #         parentid = ''

    #     try:
    #         owner   = xstr(myissue['fields']['assignee']['displayName'])
    #     except Exception as e:
    #         owner = ''

    #     try:
    #         estimate = xstr(myissue['fields']['timeestimate'])
    #     except Exception as e:
    #         estimate = ''

    #     try:
    #         team = xstr(myissue['fields']['customfield_10601'][0]['value'])
    #     except Exception as e:
    #         team = ''

    #     try:
    #         epiclink = xstr(myissue['fields']['summary'])
    #     except Exception as e:
    #         epiclink = ''

    #     if (curr_team != team):
    #         print(r'当前正在处理:' + team + '......')
    #         curr_team = team

    #     print('issuename:'  + issuename)
    #     print('issuekey:'   + issuekey)
    #     print('issueid:'    + issueid)
    #     print('parentid:'   + parentid)
    #     print('issuetype:'  + issuetype)
    #     print('owner:'      + owner)
    #     print('estimate:'   + estimate)
    #     print('team:'       + team)
    #     print('epiclink:'   + epiclink)

        # i += 1

        # if (i % PRT_COL == 1):
        #     trLine = outerTab << tr()

        # parentRow = 0
        # if (issuetype == 'Story') or (issuetype == r'任务'):
        #     parentRow = findNameByKey(sortedlist, epiclink)
        # else:
        #     parentRow = findNameById(sortedlist, parentid)

        # if parentRow is None:
        #     parentRow = ['','','','','','']

def xstr(s):
    return '' if s is None else str(s)

if __name__ == '__main__':
    jira()


text:
package mimematcher

import (
	"testing"

	"github.com/richardlehane/siegfried/internal/persist"
	"github.com/richardlehane/siegfried/pkg/core"
)

var fmts = SignatureSet{"application/json", "application/json;v1", "text/plain", "x-world/x-3dmf", "application/x-cocoa"}

var sm core.Matcher

func init() {
	sm, _, _ = Add(nil, fmts, nil)
}

func TestJsonMatch(t *testing.T) {
	res, _ := sm.Identify("application/json;v1", nil)
	e := <-res
	if e.Index() != 1 {
		t.Errorf("Expecting 0, got %v", e)
	}
	e = <-res
	if e.Index() != 0 {
		t.Errorf("Expecting 1, got %v", e)
	}
	_, ok := <-res
	if ok {
		t.Error("Expecting a length of 2")
	}
}

func TestNoMatch(t *testing.T) {
	res, _ := sm.Identify("application/java", nil)
	_, ok := <-res
	if ok {
		t.Error("Should not match")
	}
}

func TestIO(t *testing.T) {
	str := sm.String()
	saver := persist.NewLoadSaver(nil)
	Save(sm, saver)
	if len(saver.Bytes()) < 10 {
		t.Errorf("Save mime matcher: too small, only got %v", saver.Bytes())
	}
	loader := persist.NewLoadSaver(saver.Bytes())
	newsm := Load(loader)
	str2 := newsm.String()
	if str != str2 {
		t.Errorf("Load mime matcher: expecting first matcher (%v), to equal second matcher (%v)", str, str2)
	}
}


text:
class DropActivity < Activity
  def self.from(message_type, description, booking_request)
    create(
      message: "#{message_from(message_type)}#{description}",
      booking_request_id: booking_request.id
    )
  end

  def self.message_from(message_type)
    return '' unless message_type

    message_type.humanize.downcase + ' - '
  end
end


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "primme.h"
#include "numerical_d.h"
#include "ortho_d.h"

/**********************************************************************
 * Function ortho - This routine orthonormalizes a block of of vectors
 * against other vectors in the same array, against a set of locked vectors,
 * and themselves.
 *
 * The following conditions must always be met:
 * ldBasis > 0, nLocal > 0, b1 >= 0, b2 >= 0, b2 >= b1, numLocked >= 0,
 * rworkSize > 0
 *
 * INPUT ARRAYS AND PARAMETERS
 * ---------------------------
 * ldBasis    Leading dimension of the basis
 * b1, b2     Range of indices of vectors to be orthonormalized
 *            (b1 can be zero, but b1 must be <= b2)
 * locked     Array that holds locked vectors if they are in-core
 * ldLocked   Leading dimension of locked
 * numLocked  Number of vectors in locked
 * nLocal     Number of rows of each vector stored on this node
 * machEps    Double machine precision
 *
 * lockFile   Handle of file containing the locked vectors
 * rworkSize  Length of rwork array
 * primme     Primme struct. Contains globalSumDouble and Parallelism info
 *
 * INPUT/OUTPUT ARRAYS AND PARAMETERS
 * ----------------------------------
 * basis   Basis vectors stored in core memory
 * iseed   Seeds used to generate random vectors
 * rwork   Contains buffers and other necessary work arrays
 *
 * Return Value
 * ------------
 * >0  - Insufficient workspace provided.  Positive number indicates
 *       appropriate amount.
 *  0  - success
 * -1  - some size or leading dimension was < 0
 * -2  - b1 > b2
 * -3  - A limit number of randomizations has been performed without
 *  	 yielding an orthogonal direction
 *
 **********************************************************************/

int ortho_dprimme(double *basis, int ldBasis, int b1, int b2,
   double *locked, int ldLocked, int numLocked, int nLocal, int *iseed,
   double machEps, double *rwork, int rworkSize, primme_params *primme) {

   int i;                   // Loop indices
   int count;
   int returnValue;
   int minWorkSize;
   int nOrth, reorth;
   int randomizations;
   int messages = 0;        // messages = 1 prints the intermediate results
   int maxNumOrthos = 2;    // We let 2 reorthogonalization before we randomize
   int maxNumRandoms = 10;  // We do not allow more than 10 randomizations
   double tol = sqrt(2.0L)/2.0L; // We set Daniel et al. test to .707
   double s0, s02, s1;
   double temp;
   double ztmp;
   double *overlaps;
   double tpone = +1.0e+00, tzero = +0.0e+00, tmone = -1.0e+00;
   FILE *outputFile;

   // messages = (primme->procID == 0 && primme->printLevel >= 5);
   // outputFile = primme->outputFile;
   outputFile = stderr;

   returnValue = 0;

   //----------------------------------
   // input and workspace verification
   //----------------------------------
   if (ldBasis <= 0 || nLocal <= 0 || b1 < 0 || b2 < 0 || numLocked < 0
      || rworkSize < 0)
   {
      returnValue = -1;
   }
   else if (b1 > b2) {
      returnValue = -2;
   }

   if (returnValue != 0) {
      return(returnValue);
   }

   minWorkSize = 2*(numLocked + b2 + 1);

   if (rworkSize < minWorkSize) {
      return(minWorkSize);
   }

   tol = sqrt(2.0L)/2.0L;

   //---------------------------------------------------
   // main loop to orthogonalize new vectors one by one
   //---------------------------------------------------

   for(i=b1; i <= b2; i++) {

      nOrth = 0;
      reorth = 1;
      randomizations = 0;

      while (reorth) {

         if (nOrth >= maxNumOrthos) {
            if (randomizations >= maxNumRandoms) {
	       return -3;
	    }
	    if (messages){
               fprintf(outputFile, "Randomizing in ortho:\n");
	    }

            Num_larnv_dprimme(2, iseed, nLocal, &basis[ldBasis*i]);
	    randomizations++;
            nOrth = 0;
         }

         nOrth++;

         if (nOrth == 1) {
            ztmp = Num_dot_dprimme(nLocal, &basis[ldBasis*i], 1,
			                   &basis[ldBasis*i], 1);
         }

         if (i > 0) {
            Num_gemv_dprimme("C", nLocal, i, tpone, basis, ldBasis,
               &basis[ldBasis*i], 1, tzero, rwork, 1);
         }

         if (numLocked > 0) {
            Num_gemv_dprimme("C", nLocal, numLocked, tpone, locked, ldLocked,
               &basis[ldBasis*i], 1, tzero, &rwork[i], 1);
         }

         rwork[i+numLocked] = ztmp;
         overlaps = &rwork[i+numLocked+1];
	 count = i + numLocked + 1;
         (*primme->globalSumDouble)(rwork, overlaps, &count, primme);

         if (numLocked > 0) { // locked array most recently accessed
            Num_gemv_dprimme("N", nLocal, numLocked, tmone, locked, ldLocked,
               &overlaps[i], 1, tpone, &basis[ldBasis*i], 1);
         }

         if (i > 0) {
            Num_gemv_dprimme("N", nLocal, i, tmone, basis, ldBasis,
	       overlaps, 1, tpone, &basis[ldBasis*i], 1);
         }

         if (nOrth == 1) {
	    s02 = overlaps[i+numLocked];
            s0 = sqrt(s02);
         }

	 // Compute the norm of the resulting vector implicitly

	 temp = Num_dot_dprimme(i+numLocked,overlaps,1,overlaps,1);
	 s1 = sqrt(max(0.0L, s02-temp));

	 // s1 decreased too much. Numerical problems expected
         // with its implicit computation. Compute s1 explicitly

	 if ( s1 < s0*sqrt(machEps) || nOrth > 1) {
	    temp = Num_dot_dprimme(nLocal, &basis[ldBasis*i], 1,
			    		   &basis[ldBasis*i], 1);
	    count = 1;
	    (*primme->globalSumDouble)(&temp, &s1, &count, primme);
	    s1 = sqrt(s1);
	 }

         if (s1 <= machEps*s0) {
            if (messages) {
               fprintf(outputFile,
		 "Vector %d lost all significant digits in ortho\n", i-b1);
            }
            nOrth = maxNumOrthos;
         }
         else if (s1 <= tol*s0) {
            if (messages) {
               fprintf(outputFile, "Reorthogonalizing: %d\n", i-b1);
            }
	    // No numerical benefit in normalizing the vector before reortho
            s0 = s1;
	    s02 = s1*s1;
         }
         else {
	    if (nOrth > 1) {
	       // Previous reorthogonalizaton implies inaccurate norm s1 of
	       // resulting vector. Compute the numerically accurate one.
	       temp = Num_dot_dprimme(nLocal,&basis[ldBasis*i], 1,
			       		     &basis[ldBasis*i],1);
	       count = 1;
               (*primme->globalSumDouble)(&temp, &s1, &count, primme);
               s1 = sqrt(s1);
	    }
	    ztmp = 1.0L/s1;
            Num_scal_dprimme(nLocal, ztmp, &basis[ldBasis*i], 1);
            reorth = 0;
         }

      }
   }

   return 0;
}

/**********************************************************************
 * Function ortho_retained_vectors -- This function orthogonalizes
 *   coefficient vectors (the eigenvectors of the projection H) that
 *   are retained from a previous iteration.  The retained coefficient
 *   vectors are orthogonalized versus the coefficient vectors of the
 *   restarted basis.  This orthogonalizes previous and current Ritz
 *   vectors cheaply and without communication because the coefficient
 *   vectors are stored by each process.
 *
 * Input parameters
 * ----------------
 * currentVectors  Coefficient vectors from the current iteration to
 *    be orthogonalized against.
 *
 * length          The dimension of each vector
 *
 * numVectors      The number of current vectors
 *
 *
 * Input/Output parameters
 * -----------------------
 * previousVectors The coefficient vectors obtained from the previous iteration
 * 		   Note that their leading dimension is primme->maxBasisSize.
 *
 * numPrevious     The number of previous vectors to retain
 *
 * rwork           work array of size max(numVectors, numPrevious).  If it
 *                 is of size maxBasisSize, then it will always be sufficiently
 *                 large.
 *
 *
 * Return value
 * ------------
 * int   The number of previous vectors successfully orthogonalized
 *
 ****************************************************************************/

int ortho_retained_vectors_dprimme (double *currentVectors,
  int length, int numVectors, double *previousVectors, int numPrevious,
  double machEps, double *rwork) {

   int i;       /* Loop counter                                     */
   int nOrths;  /* Number of times a vector has been orthogonalized */
   int zeroed;  /* True if the vector norm was reduced below 1e-14  */
   double norm; /* Vector norm.                                     */
   double ztmp;/* Temp accumulation var  			    */
   		/* and some constants				    */
   double tpone = +1.0e+00, tzero = +0.0e+00, tmone = -1.0e+00;

   /* Orthogonalize each of the numPrevious vectors against the current */
   /* vectors and amongst themselves.                                   */

   i = 0;

   while (i < numPrevious) {
      zeroed = 0;

      /* Orthogonalize each vector twice to ensure numerical stability */

      for (nOrths = 0; nOrths < 3; nOrths++) {

         /* Orthogonalize versus the numVectors current vectors */

         Num_gemv_dprimme("C", length, numVectors, tpone, currentVectors,
	    length, &previousVectors[length*i], 1, tzero, rwork, 1);

         Num_gemv_dprimme("N", length, numVectors, tmone, currentVectors,
	    length, rwork, 1, tpone, &previousVectors[length*i], 1);

         /* Orthogonalize against the i previous vectors that have */
         /* been orthogonalized thus far.                          */

         if (i > 0) {
            Num_gemv_dprimme("C", length, i, tpone, previousVectors,
	       length, &previousVectors[length*i], 1, tzero, rwork, 1);

            Num_gemv_dprimme("N", length, i, tmone, previousVectors,
	       length, rwork, 1, tpone, &previousVectors[length*i], 1);
	 }

         norm = Num_dot_dprimme(length, &previousVectors[length*i], 1,
            				&previousVectors[length*i], 1);
         norm = sqrt(norm);

         if (norm < 5.0L*machEps) {
            numPrevious--;
            Num_dcopy_dprimme(length*(numPrevious-i),
	      &previousVectors[length*(i+1)], 1, &previousVectors[length*i], 1);
            zeroed = 1;
            break;
         }

	    ztmp = 1.0L/norm;
         Num_scal_dprimme(length, ztmp, &previousVectors[length*i], 1);

      } // for 3 reorthos

      if (!zeroed) {
         i++;
      }

   } // main while loop

   return numPrevious;
}


text:
package sep.gaia.controller.toolbar;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import sep.gaia.renderer.GaiaRenderer;
import sep.gaia.renderer.layer.ScreenshotLayer;

/**
 * This Listener launches creating a screenshot by setting a
 * specific flag in the GaiaRenderer class.
 *
 * Performance issues are avoided by not directly manipulating the flag or the
 * number of screenshots to be taken.
 *
 * A screenshot can only be requested, but the GaiaRenderer decides
 * when he is taking a screenshot.
 *
 * @author Johannes Bauer
 */
public class ScreenshotToolbarListener implements ActionListener {

	private ScreenshotLayer layer;

	public ScreenshotToolbarListener(ScreenshotLayer layer) {
		this.layer = layer;
	}

	 public void playSound() {
	        try {
	            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("/camera.wav"));
	            Clip clip = AudioSystem.getClip( );
	            clip.open(audioInputStream);
	            clip.start( );
	        }
	        catch(Exception e)  {
	            e.printStackTrace( );
	        }
	    }

	@Override
	public void actionPerformed(ActionEvent e) {

		playSound();
		GaiaRenderer.getInstance().requestScreenshot();

		if(layer != null) {
			layer.setActive(true);
		}

		Runnable disableRoutine = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(400);
				} catch (InterruptedException e) { }

				layer.setActive(false);
			}
		};

		new Thread(disableRoutine).start();
	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="arcUtility.cs" company="DigitalGlobe">
//   Copyright 2015 DigitalGlobe
//
//      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.
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Gbdx
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Text.RegularExpressions;

    using ESRI.ArcGIS.ArcMapUI;
    using ESRI.ArcGIS.Carto;
    using ESRI.ArcGIS.Display;
    using ESRI.ArcGIS.esriSystem;
    using ESRI.ArcGIS.Geodatabase;
    using ESRI.ArcGIS.Geometry;
    using ESRI.ArcGIS.LocationUI;

    using Path = System.IO.Path;

    /// <summary>
    /// The arc utility.
    /// </summary>
    internal class ArcUtility
    {
        /// <summary>
        /// The hit regex.
        /// </summary>
        public static readonly Regex HitRegex = new Regex("\"hits\":{\"total\":(?<hits>.*?),");

        /// <summary>
        /// The number random.
        /// </summary>
        private static readonly Random NumberRandom = new Random();

        #region Viewable Colors

        /// <summary>
        /// The colors.
        /// </summary>
        private static readonly IList<Color> Colors = new[]
        {
            Color.Magenta,
            Color.Indigo,
            Color.Aquamarine,
            Color.OrangeRed,
            Color.Blue,
            Color.Lime,
            Color.MediumBlue,
            Color.DarkMagenta,
            Color.Crimson,
            Color.YellowGreen,
            Color.DodgerBlue,
            Color.Brown,
            Color.MediumVioletRed,
            Color.DarkSalmon,
            Color.Aqua,
            Color.MediumSeaGreen,
            Color.Navy,
            Color.Orange,
            Color.Yellow,
            Color.BlueViolet,
            Color.LightSkyBlue,
            Color.DeepSkyBlue,
            Color.CadetBlue,
            Color.DarkSeaGreen,
            Color.DarkRed,
            Color.Gold,
            Color.Salmon,
            Color.MediumSlateBlue,
            Color.Cyan,
            Color.DarkTurquoise,
            Color.MediumPurple,
            Color.MediumAquamarine,
            Color.LightCoral,
            Color.Coral,
            Color.SaddleBrown,
            Color.LawnGreen,
            Color.GreenYellow,
            Color.Fuchsia,
            Color.DarkSlateBlue,
            Color.Chartreuse,
            Color.Black,
            Color.CornflowerBlue,
            Color.DarkCyan,
            Color.SpringGreen,
            Color.DarkOrange,
            Color.DeepPink,
            Color.IndianRed,
            Color.DarkOrchid,
            Color.RoyalBlue,
            Color.Tomato,
            Color.DarkBlue,
            Color.Red,
            Color.SeaGreen,
            Color.ForestGreen,
            Color.DarkOliveGreen,
            Color.MediumOrchid,
            Color.MediumSpringGreen,
            Color.Orchid,
            Color.DarkViolet,
            Color.Teal,
            Color.Green,
            Color.HotPink,
            Color.MediumTurquoise
        };

        #endregion
        /// <summary>
        /// The validate WGS 84 polygon.
        /// </summary>
        /// <param name="env">
        /// The env.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool ValidateWgs84Polygon(IEnvelope env)
        {
            if (env.IsEmpty || env.XMin < -180 || env.XMax > +180 || env.YMin < -90 || env.YMax > +90)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// The validate rounded WGS 84 polygon.
        /// </summary>
        /// <param name="env">
        /// The env.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool ValidateRoundedWgs84Polygon(IEnvelope env)
        {
            if (env.IsEmpty || Math.Round(env.XMin, 6) < -180 || Math.Round(env.XMax, 6) > +180 ||
                Math.Round(env.YMin, 6) < -90 || Math.Round(env.YMax, 6) > +90)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Converts screen coordinates to esri point coordinates
        /// </summary>
        /// <param name="screenPoint">
        /// the point on the screen
        /// </param>
        /// <param name="activeView">
        /// esri active view
        /// </param>
        /// <returns>
        /// Esri point transformed from screen coordinates
        /// </returns>
        public static IPoint GetMapCoordinatesFromScreenCoordinates(IPoint screenPoint, IActiveView activeView)
        {
            if (screenPoint == null || screenPoint.IsEmpty || activeView == null)
            {
                return null;
            }

            var screenDisplay = activeView.ScreenDisplay;
            var displayTransformation = screenDisplay.DisplayTransformation;

            return displayTransformation.ToMapPoint((int) screenPoint.X, (int) screenPoint.Y);
        }

        /// <summary>
        /// Deletes the targeted Element from the maps graphics container.
        /// </summary>
        /// <param name="activeView">
        /// active view of the map
        /// </param>
        /// <param name="target">
        /// element that is to be deleted.
        /// </param>
        public static void DeleteElementFromGraphicContainer(IActiveView activeView, IElement target)
        {
            // Delete element from graphics container.
            var graphicsContainer = activeView.GraphicsContainer;
            try
            {
                graphicsContainer.DeleteElement(target);

                // Do a partial refresh of only the layer that has been updated in this case
                // ViewGraphics.
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            catch
            {
                // We had a problem in attempting the deletion of the target element.
            }
        }

        /// <summary>
        /// The create table name.
        /// </summary>
        /// <param name="layerName">
        /// The layer name.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string CreateTableName(string layerName)
        {
            var output = string.Format("SMA_{0}_{1}", layerName, DateTime.Now.ToString("ddMMMHHmmss"));
            string regexSearch = new string(Path.GetInvalidFileNameChars()) +
                                 new string(Path.GetInvalidPathChars());
            var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            output = r.Replace(output, string.Empty);
            output = output.Replace(" ", "_");
            output = output.Replace("-", "_");
            Regex rgx = new Regex("[^a-zA-Z0-9]");
            output = rgx.Replace(output, string.Empty);
            return output;
        }

        /// <summary>
        /// Returns the distance between the two points
        /// </summary>
        /// <param name="point1">
        /// Point 1
        /// </param>
        /// <param name="point2">
        /// Point 2
        /// </param>
        /// <returns>
        /// The distance between the two points
        /// </returns>
        public static double DistanceTo(IPoint point1, IPoint point2)
        {
            var a = point2.X - point1.X;
            var b = point2.Y - point1.Y;

            return Math.Sqrt((a*a) + (b*b));
        }

        /// <summary>
        /// The add XY event layer.
        /// </summary>
        /// <param name="table">
        /// The table.
        /// </param>
        /// <param name="query">
        /// The query.
        /// </param>
        /// <param name="tweetShow">
        /// The tweet show.
        /// </param>
        public static void AddXyEventLayer(ITable table, string query, bool tweetShow = true)
        {
            var mxdoc = ArcMap.Application.Document as IMxDocument;
            if (mxdoc != null)
            {
                var map = mxdoc.FocusMap;

                // Get the table named XYSample.txt
                var stTableCollection = map as IStandaloneTableCollection;

                // Get the table name object
                var dataset = table as IDataset;
                var tableName = dataset.FullName;

                // Specify the X and Y fields
                var xyEvent2FieldsProperties = new XYEvent2FieldsProperties() as IXYEvent2FieldsProperties;
                if (xyEvent2FieldsProperties != null)
                {
                    xyEvent2FieldsProperties.XFieldName = "x";
                    xyEvent2FieldsProperties.YFieldName = "y";
                    xyEvent2FieldsProperties.ZFieldName = string.Empty;

                    // Specify the projection
                    var spatialReferenceFactory = new SpatialReferenceEnvironment() as ISpatialReferenceFactory;
                    var projectedCoordinateSystem =
                        spatialReferenceFactory.CreateGeographicCoordinateSystem(
                            (int) esriSRGeoCSType.esriSRGeoCS_WGS1984);

                    // Create the XY name object as set it's properties
                    var xyEventSourceName = new XYEventSourceName() as IXYEventSourceName;
                    xyEventSourceName.EventProperties = xyEvent2FieldsProperties;
                    xyEventSourceName.SpatialReference = projectedCoordinateSystem;
                    xyEventSourceName.EventTableName = tableName;

                    IName xyName = xyEventSourceName as IName;
                    IXYEventSource xyEventSource = xyName.Open() as IXYEventSource;

                    // Create a new Map Layer
                    IFeatureLayer featureLayer = new FeatureLayer() as IFeatureLayer;
                    featureLayer.FeatureClass = xyEventSource as IFeatureClass;
                    featureLayer.Name = query;

                    // Add the layer extension (this is done so that when you edit
                    // the layer's Source properties and click the Set Data Source
                    // button, the Add XY Events Dialog appears)
                    ILayerExtensions layerExtensions = featureLayer as ILayerExtensions;
                    XYDataSourcePageExtension resPageExtension = new XYDataSourcePageExtension();
                    layerExtensions.AddExtension(resPageExtension);

                    IGeoFeatureLayer geoLayer = (IGeoFeatureLayer) featureLayer;
                    ISimpleRenderer simpleRenderer = (ISimpleRenderer) geoLayer.Renderer;

                    var randomNumber = NumberRandom.Next(0, Colors.Count - 1);
                    var color = Colors[randomNumber];

                    IRgbColor rgbColor = new RgbColorClass();
                    rgbColor.Blue = color.B;
                    rgbColor.Red = color.R;
                    rgbColor.Green = color.G;

                    IMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass();
                    markerSymbol.Color = rgbColor;
                    markerSymbol.Size = 5;
                    simpleRenderer.Symbol = (ISymbol) markerSymbol;

                    try
                    {
                        map.AddLayer(featureLayer);
                    }
                    catch (Exception error)
                    {
                        Console.WriteLine(error.Message);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the length of a given Polyline. This function assumes that the Line is WGS84 Latitude, Longitude
        /// </summary>
        /// <param name="polyLine">
        /// Input Polyline
        /// </param>
        /// <returns>
        /// Length in KM
        /// </returns>
        public static double GetLength(IPolyline polyLine)
        {
            double distance = 0;

            //first check the Geometry's SR
            ISpatialReference sr = polyLine.SpatialReference;
            int factoryCode = sr.FactoryCode;
            if (factoryCode == 4326)
            {
                //this is in WGS 84 Lat long
                //iterate over the parts of the PolyLine
                var geomColl = (IGeometryCollection)polyLine;
                for (var i = 0; i < geomColl.GeometryCount; i++)
                {
                    var geom = geomColl.Geometry[i];
                    if (geom.GeometryType == esriGeometryType.esriGeometryPath)
                    {
                        //Now that we have a Path, we need to find the individual Segments
                        var segColl = (ISegmentCollection)geom;
                        for (int j = 0; j < segColl.SegmentCount; j++)
                        {
                            var segment = segColl.Segment[j];
                            if (segment.GeometryType == esriGeometryType.esriGeometryLine)
                            {
                                //Calculate the length of the segment and add it to running total
                                distance += GetHaverSineDistance(segment);
                            }
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Polyline is not in EPSG:4326");
            }

            return distance;
        }

        /// <summary>
        /// Returns the distance in kilometers of a segment
        /// </summary>
        /// <param name="seg">
        /// The ISegment whose Length is to be calculated
        /// </param>
        /// <returns>
        /// The length in KM
        /// </returns>
        private static double GetHaverSineDistance(ISegment seg)
        {
            // It's based on the code present at: "http://megocode3.wordpress.com/2008/02/05/haversine-formula-in-c/"
            const double R = 6371;
            double dLat = ToRadian(seg.ToPoint.Y - seg.FromPoint.Y);
            double dLong = ToRadian(seg.ToPoint.X - seg.FromPoint.X);

            double a = (Math.Sin(dLat/2)*Math.Sin(dLat/2)) +
                       (Math.Cos(ToRadian(seg.FromPoint.Y))*Math.Cos(ToRadian(seg.ToPoint.Y))*
                       Math.Sin(dLong/2)*Math.Sin(dLong/2));

            double c = 2*Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R*c;

            return d;
        }

        /// <summary>
        /// Convert to Radians.
        /// </summary>
        /// <param name="val">
        /// The angle is degrees
        /// </param>
        /// <returns>
        /// Angle in Radians
        /// </returns>
        private static double ToRadian(double val)
        {
            return (Math.PI / 180) * val;
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Blockly Demo: Realtime Collaboration</title>

Blockly >
    Demos > Realtime Collaboration

This is a simple demo of realtime collaboration in Blockly.

→ More info on

      realtime collaboration in Blockly...

  <xml id="toolbox" style="display: none">
    <block type="controls_if"></block>
    <block type="controls_repeat_ext"></block>
    <block type="logic_compare"></block>
    <block type="math_number"></block>
    <block type="math_arithmetic"></block>
    <block type="text"></block>
    <block type="text_print"></block>
  </xml>

Test realtime collaboration by opening

      this link in a separate browser window or tab and they will be
    synchronized.  You can even share the link with a friend!.

  <textarea id="chatbox" style="width: 26%; height: 12em" disabled="true"></textarea>