text:
<?php

namespace Clue\Tests\React\Quassel;

use Clue\React\Block;
use Clue\React\Quassel\Client;
use Clue\React\Quassel\Factory;
use Clue\React\Quassel\Io\Protocol;
use React\EventLoop\Loop;
use React\Socket\SocketServer;
use React\Socket\ConnectionInterface;

class FactoryIntegrationTest extends TestCase
{
    public function testCreateClientCreatesConnection()
    {
        $server = new SocketServer('127.0.0.1:0');
        $server->on('connection', $this->expectCallableOnce());

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientSendsProbeOverConnection()
    {
        $server = new SocketServer('127.0.0.1:0');

        $data = $this->expectCallableOnceWith("\x42\xb3\x3f\x00" . "\x00\x00\x00\x02" . "\x80\x00\x00\x01");
        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->on('data', $data);
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientResolvesIfServerRespondsWithProbeResponse()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->on('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        $client = Block\await($promise, Loop::get(), 10.0);

        $this->assertTrue($client instanceof Client);
        $client->close();
    }

    public function testCreateClientCreatesSecondConnectionWithoutProbeIfConnectionClosesDuringProbe()
    {
        $server = new SocketServer('127.0.0.1:0');

        $once = $this->expectCallableOnce();
        $server->on('connection', function (ConnectionInterface $conn) use ($once) {
            $conn->on('data', function () use ($conn) {
                $conn->close();
            });
            $conn->on('data', $once);
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientRejectsIfServerRespondsWithInvalidData()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->on('data', function () use ($conn) {
                $conn->write('invalid');
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthSendsClientInitAfterProbe()
    {
        $server = new SocketServer('127.0.0.1:0');

        $data = $this->expectCallableOnceWith($this->callback(function ($packet) {
            $data = FactoryIntegrationTest::decode($packet);

            return (isset($data->MsgType) && $data->MsgType === 'ClientInit');
        }));

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->on('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");
                $conn->on('data', $data);
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientWithAuthRejectsIfServerClosesAfterClientInit()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->on('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");
                $conn->on('data', function () use ($conn) {
                    $conn->close();
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthRejectsIfServerSendsClientInitRejectAfterClientInit()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->once('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");

                $conn->on('data', function () use ($conn) {
                    // respond with rejection
                    $conn->write(FactoryIntegrationTest::encode(array(
                        'MsgType' => 'ClientInitReject',
                        'Error' => 'Too old'
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthRejectsIfServerSendsUnknownMessageAfterClientInit()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->once('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");

                $conn->on('data', function () use ($conn) {
                    // respond with unknown message
                    $conn->write(FactoryIntegrationTest::encode(array(
                        'MsgType' => 'Unknown',
                        'Error' => 'Ignored'
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthRejectsIfServerSendsInvalidTruncatedResponseAfterClientInit()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->once('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");
                $conn->on('data', function () use ($conn) {
                    $conn->end("\x00\x00");
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthRejectsIfServerSendsClientInitAckNotConfigured()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->once('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");
                $conn->on('data', function () use ($conn) {
                    // respond with not configured
                    $conn->write(FactoryIntegrationTest::encode(array(
                        'MsgType' => 'ClientInitAck',
                        'Configured' => false
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        $this->setExpectedException('RuntimeException');
        Block\await($promise, Loop::get(), 10.0);
    }

    public function testCreateClientWithAuthSendsClientLoginAfterClientInit()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect login packet
        $data = $this->expectCallableOnceWith($this->callback(function ($packet) {
            $protocol = Protocol::createFromProbe(0x02);
            $data = $protocol->parseVariantPacket(substr($packet, 4));

            return (isset($data->MsgType, $data->User, $data->Password) && $data->MsgType === 'ClientLogin');
        }));

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");
                $conn->once('data', function () use ($conn, $data) {
                    // expect login next
                    $conn->on('data', $data);

                    // response with successful init
                    $conn->write(FactoryIntegrationTest::encode(array(
                        'MsgType' => 'ClientInitAck',
                        'Configured' => true
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient('user:pass@' . $uri);

        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientRespondsWithHeartBeatResponseAfterHeartBeatRequest()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect heartbeat response packet
        $data = $this->expectCallableOnceWith($this->callback(function ($packet) {
            $protocol = Protocol::createFromProbe(0x02);
            $data = $protocol->parseVariantPacket(substr($packet, 4));

            return (isset($data[0]) && $data[0] === Protocol::REQUEST_HEARTBEATREPLY);
        }));

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");

                // expect heartbeat response next
                $conn->on('data', $data);

                Loop::addTimer(0.01, function() use ($conn) {
                    // response with successful init
                    $conn->write(FactoryIntegrationTest::encode(array(
                        Protocol::REQUEST_HEARTBEAT,
                        new \DateTime('2018-05-29 23:05:00')
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri);

        Block\sleep(0.1, Loop::get());

        $client = Block\await($promise, Loop::get());
        $client->close();
    }

    public function testCreateClientDoesNotRespondWithHeartBeatResponseIfPongIsDisabled()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect no message in response
        $data = $this->expectCallableNever();

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");

                // expect no message in response
                $conn->on('data', $data);

                Loop::addTimer(0.01, function() use ($conn) {
                    // response with successful init
                    $conn->write(FactoryIntegrationTest::encode(array(
                        Protocol::REQUEST_HEARTBEAT,
                        new \DateTime('2018-05-29 23:05:00')
                    )));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri . '?pong=0');

        Block\sleep(0.1, Loop::get());

        $client = Block\await($promise, Loop::get());
        $client->close();
    }

    public function testCreateClientSendsHeartBeatRequestAtInterval()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect heartbeat response packet
        $data = $this->expectCallableOnceWith($this->callback(function ($packet) {
            $protocol = Protocol::createFromProbe(0x02);
            $data = $protocol->parseVariantPacket(substr($packet, 4));

            return (isset($data[0]) && $data[0] === Protocol::REQUEST_HEARTBEAT);
        }));

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");

                // expect heartbeat request next
                $conn->on('data', $data);
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri . '?ping=0.05');

        Block\sleep(0.1, Loop::get());

        $client = Block\await($promise, Loop::get());
        $client->close();
    }

    public function testCreateClientSendsNoHeartBeatRequestIfServerKeepsSendingMessages()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect heartbeat response packet
        $data = $this->expectCallableNever();

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");

                // expect no heartbeat request
                $conn->on('data', $data);

                // periodically send some dummy messages
                Loop::addPeriodicTimer(0.01, function() use ($conn) {
                    $conn->write(FactoryIntegrationTest::encode(array(0)));
                });
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri . '?ping=0.05&pong=0');

        Block\sleep(0.1, Loop::get());

        $client = Block\await($promise, Loop::get());
        $client->close();
    }

    public function testCreateClientClosesWithErrorIfServerDoesNotRespondToHeartBeatRequests()
    {
        $server = new SocketServer('127.0.0.1:0');

        $server->on('connection', function (ConnectionInterface $conn) {
            $conn->once('data', function () use ($conn) {
                $conn->write("\x00\x00\x00\x02");
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri . '?ping=0.03');

        $client = Block\await($promise, Loop::get(), 0.1);

        $client->on('error', $this->expectCallableOnce());
        $client->on('close', $this->expectCallableOnce());
        Block\sleep(0.1, Loop::get());
    }

    public function testCreateClientSendsNoHeartBeatRequestIfPingIsDisabled()
    {
        $server = new SocketServer('127.0.0.1:0');

        // expect heartbeat response packet
        $data = $this->expectCallableNever();

        $server->on('connection', function (ConnectionInterface $conn) use ($data) {
            $conn->once('data', function () use ($conn, $data) {
                $conn->write("\x00\x00\x00\x02");

                // expect no heartbeat request
                $conn->on('data', $data);
            });
        });

        $uri = str_replace('tcp://', '', $server->getAddress());
        $factory = new Factory();
        $promise = $factory->createClient($uri . '?ping=0');

        Block\sleep(0.1, Loop::get());

        $client = Block\await($promise, Loop::get());
        $client->close();
    }

    public static function encode($data)
    {
        $protocol = Protocol::createFromProbe(0x02);
        $packet = $protocol->serializeVariantPacket($data);

        return pack('N', strlen($packet)) . $packet;
    }

    public static function decode($packet)
    {
        $protocol = Protocol::createFromProbe(0x02);

        return $protocol->parseVariantPacket(substr($packet, 4));
    }
}


text:
		<?php

			echo "
" . $text . "
";

			$data = array('class' => 'form-horizontal');
			echo form_open('user/update_profile', $data);

			echo "<input type=\"hidden\" name=\"email\" value=\"" . $userInfo['email'] . "\" />";
			echo "<input type=\"hidden\" name=\"id\" value=\"" . $userInfo['id'] . "\" />";

			$data = array('class' => 'form-control', 'name' => 'nickname', 'placeholder' => $userInfo['nickname']);
			echo "
";
			echo '
';
			echo 'Nickname';
			echo form_input($data);
			echo '
';
			echo "
";

			$data = array('class' => 'form-control', 'name' => 'role', 'placeholder' => $userInfo['role']);
			echo "
";
			echo '
';
			echo 'Role';
			echo form_input($data);
			echo '
';
			echo "
";

			$data = array('class' => 'form-control', 'name' => 'password', 'placeholder' => 'Old Password');
			echo "
";
			echo form_password($data);
			echo "
";

			$data = array('class' => 'form-control', 'name' => 'newpassword', 'placeholder' => 'New Password');
			echo "
";
			echo form_password($data);
			echo "
";

			$data = array('class' => 'form-control', 'name' => 'cpassword', 'placeholder' => 'Confirm password');
			echo "
";
			echo form_password($data);
			echo "
";

			$data = array('class' => 'btn btn-default', 'name' => 'update_submit', 'value' => 'Update');
			echo "
";
			echo form_submit($data);
			echo "
";

			echo form_close();
		?>

		<?php
			echo validation_errors();
			if ($alert != '') {
				echo '
';
  				echo $alert;
				echo '
';
			}
		?>

redpajama_set_name: RedPajamaGithub


text:
"""Custom HTML builder.

This is used to verify that all snippets are ``doctest``-ed.

See http://www.sphinx-doc.org/en/stable/extdev/tutorial.html to learn
how to write a custom Sphinx extension.
"""

from sphinx import errors
from sphinx.writers import html

_LITERAL_ERR_TEMPLATE = """\
All literal blocks must either be used for doctest or explicitly
declared as a language other than Python. Current node:

{}

has combination of language ({!r}) and test node type ({!r}) which
are not allowed.
"""

class CustomHTMLWriter(html.HTMLTranslator):
    """Custom HTML writer.

    This makes sure that code blocks are all tested. It does this by
    asserting that a code block has a language other than Python **OR**
    that the code block has test node type ``doctest``.
    """

    def visit_literal_block(self, node):
        """Visit a ``literal_block`` node.

        This verifies the state of each literal / code block.
        """
        language = node.attributes.get("language", "")
        test_type = node.attributes.get("testnodetype", "")
        if test_type != "doctest":
            if language.lower() in ("", "python"):
                msg = _LITERAL_ERR_TEMPLATE.format(
                    node.rawsource, language, test_type
                )
                raise errors.ExtensionError(msg)

        # The base classes are not new-style, so we can't use super().
        return html.HTMLTranslator.visit_literal_block(self, node)

def setup(app):
    """Set-up this extension.

    Args:
        app (sphinx.application.Sphinx): A running Sphinx app.
    """
    app.set_translator("html", CustomHTMLWriter)


text:
FactoryGirl.define do
  factory :line_item, class: Spree::LineItem do
    quantity 1
    price { BigDecimal.new('10.00') }
    pre_tax_amount { price }
    order
    transient do
      association :product
    end
    variant{ product.master }
  end
end


text:
<TITLE>Review for Blair Witch Project, The (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Blair Witch Project, The (1999)

reviewed by
Jamey Hughton

THE BLAIR WITCH PROJECT
**** (out of five stars)
A review by Jamey Hughton

Starring-Heather Donahue, Michael Williams and Joshua Leonard
Directors-Eduardo Sanchez, Daniel Myrick
Rated 14A
Released July 1999
Artisan

For More "MOVIE VIEWS by Jamey Hughton"
Visit:  http://Welcome.to/MovieViews

The Blair Witch Project, a low-budget horror movie that scared audiences
silly at the Sundance Film Festival, has been receiving incredible
acclaim among moviegoers. Certain critics have dubbed it `the scariest
movie since The Exorcist'. I'll be honest with you: it ain't. But what
director tag-team Eduardo Sanchez and Daniel Myrick have achieved here
is nothing short of extraordinary: opening the imagination to a world of
frightening possibilities. Tell yourself calmly `It isn't real' before
you enter the theater, and all should go smoothly.

The Blair Witch is a mythical creature said to live in the backwoods of
a small town called Burkitsville, Maryland. There have been many
campfire stories told about the murders of children and other
frightening occurrences, but no solid proof that the witch in question
ever existed. Three young college students - Heather (Heather Donahue),
Mikey (Michael Williams) and Josh (Joshua Leonard) - have set out to
make a documentary of the Blair Witch. Food and supplies have been
packed for a 2 or 3 day venture into the woods, where they hope to find
historical landmarks that have a significance in their project. They
interview the locals and find it to be common knowledge. However,
neither three show any particular respect toward the legend; they merely
view it as a fun trip into the woods and a chance to get very drunk.

The entire 90-minutes of The Blair Witch Project is composed of choppy
footage that, we are told, was found one year later. There are two
cameras that the trio use: a full color hand-held camcorder operated by
Heather to record the documentary in process, and a larger one used by
Josh for real footage. Mikey, meanwhile, is the sound man.

Sanchez and Myrick have made this film as real as humanly possible. The
actors use their actual names, and the shoot was supposedly composed
largely of improvisation, brought on by fear of the dark woods. When
things become scary for the characters, the tension begins to build in
the audience. They find themselves lost in the woods, stumbling upon
frightening crosses and stick figures dangling from the trees. Some
monologues are carried on in a pitch black setting taking place in the
tent, and you can only imagine what's going on around them. Things
become creepier than creepy when the group begins to hear children's
voices, and other mysterious sounds, echoing through the woods in the
night. We're very thankful when daylight hits.

As spooky as all of this sounds, it is much scarier in the aftermath.
You will go over certain scenes in your mind - in fact, one character's
helpless screams are still repeating themselves in my head. The
performances are air-tight, especially by Williams and Leonard.
Occasionally, Heather Donahue's cries and outbursts of profanity seem
forced. But, she also owns the most effective scene in the movie, in
which she records her apologies to the group's parents while holding
back sobs of terror. `I'm too scared to close my eyes, and I'm too
scared to open them,' she explains.

Sanchez and Myrick have wrung this great premise for every ounce of
possible fear. It is not so horrific that you'll find yourself quivering
in your seat, but it is scary. The ending contains one of the most
frightening frames in movie history. And, with only one scene of brief
violence, the directors have largely succeeded in proving one fact: that
images the imagination can conjure up are far more frightening than
anything shown on film. The Blair Witch Project is no phenomenon, but it
is very, very well done.

(C) 1999, Jamey Hughton

MOVIE VIEWS by Jamey Hughton:  http://Welcome.to/MovieViews
.......................

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.zengcanxiang.example;

import android.content.Context;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.zengcanxiang.baseAdapter.absListView.HelperAdapter;
import com.zengcanxiang.baseAdapter.absListView.HelperHolder;
import com.zengcanxiang.ptrlistviewfragment.ListViewFragment;

import java.util.ArrayList;
import java.util.List;

public class ExampleFragment extends ListViewFragment {
    private List<String> mList;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mList = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            mList.add(i + "");
        }
//        默认开启了刷新功能
//        installRefresh(true);
        installLoadMore(true);
        initOk();
    }

    @Override
    public void install() {
//      material风格head
//        materialHeadInstall();
//      文字头部head
        valueHeadInstall("zengcanxiang");
    }

    @Override
    protected void refresh() {
        Toast.makeText(getActivity(), "下拉刷新", Toast.LENGTH_SHORT).show();
        refreshComplete();
    }

    @Override
    protected void loadMore() {
        Toast.makeText(getActivity(), "加载更多", Toast.LENGTH_SHORT).show();
        loadMoreComplete();
    }

    @Override
    protected BaseAdapter bindAdapter() {
        return new MyAdapter(mList, getActivity(), R.layout.test_list_item, R.layout.test_list_item2);
    }

    //listView的适配器
    class MyAdapter extends HelperAdapter<String> {
        public MyAdapter(List data, Context context, int... layoutIds) {
            super(data, context, layoutIds);
        }

        @Override
        public int checkLayout(int position, String item) {
            if (position % 2 == 0) {
                return 1;
            }
            return 0;
        }

        @Override
        public void HelpConvert(HelperHolder helperHolder, int i, String s) {
            TextView testText = helperHolder.getView(R.id.testText);
            testText.setText(i + "");
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Mitt. bot. StSamml. , Münch. 1: 22 (1954)

#### Original name
Amphiloma heppianum Müll. Arg.

### Remarks
null


text:
name 'delivery-truck-build-cookbook'
maintainer 'Chef Delivery Team'
maintainer_email 'delivery-team@chef.io'
license 'Apache 2.0'
description 'Build the delivery-truck cookbook'
version '0.1.0'

depends 'delivery-truck'


text:
using System.Collections.Generic;

namespace Senparc.Weixin.QY.Entities
{
    public class ResponseMessageMpNews : ResponseMessageBase, IResponseMessageBase
    {
        public new virtual ResponseMsgType MsgType
        {
            get { return ResponseMsgType.MpNews; }
        }

        public int MpNewsArticleCount
        {
            get
            {
                return MpNewsArticles == null ? 0 : MpNewsArticles.Count;
            }
            set
            {
                //这里开放set只为了逆向从Response的Xml转成实体的操作一致性,没有实际意义。
            }
        }

        /// <summary>
        /// 文章列表,微信客户端只能输出前10条(可能未来数字会有变化,出于视觉效果考虑,建议控制在8条以内)
        /// </summary>
        public List<MpNewsArticle> MpNewsArticles { get; set; }

        public ResponseMessageMpNews()
        {
            MpNewsArticles = new List<MpNewsArticle>();
        }
    }
}


text:
package qibo.org.myapptools.utils;

import android.content.Context;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * author:jmm
 * date:2017/1/5 20:34
 * e-mail:jianmingmi@foxmail.com
 */
public class BaseUtil {
    /**
     * 将map型转为请求参数型
     */
    public static String map2str(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * getVersionCode
     */
    public static int getVersionCode(Context context) {
        int result = 0;
        try {
            String pkName = context.getPackageName();
            int versionCode = context.getPackageManager().getPackageInfo(pkName, 0).versionCode;
            result = versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}


text:
package com.yahoo.time;

import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.test.ManualClock;
import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.Optional;

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

public class TimeBudgetTest {

    @Test
    public void testBasics() {
        ManualClock clock = new ManualClock();
        clock.setInstant(Instant.ofEpochSecond(0));
        TimeBudget timeBudget = TimeBudget.fromNow(clock, Duration.ofSeconds(10));

        clock.advance(Duration.ofSeconds(7));
        assertEquals(Duration.ofSeconds(3), timeBudget.timeLeftOrThrow().get());

        // Verify that toMillis() of >=1 is fine, but 0 is not.

        clock.setInstant(Instant.ofEpochSecond(9, 999000000));
        assertEquals(1, timeBudget.timeLeftOrThrow().get().toMillis());
        clock.setInstant(Instant.ofEpochSecond(9, 999000001));
        try {
            timeBudget.timeLeftOrThrow();
            fail();
        } catch (UncheckedTimeoutException e) {
            // OK
        }
    }

    @Test
    public void noDeadline() {
        ManualClock clock = new ManualClock();
        clock.setInstant(Instant.ofEpochSecond(0));
        TimeBudget timeBudget = TimeBudget.from(clock, clock.instant(), Optional.empty());

        assertFalse(timeBudget.originalTimeout().isPresent());
        assertFalse(timeBudget.timeLeftOrThrow().isPresent());
        assertFalse(timeBudget.deadline().isPresent());
    }
}


text:
This folder contains example applications to demonstrate the use of Sarama. For code snippet examples on how to use the different types in Sarama, see [Sarama's API documentation on pkg.go.dev](https://pkg.go.dev/github.com/Shopify/sarama)

In these examples, we use `github.com/Shopify/sarama` as import path. We do this to ensure all the examples are up to date with the latest changes in Sarama. For your own applications, you may want to use `gopkg.in/Shopify/sarama.v1` to lock into a stable API version.

#### HTTP server

[http_server](./http_server) is a simple HTTP server uses both the sync producer to produce data as part of the request handling cycle, as well as the async producer to maintain an access log. It also uses the [mocks subpackage](https://pkg.go.dev/github.com/Shopify/sarama/mocks) to test both.

#### Interceptors

Basic example to use a producer interceptor that produces [OpenTelemetry](https://github.com/open-telemetry/opentelemetry-go/) spans and add some headers for each intercepted message.

#### Transactional Producer

[txn_producer](./txn_producer) Basic example to use a transactional producer that produce on some topic within a Kafka transaction. To ensure transactional-id uniqueness it implement some ***ProducerProvider*** that build a producer appending an integer that grow when producer is created.

#### Exacly-once transactional paradigm

[exactly_once](./exactly_once) Basic example to use a transactional producer that produce consumed message from some topics within a Kafka transaction. To ensure transactional-id uniqueness it implement some ***ProducerProvider*** that build a producer using current message topic-partition.


text:
$(function() {
    $('.btn-approve').click(function() {
        var listItem = $(this).closest('.list-group-item');
        var versionPath = listItem.data('version');
        var icon = toggleSpinner($(this).find('[data-fa-i2svg]').removeClass('fa-thumbs-up'));
        $.ajax({
            type: 'post',
            url: '/' + versionPath + '/approve',
            complete: function() { toggleSpinner($('.btn-approve').find('[data-fa-i2svg]').addClass('fa-thumbs-up')); },
            success: function() {
                $.when(listItem.fadeOut('slow')).done(function() {
                    listItem.remove();
                    if (!$('.list-versions').find('li').length) {
                        $('.no-versions').fadeIn();
                        clearUnread($('a[href="/admin/queue"]'));
                    }
                });
            }
        });
    });
});


text:
package org.openspaces.admin.internal.gsc;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.openspaces.admin.Admin;
import org.openspaces.admin.AdminException;
import org.openspaces.admin.dump.CompoundDumpResult;
import org.openspaces.admin.dump.DumpResult;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.gsc.events.ElasticGridServiceContainerProvisioningFailureEvent;
import org.openspaces.admin.gsc.events.ElasticGridServiceContainerProvisioningFailureEventManager;
import org.openspaces.admin.gsc.events.ElasticGridServiceContainerProvisioningProgressChangedEvent;
import org.openspaces.admin.gsc.events.ElasticGridServiceContainerProvisioningProgressChangedEventManager;
import org.openspaces.admin.gsc.events.GridServiceContainerAddedEventListener;
import org.openspaces.admin.gsc.events.GridServiceContainerAddedEventManager;
import org.openspaces.admin.gsc.events.GridServiceContainerLifecycleEventListener;
import org.openspaces.admin.gsc.events.GridServiceContainerRemovedEventListener;
import org.openspaces.admin.gsc.events.GridServiceContainerRemovedEventManager;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.gsa.events.InternalElasticGridServiceContainerProvisioningFailureEventManager;
import org.openspaces.admin.internal.gsc.events.DefaultElasticGridServiceContainerProvisioningFailureEventManager;
import org.openspaces.admin.internal.gsc.events.DefaultElasticGridServiceContainerProvisioningProgressChangedEventManager;
import org.openspaces.admin.internal.gsc.events.DefaultGridServiceContainerAddedEventManager;
import org.openspaces.admin.internal.gsc.events.DefaultGridServiceContainerRemovedEventManager;
import org.openspaces.admin.internal.gsc.events.InternalElasticGridServiceContainerProvisioningProgressChangedEventManager;
import org.openspaces.admin.internal.gsc.events.InternalGridServiceContainerAddedEventManager;
import org.openspaces.admin.internal.gsc.events.InternalGridServiceContainerRemovedEventManager;
import org.openspaces.admin.pu.elastic.events.ElasticProcessingUnitEvent;

import com.j_spaces.kernel.SizeConcurrentHashMap;

/**
 * @author kimchy
 */
public class DefaultGridServiceContainers implements InternalGridServiceContainers {

    private final InternalAdmin admin;

    private final Map<String, GridServiceContainer> containers = new SizeConcurrentHashMap<String, GridServiceContainer>();

    private final InternalGridServiceContainerAddedEventManager gridServiceContainerAddedEventManager;

    private final InternalGridServiceContainerRemovedEventManager gridServiceContainerRemovedEventManager;

    private final InternalElasticGridServiceContainerProvisioningFailureEventManager elasticGridServiceContainerProvisioningFailureEventManager;

    private final InternalElasticGridServiceContainerProvisioningProgressChangedEventManager elasticGridServiceContainerProvisioningProgressChangedEventManager;

    public DefaultGridServiceContainers(InternalAdmin admin) {
        this.admin = admin;
        this.gridServiceContainerAddedEventManager = new DefaultGridServiceContainerAddedEventManager(this);
        this.gridServiceContainerRemovedEventManager = new DefaultGridServiceContainerRemovedEventManager(this);
        this.elasticGridServiceContainerProvisioningFailureEventManager = new DefaultElasticGridServiceContainerProvisioningFailureEventManager(admin);
        this.elasticGridServiceContainerProvisioningProgressChangedEventManager = new DefaultElasticGridServiceContainerProvisioningProgressChangedEventManager(admin);
    }

    public Admin getAdmin() {
        return this.admin;
    }

    public GridServiceContainerAddedEventManager getGridServiceContainerAdded() {
        return this.gridServiceContainerAddedEventManager;
    }

    public GridServiceContainerRemovedEventManager getGridServiceContainerRemoved() {
        return this.gridServiceContainerRemovedEventManager;
    }

    public GridServiceContainer[] getContainers() {
        return containers.values().toArray(new GridServiceContainer[0]);
    }

    public GridServiceContainer getContainerByUID(String uid) {
        return containers.get(uid);
    }

    public Map<String, GridServiceContainer> getUids() {
        return Collections.unmodifiableMap(containers);
    }

    public int getSize() {
        return containers.size();
    }

    public boolean isEmpty() {
        return containers.isEmpty();
    }

    public boolean waitFor(int numberOfGridServiceContainers) {
        return waitFor(numberOfGridServiceContainers, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit());
    }

    public boolean waitFor(int numberOfGridServiceContainers, long timeout, TimeUnit timeUnit) {
        if (numberOfGridServiceContainers == 0) {
            final CountDownLatch latch = new CountDownLatch(getSize());
            GridServiceContainerRemovedEventListener removed = new GridServiceContainerRemovedEventListener() {
                public void gridServiceContainerRemoved(GridServiceContainer gridServiceContainer) {
                    latch.countDown();
                }
            };
            getGridServiceContainerRemoved().add(removed);
            try {
                return latch.await(timeout, timeUnit);
            } catch (InterruptedException e) {
                return false;
            } finally {
                getGridServiceContainerRemoved().remove(removed);
            }
        } else {
            final CountDownLatch latch = new CountDownLatch(numberOfGridServiceContainers);
            GridServiceContainerAddedEventListener added = new GridServiceContainerAddedEventListener() {
                public void gridServiceContainerAdded(GridServiceContainer gridServiceContainer) {
                    latch.countDown();
                }
            };
            getGridServiceContainerAdded().add(added);
            try {
                return latch.await(timeout, timeUnit);
            } catch (InterruptedException e) {
                return false;
            } finally {
                getGridServiceContainerAdded().remove(added);
            }
        }
    }

    public void addLifecycleListener(GridServiceContainerLifecycleEventListener eventListener) {
        getGridServiceContainerAdded().add(eventListener);
        getGridServiceContainerRemoved().add(eventListener);
    }

    public void removeLifecycleListener(GridServiceContainerLifecycleEventListener eventListener) {
        getGridServiceContainerAdded().remove(eventListener);
        getGridServiceContainerRemoved().remove(eventListener);
    }

    public Iterator<GridServiceContainer> iterator() {
        return Collections.unmodifiableCollection(containers.values()).iterator();
    }

    public void addGridServiceContainer(final InternalGridServiceContainer gridServiceContainer) {
        assertStateChangesPermitted();
        final GridServiceContainer existingGSC = containers.put(gridServiceContainer.getUid(), gridServiceContainer);
        if (existingGSC == null) {
            gridServiceContainerAddedEventManager.gridServiceContainerAdded(gridServiceContainer);
        }
    }

    public InternalGridServiceContainer removeGridServiceContainer(String uid) {
        assertStateChangesPermitted();
        final InternalGridServiceContainer existingGSC = (InternalGridServiceContainer) containers.remove(uid);
        if (existingGSC != null) {
            gridServiceContainerRemovedEventManager.gridServiceContainerRemoved(existingGSC);
        }
        return existingGSC;
    }

    public DumpResult generateDump(String cause, Map<String, Object> context) throws AdminException {
        return generateDump(cause, context, (String[]) null);
    }

    public DumpResult generateDump(String cause, Map<String, Object> context, String... processor) throws AdminException {
        CompoundDumpResult dumpResult = new CompoundDumpResult();
        for (GridServiceContainer gsc : this) {
            dumpResult.add(gsc.generateDump(cause, context, processor));
        }
        return dumpResult;
    }

    private void assertStateChangesPermitted() {
        admin.assertStateChangesPermitted();
    }

    @Override
    public ElasticGridServiceContainerProvisioningFailureEventManager getElasticGridServiceContainerProvisioningFailure() {
        return elasticGridServiceContainerProvisioningFailureEventManager;
    }

    @Override
    public ElasticGridServiceContainerProvisioningProgressChangedEventManager getElasticGridServiceContainerProvisioningProgressChanged() {
        return elasticGridServiceContainerProvisioningProgressChangedEventManager;
    }

    @Override
    public void processElasticScaleStrategyEvent(ElasticProcessingUnitEvent event) {
        if (event instanceof ElasticGridServiceContainerProvisioningFailureEvent) {
            elasticGridServiceContainerProvisioningFailureEventManager.elasticGridServiceContainerProvisioningFailure((ElasticGridServiceContainerProvisioningFailureEvent)event);
        }
        else if (event instanceof ElasticGridServiceContainerProvisioningProgressChangedEvent) {
            elasticGridServiceContainerProvisioningProgressChangedEventManager.elasticGridServiceContainerProvisioningProgressChanged((ElasticGridServiceContainerProvisioningProgressChangedEvent)event);
        }
    }
}


text:
Page top, © @name @current_year, GFDL

@site_name, <?php $time = microtime(); echo number_format($time, 2) . "s loading"; ?>, RSS


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Security.Permissions
{
    using System;
    using System.Data;
    using System.Xml.Serialization;

    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;

    /// -----------------------------------------------------------------------------
    /// Project  : DotNetNuke
    /// Namespace: DotNetNuke.Security.Permissions
    /// Class    : PermissionInfoBase
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// PermissionInfoBase provides a base class for PermissionInfo classes.
    /// </summary>
    /// <remarks>All Permission calsses have  a common set of properties
    ///   - AllowAccess
    ///   - RoleID
    ///   - RoleName
    ///   - UserID
    ///   - Username
    ///   - DisplayName
    ///
    /// and these are implemented in this base class.
    /// </remarks>
    /// -----------------------------------------------------------------------------
    [Serializable]
    public abstract class PermissionInfoBase : PermissionInfo
    {
        private bool allowAccess;
        private string displayName;
        private int roleID;
        private string roleName;
        private int userID;
        private string username;

        /// <summary>
        /// Initializes a new instance of the <see cref="PermissionInfoBase"/> class.
        /// </summary>
        public PermissionInfoBase()
        {
            this.roleID = int.Parse(Globals.glbRoleNothing);
            this.allowAccess = false;
            this.roleName = Null.NullString;
            this.userID = Null.NullInteger;
            this.username = Null.NullString;
            this.displayName = Null.NullString;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets a value indicating whether gets and sets  aflag that indicates whether the user or role has permission.
        /// </summary>
        /// <returns>A Boolean.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("allowaccess")]
        public bool AllowAccess
        {
            get
            {
                return this.allowAccess;
            }

            set
            {
                this.allowAccess = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the User's DisplayName.
        /// </summary>
        /// <returns>A String.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("displayname")]
        public string DisplayName
        {
            get
            {
                return this.displayName;
            }

            set
            {
                this.displayName = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the Role ID.
        /// </summary>
        /// <returns>An Integer.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("roleid")]
        public int RoleID
        {
            get
            {
                return this.roleID;
            }

            set
            {
                this.roleID = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the Role Name.
        /// </summary>
        /// <returns>A String.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("rolename")]
        public string RoleName
        {
            get
            {
                return this.roleName;
            }

            set
            {
                this.roleName = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the User ID.
        /// </summary>
        /// <returns>An Integer.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("userid")]
        public int UserID
        {
            get
            {
                return this.userID;
            }

            set
            {
                this.userID = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the User Name.
        /// </summary>
        /// <returns>A String.</returns>
        /// -----------------------------------------------------------------------------
        [XmlElement("username")]
        public string Username
        {
            get
            {
                return this.username;
            }

            set
            {
                this.username = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// FillInternal fills the PermissionInfoBase from a Data Reader.
        /// </summary>
        /// <param name="dr">The Data Reader to use.</param>
        /// -----------------------------------------------------------------------------
        protected override void FillInternal(IDataReader dr)
        {
            // Call the base classes fill method to populate base class proeprties
            base.FillInternal(dr);

            this.UserID = Null.SetNullInteger(dr["UserID"]);
            this.Username = Null.SetNullString(dr["Username"]);
            this.DisplayName = Null.SetNullString(dr["DisplayName"]);
            if (this.UserID == Null.NullInteger)
            {
                this.RoleID = Null.SetNullInteger(dr["RoleID"]);
                this.RoleName = Null.SetNullString(dr["RoleName"]);
            }
            else
            {
                this.RoleID = int.Parse(Globals.glbRoleNothing);
                this.RoleName = string.Empty;
            }

            this.AllowAccess = Null.SetNullBoolean(dr["AllowAccess"]);
        }
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DynamicRange extends AbstractTag
{

    protected $Id = '0018,5030';

    protected $Name = 'DynamicRange';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Dynamic Range';

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

internal static partial class Interop
{
    internal static partial class libcrypto
    {
        [DllImport(Libraries.LibCrypto)]
        private static extern uint ERR_get_error();

        [DllImport(Libraries.LibCrypto, CharSet = CharSet.Ansi)]
        private static extern void ERR_error_string_n(uint e, StringBuilder buf, int len);

        private static string ERR_error_string_n(uint error)
        {
            StringBuilder buf = new StringBuilder(1024);

            ERR_error_string_n(error, buf, buf.Capacity);
            return buf.ToString();
        }

        internal static Exception CreateOpenSslCryptographicException()
        {
            const uint ReasonMask = 0x0FFF;
            const uint ERR_R_MALLOC_FAILURE = 64 | 1;

            // The Windows cryptography library reports error codes through
            // Marshal.GetLastWin32Error, which has a single value when the
            // function exits, last writer wins.
            //
            // OpenSSL maintains an error queue. Calls to ERR_get_error read
            // values out of the queue in the order that ERR_set_error wrote
            // them. Nothing enforces that a single call into an OpenSSL
            // function will guarantee at-most one error being set.
            //
            // In order to maintain parity in how error flows look between the
            // Windows code and the OpenSSL-calling code, drain the queue
            // whenever an Exception is desired, and report the exception
            // related to the last value in the queue.
            uint error = ERR_get_error();
            uint lastRead = error;

            // 0 (there's no named constant) is only returned when the calls
            // to ERR_get_error exceed the calls to ERR_set_error.
            while (lastRead != 0)
            {
                error = lastRead;
                lastRead = ERR_get_error();
            }

            // If we're in an error flow which results in an Exception, but
            // no calls to ERR_set_error were made, throw the unadorned
            // CryptographicException.
            if (error == 0)
            {
                return new CryptographicException();
            }

            // Inline version of the ERR_GET_REASON macro.
            uint reason = error & ReasonMask;

            if (reason == ERR_R_MALLOC_FAILURE)
            {
                return new OutOfMemoryException();
            }

            // If there was an error code, and it wasn't something handled specially,
            // use the OpenSSL error string as the message to a CryptographicException.
            return new CryptographicException(ERR_error_string_n(error));
        }

        internal static void CheckValidOpenSslHandle(SafeHandle handle)
        {
            if (handle == null || handle.IsInvalid)
            {
                throw CreateOpenSslCryptographicException();
            }
        }

        internal static void CheckValidOpenSslHandle(IntPtr handle)
        {
            if (handle == IntPtr.Zero)
            {
                throw CreateOpenSslCryptographicException();
            }
        }
    }
}


text:
package javax.naming;

import java.util.Hashtable;

/**
  * This exception is thrown to indicate that the operation reached
  * a point in the name where the operation cannot proceed any further.
  * When performing an operation on a composite name, a naming service
  * provider may reach a part of the name that does not belong to its
  * namespace.  At that point, it can construct a
  * CannotProceedException and then invoke methods provided by
  * javax.naming.spi.NamingManager (such as getContinuationContext())
  * to locate another provider to continue the operation.  If this is
  * not possible, this exception is raised to the caller of the
  * context operation.
  *

  * If the program wants to handle this exception in particular, it
  * should catch CannotProceedException explicitly before attempting to
  * catch NamingException.
  *

  * A CannotProceedException instance is not synchronized against concurrent
  * multithreaded access. Multiple threads trying to access and modify
  * CannotProceedException should lock the object.
  *
  * @author Rosanna Lee
  * @author Scott Seligman
  * @since 1.3
  */

/*
  * The serialized form of a CannotProceedException object consists of
  * the serialized fields of its NamingException superclass, the remaining new
  * name (a Name object), the environment (a Hashtable), the altName field
  * (a Name object), and the serialized form of the altNameCtx field.
  */

public class CannotProceedException extends NamingException {
    /**
     * Contains the remaining unresolved part of the second
     * "name" argument to Context.rename().
     * This information necessary for
     * continuing the Context.rename() operation.
     *

     * This field is initialized to null.
     * It should not be manipulated directly:  it should
     * be accessed and updated using getRemainingName() and setRemainingName().
     * @serial
     *
     * @see #getRemainingNewName
     * @see #setRemainingNewName
     */
    protected Name remainingNewName = null;

    /**
     * Contains the environment
     * relevant for the Context or DirContext method that cannot proceed.
     *

     * This field is initialized to null.
     * It should not be manipulated directly:  it should be accessed
     * and updated using getEnvironment() and setEnvironment().
     * @serial
     *
     * @see #getEnvironment
     * @see #setEnvironment
     */
    protected Hashtable<?,?> environment = null;

    /**
     * Contains the name of the resolved object, relative
     * to the context altNameCtx.  It is a composite name.
     * If null, then no name is specified.
     * See the javax.naming.spi.ObjectFactory.getObjectInstance
     * method for details on how this is used.
     *

     * This field is initialized to null.
     * It should not be manipulated directly:  it should
     * be accessed and updated using getAltName() and setAltName().
     * @serial
     *
     * @see #getAltName
     * @see #setAltName
     * @see #altNameCtx
     * @see javax.naming.spi.ObjectFactory#getObjectInstance
     */
    protected Name altName = null;

    /**
     * Contains the context relative to which
     * altName is specified.  If null, then the default initial
     * context is implied.
     * See the javax.naming.spi.ObjectFactory.getObjectInstance
     * method for details on how this is used.
     *

     * This field is initialized to null.
     * It should not be manipulated directly:  it should
     * be accessed and updated using getAltNameCtx() and setAltNameCtx().
     * @serial
     *
     * @see #getAltNameCtx
     * @see #setAltNameCtx
     * @see #altName
     * @see javax.naming.spi.ObjectFactory#getObjectInstance
     */
    protected Context altNameCtx = null;

    /**
     * Constructs a new instance of CannotProceedException using an
     * explanation. All unspecified fields default to null.
     *
     * @param   explanation     A possibly null string containing additional
     *                          detail about this exception.
     *   If null, this exception has no detail message.
     * @see java.lang.Throwable#getMessage
     */
    public CannotProceedException(String explanation) {
        super(explanation);
    }

    /**
      * Constructs a new instance of CannotProceedException.
      * All fields default to null.
      */
    public CannotProceedException() {
        super();
    }

    /**
     * Retrieves the environment that was in effect when this exception
     * was created.
     * @return Possibly null environment property set.
     *          null means no environment was recorded for this exception.
     * @see #setEnvironment
     */
    public Hashtable<?,?> getEnvironment() {
        return environment;
    }

    /**
     * Sets the environment that will be returned when getEnvironment()
     * is called.
     * @param environment A possibly null environment property set.
     *          null means no environment is being recorded for
     *          this exception.
     * @see #getEnvironment
     */
    public void setEnvironment(Hashtable<?,?> environment) {
        this.environment = environment; // %%% clone it??
    }

    /**
     * Retrieves the "remaining new name" field of this exception, which is
     * used when this exception is thrown during a rename() operation.
     *
     * @return The possibly null part of the new name that has not been resolved.
     *          It is a composite name. It can be null, which means
     *          the remaining new name field has not been set.
     *
     * @see #setRemainingNewName
     */
    public Name getRemainingNewName() {
        return remainingNewName;
    }

    /**
     * Sets the "remaining new name" field of this exception.
     * This is the value returned by getRemainingNewName().
     *

     * <tt>newName</tt> is a composite name. If the intent is to set
     * this field using a compound name or string, you must
     * "stringify" the compound name, and create a composite
     * name with a single component using the string. You can then
     * invoke this method using the resulting composite name.
     *

     * A copy of newName is made and stored.
     * Subsequent changes to name does not
     * affect the copy in this NamingException and vice versa.
     *
     * @param newName The possibly null name to set the "remaining new name" to.
     *          If null, it sets the remaining name field to null.
     *
     * @see #getRemainingNewName
     */
    public void setRemainingNewName(Name newName) {
        if (newName != null)
            this.remainingNewName = (Name)(newName.clone());
        else
            this.remainingNewName = null;
    }

    /**
     * Retrieves the altName field of this exception.
     * This is the name of the resolved object, relative to the context
     * altNameCtx. It will be used during a subsequent call to the
     * javax.naming.spi.ObjectFactory.getObjectInstance method.
     *
     * @return The name of the resolved object, relative to
     *          altNameCtx.
     *          It is a composite name.  If null, then no name is specified.
     *
     * @see #setAltName
     * @see #getAltNameCtx
     * @see javax.naming.spi.ObjectFactory#getObjectInstance
     */
    public Name getAltName() {
        return altName;
    }

    /**
     * Sets the altName field of this exception.
     *
     * @param altName   The name of the resolved object, relative to
     *                  altNameCtx.
     *                  It is a composite name.
     *                  If null, then no name is specified.
     *
     * @see #getAltName
     * @see #setAltNameCtx
     */
    public void setAltName(Name altName) {
        this.altName = altName;
    }

    /**
     * Retrieves the altNameCtx field of this exception.
     * This is the context relative to which altName is named.
     * It will be used during a subsequent call to the
     * javax.naming.spi.ObjectFactory.getObjectInstance method.
     *
     * @return  The context relative to which altName is named.
     *          If null, then the default initial context is implied.
     *
     * @see #setAltNameCtx
     * @see #getAltName
     * @see javax.naming.spi.ObjectFactory#getObjectInstance
     */
    public Context getAltNameCtx() {
        return altNameCtx;
    }

    /**
     * Sets the altNameCtx field of this exception.
     *
     * @param altNameCtx
     *                  The context relative to which altName
     *                  is named.  If null, then the default initial context
     *                  is implied.
     *
     * @see #getAltNameCtx
     * @see #setAltName
     */
    public void setAltNameCtx(Context altNameCtx) {
        this.altNameCtx = altNameCtx;
    }

    /**
     * Use serialVersionUID from JNDI 1.1.1 for interoperability
     */
    private static final long serialVersionUID = 1219724816191576813L;
}


text:
package samples.strawberry;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.sf.blackberry.facebook.FBUser;
import net.sf.blackberry.facebook.Facebook;
import net.sf.blackberry.facebook.FacebookContext;
import net.sf.blackberry.facebook.Post;
import net.sf.blackberry.facebook.ui.FacebookScreen;
import net.sf.blackberry.util.log.Logger;
import net.sf.blackberry.util.network.HttpClient;

final class RecentUpdatesScreen extends FacebookScreen {

	// List of actions:
	static final String ACTION_ENTER = "recentUpdates";
	static final String ACTION_SUCCESS = "success";
	static final String ACTION_ERROR = "error";

	// List of labels:
	private static final String LABEL_TITLE = "Recent Updates";

	private ListField listField;
	private StreamListCallback streamListCallback = new StreamListCallback();

	protected Logger log = Logger.getLogger(getClass());

	/**
	 * Default constructor.
	 *
	 */
	RecentUpdatesScreen(FacebookContext pfbc) {
		super(pfbc);
		setTitle(new LabelField(LABEL_TITLE, LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));

		listField = new ListField();
		listField.setRowHeight(50);
		listField.setCallback(streamListCallback);
		add(listField);
	}

	/**
	 * Load the list of posts.
	 *
	 */
	void loadList() {
		while (listField.getSize() > 0) {
			listField.delete(0);
		}

		try {
			Post[] posts = new FBUser("me", fbc.getAccessToken()).getStream(5);
			streamListCallback.clear();

			for (int i = 0; i < posts.length; i++) {
				listField.insert(listField.getSize());
				streamListCallback.add(posts[i]);
			}

			streamListCallback.loadBitmaps();
		} catch (Exception e) {
			fireAction(ACTION_ERROR, e.getMessage());
		}
	}

	private class StreamListCallback implements ListFieldCallback {

		private Vector posts = new Vector();
		private Hashtable pictureBitmaps = new Hashtable();

		public StreamListCallback() {
		}

		public void clear() {
			posts.removeAllElements();
		}

		public void add(Post post) {
			posts.addElement(post);
		}

		public void insert(Post post, int index) {
			posts.insertElementAt(post, index);
		}

		public void loadBitmaps() {
			(new BitmapThread()).start();
		}

		public void drawListRow(ListField listField, Graphics g, int index, int y, int width) {
			if (index < posts.size()) {
				int height = listField.getRowHeight();
				Post post = (Post) posts.elementAt(index);
				Bitmap bitmap = getBitmap(post.getPoster().getId());

				if (bitmap != null) {
					g.drawBitmap(0, y + ((height - Math.min(bitmap.getHeight(), height)) / 2), 50, height, bitmap, 0, 0);
				}

				Font font = Font.getDefault();
				font.derive(Font.BOLD);
				g.setFont(font);
				g.drawText(post.getMessage(), 52, y, 0, width - 52);
				g.drawText(((post.getComments() != null) ? post.getComments().length : 0) + " Comments, " + post.getLikesCount() + " Likes", 52, y + (height / 2), DrawStyle.ELLIPSIS, width - 52);
				g.drawLine(0, y + height - 1, width, y + height - 1);
			}
		}

		public Object get(ListField listField, int index) {
			if (index < posts.size()) {
				return posts.elementAt(index);
			}

			return null;
		}

		public int getPreferredWidth(ListField listField) {
			return Display.getWidth();
		}

		public int indexOfList(ListField listField, String prefix, int start) {
			for (int i = start; i < posts.size(); i++) {
				Post post = (Post) posts.elementAt(i);

				if (post.getMessage().indexOf(prefix) > -1) {
					return i;
				}
			}

			return -1;
		}

		private Bitmap getBitmap(String id) {
			return (Bitmap) pictureBitmaps.get(id);
		}

		private class BitmapThread extends Thread {

			public void run() {
				Enumeration postsEnum = posts.elements();

				while (postsEnum.hasMoreElements()) {
					Post post = (Post) postsEnum.nextElement();
					String id = post.getPoster().getId();
					String url = Facebook.API_URL + "/" + id + "/picture?type=square";

					try {
						StringBuffer response = HttpClient.getInstance().doGet(url);
						byte[] data = response.toString().getBytes();

						if (data.length > 0) {
							Bitmap bitmap = Bitmap.createBitmapFromBytes(data, 0, data.length, 1);
							pictureBitmaps.put(id, bitmap);
							listField.invalidate();
						}
					} catch (Exception e) {
						log.error(e.getMessage());
					}
				}
			}

		}

	}

}


text:
package namespace

import (
	"encoding/json"

	"github.com/containerum/chkit/pkg/model"
)

var (
	_ model.JSONrenderer = new(NamespaceList)
)

func (list NamespaceList) RenderJSON() (string, error) {
	data, err := json.MarshalIndent(list.ToKube(), "", model.Indent)
	return string(data), err
}


text:
package spark.streaming.examples

import spark.streaming._
import spark.RDD
import scala.actors.Actor._
import scala.actors.Actor
import scala.io._
import java.io.{File, PrintWriter}
import java.util.Calendar
import scala.Tuple2

/**
 * Created with IntelliJ IDEA.
 * User: peter
 * Date: 10/13/13
 * Time: 8:25 PM
 * To change this template use File | Settings | File Templates.
 */
class SqlSparkStreamingContext(master: String,
                               appName: String,
                               batchDuration: Duration,
                               sparkHome: String = null,
                               jars: Seq[String] = Nil,
                               environment: Map[String, String] = Map()) {
  val ssc = new StreamingContext(master, appName, batchDuration,sparkHome, jars, environment)
  val inputStreams = scala.collection.mutable.Map[String, DStream[String]]()
  val recentBatchOfInputStreams = scala.collection.mutable.Map[Time, scala.collection.mutable.Map[String, RDD[String]]]()
  val operatorGraph = new OperatorGraph(this)
  val tables = scala.collection.mutable.Map[String, Table]()
  val parser = new SqlParser()
  var args :Array[String] = null

  var incrementalOperator = true

  def getBatchDuration = batchDuration

  object columns {
    private var globalColumnCount = 0
    def getGlobalColId = {globalColumnCount += 1; globalColumnCount - 1}
  }

  def socketTextStream(ip : String, port : Int, name: String) {
    inputStreams += name -> ssc.socketTextStream(ip, port)
  }

  def start(){
    operatorGraph.groupInnerJoin();

    inputStreams.foreach(kvp => {
      val name = kvp._1
      val stream = kvp._2
      stream.foreach((rdd,time) => {

        if (!recentBatchOfInputStreams.contains(time))
          recentBatchOfInputStreams += time -> scala.collection.mutable.Map[String, RDD[String]]()
        recentBatchOfInputStreams(time) += name -> rdd
        if(recentBatchOfInputStreams(time).keySet == inputStreams.keys){
          //processRDDActor ! (time,recentBatchOfInputStreams(time))
          processBatch(time, recentBatchOfInputStreams(time))
          recentBatchOfInputStreams - time
        }
      })
    })
    ssc.start()
  }

  def stop(){
    ssc.stop()
  }

//  val processRDDActor = actor{
//    while(true){
//      receive{
//        case (time:Time, rdds :scala.collection.mutable.Map[String, RDD[String]]) =>
//        {
//          processBatch(time,rdds)
//        }
//      }
//    }
//  }

  var timeSum = 0.0
  var batchCount = 0
  var usedCount = 0
  def processBatch(time:Time, rdds : scala.collection.mutable.Map[String, RDD[String]]){
   val optimizeStart = System.nanoTime()
    if(args.contains("-reorder"))
      operatorGraph.innerJoinOperatorSets.foreach(s => s.optimize())
    println("running " + time)
    val starttime = System.nanoTime()
    val exec = new Execution(time,rdds)
    operatorGraph.execute(SqlHelper.printRDD,exec)
    val timeUsed = (System.nanoTime() - starttime)/1000000.0
    if(batchCount > 10){
      timeSum += timeUsed
      usedCount += 1
    }
    batchCount += 1
    println("optimization time in ms:" + (starttime - optimizeStart)/1000000.0 )
    println("execution time in ms:" + timeUsed + " Avg:" + (timeSum/usedCount))
    SqlHelper.writeln(timeUsed.toString)
    operatorGraph.innerJoinOperators.foreach(println(_))
  }

  def executeQuery(q : Any) = q match{
    case (t:Identifier, s:SelectStatement) => {
      executeSelectQuery(t,s)
    }
    case (t:Identifier, s:InputStatement) => {
      socketTextStream(s.ip, s.port, t.name + "_input")
      val nameTypeGID = s.column.map(tp => (tp._1,(tp._2, columns.getGlobalColId))).toMap
      val schema = new Schema(nameTypeGID.values.toIndexedSeq)
      val operator = new ParseOperator(schema, s.dilimiter, t.name + "_input",this)
      tables += t.name -> new Table(nameTypeGID, operator)
    }
    case o:OutputStatement =>{
      new OutputOperator(tables(o.table).getSinkOperator, tables(o.table).getTypeGIDFromName.map(tp => tp._2._2).toIndexedSeq, this)
    }
    case c:Comment => {}
  }

  def executeSelectQuery(t : Identifier, s: SelectStatement){
    def getFunctionFromName(name : String, typeName : String) : GroupByCombiner = {
      //createCombiner: V => C,
      //mergeValue: (C, V) => C,
      //mergeCombiners: (C, C) => C,
      //final processing: C => U
      typeName match{
        case "int" => {
          name match{
            case "sum" => new GroupByCombiner(
              ((a : Int) => a),
              ((a:Int, b:Int) => a + b),
              ((a:Int, b:Int) => a + b),
              ((a : Int) => a),
              "int")
            case "max" =>  new GroupByCombiner(
              ((a : Int) => a),
              ((a:Int, b:Int) => scala.math.max(a,b)),
              ((a:Int, b:Int) => scala.math.max(a,b)),
              ((a : Int) => a),
              "int")
            case "min" =>  new GroupByCombiner(
              ((a : Int) => a),
              ((a:Int, b:Int) => scala.math.min(a,b)),
              ((a:Int, b:Int) => scala.math.min(a,b)),
              ((a : Int) => a),
              "int")
            case "avg" =>  new GroupByCombiner(
              ((a : Int) => (a,1)),
              ((t : Tuple2[Int,Int], b:Int) => (t._1 + b ,t._2 + 1)),
              ((t1:Tuple2[Int,Int], t2:Tuple2[Int,Int]) => (t1._1 + t2._1, t1._2 + t2._2)),
              ((t : Tuple2[Int,Int]) => t._1.toDouble/t._2),
              "double")
            case "count" =>  new GroupByCombiner(
              ((a : Int) => 1),
              ((t : Int, b:Int) => t + 1),
              ((t1: Int, t2: Int) => t1 + t2),
              ((t : Int) => t),
              "int")

          }
        }
        case "double" => {
          name match{
            case "sum" =>  new GroupByCombiner(
              ((a : Double) => a),
              ((a:Double, b:Double) => a + b),
              ((a:Double, b:Double) => a + b),
              ((a : Double) => a),
              "double")
            case "max" =>  new GroupByCombiner(
              ((a : Double) => a),
              ((a:Double, b:Double) => scala.math.max(a,b)),
              ((a:Double, b:Double) => scala.math.max(a,b)),
              ((a : Double) => a),
              "double")
            case "min" =>  new GroupByCombiner(
              ((a : Double) => a),
              ((a:Double, b:Double) => scala.math.min(a,b)),
              ((a:Double, b:Double) => scala.math.min(a,b)),
              ((a : Double) => a),
              "double")
            case "avg" =>  new GroupByCombiner(
              ((a : Double) => (a,1)),
              ((t : Tuple2[Double,Int], b:Double) => (t._1 + b ,t._2 + 1)),
              ((t1:Tuple2[Double,Int], t2:Tuple2[Double,Int]) => (t1._1 + t2._1, t1._2 + t2._2)),
              ((t : Tuple2[Double,Int]) => t._1/t._2),
              "double")
            case "count" =>  new GroupByCombiner(
              ((a : Double) => 1),
              ((t : Int, b:Double) => t + 1),
              ((t1: Int, t2: Int) => t1 + t2),
              ((t : Int) => t),
              "int")
          }
        }
      }
    }

    val sql = s.sql
    val fromTable = tables(sql("from").asInstanceOf[Identifier].name)
    var tailOperator = fromTable.getSinkOperator

    var getTypeGIDFromName = fromTable.getTypeGIDFromName
    val joinedTables = scala.collection.mutable.Map[String, Table](sql("from").asInstanceOf[Identifier].name -> fromTable)

    if(sql.contains("where"))
    {
      val condition = sql("where").asInstanceOf[Condition]
      val whereColName = condition.GetVariableSet()
      val whereColGID = whereColName.map(name => fromTable.getTypeGIDFromName(name)._2)
      val getColumnGIdFromName = fromTable.getTypeGIDFromName.filter(tp => whereColName(tp._1)).map(tp => (tp._1, tp._2._2))
      val f = (record : IndexedSeq[Any], schema : Schema) => {
        val _condition : Condition = condition
        val _getColumnLocalIdFromName = getColumnGIdFromName.map(tp => (tp._1, schema.getLocalIdFromGlobalId(tp._2)))
        condition.Eval(_getColumnLocalIdFromName, record)
      }
      tailOperator = new WhereOperator(tailOperator, f, whereColGID, this)
    }
    if(sql.contains("window")){
      tailOperator = new WindowOperator(tailOperator, sql("window").asInstanceOf[WindowProperty].windowDuration, this)
    }
    if(sql.contains("groupby") ||
      sql("select").asInstanceOf[List[SelectItem]]
        .map(si => if(si.function != null) 1 else 0)
        .reduce(_+_) > 0)
    {
      val keys = sql("select").asInstanceOf[List[SelectItem]].filter(si => si.function == null).map(si => fromTable.getTypeGIDFromName(si.selectCol.name)._2).toIndexedSeq
      assert(!sql.contains("groupby") ||
        keys.toSet.equals(
        sql("groupby").asInstanceOf[List[Identifier]].map(i => fromTable.getTypeGIDFromName(i.name)._2).toSet)
      )

      val functions = sql("select").asInstanceOf[List[SelectItem]].filter(i => i.function != null).map(i => (getTypeGIDFromName(i.selectCol.name)._2, getFunctionFromName(i.function.name, getTypeGIDFromName(i.selectCol.name)._1))).toMap
      val getNewNameFromOldGID = sql("select").asInstanceOf[List[SelectItem]].filter(i => i.function != null).map(i => (fromTable.getTypeGIDFromName(i.selectCol.name)._2, i.asName.name)).toMap

      val groupByOp = new GroupByOperator(tailOperator,keys,functions,this)
      val getGroupByNewNameFromNewGID = groupByOp.getNewGIDFromOldGID.map(tp => (tp._2 , getNewNameFromOldGID(tp._1))).toMap

      tailOperator = groupByOp
      val getNameTypeFromGID = getTypeGIDFromName.map(tp => (tp._2._2,(tp._1,tp._2._1))).toMap
      getTypeGIDFromName =  tailOperator.outputSchema.getSchemaArray.map(tp =>
        (
          if(getGroupByNewNameFromNewGID.contains(tp._2)){
            getGroupByNewNameFromNewGID(tp._2)
          }else{
            getNameTypeFromGID(tp._2)._1
          },
          (tp._1, tp._2)
          )).toMap
      println(getTypeGIDFromName)

    }
    if(sql.contains("join")){
      sql("join").asInstanceOf[List[JoinStatement]].foreach(j => {
        val rightTable = tables(j.table.name)
        if(j.joinType == "inner"){
          val leftParent = tailOperator
          val rightParent = rightTable.getSinkOperator
          val joinCond = j.onCol.map(tp => {
            if(joinedTables.contains(tp._1.table.name)
              && tp._2.table.name == j.table.name){
              ( if(getTypeGIDFromName.contains(tp._1.column.name))
                  getTypeGIDFromName(tp._1.column.name)._2
                else if(getTypeGIDFromName.contains(tp._1.table.name + "." + tp._1.column.name))
                  getTypeGIDFromName(tp._1.table.name + "." + tp._1.column.name)._2
                else
                  throw new Exception("Can't find  table name")
                ,
                rightTable.getTypeGIDFromName(tp._2.column.name)._2)
            } else if(joinedTables.contains(tp._2.table.name)
              && tp._1.table.name == j.table.name){
              (rightTable.getTypeGIDFromName(tp._2.column.name)._2,
                if(getTypeGIDFromName.contains(tp._1.column.name))
                  getTypeGIDFromName(tp._1.column.name)._2
                else if(getTypeGIDFromName.contains(tp._1.table.name + "." + tp._1.column.name))
                  getTypeGIDFromName(tp._1.table.name + "." + tp._1.column.name)._2
                else
                  throw new Exception("Can't find  table name")
                )
            }else{
              throw new Exception("join condition mismatch")
            }
          }).toIndexedSeq
          joinedTables += j.table.name -> tables(j.table.name)
          tailOperator = new InnerJoinOperator(leftParent,rightParent, joinCond, this)

          val getNameTypeFromGID = getTypeGIDFromName.map(tp => (tp._2._2,(tp._1,tp._2._1))).toMap
          val rightTable_getNameTypeFromGID = rightTable.getTypeGIDFromName.map(tp => (tp._2._2,(tp._1,tp._2._1))).toMap
          getTypeGIDFromName = tailOperator.outputSchema.getSchemaArray.map(tp => {
            (
            if(getNameTypeFromGID.contains(tp._2)){
              val newName = getNameTypeFromGID(tp._2)._1
              if(!newName.contains("."))
                sql("from").asInstanceOf[Identifier].name + "." + newName
              else
                newName
            }
            else if(rightTable_getNameTypeFromGID.contains(tp._2)){
              println("join " + j.table.name + "." + rightTable_getNameTypeFromGID(tp._2)._1 )
              j.table.name + "." + rightTable_getNameTypeFromGID(tp._2)._1
            }
            else
              throw new Exception("Can't find GID")
            ,
            (tp._1, tp._2))
          }).toMap
        }
      })
    }

    val getSelectItemFromGID = sql("select").asInstanceOf[List[SelectItem]].map(si => ({
      if(si.asName != null && getTypeGIDFromName.contains(si.asName.name))
        getTypeGIDFromName(si.asName.name)._2
      else if(si.table != null && si.selectCol != null && getTypeGIDFromName.contains(si.table.name + "." + si.selectCol.name))
        getTypeGIDFromName(si.table.name + "." + si.selectCol.name)._2
      else if(getTypeGIDFromName.contains(si.selectCol.name))
        getTypeGIDFromName(si.selectCol.name)._2
      else
        throw new Exception("cant find name " + si)
    },si)).toMap

    tailOperator = new SelectOperator(tailOperator,getSelectItemFromGID.keys.toIndexedSeq,this)

    getTypeGIDFromName = getTypeGIDFromName.filter(tp => getSelectItemFromGID.contains(tp._2._2)).map(tp => (
      {
        val si = getSelectItemFromGID(tp._2._2)
        if(si.asName != null)
          si.asName.name
        else
          si.selectCol.name
      }
      ,tp._2))

    tables += t.name -> new Table(getTypeGIDFromName, tailOperator)
  }

  def test(args : Array[String]){
    this.args = args
    SqlHelper.results = new PrintWriter(new File("results/" + args(1)  + ".txt" ))
    val parsedLines = parser.parseFile("sql.txt")
    parsedLines.foreach(p => executeQuery(p) )

    print(this.operatorGraph.toString())

//    val f = (record : IndexedSeq[Any], schema : Schema) => {
//      record.head.asInstanceOf[Int] > 0
//    }
//
//    val f2 = (record : IndexedSeq[Any], schema : Schema) => {
//      record.tail.head.asInstanceOf[Int] > 0
//    }
//
//
//    val s = new Schema(IndexedSeq(
//      ("int", columns.getGlobalColId),
//      ("int", columns.getGlobalColId),
//      ("int", columns.getGlobalColId),
//      ("int", columns.getGlobalColId),
//      ("int", columns.getGlobalColId),
//      ("int", columns.getGlobalColId)) )

//    socketTextStream("localhost", 9999, "ii")
//    val in = new ParseOperator(s, "ii", this)
//    val wh = new WhereOperator(in,f,this)
//    val wh2 = new WhereOperator(wh,f2,this)
//    val ou = new OutputOperator(wh2, IndexedSeq(0,1,2,3), this)

//    val x = new ParseOperator(s, "ii", this)
//    val in = new WindowOperator(x, 5,this)

//    val se = new SelectOperator(in,IndexedSeq(0,1), this)
//    val wh = new WhereOperator(se,f,Set(0),this){selectivity = 0.9}
//    val se2 = new SelectOperator(in,IndexedSeq(2,3), this)
//
//    val jo = new InnerJoinOperator(wh,se2,IndexedSeq((0,2)),this)
//    val wh2 = new WhereOperator(jo, f2, Set(1), this){selectivity = 0.7}
//    val ou = new OutputOperator(wh2, IndexedSeq(0,1,2,3), this)

//    val se0 = new SelectOperator(in,IndexedSeq(0,1), this)
//    val se1 = new SelectOperator(in,IndexedSeq(2,3), this)
//    val se2 = new SelectOperator(in,IndexedSeq(4,5), this)
//
//    val ja = new InnerJoinOperator(se0,se1,IndexedSeq((0,2)),this){selectivity = 2.1}
//    val jb = new InnerJoinOperator(ja,se2,IndexedSeq((0,4)),this){selectivity = 1.9}
//
//    val ou = new OutputOperator(jb, IndexedSeq(0,1,2,3,4,5), this)

//    print(this.operatorGraph.toString())
//    println("pushing")
//    this.operatorGraph.pushAllPredicates
//    print(this.operatorGraph.toString())
//    println("grouging where")
//    this.operatorGraph.groupPredicate()
//    print(this.operatorGraph.toString())
//    println("optimizing where")
//    this.operatorGraph.whereOperatorSets.foreach(s => s.optimize())

//    println("grouping & optimizing inner join")
//    this.operatorGraph.groupInnerJoin()
//    this.operatorGraph.InnerJoinOperatorSets.foreach(s => s.optimize())
//    print(this.operatorGraph.toString())

    start()
  }

}

class Execution(time:Time, inputRdds :scala.collection.mutable.Map[String, RDD[String]]){
  def getInputRdds = inputRdds
  def getTime = time
}

class Schema (schemaArray : IndexedSeq[(String, Int)]) extends Serializable{
  //schamaArray is an array of (className, globalID)
  val getClassFromLocalColId = schemaArray.zipWithIndex.map(kvp => (kvp._2,kvp._1._1)).toMap
  val getLocalIdFromGlobalId = schemaArray.zipWithIndex.map(kvp => (kvp._1._2, kvp._2)).toMap
  val getClassFromGlobalId = schemaArray.map(tp => (tp._2,tp._1)).toMap
  val getGlobalIdSet = schemaArray.map(_._2).toSet
  def getSchemaArray = schemaArray
  override def toString = schemaArray.toString()
}

class Table(nameTypeGID : Map[String,(String, Int)], sinkOperator : Operator){
  def getTypeGIDFromName = nameTypeGID
  def getSinkOperator = sinkOperator
}

object SqlHelper{
  def printRDD(rdd : RDD[_]) {
    rdd.collect.foreach(record => record match {
      case record:IndexedSeq[Any] => println(record.toList)
      case record:Any => println(record)
    })
  }

  var results : PrintWriter = null

  def write(s : String) = {
    results.write(s)
    results.flush()
  }
  def writeln(s : String) = write(s + "\n")
}


text:
/**
 *
 */
package com.jmw.konfman.validator;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.jmw.konfman.model.Reservation;
import com.jmw.konfman.service.ReservationManager;

/**
 * @author judahw
 *
 */
@Service(value = "reservationValidator")
public class ReservationValidator implements Validator {
    private final Log log = LogFactory.getLog(ReservationValidator.class);

    @Autowired
    ReservationManager reservationManager;

	/* (non-Javadoc)
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	public boolean supports(Class clazz) {
		return Reservation.class.equals(clazz);
	}

	/* (non-Javadoc)
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	public void validate(Object obj, Errors errors) {
		log.debug("Validating a reservaion");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "comment", "field.required");
		ValidationUtils.rejectIfEmpty(errors, "room", "noroom");
		ValidationUtils.rejectIfEmpty(errors, "user", "nouser");
		ValidationUtils.rejectIfEmpty(errors, "startDateTime", "nouser");
		ValidationUtils.rejectIfEmpty(errors, "endDateTime", "nouser");
		Reservation reservation = (Reservation) obj;
		Date now = new Date();
		if (reservation.getStartDateTime() != null && reservation.getStartDateTime().before(now)){
			errors.rejectValue("date", "past");
		}

		//if the start and end times are not null and the start time is not >= to end time
		if (reservation.getStartDateTime() != null && reservation.getEndDateTime() != null &&
				(reservation.getStartDateTime().after(reservation.getEndDateTime()) ||
				reservation.getStartDateTime().equals(reservation.getEndDateTime()))){
			errors.rejectValue("startTime", "startsafterend");
		}

		//if there are no other issues then see if there is a conflict with existing reservations
		if (errors.getErrorCount() == 0){
		//if (reservation.getStartDateTime() != null && reservation.getEndDateTime() != null){
			log.debug("Checking for a conflict");
			boolean conflict = reservationManager.isConflict(reservation);
	    	if (conflict){
	    		errors.reject("reservation.conflicted", new String[] {reservation.getComment()}, "" );
	    	}
		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HZLApp.UserWindows
{
    public partial class PreView : Form
    {
        public string PicName = "";
        LogHelper log = new LogHelper();

        public PreView()
        {
            InitializeComponent();
        }

        private void PreView_Load(object sender, EventArgs e)
        {
            try
            {
                string url = AppDomain.CurrentDomain.BaseDirectory + "image\\" + PicName;
                pictureBox1.Load(url);
            }
            catch (Exception ex){
                log.wrirteLog("预览","-预览",ex.Message);
            }
        }
    }
}


text:
\hypertarget{plots__object_8cpp}{\section{plots\-\_\-object.\-cpp File Reference}
\label{plots__object_8cpp}\index{plots\-\_\-object.\-cpp@{plots\-\_\-object.\-cpp}}
}
{\ttfamily \#include \char`\"{}plots\-\_\-object.\-h\char`\"{}}\\*


text:
/*global slice create*/

// ##Navigator Class Object

// Abstracts location and history events, parsing their information into a
// normalized object that is then set to an Observable class instance
//
// `constructor`
sudo.Navigator = function(data) {
  this.started = false;
  this.slashStripper = /^\/+|\/+$/g;
  this.leadingStripper = /^[#\/]|\s+$/g;
  this.trailingStripper = /\/$/;
  this.construct(data);
};
// Navigator inherits from `sudo.Model`
sudo.Navigator.prototype = create(sudo.Model.prototype);
// ###buildPath
// Put together a path from the arguments passed in.
// If you want a hash paramaterized pass it as the last arg.
//
// `params` {*} N number of path fragments
// `returns` {string} /a/completed/path?withParams=ifPresent
sudo.Navigator.prototype.buildPath = function() {
  var args = slice.call(arguments), query;
  // check if the last arg is a hash
  if($.isObject(args[args.length - 1])) {query = this.getQuery(args.pop());}
  return this.data.root + args.join('/') + (query || '');
};
// ###buildRelativePath
// Extend the already existing getUrl type functionality with the ability to append
// to that path as well as paramaterize a hash
//
// `params` {*} N number of path fragments
// `returns` {string} /a/completed/path?withParams=ifPresent
sudo.Navigator.prototype.buildRelativePath = function() {
  var args = slice.call(arguments);
  args.unshift(this.data.fragment);
  return this.buildPath.apply(this, args);
};
// ###getFragment
// 'Fragment' is defined as any URL information after the 'root' path
// including the `search` or `hash`
//
// `returns` {String} `fragment`
// `returns` {String} the normalized current fragment
sudo.Navigator.prototype.getFragment = function(fragment) {
  var root = this.data.root;
  if(!fragment) {
    // intentional use of coersion
    if (this.isPushState) {
      fragment = window.location.pathname + window.location.search;
      root = root.replace(this.trailingStripper, '');
      if(!fragment.indexOf(root)) fragment = fragment.substr(root.length);
    } else {
      fragment = this.getHash();
    }
  }
  return decodeURIComponent(fragment.replace(this.leadingStripper, ''));
};
// ###getHash
// Check either the passed in fragment, or the full location.href
// for a `hash` value
//
// `param` {string} `fragment` Optional fragment to check
// `returns` {string} the normalized current `hash`
sudo.Navigator.prototype.getHash = function(fragment) {
  fragment || (fragment = window.location.href);
  var match = fragment.match(/#(.*)$/);
  return match ? match[1] : '';
};
// ###getQuery
// Take a hash and convert it to a `search` query
//
// `param` {object} `obj`
// `returns` {string} the serialized query string
sudo.Navigator.prototype.getQuery = function(obj) {
  return '?' + ($.serialize(obj));
};

// ###getSearch
// Check either the passed in fragment, or the full location.href
// for a `search` value
//
// `param` {string} `fragment` Optional fragment to check
// `returns` {String} the normalized current `search`
sudo.Navigator.prototype.getSearch = function(fragment) {
  fragment || (fragment = window.location.href);
  var match = fragment.match(/\?(.*)$/);
  return match ? match[1] : '';
};
// ###getUrl
// fetch the URL in the form <root + fragment>
//
// `returns` {String}
sudo.Navigator.prototype.getUrl = function() {
  // note that delegate(_role_) returns the deleagte
  return this.data.root + this.data.fragment;
};
// ###go
// If the passed in 'fragment' is different than the currently stored one,
// push a new state entry / hash event and set the data where specified.
// If the second argument is true and pushState is being used, replaceState
// rather than pushing a new state onto window.history.
//
// `param` {string} `fragment`
// `param` {boolean} `bool`
// `returns` {*} call to `setData`
sudo.Navigator.prototype.go = function(fragment, bool) {
  if(!this.started) return false;
  if(!this.urlChanged(fragment)) return;
  if(this.isPushState) {
    window.history[bool ? 'replaceState' : 'pushState']({}, document.title, this.getUrl());
  } else if(this.isHashChange) {
    window.location.hash = '#' + this.data.fragment;
  }
  return this.setData();
};
// ###handleChange
// Bound to either the `popstate` or `hashchange` events, if the
// URL has indeed changed then parse the relevant data and set it -
// triggering change observers
//
// `returns` {*} call to `setData` or undefined
sudo.Navigator.prototype.handleChange = function() {
  if(this.urlChanged()) {
    return this.setData();
  }
};
// ###parseQuery
// Parse and return a hash of the key value pairs contained in
// the current `query` if there is one
//
// `returns` {object}
sudo.Navigator.prototype.parseQuery = function() {
  return this.data.query && $.deserialize(this.data.query);
};
// ###setData
// Using the current `fragment` (minus any search or hash data) as a key,
// use `parseQuery` as the value for the key, setting it into the specified
// model (a stated `Observable` or `this.data`)
//
// `returns` {object} `this`
sudo.Navigator.prototype.setData = function() {
  var frag = this.data.fragment,
    // data is set in a specified model or in self
    observable = this.data.observable || this;
  if(this.data.query) {
    // we want to set the key minus any search/hash
    frag = ~frag.indexOf('?') ? frag.split('?')[0] : frag.split('#')[0];
  }
  observable.set(frag, this.parseQuery());
  return this;
};
// ###start
// Gather the necessary information about the current environment and
// bind to either (push|pop)state or hashchange.
// Also, if given an imcorrect URL for the current environment (hashchange
// vs pushState) normalize it and set accordingly (or don't).
//
// `returns` {object} `this`
sudo.Navigator.prototype.start = function() {
  var hasPushState, atRoot, tmp;
  if(this.started) return;
  hasPushState = window.history && window.history.pushState;
  this.started = true;
  // setup the initial configuration
  this.isHashChange = this.data.useHashChange && 'onhashchange' in window ||
    (!hasPushState && 'onhashchange' in window);
  this.isPushState = !this.isHashChange && !!hasPushState;
  // normalize the root to always contain a leading and trailing slash
  this.data.root = ('/' + this.data.root + '/').replace(this.slashStripper, '/');
  // Get a snapshot of the current fragment
  this.urlChanged();
  // monitor URL changes via popState or hashchange
  if (this.isPushState) {
    $(window).on('popstate', this.handleChange.bind(this));
  } else if (this.isHashChange) {
    $(window).on('hashchange', this.handleChange.bind(this));
  } else return;
  atRoot = window.location.pathname.replace(/[^\/]$/, '$&/') === this.data.root;
  // somehow a URL got here not in my 'format', unless explicitly told not too, correct this
  if(!this.data.stay) {
   if(this.isHashChange && !atRoot) {
      window.location.replace(this.data.root + window.location.search + '#' +
        this.data.fragment);
      // return early as browser will redirect
      return true;
      // the converse of the above
    } else if(this.isPushState && atRoot && window.location.hash) {
      tmp = this.getHash().replace(this.leadingStripper, '');
      window.history.replaceState({}, document.title, this.data.root +
        tmp + window.location.search);
    }
  }
  // TODO provide option to `go` from inital `start` state?
  return this;
};
// ###urlChanged
// Is a passed in fragment different from the one currently set at `this.get('fragment')`?
// If so set the fragment to the passed fragment passed in (as well as any 'query' data), else
// simply return false
//
// `param` {String} `fragment`
// `returns` {bool}
sudo.Navigator.prototype.urlChanged = function(fragment) {
  var current = this.getFragment(fragment);
  // nothing has changed
  if (current === this.data.fragment) return false;
  this.data.fragment = current;
  // the fragment and the href need to checked here, optimized for the 'go' scenario
  this.data.query = this.getSearch(current) || this.getHash(current);
  return true;
};