text:
#include <stdint.h>
#include <thread>

#include "CppUTest/TestHarness.h"

#include "flow.h"

#include "data.h"

using Flow::Connection;
using Flow::InTrigger;
using Flow::OutTrigger;
using Flow::connect;

TEST_GROUP(Trigger_TestBench)
{
	OutTrigger unitUnderTestOut;
	InTrigger unitUnderTestIn{  nullptr  };
	Connection* connection;

	void setup()
	{
		connection = connect(unitUnderTestOut, unitUnderTestIn);
	}

	void teardown()
	{
		disconnect(connection);
	}
};

TEST(Trigger_TestBench, SendReceiveTrigger)
{
	CHECK(!unitUnderTestIn.peek());

	CHECK(unitUnderTestOut.send());

	CHECK(unitUnderTestIn.peek());
	CHECK(unitUnderTestIn.receive());

	CHECK(!unitUnderTestIn.peek());
	CHECK(!unitUnderTestIn.receive());
}

TEST(Trigger_TestBench, Connect)
{
	CHECK(unitUnderTestOut.send());
	CHECK(unitUnderTestIn.peek());
	CHECK(unitUnderTestIn.receive());

	disconnect(connection);

	CHECK_FALSE(unitUnderTestIn.full());
	CHECK(!unitUnderTestOut.send());
	CHECK(!unitUnderTestIn.peek());
	CHECK(!unitUnderTestIn.receive());

	connection = connect(&unitUnderTestOut, unitUnderTestIn);

	CHECK(unitUnderTestOut.send());
	CHECK(unitUnderTestIn.peek());
	CHECK(unitUnderTestIn.receive());

	disconnect(connection);

	CHECK_FALSE(unitUnderTestIn.full());
	CHECK(!unitUnderTestOut.send());
	CHECK(!unitUnderTestIn.peek());
	CHECK(!unitUnderTestIn.receive());

	connection = connect(unitUnderTestOut, &unitUnderTestIn);

	CHECK(unitUnderTestOut.send());
	CHECK(unitUnderTestIn.peek());
	CHECK(unitUnderTestIn.receive());

	disconnect(connection);

	CHECK_FALSE(unitUnderTestIn.full());
	CHECK(!unitUnderTestOut.send());
	CHECK(!unitUnderTestIn.peek());
	CHECK(!unitUnderTestIn.receive());

	connection = connect(&unitUnderTestOut, &unitUnderTestIn);

	CHECK(unitUnderTestOut.send());
	CHECK(unitUnderTestIn.peek());
	CHECK(unitUnderTestIn.receive());
}

TEST(Trigger_TestBench, SendReceiveTriggerFullEmptyWithOverflow)
{
	CHECK(!unitUnderTestIn.peek());

	CHECK(unitUnderTestOut.send());
	CHECK(unitUnderTestIn.receive());

	CHECK(!unitUnderTestIn.peek());

	for(int32_t i = 0; i < UINT16_MAX; i++)
	{
		CHECK(unitUnderTestOut.send());
	}

	CHECK(!unitUnderTestOut.send());
	CHECK(unitUnderTestIn.full());
	CHECK(unitUnderTestOut.full());

	for(int32_t i = 0; i < UINT16_MAX; i++)
	{
		CHECK(unitUnderTestIn.peek());
		CHECK(unitUnderTestIn.receive());
	}

	CHECK(!unitUnderTestIn.peek());
	CHECK(!unitUnderTestIn.receive());
}

static void producer(OutTrigger* _unitUnderTest,
		const unsigned long long count)
{
	for (unsigned long long c = 0; c <= count; c++)
	{
		while (!_unitUnderTest->send())
			;
	}
}

static void consumer(InTrigger* _unitUnderTest,
		const unsigned long long count, bool* success)
{
	unsigned long long c = 0;

	*success = false;

	while (c <= count)
	{
		if (_unitUnderTest->receive())
		{
			c++;
		}
	}

	*success = true;
}

TEST(Trigger_TestBench, Threadsafe)
{
	const unsigned long long count = 100000;
	bool success = true;

	std::thread producerAThread(producer, &unitUnderTestOut, count);
	std::thread consumerBThread(consumer, &unitUnderTestIn, count, &success);

	producerAThread.join();
	consumerBThread.join();

	CHECK(success);
}


text:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 *
 * @author Jukka
 */
public class Server implements Runnable {

    //Server status
    private boolean alive = true;
    private ServerSocket server;
    //Server's global user- and room list
    private ArrayList<User> userList;
    private ArrayList<Room> roomList;

    /*
        The commands available
     */
    public static final String JOIN = "JOIN";
    public static final String NICK = "NICK";
    public static final String PART = "PART";
    public static final String QUIT = "QUIT";
    public static final String CONNECT = "CONNECT";
    public static final String PARTALL = "PARTALL";

    public Server(int port) {
        try {
            this.server = new ServerSocket(port);
            this.userList = new ArrayList<>();
            this.roomList = new ArrayList<>();
        } catch (IOException e) {
            System.out.println(e);
            alive = false;
        }
    }

    /*
        Checks if the name is available and adds new user to global userlist
        returns null if the name was not free
     */
    public User addUser(String name, Connection connenction) {
        if(name.equalsIgnoreCase("server") || findUser(name) != null){
            return null;
        }
        User user = new User(name, connenction);
        this.userList.add(user);
        return user;
    }

    /*
        Remove user from server's user list
     */
    public boolean removeUser(User user) {
        return this.userList.remove(user);
    }

    /*
        Create new room and add it to server room list
     */
    public void addRoom(String name) {
        this.roomList.add(new Room(name));
    }

    /*
        Find room by name
     */
    public Room findRoom(String name) {
        for (Room room : roomList) {
            if (name.equals(room.getName())) {
                return room;
            }
        }
        return null;
    }

    /*
        Find user by name
     */
    public User findUser(String name) {
        for (User user : userList) {
            if (name.equals(user.getName())) {
                return user;
            }
        }
        return null;
    }

    /*
        Remove user from one rooms
     */
    public void removeUserFromRoom(User user, String name) {
        Room room = findRoom(name);
        room.removeUser(user);
        if (room.size() == 0) {
            System.out.println(room.getName() + " removed: no users");
            roomList.remove(room);
        }
        else{
            ChatPacket info = new ChatPacket("server", findRoom(name).getName(), "response", user.getName() + " has left room");
            room.getUsers().forEach(roomUser ->{
                roomUser.connection().sendMessage(info.toString());
            });
        }
    }

    /*
        Remove user from all rooms
     */
    public void removeUserFromRooms(User user) {
        if (user != null && user.getRoomList().size() > 0) {
            ArrayList<Room> rooms = user.getRoomList();
            while (rooms.size() > 0) {
                Room room = rooms.get(0);
                room.removeUser(user);
                if (room.size() == 0) {
                    System.out.println(room.getName() + " removed: no users");
                    roomList.remove(room);
                }
                else{
                    ChatPacket info = new ChatPacket("server", room.getName(), "response", user.getName() + " has left room");
                    room.getUsers().forEach(roomUser ->{
                    roomUser.connection().sendMessage(info.toString());
                    });
                }
            }
        }
    }

    /*
        Accepts new clients until server is closed.
     */
    @Override
    public void run() {
        try {
            while (alive) {
                Socket client = server.accept();
                new Thread(new Connection(client, this)).start();
                //new Thread(connection.run()).start();
            }
            server.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.airlift.sample;

import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import com.google.inject.Injector;
import io.airlift.bootstrap.Bootstrap;
import io.airlift.bootstrap.LifeCycleManager;
import io.airlift.event.client.InMemoryEventClient;
import io.airlift.event.client.InMemoryEventModule;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.StatusResponseHandler.StatusResponse;
import io.airlift.http.client.jetty.JettyHttpClient;
import io.airlift.http.server.testing.TestingHttpServer;
import io.airlift.http.server.testing.TestingHttpServerModule;
import io.airlift.jaxrs.JaxrsModule;
import io.airlift.json.JsonCodec;
import io.airlift.json.JsonModule;
import io.airlift.node.testing.TestingNodeModule;
import io.airlift.testing.Closeables;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import static io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler;
import static io.airlift.http.client.Request.Builder.prepareDelete;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.http.client.Request.Builder.preparePost;
import static io.airlift.http.client.Request.Builder.preparePut;
import static io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator;
import static io.airlift.http.client.StatusResponseHandler.createStatusResponseHandler;
import static io.airlift.json.JsonCodec.listJsonCodec;
import static io.airlift.json.JsonCodec.mapJsonCodec;
import static io.airlift.sample.PersonEvent.personAdded;
import static io.airlift.sample.PersonEvent.personRemoved;
import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;

@Test(singleThreaded = true)
public class TestServer
{
    private static final int NOT_ALLOWED = 405;

    private HttpClient client;
    private TestingHttpServer server;

    private PersonStore store;

    private final JsonCodec<Map<String, Object>> mapCodec = mapJsonCodec(String.class, Object.class);
    private final JsonCodec<List<Object>> listCodec = listJsonCodec(Object.class);
    private InMemoryEventClient eventClient;
    private LifeCycleManager lifeCycleManager;

    @BeforeMethod
    public void setup()
            throws Exception
    {
        Bootstrap app = new Bootstrap(
                new TestingNodeModule(),
                new InMemoryEventModule(),
                new TestingHttpServerModule(),
                new JsonModule(),
                new JaxrsModule(true),
                new MainModule());

        Injector injector = app
                .strictConfig()
                .doNotInitializeLogging()
                .initialize();

        lifeCycleManager = injector.getInstance(LifeCycleManager.class);

        server = injector.getInstance(TestingHttpServer.class);
        store = injector.getInstance(PersonStore.class);
        eventClient = injector.getInstance(InMemoryEventClient.class);

        client = new JettyHttpClient();
    }

    @AfterMethod(alwaysRun = true)
    public void teardown()
            throws Exception
    {
        try {
            if (lifeCycleManager != null) {
                lifeCycleManager.stop();
            }
        }
        finally {
            Closeables.closeQuietly(client);
        }
    }

    @Test
    public void testEmpty()
            throws Exception
    {
        List<Object> response = client.execute(
                prepareGet().setUri(uriFor("/v1/person")).build(),
                createJsonResponseHandler(listCodec));

        assertEquals(response, Collections.<Object>emptyList());
    }

    @Test
    public void testGetAll()
            throws IOException, ExecutionException, InterruptedException
    {
        store.put("bar", new Person("bar@example.com", "Mr Bar"));
        store.put("foo", new Person("foo@example.com", "Mr Foo"));

        List<Object> expected = listCodec.fromJson(Resources.toString(Resources.getResource("list.json"), UTF_8));

        List<Object> actual = client.execute(
                prepareGet().setUri(uriFor("/v1/person")).build(),
                createJsonResponseHandler(listCodec));

        assertEqualsIgnoreOrder(expected, actual);
    }

    @Test
    public void testGetSingle()
            throws IOException, ExecutionException, InterruptedException
    {
        store.put("foo", new Person("foo@example.com", "Mr Foo"));

        URI requestUri = uriFor("/v1/person/foo");

        Map<String, Object> expected = mapCodec.fromJson(Resources.toString(Resources.getResource("single.json"), UTF_8));
        expected.put("self", requestUri.toString());

        Map<String, Object> actual = client.execute(
                prepareGet().setUri(requestUri).build(),
                createJsonResponseHandler(mapCodec));

        assertEquals(actual, expected);
    }

    @Test
    public void testPut()
            throws IOException, ExecutionException, InterruptedException
    {
        String json = Resources.toString(Resources.getResource("single.json"), UTF_8);

        StatusResponse response = client.execute(
                preparePut()
                        .setUri(uriFor("/v1/person/foo"))
                        .addHeader(CONTENT_TYPE, APPLICATION_JSON)
                        .setBodyGenerator(createStaticBodyGenerator(json, UTF_8))
                        .build(),
                createStatusResponseHandler());

        assertEquals(response.getStatusCode(), javax.ws.rs.core.Response.Status.CREATED.getStatusCode());

        assertEquals(store.get("foo"), new Person("foo@example.com", "Mr Foo"));

        assertEquals(eventClient.getEvents(), ImmutableList.of(
                personAdded("foo", new Person("foo@example.com", "Mr Foo"))));
    }

    @Test
    public void testDelete()
            throws IOException, ExecutionException, InterruptedException
    {
        store.put("foo", new Person("foo@example.com", "Mr Foo"));

        StatusResponse response = client.execute(
                prepareDelete()
                        .setUri(uriFor("/v1/person/foo"))
                        .addHeader(CONTENT_TYPE, APPLICATION_JSON)
                        .build(),
                createStatusResponseHandler());

        assertEquals(response.getStatusCode(), javax.ws.rs.core.Response.Status.NO_CONTENT.getStatusCode());

        assertNull(store.get("foo"));

        assertEquals(eventClient.getEvents(), ImmutableList.of(
                personAdded("foo", new Person("foo@example.com", "Mr Foo")),
                personRemoved("foo", new Person("foo@example.com", "Mr Foo"))));
    }

    @Test
    public void testDeleteMissing()
            throws IOException, ExecutionException, InterruptedException
    {
        StatusResponse response = client.execute(
                prepareDelete()
                        .setUri(uriFor("/v1/person/foo"))
                        .addHeader(CONTENT_TYPE, APPLICATION_JSON)
                        .build(),
                createStatusResponseHandler());

        assertEquals(response.getStatusCode(), javax.ws.rs.core.Response.Status.NOT_FOUND.getStatusCode());
    }

    @Test
    public void testPostNotAllowed()
            throws IOException, ExecutionException, InterruptedException
    {
        String json = Resources.toString(Resources.getResource("single.json"), UTF_8);

        StatusResponse response = client.execute(
                preparePost()
                        .setUri(uriFor("/v1/person/foo"))
                        .addHeader(CONTENT_TYPE, APPLICATION_JSON)
                        .setBodyGenerator(createStaticBodyGenerator(json, UTF_8))
                        .build(),
                createStatusResponseHandler());

        assertEquals(response.getStatusCode(), NOT_ALLOWED);

        assertNull(store.get("foo"));
    }

    private URI uriFor(String path)
    {
        return server.getBaseUrl().resolve(path);
    }
}


text:
title: .Net C# Generic Thread Safe Cache, how may I help you?
categories:
- ood
tags:
- .Net
- Cache
- Thread Safe
---

A few days ago I ran repeatedly in the need of using a cache abstract data structure for storing objects (.Net C# objects) with expensive creation process. So, I said to myself:

_"Myself, you need to make a generic cache abstract data structure you can use any time without BCL restrictions, and you will improve it as your needs over time dictate. In fact the first improvement dictated would be it must be thread safe, because many objects guys will want to flatter that cache girl."_

, and after such revelation I put my fingers to work.

Was then when born the `ThreadSafeCache<TKey, TValue>` class with a static `Dictionary<TKey, TValue>` _cacheStore_ field acting as in memory cache store. There are two special thing to highlight in this code.

```csharp
public class ThreadSafeCache<TKey, TValue>: ICache<TKey, TValue>
{
    private static Dictionary<TKey, TValue> _cacheStore;

    public ThreadSafeCache()
    {
        _cacheStore = new Dictionary<TKey, TValue>();
    }

    public virtual TValue Get(TKey key)
    {
        lock (_cacheStore)
        {
            TValue value
            if (_cacheStore.TryGetValue(key, out value))
            {
                return value;
            }
        }
        return default(TValue);
    }

    public virtual void Store(TKey key, TValue value)
    {
        lock (_cacheStore)
        {
            _cacheStore[key] = value;
        }
    }

    public virtual TValue this[TKey key]
    {
        get
        {
            return Get(key);
        }
        set
        {
            Store(key,value);
        }
    }

    public virtual TValue GetLazy(TKey key, Func<TValue> valueLazyInitializer)
    {
        lock (_cacheStore)
        {
            TValue value;
            if (_cacheStore.TryGetValue(key, out value))
            {
                return value;
            }

            value = valueLazyInitializer.Invoke();
            _cacheStore[key] = value;
            return value;
          }
    }

    public bool ContainsKey(TKey key)
    {
        return _cacheStore.ContainsKey(key);
    }

    public bool ContainsValue(TValue value)
    {
        return _cacheStore.ContainsValue(value);
    }
}
```
The first is the logic of the Get and Store method:

```csharp
lock (_cacheStore)
{
      TValue value;
    if (_cacheStore.TryGetValue(key, out value))
    {
        return value;
    }
}
return default(TValue);

  // Store Logic
lock (_cacheStore)
{
    _cacheStore[key] = value;
}
```

The locking of the cache static field allows us to take  precise control over the scope and granularity of reading and storing operations. I choose this simple approach because thread safety is achieved primarily by locking to reduce the opportunities for thread interaction.

The second special things is this method called `GetLazy`, which is my favorite because it allows me to ask for an object with a 50 % possibilities of being previously cached, and it lets you provide a lambda for creating it(expensive process) if it wasn't previously cached.

```csharp
public virtual TValue GetLazy(TKey key, Func<TValue> valueLazyInitializer)
{
    lock (_cacheStore)
    {
        TValue value;
        if (_cacheStore.TryGetValue(key, out value))
        {
            return value;
        }

        value = valueLazyInitializer.Invoke();
        _cacheStore[key] = value;
        return value;
    }
}
```

This design may create a slight inefficiency while the entire cache would be locked up for the duration of the object creation operation. An alternative approach to solve this issue would be to deploy the locking in two moments, the first during the reading and the second during the storing, leaving out of lock the object creation operation and its expense of time (and processing capabilities). However, that way we are encouraging another performance inefficiency coming up if two(or more) threads simultaneously called this method looking (not locking) for the same uncached resource, the expensive object creation operation will be called twice(or more) and the Dictionary cache store will be updated unnecessarily.

Ending up, a little of advertising: I know it could be tricky to understand how to use the `GetLazy` method for some of you (I presented it to a folk and he was like: "_huhh?! It should be called GetOrSet_"), especially by the name and the lack of context. That's why I'd like to provide a practical real life example of something I'm working on In order to understand the ideal context for using `GetLazy`. Have a look at the next piece of code how it's used to retrieve the correspondent `Mapper` for the given `TEntity_Type`.

![Image]({{ site.baseurl }}/images/po.png){:class="img-responsive"}

I hope this would be useful at any level. See you in the next one.


text:
<?php
require_once 'loader.php';
$app = new \VKPollsDataGrabber\Application();

$at = !empty($_GET['access_token']) ? $_GET['access_token'] : '';
if (strlen($at) > 0 && !preg_match('/[a-z0-9]/', $at)) {
    die('Invalid access token');
}

$app->setAccessToken($at);
?>
<!DOCTYPE html>
<html>
    <body>
        <script type="text/javascript">
            window.location.href = "/auth.php";
        </script>
    </body>
</html>


text:
<?php
/**
 * @package cms
 * @subpackage tests
 */

class MemberTableFieldTest extends FunctionalTest {

	static $fixture_file = 'cms/tests/MemberTableFieldTest.yml';

	function testLimitsToMembersInGroup() {
		$member1 = $this->objFromFixture('Member', 'member1');
		$member2 = $this->objFromFixture('Member', 'member2');
		$member3 = $this->objFromFixture('Member', 'member3');
		$group1 = $this->objFromFixture('Group', 'group1');

		$tf = new MemberTableField(
			$this,
			"Members",
			$group1
		);
		$members = $tf->sourceItems();

		$this->assertContains($member1->ID, $members->column('ID'),
			'Members in the associated group are listed'
		);
		$this->assertContains($member2->ID, $members->column('ID'),
			'Members in children groups are listed as well'
		);
		$this->assertNotContains($member3->ID, $members->column('ID'),
			'Members in other groups are filtered out'
		);
	}

	function testShowsAllMembersWithoutGroupParameter() {
		$member1 = $this->objFromFixture('Member', 'member1');
		$member2 = $this->objFromFixture('Member', 'member2');
		$member3 = $this->objFromFixture('Member', 'member3');
		$group1 = $this->objFromFixture('Group', 'group1');

		$tf = new MemberTableField(
			$this,
			"Members"
			// no group assignment
		);
		$members = $tf->sourceItems();

		$this->assertContains($member1->ID, $members->column('ID'),
			'Members in the associated group are listed'
		);
		$this->assertContains($member2->ID, $members->column('ID'),
			'Members in children groups are listed as well'
		);
		$this->assertContains($member3->ID, $members->column('ID'),
			'Members in other groups are listed'
		);
	}

	function testDeleteWithGroupOnlyDeletesRelation() {
		$member1 = $this->objFromFixture('Member', 'member1');
		$group1 = $this->objFromFixture('Group', 'group1');

		$response = $this->get('MemberTableFieldTest_Controller');
		$token = SecurityToken::inst();
		$url = sprintf('MemberTableFieldTest_Controller/Form/field/Members/item/%d/delete/?usetestmanifest=1', $member1->ID);
		$url = $token->addToUrl($url);
		$response = $this->get($url);

		$group1->flushCache();

		$this->assertNotContains($member1->ID, $group1->Members()->column('ID'),
			'Member relation to group is removed'
		);
		$this->assertType(
			'DataObject',
			DataObject::get_by_id('Member', $member1->ID),
			'Member record still exists'
		);
	}

	function testDeleteWithoutGroupDeletesFromDatabase() {
		$member1 = $this->objFromFixture('Member', 'member1');
		$member1ID = $member1->ID;
		$group1 = $this->objFromFixture('Group', 'group1');

		$response = $this->get('MemberTableFieldTest_Controller');
		$token = SecurityToken::inst();
		$url = sprintf('MemberTableFieldTest_Controller/FormNoGroup/field/Members/item/%d/delete/?usetestmanifest=1', $member1->ID);
		$url = $token->addToUrl($url);
		$response = $this->get($url);

		$group1->flushCache();

		$this->assertNotContains($member1->ID, $group1->Members()->column('ID'),
			'Member relation to group is removed'
		);
		DataObject::flush_and_destroy_cache();
		$this->assertFalse(
			DataObject::get_by_id('Member', $member1ID),
			'Member record is removed from database'
		);
	}
}

class MemberTableFieldTest_Controller extends Controller implements TestOnly {

	protected $template = 'BlankPage';

	function Link($action = null) {
		return Controller::join_links('MemberTableFieldTest_Controller', $action);
	}

	function Form() {
		$group1 = DataObject::get_one('Group', '"Code" = \'group1\'');
		return new Form(
			$this,
			'FormNoGroup',
			new FieldSet(new MemberTableField($this, "Members", $group1)),
			new FieldSet(new FormAction('submit'))
		);
	}

	function FormNoGroup() {
		$tf = new MemberTableField(
			$this,
			"Members"
			// no group
		);

		return new Form(
			$this,
			'FormNoGroup',
			new FieldSet(new MemberTableField($this, "Members")),
			new FieldSet(new FormAction('submit'))
		);
	}

}


text:
import xbmcaddon
import xbmcgui
from libs.sysbox import popupSysBox
from libs.utility import debugTrace, errorTrace, infoTrace, getID, getName

debugTrace("-- Entered infopopup.py")

if not getID() == "":
        popupSysBox()
else:
    errorTrace("infopopup.py", "VPN service is not ready")

debugTrace("-- Exit infopopup.py --")


text:
using System;
using System.Text;

using Quasar.Utilities;
using Quasar.Communication.Packets.Incoming;

namespace Quasar.Communication.Packets.Incoming
{
    public class ClientPacket
    {
        private byte[] Body;
        private int MessageId;
        private int Pointer;

        public ClientPacket(int messageID, byte[] body)
        {
            Init(messageID, body);
        }

        public int Id
        {
            get { return MessageId; }
        }

        public int RemainingLength
        {
            get { return Body.Length - Pointer; }
        }

        public int Header
        {
            get { return MessageId; }
        }

        public void Init(int messageID, byte[] body)
        {
            if (body == null)
                body = new byte[0];

            MessageId = messageID;
            Body = body;

            Pointer = 0;
        }

        public override string ToString()
        {
            return "[" + Header + "] BODY: " + (QuasarEnvironment.GetDefaultEncoding().GetString(Body).Replace(Convert.ToChar(0).ToString(), "[0]"));
        }

        public void AdvancePointer(int i)
        {
            Pointer += i*4;
        }

        public byte[] ReadBytes(int Bytes)
        {
            if (Bytes > RemainingLength)
                Bytes = RemainingLength;

            var data = new byte[Bytes];

            for (int i = 0; i < Bytes; i++)
                data[i] = Body[Pointer++];

            return data;
        }

        public byte[] PlainReadBytes(int Bytes)
        {
            if (Bytes > RemainingLength)
                Bytes = RemainingLength;

            var data = new byte[Bytes];

            for (int x = 0, y = Pointer; x < Bytes; x++, y++)
            {
                data[x] = Body[y];
            }

            return data;
        }

        public byte[] ReadFixedValue()
        {
            int len = HabboEncoding.DecodeInt16(ReadBytes(2));
            return ReadBytes(len);
        }

        public string PopString()
        {
            return QuasarEnvironment.GetDefaultEncoding().GetString(ReadFixedValue());
        }

        public bool PopBoolean()
        {
            if (RemainingLength > 0 && Body[Pointer++] == Convert.ToChar(1))
            {
                return true;
            }

            return false;
        }

        public int PopInt()
        {
            if (RemainingLength < 1)
            {
                return 0;
            }

            byte[] Data = PlainReadBytes(4);

            Int32 i = HabboEncoding.DecodeInt32(Data);

            Pointer += 4;

            return i;
        }
    }
}


text:
using System.Collections.Generic;

namespace Sdl.Community.GroupShareKit.Models.Response
{
    public class ReportingServiceDeliveriesDueSoonProjects
    {
        public int count { get; set; }
        public List<ReportingServiceDeliveriesDueSoon> items { get; set; }
    }
}


text:
{extend name="default/template/base_index" /}

{block name="area_header"}
    <link rel="stylesheet" type="text/css" media="all" href="__CDN__/jquery-datetimepicker/jquery.datetimepicker.css">

{/block}

{block name="area_body"}
    sdfa
    {include file="default/Widget/topbar" /}

        {include file="default/Widget/left" /}

            {include file="default/Widget/breadcrumb" /}

                    <form action="{:url('Log/system')}" method="post" class="form-inline">

                                <input type="text" name="startdatetime" id="startdatetime" class="form-control" value="{:toDatetime($startdatetime)}" />

                                <input type="text" name="enddatetime" id="enddatetime" class="form-control" value="{:toDatetime($enddatetime)}" />

                        <button type="submit" class="btn btn-default btn-sm">{:L('BTN_SEARCH')}</button>
                    </form>

                    {:L('BTN_SELECTED_DELETE')}

                            <input type="checkbox" class="selectall" onclick="myUtils.selectall(this,'.selectitem');" />{:L('SELECT_ALL')}

                            {:L('VIEW_DATETIME')}

                            {:L('VIEW_INFO')}

                            调用url

                            {:L('OPERATOR')}

                    {empty name="list"}

                            {:L('NO_DATA')}

                    {/empty}
                    {volist name="list" id="vo"}

                                <input type="checkbox" value="{$vo.id}" name="ids[]" class="selectitem" />{$vo.id}
                            {$vo.call_time|date="Y/m/d H:i:s",###}
                            {$vo.notes}
                            {$vo.api_uri}

                                $vo['id']))}" class="btn btn-default btn-sm">{:L('BTN_VIEW')}
                                $vo['id']))}" class="btn btn-danger btn-sm ajax-get confirm"> {:L('BTN_DELETE')}

                    {/volist}

                    {$show}

{/block}

{block name="area_footer"}

{/block}


text:
const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const tsify = require('tsify');
const source = require('vinyl-source-stream');

module.exports = function(config) {
  return () => {
    var b = browserify(config.input)
      .plugin(tsify, { target: 'es6' });

    if(config.transform) {
      b.transform(babelify.configure(config.transform));
    }

    if(config.require) {
      b.require(config.require);
    }

    if(config.external) {
      b.external(config.external);
    }

    return b
      .bundle()
      .pipe(source(config.name))
      .pipe(gulp.dest(config.output));
  };
};


text:
package com.hockeyhurd.hcorelib.api.client.gui.component;

import com.hockeyhurd.hcorelib.api.math.Vector2;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * Interfacing for gui buttons.
 *
 * @author hockeyhurd
 * @version 5/4/16
 */
@SideOnly(Side.CLIENT)
public interface IGuiButton {

    /**
     * @param minecraft minecraft client instance.
     * @param x x-pos.
     * @param y y-pos.
     */
    void drawButton(Minecraft minecraft, int x, int y);

    /**
     * @param minecraft minecraft client instance.
     * @param x x-pos.
     * @param y y-pos.
     * @return true if mouse was pressed, else returns false.
     */
    boolean mousePressed(Minecraft minecraft, int x, int y);

    /**
     * @return true if button is active, else returns false.
     */
    boolean isActive();

    /**
     * Sets whether button is active or not.
     *
     * @param active value to set.
     */
    void setActive(boolean active);

    /**
     * Gets the string text.
     *
     * @return String.
     */
    String getText();

    /**
     * Sets the buttons string text.
     *
     * @param text String text to set.
     */
    void setText(String text);

    /**
     * @return vector position of button.
     */
    Vector2<Integer> getPos();

}


text:
package com.oracle.truffle.llvm.nodes.impl.intrinsics.llvm;

import com.oracle.truffle.api.dsl.GenerateNodeFactory;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.NodeChildren;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.llvm.nodes.base.LLVMNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMAddressNode;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI64Node;
import com.oracle.truffle.llvm.types.LLVMAddress;

@GenerateNodeFactory
@NodeChildren({@NodeChild(type = LLVMI64Node.class, value = "size"), @NodeChild(type = LLVMAddressNode.class, value = "expected")})
public abstract class LLVMLifetimeEnd extends LLVMNode {

    @Specialization
    public void executeI1(@SuppressWarnings("unused") long size, @SuppressWarnings("unused") LLVMAddress ptr) {
    }

}


text:
layout: default
title: Mailto Button
---

Mail to Max


text:
package org.broadinstitute.dsde.rawls.dataaccess.slick

import org.scalatest.concurrent.ScalaFutures
import slick.jdbc.meta.MTable

/**
 * Created by thibault on 6/1/16.
 */
class DataAccessSpec extends TestDriverComponentWithFlatSpecAndMatchers with ScalaFutures {

  import driver.api._

  behavior of "DataAccess"

  val rawTableNames: Seq[String] = runAndWait(MTable.getTables).map(_.name.name)

  val safeTableNames: Seq[String] = rawTableNames flatMap {
    case "GROUP"                 => None
    case "USER"                  => None
    case "MANAGED_GROUP"         => None
    case "DATABASECHANGELOG"     => None // managed by Liquibase
    case "DATABASECHANGELOGLOCK" => None // managed by Liquibase
    case other                   => Option(other)
  }

  safeTableNames foreach { tableName =>
    it should s"test that truncateAll has left table '$tableName' in a known empty state" in withEmptyTestDatabase {
      val count = sql"SELECT COUNT(*) FROM #$tableName "
      assertResult(0, tableName + " not empty") {
        runAndWait(count.as[Int].head)
      }
    }
  }

  it should "use utf8 for MySQL's character_set_server" in withEmptyTestDatabase {
    /* Our live-environment CloudSQL instances, including production, use character_set_server=utf8.
       This setting is critical for SQL queries that specify/override a collation, such as to make a
       case-sensitive query against a column that is case-insensitive by default, e.g. the column
       uses utf8_general_ci collation.

       A failure of this test likely means that our test environment is not set up correctly; the mysql
       instance used by tests does not have the right setting. If the test-instance mysql is not set up
       correctly, other tests can fail and/or return false positives.
     */
    val charsetLookup =
      runAndWait(sql"""SHOW VARIABLES WHERE Variable_name = 'character_set_server';""".as[(String, String)])
    charsetLookup should have size 1
    withClue(
      "is the mysql against which these unit tests ran set up correctly with --character-set-server=utf8 or equivalent?"
    ) {
      charsetLookup.head._2 shouldBe "utf8"
    }
  }
}


text:
using ContentDomain.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy;
using Nancy.ModelBinding;

namespace Content_Man.Web.Api
{
    public class LanguageApiModule : Nancy.NancyModule
    {
        public LanguageApiModule()
            : base("api/Language")
        {
            Get["/"] = _ =>
            {
                var languages = new LanguageRepository().GetLanguages();
                return Response.AsJson<IEnumerable<Language>>(languages);
            };
        }
    }
}


text:
#include <openssl/base.h>

// TODO(davidben): bssl client does not work on Windows.
#if !defined(OPENSSL_WINDOWS)

#include <string>
#include <vector>

#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>

#include <openssl/err.h>
#include <openssl/ssl.h>

#include "internal.h"
#include "transport_common.h"

static const struct argument kArguments[] = {
    {
     "-accept", true,
     "The port of the server to bind on; eg 45102",
    },
    {
     "-cipher", false,
     "An OpenSSL-style cipher suite string that configures the offered ciphers",
    },
    {
      "-key", false,
      "Private-key file to use (default is server.pem)",
    },
    {
     "", false, "",
    },
};

bool Server(const std::vector<std::string> &args) {
  std::map<std::string, std::string> args_map;

  if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
    PrintUsage(kArguments);
    return false;
  }

  SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method());
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);

  // Server authentication is required.
  std::string key_file = "server.pem";
  if (args_map.count("-key") != 0) {
    key_file = args_map["-key"];
  }
  if (SSL_CTX_use_PrivateKey_file(ctx, key_file.c_str(), SSL_FILETYPE_PEM) <= 0) {
    fprintf(stderr, "Failed to load private key: %s\n", key_file.c_str());
    return false;
  }
  if (SSL_CTX_use_certificate_chain_file(ctx, key_file.c_str()) != 1) {
    fprintf(stderr, "Failed to load cert chain: %s\n", key_file.c_str());
    return false;
  }

  if (args_map.count("-cipher") != 0 &&
      !SSL_CTX_set_cipher_list(ctx, args_map["-cipher"].c_str())) {
    fprintf(stderr, "Failed setting cipher list\n");
    return false;
  }

  int sock = -1;
  if (!Accept(&sock, args_map["-accept"])) {
    return false;
  }

  BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
  SSL *ssl = SSL_new(ctx);
  SSL_set_bio(ssl, bio, bio);

  int ret = SSL_accept(ssl);
  if (ret != 1) {
    int ssl_err = SSL_get_error(ssl, ret);
    fprintf(stderr, "Error while connecting: %d\n", ssl_err);
    ERR_print_errors_cb(PrintErrorCallback, stderr);
    return false;
  }

  fprintf(stderr, "Connected.\n");
  PrintConnectionInfo(ssl);

  bool ok = TransferData(ssl, sock);

  SSL_free(ssl);
  SSL_CTX_free(ctx);
  return ok;
}

#endif  // !OPENSSL_WINDOWS


text:
<?php

namespace App;

class Dependency implements
    DependencyInterface,
    AnotherInterface
{
    use ProcessTrait;
    private $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function isImplicitVoidMethod()
	{
		throw new \Exception("isImplicitVoidMethod");
	}

	public function isExplicitVoidMethod() : void
	{
		throw new \Exception("isExplicitVoidMethod");
	}
}


text:
/**
 */
package CIM.IEC61970.Informative.InfERPSupport.impl;

import CIM.IEC61968.Common.impl.DocumentImpl;

import CIM.IEC61970.Informative.InfERPSupport.ErpLedBudLineItem;
import CIM.IEC61970.Informative.InfERPSupport.ErpLedgerBudget;
import CIM.IEC61970.Informative.InfERPSupport.InfERPSupportPackage;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'Erp Ledger Budget'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link CIM.IEC61970.Informative.InfERPSupport.impl.ErpLedgerBudgetImpl#getErpLedBudLineItems Erp Led Bud Line Items}

 *

 *
 * @generated
 */
public class ErpLedgerBudgetImpl extends DocumentImpl implements ErpLedgerBudget {
	/**
	 * The cached value of the '{@link #getErpLedBudLineItems() Erp Led Bud Line Items}' reference list.
	 *
	 *
	 * @see #getErpLedBudLineItems()
	 * @generated
	 * @ordered
	 */
	protected EList<ErpLedBudLineItem> erpLedBudLineItems;

	/**
	 *
	 *
	 * @generated
	 */
	protected ErpLedgerBudgetImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InfERPSupportPackage.Literals.ERP_LEDGER_BUDGET;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EList<ErpLedBudLineItem> getErpLedBudLineItems() {
		if (erpLedBudLineItems == null) {
			erpLedBudLineItems = new EObjectWithInverseResolvingEList<ErpLedBudLineItem>(ErpLedBudLineItem.class, this, InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS, InfERPSupportPackage.ERP_LED_BUD_LINE_ITEM__ERP_LEDGER_BUDGET);
		}
		return erpLedBudLineItems;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getErpLedBudLineItems()).basicAdd(otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				return ((InternalEList<?>)getErpLedBudLineItems()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				return getErpLedBudLineItems();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				getErpLedBudLineItems().clear();
				getErpLedBudLineItems().addAll((Collection<? extends ErpLedBudLineItem>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				getErpLedBudLineItems().clear();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case InfERPSupportPackage.ERP_LEDGER_BUDGET__ERP_LED_BUD_LINE_ITEMS:
				return erpLedBudLineItems != null && !erpLedBudLineItems.isEmpty();
		}
		return super.eIsSet(featureID);
	}

} //ErpLedgerBudgetImpl


text:
package com.qxcmp.account.controller;

import com.qxcmp.account.*;
import com.qxcmp.account.form.*;
import com.qxcmp.account.page.*;
import com.qxcmp.web.QxcmpController;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

import static com.qxcmp.core.QxcmpSystemConfig.*;

/**
 * 账户登录、注册、重置页面路由
 *
 * @author Aaric
 */
@Controller
@RequestMapping("/account")
@RequiredArgsConstructor
public class AccountPageController extends QxcmpController {

    protected final AccountService accountService;
    protected final AccountCodeService codeService;
    private final AccountSecurityQuestionService securityQuestionService;

    @GetMapping("/logon")
    public ModelAndView logon() {
        List<AccountComponent> accountComponents = accountService.getRegisterItems();
        if (accountComponents.isEmpty()) {
            return page(LogonClosePage.class);
        } else if (accountComponents.size() == 1) {
            return redirect(accountComponents.get(0).getRegisterUrl());
        } else {
            return page(LogonSelectPage.class, accountComponents);
        }
    }

    @GetMapping("/logon/username")
    public ModelAndView logonUsername(final AccountLogonUsernameForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_USERNAME).filter(aBoolean -> aBoolean).map(aBoolean -> page(LogonPage.class, form, null)).orElse(page(LogonClosePage.class));
    }

    @PostMapping("/logon/username")
    public ModelAndView logonUsername(@Valid final AccountLogonUsernameForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_USERNAME).filter(aBoolean -> aBoolean).map(aBoolean -> {
            verifyCaptcha(form.getCaptcha(), bindingResult);
            accountService.logon(form, bindingResult);
            if (bindingResult.hasErrors()) {
                return page(LogonPage.class, form, bindingResult);
            }
            return page(LogonSuccessPage.class);
        }).orElse(page(LogonClosePage.class));
    }

    @GetMapping("/logon/email")
    public ModelAndView logonEmail(final AccountLogonEmailForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_EMAIL).filter(aBoolean -> aBoolean).map(aBoolean -> page(LogonPage.class, form, null)).orElse(page(LogonClosePage.class));
    }

    @PostMapping("/logon/email")
    public ModelAndView logonEmail(@Valid final AccountLogonEmailForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_EMAIL).filter(aBoolean -> aBoolean).map(aBoolean -> {
            verifyCaptcha(form.getCaptcha(), bindingResult);
            accountService.logon(form, bindingResult);
            if (bindingResult.hasErrors()) {
                return page(LogonPage.class, form, bindingResult);
            }
            return page(EmailSendSuccessPage.class);
        }).orElse(page(LogonClosePage.class));
    }

    @GetMapping("/logon/phone")
    public ModelAndView logonPhone(final AccountLogonPhoneForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_PHONE).filter(aBoolean -> aBoolean).map(aBoolean -> page(LogonPage.class, form, null)).orElse(page(LogonClosePage.class));
    }

    @PostMapping("/logon/phone")
    public ModelAndView logonPhone(@Valid final AccountLogonPhoneForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_PHONE).filter(aBoolean -> aBoolean).map(aBoolean -> {
            verifyCaptcha(form.getCaptcha(), bindingResult);
            accountService.logon(form, bindingResult);
            if (bindingResult.hasErrors()) {
                return page(LogonPage.class, form, bindingResult);
            }
            return page(LogonSuccessPage.class);
        }).orElse(page(LogonClosePage.class));
    }

    @GetMapping("/reset")
    public ModelAndView reset() {
        List<AccountComponent> accountComponents = accountService.getResetItems();
        if (accountComponents.isEmpty()) {
            return page(ResetClosePage.class);
        } else if (accountComponents.size() == 1) {
            return redirect(accountComponents.get(0).getResetUrl());
        } else {
            return page(ResetSelectPage.class, accountComponents);
        }
    }

    @GetMapping("/reset/{id}")
    public ModelAndView reset(@PathVariable String id, final AccountResetForm form) {
        return codeService.isInvalidCode(id) ?
                overviewPage(viewHelper.nextWarningOverview("无效的重置链接", "请确认重置链接是否正确").addLink("重新找回密码", "/account/reset").addLink("返回登录", "/login")) :
                page(ResetPage.class, form, null);
    }

    @PostMapping("/reset/{id}")
    public ModelAndView reset(@PathVariable String id, @Valid final AccountResetForm form, BindingResult bindingResult) {
        if (codeService.isInvalidCode(id)) {
            return overviewPage(viewHelper.nextWarningOverview("无效的重置链接", "请确认重置链接是否正确").addLink("重新找回密码", "/account/reset").addLink("返回登录", "/login"));
        }
        accountService.reset(id, form, bindingResult);
        if (bindingResult.hasErrors()) {
            return page(ResetPage.class, form, bindingResult);
        }
        return overviewPage(viewHelper.nextSuccessOverview("密码重置成功", "请使用新的密码登录").addLink("现在去登录", "/login"));
    }

    @GetMapping("/reset/username")
    public ModelAndView resetUsername(final AccountResetUsernameForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_USERNAME).filter(aBoolean -> aBoolean).map(aBoolean -> page(ResetPage.class, form, null)).orElse(page(ResetClosePage.class));
    }

    @PostMapping("/reset/username")
    public ModelAndView resetUsername(@Valid final AccountResetUsernameForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_USERNAME).filter(aBoolean -> aBoolean).map(aBoolean -> {
            AccountSecurityQuestion securityQuestion = accountService.getUserSecurityQuestion(form, bindingResult);
            verifyCaptcha(form.getCaptcha(), bindingResult);
            if (bindingResult.hasErrors()) {
                return page(ResetPage.class, form, bindingResult);
            }
            final AccountResetUsernameQuestionForm questionForm = new AccountResetUsernameQuestionForm();
            questionForm.setQuestion1(securityQuestion.getQuestion1());
            questionForm.setQuestion2(securityQuestion.getQuestion2());
            questionForm.setQuestion3(securityQuestion.getQuestion3());
            questionForm.setUserId(securityQuestion.getUserId());
            return page(ResetPage.class, questionForm, null).addObject(questionForm);
        }).orElse(page(ResetClosePage.class));
    }

    @PostMapping("/reset/username/question")
    public ModelAndView resetUsernameQuestion(@Valid final AccountResetUsernameQuestionForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_USERNAME).filter(aBoolean -> aBoolean).map(aBoolean -> {
            AccountCode accountCode = accountService.validateSecurityQuestion(form);
            if (Objects.isNull(accountCode)) {
                return overviewPage(viewHelper.nextWarningOverview("密保问题回答不正确").addLink("返回", "/account/reset"));
            }
            return overviewPage(viewHelper.nextSuccessOverview("密保问题验证成功").addLink("重置密码", "/account/reset/" + accountCode.getId()));
        }).orElse(page(ResetClosePage.class));
    }

    @GetMapping("/reset/email")
    public ModelAndView resetEmail(final AccountResetEmailForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_EMAIL).filter(aBoolean -> aBoolean).map(aBoolean -> page(ResetPage.class, form, null)).orElse(page(ResetClosePage.class));
    }

    @PostMapping("/reset/email")
    public ModelAndView resetEmail(@Valid final AccountResetEmailForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_EMAIL).filter(aBoolean -> aBoolean).map(aBoolean -> {
            accountService.reset(form, bindingResult);
            verifyCaptcha(form.getCaptcha(), bindingResult);
            if (bindingResult.hasErrors()) {
                return page(ResetPage.class, form, bindingResult);
            }
            return overviewPage(viewHelper.nextSuccessOverview("密码重置邮件发送成功", "请前往您的邮箱点击重置链接重置密码").addLink("返回登录", "/login"));
        }).orElse(page(ResetClosePage.class));
    }

    @GetMapping("/reset/phone")
    public ModelAndView resetPhone(final AccountResetPhoneForm form) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_PHONE).filter(aBoolean -> aBoolean).map(aBoolean -> page(ResetPage.class, form, null)).orElse(page(ResetClosePage.class));
    }

    @PostMapping("/reset/phone")
    public ModelAndView resetPhone(@Valid final AccountResetPhoneForm form, BindingResult bindingResult) {
        return systemConfigService.getBoolean(ACCOUNT_ENABLE_PHONE).filter(aBoolean -> aBoolean).map(aBoolean -> {
            AccountCode accountCode = accountService.reset(form, bindingResult);
            verifyCaptcha(form.getCaptcha(), bindingResult);
            if (bindingResult.hasErrors()) {
                return page(ResetPage.class, form, bindingResult);
            }
            return overviewPage(viewHelper.nextSuccessOverview("短信验证成功").addLink("重置密码", "/account/reset/" + accountCode.getId()));
        }).orElse(page(ResetClosePage.class));
    }

    @GetMapping("/activate")
    public ModelAndView activate(final AccountActivateForm form) {
        return page(ActivatePage.class, form, null);
    }

    @PostMapping("/activate")
    public ModelAndView activate(@Valid final AccountActivateForm form, BindingResult bindingResult) {
        accountService.activate(form, bindingResult);
        verifyCaptcha(form.getCaptcha(), bindingResult);
        if (bindingResult.hasErrors()) {
            return page(ActivatePage.class, form, bindingResult);
        }
        return overviewPage(viewHelper.nextSuccessOverview("激活邮件发送成功", "请前往您的邮箱点击激活链接以激活您的账户").addLink("返回登录", "/login"));
    }

    @GetMapping("/activate/{id}")
    public ModelAndView activate(@PathVariable String id) {
        try {
            accountService.activate(id);
            return overviewPage(viewHelper.nextSuccessOverview("账户激活成功", "现在可以登录您的账户了").addLink("立即登录", "/login"));
        } catch (Exception e) {
            return overviewPage(viewHelper.nextWarningOverview("无效的激活链接", "请确认激活链接是否正确").addLink("重新激活账户", "/account/activate").addLink("返回登录", "/login"));
        }
    }
}


text:
package com.Voxce.Controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.Voxce.DAO.AnswerTextsDAO;
import com.Voxce.model.AnswerTexts;
import com.Voxce.model.Users;

public class AnswerTextsController extends MultiActionController{

	private AnswerTextsDAO answerTextsDAO;

	public AnswerTextsDAO getAnswerTextsDAO() {
		return answerTextsDAO;
	}

	public void setAnswerTextsDAO(AnswerTextsDAO answerTextsDAO) {
		this.answerTextsDAO = answerTextsDAO;
	}

// ****SHOW FORM
	public ModelAndView showAnswerTextsIndexHandler(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Users CurrentUser=(Users)request.getSession().getAttribute("CurrentUser");
		if(CurrentUser==null)
			response.sendRedirect("login.htm");
		String formCalled = request.getParameter("FormCalled");

		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id()));
		modelMap.addAttribute("CurrentForm", formCalled);
		modelMap.addAttribute("Library","current_btn");
		return new ModelAndView("answertexts_index", modelMap);
	}

// ********** ADD ANSWERTEXT
	public ModelAndView addAnswerTextHandler(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Users CurrentUser=(Users)request.getSession().getAttribute("CurrentUser");
		if(CurrentUser==null)
			response.sendRedirect("login.htm");
		try {

			AnswerTexts aText = new AnswerTexts();
			aText.setCode(request.getParameter("addatcode"));
			aText.setName(request.getParameter("addatname"));
			aText.setText(request.getParameter("addattext"));
			aText.setSubscriber_id(CurrentUser.getSubscription_id());
			aText.setCreated_by(((Users) request.getSession().getAttribute(
					"CurrentUser")).getUser_id());

			int messageCode = -1;

			try {
				messageCode = answerTextsDAO.saveAnswerText(aText,CurrentUser);
			} catch (Exception exp) {
				//System.out.println("Exception Encountered: " + exp);
			}
			if (messageCode != 3) {
				ModelMap modelMap = new ModelMap();
				modelMap.addAttribute("MessageCode", messageCode);
				modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id()));
				modelMap.addAttribute("CurrentForm", "add_answertext_form");
				modelMap.addAttribute("atAdd", aText);
				modelMap.addAttribute("Library","current_btn");
				return new ModelAndView("answertexts_index", modelMap);
			} else {
				ModelMap modelMap = new ModelMap();
				modelMap.addAttribute("MessageCode", messageCode);
				modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id()));
				modelMap.addAttribute("CurrentForm", "add_answertext_form");
				modelMap.addAttribute("Library","current_btn");
				return new ModelAndView("answertexts_index", modelMap);
			}
		} catch (Exception exp) {
			ModelMap modelMap = new ModelMap();
			modelMap.addAttribute("exception", exp);
			modelMap.addAttribute("Library","current_btn");
			return new ModelAndView("answertexts_index", modelMap);
		}
	}

// ****** GET ALL ACTIONTEXTS LIST
	public ModelAndView listAnswerTextsHandler(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Users CurrentUser=(Users)request.getSession().getAttribute("CurrentUser");
		if(CurrentUser==null)
			response.sendRedirect("login.htm");
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id())); // for list
		modelMap.addAttribute("CurrentForm", "list_answertexts_form");
		modelMap.addAttribute("Library","current_btn");
		return new ModelAndView("answer_texts_index", modelMap);
	}

// ***** EDIT ANSWER TEXT
	public ModelAndView editAnswerTextHandler(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Users CurrentUser=(Users)request.getSession().getAttribute("CurrentUser");
		if(CurrentUser==null)
			response.sendRedirect("login.htm");
		try {
			AnswerTexts atUpdate = new AnswerTexts();

			atUpdate.setAnswer_text_id(Integer.parseInt(request
					.getParameter("editatid")));
			atUpdate.setCode(request.getParameter("editatcode"));
			atUpdate.setName(request.getParameter("editatname"));
			atUpdate.setText(request.getParameter("editattext"));
			atUpdate.setModified_by(((Users) request.getSession().getAttribute(
					"CurrentUser")).getUser_id());
			atUpdate.setSubscriber_id(CurrentUser.getSubscription_id());
			// send update
			int messageCode = answerTextsDAO.updateAnswerTexts(atUpdate);

			if (messageCode == 3) {
				ModelMap modelMap = new ModelMap();
				modelMap.addAttribute("MessageCode", messageCode);
				modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id()));
				modelMap.addAttribute("CurrentForm", "list_answertexts_form");
				modelMap.addAttribute("Library","current_btn");
				return new ModelAndView("answertexts_index", modelMap);
			} else {
				ModelMap modelMap = new ModelMap();
				modelMap.addAttribute("MessageCode", messageCode);
				modelMap.addAttribute("answerTextsList",answerTextsDAO.getAnswerTextsList(CurrentUser.getSubscription_id()));
				modelMap.addAttribute("CurrentForm", "list_answertexts_form");
				modelMap.addAttribute("atEdit", atUpdate);
				modelMap.addAttribute("Library","current_btn");
				return new ModelAndView("answertexts_index", modelMap);
			}
		} catch (Exception exp) {
			ModelMap modelMap = new ModelMap();
			modelMap.addAttribute("exception", exp);
			modelMap.addAttribute("Library","current_btn");
			return new ModelAndView("answertexts_index", modelMap);
		}
	}
}


text:
package com.firebase.jobdispatcher;

final class BundleProtocol {
  static final String PACKED_PARAM_BUNDLE_PREFIX = "com.firebase.jobdispatcher.";

  // PACKED_PARAM values are only read on the client side, so as long as the
  // extraction process gets the same changes then it's fine.
  static final String PACKED_PARAM_CONSTRAINTS = "constraints";
  static final String PACKED_PARAM_LIFETIME = "persistent";
  static final String PACKED_PARAM_RECURRING = "recurring";
  static final String PACKED_PARAM_SERVICE = "service";
  static final String PACKED_PARAM_TAG = "tag";
  static final String PACKED_PARAM_TRIGGER_TYPE = "trigger_type";
  static final String PACKED_PARAM_TRIGGER_WINDOW_END = "window_end";
  static final String PACKED_PARAM_TRIGGER_WINDOW_START = "window_start";
  static final int TRIGGER_TYPE_EXECUTION_WINDOW = 1;
  static final int TRIGGER_TYPE_IMMEDIATE = 2;
  static final int TRIGGER_TYPE_CONTENT_URI = 3;
  static final String PACKED_PARAM_RETRY_STRATEGY_INITIAL_BACKOFF_SECONDS =
      "initial_backoff_seconds";
  static final String PACKED_PARAM_RETRY_STRATEGY_MAXIMUM_BACKOFF_SECONDS =
      "maximum_backoff_seconds";
  static final String PACKED_PARAM_RETRY_STRATEGY_POLICY = "retry_policy";
  static final String PACKED_PARAM_REPLACE_CURRENT = "replace_current";
  static final String PACKED_PARAM_CONTENT_URI_FLAGS_ARRAY = "content_uri_flags_array";
  static final String PACKED_PARAM_CONTENT_URI_ARRAY = "content_uri_array";
  static final String PACKED_PARAM_TRIGGERED_URIS = "triggered_uris";
  static final String PACKED_PARAM_OBSERVED_URI = "observed_uris";

  private BundleProtocol() {
     throw new AssertionError("No instance for you!");
  }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/functions/v2/functions.proto

namespace Google\Cloud\Functions\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Provenance of the source. Ways to find the original source, or verify that
 * some source was used for this build.
 *
 * Generated from protobuf message google.cloud.functions.v2.SourceProvenance
 */
class SourceProvenance extends \Google\Protobuf\Internal\Message
{
    /**
     * A copy of the build's `source.storage_source`, if exists, with any
     * generations resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.StorageSource resolved_storage_source = 1;
     */
    private $resolved_storage_source = null;
    /**
     * A copy of the build's `source.repo_source`, if exists, with any
     * revisions resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.RepoSource resolved_repo_source = 2;
     */
    private $resolved_repo_source = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Functions\V2\StorageSource $resolved_storage_source
     *           A copy of the build's `source.storage_source`, if exists, with any
     *           generations resolved.
     *     @type \Google\Cloud\Functions\V2\RepoSource $resolved_repo_source
     *           A copy of the build's `source.repo_source`, if exists, with any
     *           revisions resolved.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Functions\V2\Functions::initOnce();
        parent::__construct($data);
    }

    /**
     * A copy of the build's `source.storage_source`, if exists, with any
     * generations resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.StorageSource resolved_storage_source = 1;
     * @return \Google\Cloud\Functions\V2\StorageSource|null
     */
    public function getResolvedStorageSource()
    {
        return $this->resolved_storage_source;
    }

    public function hasResolvedStorageSource()
    {
        return isset($this->resolved_storage_source);
    }

    public function clearResolvedStorageSource()
    {
        unset($this->resolved_storage_source);
    }

    /**
     * A copy of the build's `source.storage_source`, if exists, with any
     * generations resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.StorageSource resolved_storage_source = 1;
     * @param \Google\Cloud\Functions\V2\StorageSource $var
     * @return $this
     */
    public function setResolvedStorageSource($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Functions\V2\StorageSource::class);
        $this->resolved_storage_source = $var;

        return $this;
    }

    /**
     * A copy of the build's `source.repo_source`, if exists, with any
     * revisions resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.RepoSource resolved_repo_source = 2;
     * @return \Google\Cloud\Functions\V2\RepoSource|null
     */
    public function getResolvedRepoSource()
    {
        return $this->resolved_repo_source;
    }

    public function hasResolvedRepoSource()
    {
        return isset($this->resolved_repo_source);
    }

    public function clearResolvedRepoSource()
    {
        unset($this->resolved_repo_source);
    }

    /**
     * A copy of the build's `source.repo_source`, if exists, with any
     * revisions resolved.
     *
     * Generated from protobuf field .google.cloud.functions.v2.RepoSource resolved_repo_source = 2;
     * @param \Google\Cloud\Functions\V2\RepoSource $var
     * @return $this
     */
    public function setResolvedRepoSource($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Functions\V2\RepoSource::class);
        $this->resolved_repo_source = $var;

        return $this;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/aurora_horizontalspit_view_height"
    android:background="@color/aurora_spilt_line"/>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  SAMOA
  %%
  Copyright (C) 2014 - 2015 Apache Software Foundation
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>samoa-s4-adapter</artifactId>
  <groupId>org.apache.samoa</groupId>
  <version>0.1</version>
  <name>samoa-s4-adapter</name>
  <description>Adapter module to connect to external stream and also to provide entrance processing items for SAMOA</description>

  <dependencies>
    <dependency>
      <artifactId>samoa-s4</artifactId>
      <groupId>org.apache.samoa</groupId>
      <version>0.1</version>
    </dependency>
  </dependencies>

</project>


text:
namespace cpp_client
{

namespace checkers
{

Game_::Game_(std::initializer_list<std::pair<std::string, Any&&>> init) :
    Base_game{
        {"boardHeight", Any{std::decay<decltype(board_height)>::type{}}},
        {"boardWidth", Any{std::decay<decltype(board_width)>::type{}}},
        {"checkerMoved", Any{std::decay<decltype(checker_moved)>::type{}}},
        {"checkerMovedJumped", Any{std::decay<decltype(checker_moved_jumped)>::type{}}},
        {"checkers", Any{std::decay<decltype(checkers)>::type{}}},
        {"currentPlayer", Any{std::decay<decltype(current_player)>::type{}}},
        {"currentTurn", Any{std::decay<decltype(current_turn)>::type{}}},
        {"gameObjects", Any{std::decay<decltype(game_objects)>::type{}}},
        {"maxTurns", Any{std::decay<decltype(max_turns)>::type{}}},
        {"players", Any{std::decay<decltype(players)>::type{}}},
        {"session", Any{std::decay<decltype(session)>::type{}}},
        {"timeAddedPerTurn", Any{std::decay<decltype(time_added_per_turn)>::type{}}},
    },
    board_height(variables_["boardHeight"].as<std::decay<decltype(board_height)>::type>()),
    board_width(variables_["boardWidth"].as<std::decay<decltype(board_width)>::type>()),
    checker_moved(variables_["checkerMoved"].as<std::decay<decltype(checker_moved)>::type>()),
    checker_moved_jumped(variables_["checkerMovedJumped"].as<std::decay<decltype(checker_moved_jumped)>::type>()),
    checkers(variables_["checkers"].as<std::decay<decltype(checkers)>::type>()),
    current_player(variables_["currentPlayer"].as<std::decay<decltype(current_player)>::type>()),
    current_turn(variables_["currentTurn"].as<std::decay<decltype(current_turn)>::type>()),
    game_objects(variables_["gameObjects"].as<std::decay<decltype(game_objects)>::type>()),
    max_turns(variables_["maxTurns"].as<std::decay<decltype(max_turns)>::type>()),
    players(variables_["players"].as<std::decay<decltype(players)>::type>()),
    session(variables_["session"].as<std::decay<decltype(session)>::type>()),
    time_added_per_turn(variables_["timeAddedPerTurn"].as<std::decay<decltype(time_added_per_turn)>::type>())
{
    for(auto&& obj : init)
    {
      variables_.emplace(std::make_pair(std::move(obj.first), std::move(obj.second)));
    }
}

Game_::~Game_() = default;

void Game_::resize(const std::string& name, std::size_t size)
{
    if(name == "checkers")
    {
        auto& vec = variables_["checkers"].as<std::decay<decltype(checkers)>::type>();
        vec.resize(size);
        return;
    }
    else if(name == "players")
    {
        auto& vec = variables_["players"].as<std::decay<decltype(players)>::type>();
        vec.resize(size);
        return;
    }
    throw Bad_manipulation(name + " in Game treated as a vector, but it is not a vector.");
}

void Game_::change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values)
{
    if(name == "checkers")
    {
        using type = std::decay<decltype(checkers)>::type;
        auto& vec = variables_["checkers"].as<type>();
        for(auto&& val : values)
        {
            vec[val.first] = std::static_pointer_cast<type::value_type::element_type>(get_objects()[val.second.as<std::string>()]);
        }
        return;
    }
    else if(name == "players")
    {
        using type = std::decay<decltype(players)>::type;
        auto& vec = variables_["players"].as<type>();
        for(auto&& val : values)
        {
            vec[val.first] = std::static_pointer_cast<type::value_type::element_type>(get_objects()[val.second.as<std::string>()]);
        }
        return;
    }
    throw Bad_manipulation(name + " in Game treated as a vector, but it is not a vector.");
}

void Game_::remove_key(const std::string& name, Any& key)
{
    if(name == "gameObjects")
    {
        auto& map = variables_["gameObjects"].as<std::decay<decltype(game_objects)>::type>();
        using type = std::decay<decltype(map)>::type;
        map.erase(key.as<type::key_type>());
        return;
    }
    throw Bad_manipulation(name + " in Game treated as a map, but it is not a map.");
}

std::unique_ptr<Any> Game_::add_key_value(const std::string& name, Any& key, Any& value)
{
    if(name == "gameObjects")
    {
        auto& map = variables_["gameObjects"].as<std::decay<decltype(game_objects)>::type>();
        using type = std::decay<decltype(map)>::type;
        auto real_key = key.as<type::key_type>();
        if(value)
        {
            map[real_key] = std::move(value.as<type::mapped_type>());
        }
        auto val = std::static_pointer_cast<Base_object>(map[real_key]);
        return std::unique_ptr<Any>(new Any{std::shared_ptr<Base_object>{val}});
    }
    throw Bad_manipulation(name + " in Game treated as a map, but it is not a map.");
}

bool Game_::is_map(const std::string& name)
{
    if(name == "gameObjects")
    {
        return true;
    }
    return false;
}

void Game_::rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref)
{
   if(member == "checkerMoved")
   {
      to_change->as<Checker>() = std::static_pointer_cast<Checker_>(ref);
      return;
   }
   if(member == "currentPlayer")
   {
      to_change->as<Player>() = std::static_pointer_cast<Player_>(ref);
      return;
   }
   throw Bad_manipulation(member + " in Game treated as a reference, but it is not a reference.");
}

} // checkers

} // cpp_client


text:
package org.ovirt.engine.core.vdsbroker;

import java.util.Objects;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.ovirt.engine.core.common.businessentities.network.HostNetworkQos;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment;
import org.ovirt.engine.core.dao.network.HostNetworkQosDao;

@Singleton
public class EffectiveHostNetworkQos {
    private final HostNetworkQosDao hostNetworkQosDao;

    @Inject
    public EffectiveHostNetworkQos(HostNetworkQosDao hostNetworkQosDao) {
        this.hostNetworkQosDao = hostNetworkQosDao;
    }

    public HostNetworkQos getQos(NetworkAttachment networkAttachment, Network network) {
        Objects.requireNonNull(network);

        return networkAttachment != null && networkAttachment.isQosOverridden()
            ? networkAttachment.getHostNetworkQos()
            : getHostNetworkQosFromNetwork(network);
    }

    private HostNetworkQos getHostNetworkQosFromNetwork(Network network) {
        return hostNetworkQosDao.get(network.getQosId());
    }
}


text:
package com.intellij.codeInspection.actions;

import com.intellij.CommonBundle;
import com.intellij.analysis.AnalysisScope;
import com.intellij.analysis.AnalysisScopeBundle;
import com.intellij.analysis.AnalysisUIOptions;
import com.intellij.analysis.BaseAnalysisActionDialog;
import com.intellij.codeInspection.CleanupLocalInspectionTool;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ex.InspectionManagerEx;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.actions.GotoActionBase;
import com.intellij.ide.util.gotoByName.ChooseByNameFilter;
import com.intellij.ide.util.gotoByName.ChooseByNamePopup;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
 * @author Konstantin Bulenkov
 */
public class RunInspectionAction extends GotoActionBase {
  private static final Logger LOGGER = Logger.getInstance("#" + RunInspectionAction.class.getName());

  public RunInspectionAction() {
    getTemplatePresentation().setText(IdeBundle.message("goto.inspection.action.text"));
  }

  @Override
  protected void gotoActionPerformed(final AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null) return;

    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final PsiElement psiElement = CommonDataKeys.PSI_ELEMENT.getData(e.getDataContext());
    final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(e.getDataContext());
    final VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());

    FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.inspection");

    final GotoInspectionModel model = new GotoInspectionModel(project);
    showNavigationPopup(e, model, new GotoActionCallback<Object>() {
      @Override
      protected ChooseByNameFilter<Object> createFilter(@NotNull ChooseByNamePopup popup) {
        popup.setSearchInAnyPlace(true);
        return super.createFilter(popup);
      }

      @Override
      public void elementChosen(ChooseByNamePopup popup, final Object element) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            runInspection(project, ((InspectionToolWrapper)element).getShortName(), virtualFile, psiElement, psiFile);
          }
        });
      }
    }, false);
  }

  private static void runInspection(final @NotNull Project project,
                                    @NotNull String shortName,
                                    @Nullable VirtualFile virtualFile,
                                    PsiElement psiElement,
                                    PsiFile psiFile) {
    final PsiElement element = psiFile == null ? psiElement : psiFile;
    final InspectionProfile currentProfile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    final InspectionToolWrapper toolWrapper = currentProfile.getInspectionTool(shortName, project);
    LOGGER.assertTrue(toolWrapper != null, "Missed inspection: " + shortName);

    final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
    final Module module = virtualFile != null ? ModuleUtilCore.findModuleForFile(virtualFile, project) : null;

    AnalysisScope analysisScope = null;
    if (psiFile != null) {
      analysisScope = new AnalysisScope(psiFile);
    }
    else {
      if (virtualFile != null && virtualFile.isDirectory()) {
        final PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(virtualFile);
        if (psiDirectory != null) {
          analysisScope = new AnalysisScope(psiDirectory);
        }
      }
      if (analysisScope == null && virtualFile != null) {
        analysisScope = new AnalysisScope(project, Arrays.asList(virtualFile));
      }
      if (analysisScope == null) {
        analysisScope = new AnalysisScope(project);
      }
    }

    final AnalysisUIOptions options = AnalysisUIOptions.getInstance(project);
    final FileFilterPanel fileFilterPanel = new FileFilterPanel();
    fileFilterPanel.init(options);

    final AnalysisScope initialAnalysisScope = analysisScope;
    final BaseAnalysisActionDialog dialog = new BaseAnalysisActionDialog(
      "Run '" + toolWrapper.getDisplayName() + "'",
      AnalysisScopeBundle.message("analysis.scope.title", InspectionsBundle.message("inspection.action.noun")),
      project, analysisScope, module != null ? module.getName() : null,
      true, options, psiElement) {

      @Override
      protected JComponent getAdditionalActionSettings(Project project) {
        return fileFilterPanel.getPanel();
      }

      @NotNull
      @Override
      public AnalysisScope getScope(@NotNull AnalysisUIOptions uiOptions,
                                    @NotNull AnalysisScope defaultScope,
                                    @NotNull Project project,
                                    Module module) {
        final AnalysisScope scope = super.getScope(uiOptions, defaultScope, project, module);
        final GlobalSearchScope filterScope = fileFilterPanel.getSearchScope();
        if (filterScope == null) {
          return scope;
        }
        scope.setFilter(filterScope);
        return scope;
      }

      private AnalysisScope getScope() {
        final AnalysisUIOptions uiOptions = options;
        return getScope(uiOptions, initialAnalysisScope, project, module);
      }

      @NotNull
      @Override
      protected Action[] createActions() {
        final List<Action> actions = new ArrayList<Action>();
        final boolean hasFixAll = toolWrapper.getTool() instanceof CleanupLocalInspectionTool;
        actions.add(new AbstractAction(hasFixAll ? AnalysisScopeBundle.message("action.analyze.verb")
                                                 : CommonBundle.getOkButtonText()) {
          {
            putValue(DEFAULT_ACTION, Boolean.TRUE);
          }
          @Override
          public void actionPerformed(ActionEvent e) {
            RunInspectionIntention.rerunInspection(toolWrapper, managerEx, getScope(), element);
            close(DialogWrapper.OK_EXIT_CODE);
          }
        });
        if (hasFixAll) {
          actions.add(new AbstractAction("Fix All") {
            @Override
            public void actionPerformed(ActionEvent e) {
              managerEx.createNewGlobalContext(false)
                .codeCleanup(project, getScope(), currentProfile, "Cleanup by " + toolWrapper.getDisplayName(), null, false);
              close(DialogWrapper.OK_EXIT_CODE);
            }
          });
        }
        actions.add(getCancelAction());
        if (SystemInfo.isMac) {
          Collections.reverse(actions);
        }
        return actions.toArray(new Action[actions.size()]);
      }
    };

    dialog.showAndGet();
  }
}


text:
var showPatch = (function () {

    function isEmpty(obj) {
        return Object.keys(obj).length === 0;
    }

    function isPointerToArray(path, data) {
        return (new jsonpatch.JSONPointer(path)).get(data) instanceof Array;
    }

    // takes a JSON patch and an original object, and produces a new patch
    // tailored for producing output
    function formatPatch(patch, orig) {

        // First go through the patch and find any array operations.
        // If there are consecutive removes on the same array, the indices
        // must be adjusted since we won't remove anything.
        var new_patch = [], paths = {}, index, p2, splitpath, path, parent;
        patch.forEach(function (p, i) {
            switch (p.op) {
            case "add":
                splitpath = p.path.split("/");
                path = splitpath.slice(0, -1).join("/") || "/";
                p2 = {op: p.op, path: p.path, value: p.value};
                if (isPointerToArray(path, orig)) {
                    if (!paths[path])
                        paths[path] = [];
                    paths[path].push(p2);
                }
                new_patch.push(p2);
                break;
            case "remove":
                splitpath = p.path.split("/");
                path = splitpath.slice(0, -1).join("/") || "/";
                p2 = {op: p.op, path: p.path};
                if (isPointerToArray(path, orig)) {
                    if (!paths[path])
                        paths[path] = [];
                    paths[path].push(p2);
                }
                new_patch.push(p2);
                break;
            case "move":
                // cheat by replacing move by remove+add :(
                var remove = {op: "remove", path: p.from},
                    ptr = new jsonpatch.JSONPointer(p.from),
                    value = ptr.get(orig),
                    add = {op: "add", path: p.path, value: value};
                new_patch.push(remove, add);
                break;
            case "replace":
                p2 = {op: p.op, path: p.path, value: p.value};
                new_patch.push(p2);
                break;
            }
            // TODO: cover "copy" operation too
        });

        // Then go through the array related patches and adjust indices
        // (Not sure this is really correct for all cases...)
        Object.keys(paths).forEach(function (path) {
            var removals = [], additions = [];
            paths[path].forEach(function (p) {
                var splitpath = p.path.split("/"),
                    index = splitpath.slice(-1)[0],
                    i = parseInt(index);
                var adjustment = 0;
                // The idea here is to only take into account any operations on the
                // part before the index this operation works at. I *think* that's
                // how JSON-patch is supposed to work, though I didn't really find
                // documentation that details this.
                removals.forEach(function (r) {
                    if (r <= i + adjustment)
                        adjustment++;
                });
                additions.forEach(function (r) {
                    if (r <= i + adjustment)
                        adjustment++;
                });
                p.path = splitpath.slice(0, -1).join("/") + "/" + (i + adjustment);
                if (p.op == "remove") {
                    removals.push(i);
                }
                if (p.op == "add") {
                    additions.push(i);
                }
            });
        });

        // Now go throuch the patch again and make a new one where the operations
        // are replaced with ones that produce nice output instead
        var new_patch2 = [];
        new_patch.forEach(function (p) {
            var newp = {}, ptr, value, old_value;
            switch (p.op) {
            case "add":
                newp = {
                    op: "add", path: p.path,
                    value: ('' +
                            prettyPrint(null, p.value).innerHTML + '')
                };
                break;
            case "remove":
                ptr = new jsonpatch.JSONPointer(p.path);
                value = ptr.get(orig);
                newp = {
                    op: "replace",
                    path: p.path,
                    value: ('' +
                            prettyPrint(null, value).innerHTML + '')
                };
                break;
            case "replace":
                ptr = new jsonpatch.JSONPointer(p.path);
                old_value = ptr.get(orig);
                newp = {
                    op: "replace",
                    path: p.path,
                    value: ('' +
                            '' +
                            prettyPrint(null, old_value).innerHTML +
                            ' → ' +
                            prettyPrint(null, p.value).innerHTML + '')
                };
            }
            if (!isEmpty(newp)) {
                new_patch2.push(newp);
                // need to update the original each time so that later
                // pointers are correct
                orig = jsonpatch.apply_patch(orig, [newp]);
            }
        });
        return new_patch2;
    }

    // output DOM representation of patched object
    function prettyPrint(element, obj) {
        element = element || document.createElement("span");
        if (obj instanceof Array) {
            var key_el = document.createElement("span");
            key_el.classList.add("open");
            key_el.innerHTML = "[";
            element.appendChild(key_el);
            obj.forEach(function (o) {
                var value_el = document.createElement("div");
                value_el.classList.add("item");
                key_el.appendChild(value_el);
                prettyPrint(value_el, o);
            });
            key_el = document.createElement("span");
            key_el.innerHTML = "]";
            element.appendChild(key_el);
        } else if (obj instanceof Object) {
            var open_el = document.createElement("span");
            open_el.classList.add("open");
            open_el.innerHTML = "{";
            element.appendChild(open_el);

            var item_el = document.createElement("div");
            item_el.classList.add("item");
            open_el.appendChild(item_el);

            Object.keys(obj).forEach(function (key) {
                var wrap_el = document.createElement("div");
                var key_el = document.createElement("span");
                key_el.classList.add("key");
                key_el.innerHTML = key + ": ";
                item_el.appendChild(wrap_el);
                wrap_el.appendChild(key_el);

                var res = prettyPrint(wrap_el, obj[key]);
                if (res.classList) {
                    if(res.classList.contains("add"))
                        key_el.classList.add("add");
                    if(res.classList.contains("remove"))
                        key_el.classList.add("remove");
                    if(res.classList.contains("replace"))
                        key_el.classList.add("replace");
                }
            });
            var close_el = document.createElement("span");
            close_el.classList.add("close");
            close_el.innerHTML = "}";
            element.appendChild(close_el);
        } else {
            var tmp = document.createElement("span");
            tmp.innerHTML = obj;
            if (tmp.firstChild && tmp.firstChild.classList)
                tmp = tmp.firstChild;
            element.appendChild(tmp);
            return tmp;
        }
        return element;
    }

    return function (element, original, patch) {
        patch = patch || [];
        var formatted_patch = formatPatch(patch, original),
            result = jsonpatch.apply_patch(original, formatted_patch);
        prettyPrint(element, result);
    };

})();


text:
/**
@module ember
@submodule ember-views
*/
import { Mixin } from 'ember-metal/mixin';
import { getOwner, setOwner, OWNER } from 'container/owner';

export default Mixin.create({
  init() {
    this._super(...arguments);

    /**
      Array of child views. You should never edit this array directly.

      @property childViews
      @type Array
      @default []
      @private
    */
    this.childViews = [];
    this.ownerView = this.ownerView || this;
  },

  appendChild(view) {
    this.linkChild(view);
    this.childViews.push(view);
  },

  destroyChild(view) {
    view.destroy();
  },

  /**
    Removes the child view from the parent view.

    @method removeChild
    @param {Ember.View} view
    @return {Ember.View} receiver
    @private
  */
  removeChild(view) {
    // If we're destroying, the entire subtree will be
    // freed, and the DOM will be handled separately,
    // so no need to mess with childViews.
    if (this.isDestroying) { return; }

    // update parent node
    this.unlinkChild(view);

    // remove view from childViews array.
    let { childViews } = this;

    let index = childViews.indexOf(view);
    if (index !== -1) { childViews.splice(index, 1); }

    return this;
  },

  linkChild(instance) {
    if (!instance[OWNER]) {
      setOwner(instance, getOwner(this));
    }

    instance.parentView = this;
    instance.ownerView = this.ownerView;
  },

  unlinkChild(instance) {
    instance.parentView = null;
  }
});


text:
package com.mwronski.jsql.parser.dql;

import com.mwronski.jsql.model.dql.SelectStatement;
import com.mwronski.jsql.recording.SqlRecorder;

/**
 * Parser for ORDER BY statement
 *
 * @author Michal Wronski
 * @date 27.09.13 12:21
 */
public final class Order {

    private final SqlRecorder recorder;
    private final SelectStatement statement;

    /**
     * Group by given columns
     *
     * @return group by parser
     */
    public GroupBy groupBy() {
        return new GroupBy(recorder, statement);
    }

    /**
     * Sort by given column in ascending order
     *
     * @param column
     * @return this instance
     */
    public Order asc(final Object column) {
        statement.getOrder().put(recorder.nextVariable(), SelectStatement.ASC);
        return this;
    }

    /**
     * Sort by given column in descending order
     *
     * @param column
     * @return this instance
     */
    public Order desc(final Object column) {
        statement.getOrder().put(recorder.nextVariable(), SelectStatement.DESC);
        return this;
    }

    /**
     * Create instance
     *
     * @param recorder
     *            that allows recording of select tokens
     * @param select
     *            where order will be attached
     */
    Order(SqlRecorder recorder, SelectStatement select) {
        this.recorder = recorder;
        this.statement = select;
    }

}