text:
package images_test

import (
	"context"
	"errors"
	"io"
	"testing"

	kubeadmapiv1alpha2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha2"
	"k8s.io/kubernetes/cmd/kubeadm/app/images"
	"k8s.io/utils/exec"
)

type fakeCmd struct {
	err error
}

func (f *fakeCmd) Run() error {
	return f.err
}
func (f *fakeCmd) CombinedOutput() ([]byte, error) { return nil, nil }
func (f *fakeCmd) Output() ([]byte, error)         { return nil, nil }
func (f *fakeCmd) SetDir(dir string)               {}
func (f *fakeCmd) SetStdin(in io.Reader)           {}
func (f *fakeCmd) SetStdout(out io.Writer)         {}
func (f *fakeCmd) SetStderr(out io.Writer)         {}
func (f *fakeCmd) Stop()                           {}

type fakeExecer struct {
	cmd        exec.Cmd
	findCrictl bool
	findDocker bool
}

func (f *fakeExecer) Command(cmd string, args ...string) exec.Cmd { return f.cmd }
func (f *fakeExecer) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
	return f.cmd
}
func (f *fakeExecer) LookPath(file string) (string, error) {
	if file == "crictl" {
		if f.findCrictl {
			return "/path", nil
		}
		return "", errors.New("no crictl for you")
	}
	if file == "docker" {
		if f.findDocker {
			return "/path", nil
		}
		return "", errors.New("no docker for you")
	}
	return "", errors.New("unknown binary")
}

func TestNewCRInterfacer(t *testing.T) {
	testcases := []struct {
		name        string
		criSocket   string
		findCrictl  bool
		findDocker  bool
		expectError bool
	}{
		{
			name:        "need crictl but can only find docker should return an error",
			criSocket:   "/not/docker",
			findCrictl:  false,
			findDocker:  true,
			expectError: true,
		},
		{
			name:        "need crictl and cannot find either should return an error",
			criSocket:   "/not/docker",
			findCrictl:  false,
			findDocker:  false,
			expectError: true,
		},
		{
			name:        "need crictl and cannot find docker should return no error",
			criSocket:   "/not/docker",
			findCrictl:  true,
			findDocker:  false,
			expectError: false,
		},
		{
			name:        "need crictl and can find both should return no error",
			criSocket:   "/not/docker",
			findCrictl:  true,
			findDocker:  true,
			expectError: false,
		},
		{
			name:        "need docker and cannot find crictl should return no error",
			criSocket:   kubeadmapiv1alpha2.DefaultCRISocket,
			findCrictl:  false,
			findDocker:  true,
			expectError: false,
		},
		{
			name:        "need docker and cannot find docker should return an error",
			criSocket:   kubeadmapiv1alpha2.DefaultCRISocket,
			findCrictl:  false,
			findDocker:  false,
			expectError: true,
		},
		{
			name:        "need docker and can find both should return no error",
			criSocket:   kubeadmapiv1alpha2.DefaultCRISocket,
			findCrictl:  true,
			findDocker:  true,
			expectError: false,
		},
		{
			name:        "need docker and can only find crictl should return an error",
			criSocket:   kubeadmapiv1alpha2.DefaultCRISocket,
			findCrictl:  true,
			findDocker:  false,
			expectError: true,
		},
	}

	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			fe := &fakeExecer{
				findCrictl: tc.findCrictl,
				findDocker: tc.findDocker,
			}
			_, err := images.NewCRInterfacer(fe, tc.criSocket)
			if tc.expectError && err == nil {
				t.Fatal("expected an error but did not get one")
			}
			if !tc.expectError && err != nil {
				t.Fatalf("did not expedt an error but got an error: %v", err)
			}
		})
	}
}

func TestImagePuller(t *testing.T) {
	testcases := []struct {
		name          string
		criSocket     string
		pullFails     bool
		errorExpected bool
	}{
		{
			name:          "using docker and pull fails",
			criSocket:     kubeadmapiv1alpha2.DefaultCRISocket,
			pullFails:     true,
			errorExpected: true,
		},
		{
			name:          "using docker and pull succeeds",
			criSocket:     kubeadmapiv1alpha2.DefaultCRISocket,
			pullFails:     false,
			errorExpected: false,
		},
		{
			name:          "using crictl pull fails",
			criSocket:     "/not/default",
			pullFails:     true,
			errorExpected: true,
		},
		{
			name:          "using crictl and pull succeeds",
			criSocket:     "/not/default",
			pullFails:     false,
			errorExpected: false,
		},
	}
	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			var err error
			if tc.pullFails {
				err = errors.New("error")
			}

			fe := &fakeExecer{
				cmd:        &fakeCmd{err},
				findCrictl: true,
				findDocker: true,
			}
			ip, _ := images.NewCRInterfacer(fe, tc.criSocket)

			err = ip.Pull("imageName")
			if tc.errorExpected && err == nil {
				t.Fatal("expected an error and did not get one")
			}
			if !tc.errorExpected && err != nil {
				t.Fatalf("expected no error but got one: %v", err)
			}
		})
	}
}

func TestImageExists(t *testing.T) {
	testcases := []struct {
		name          string
		criSocket     string
		existFails    bool
		errorExpected bool
	}{
		{
			name:          "using docker and exist fails",
			criSocket:     kubeadmapiv1alpha2.DefaultCRISocket,
			existFails:    true,
			errorExpected: true,
		},
		{
			name:          "using docker and exist succeeds",
			criSocket:     kubeadmapiv1alpha2.DefaultCRISocket,
			existFails:    false,
			errorExpected: false,
		},
		{
			name:          "using crictl exist fails",
			criSocket:     "/not/default",
			existFails:    true,
			errorExpected: true,
		},
		{
			name:          "using crictl and exist succeeds",
			criSocket:     "/not/default",
			existFails:    false,
			errorExpected: false,
		},
	}
	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			var err error
			if tc.existFails {
				err = errors.New("error")
			}

			fe := &fakeExecer{
				cmd:        &fakeCmd{err},
				findCrictl: true,
				findDocker: true,
			}
			ip, _ := images.NewCRInterfacer(fe, tc.criSocket)

			err = ip.Exists("imageName")
			if tc.errorExpected && err == nil {
				t.Fatal("expected an error and did not get one")
			}
			if !tc.errorExpected && err != nil {
				t.Fatalf("expected no error but got one: %v", err)
			}
		})
	}
}


text:
{include file=header.html}

{$lang.acategory}

{$acategory.cate_name|escape}

{$lang.new_article}

{$new_article.title|escape}

{$lang.no_new_article}

{include file=curlocal.html}

{$article.title|escape} {$article.add_time|date:Y.m.d}

{$lang.no_records}

	 {include file=page.bottom.html}

{include file=server.html}
{include file=footer.html}

redpajama_set_name: RedPajamaGithub


text:
package components.workers;

import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;

import javax.swing.ImageIcon;
import javax.swing.SwingWorker;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import commons.api.SteamAchievementsList;
import components.commons.ColoredTee;
import components.workers.responsehandlers.ImageIconResponseHandler;

/**
 * @author Naeregwen
 *
 */
public class SteamAchievementsListIconReader extends SwingWorker<ImageIcon, String> {

	ColoredTee tee;
	SteamAchievementsList steamAchievementsList;
	String playerAvatarIconURL;
	ResourceBundle messages;
	Exception exception;

	public SteamAchievementsListIconReader(ColoredTee tee, SteamAchievementsList steamAchievementsList, String playerAvatarIconURL, ResourceBundle messages) {
		this.tee = tee;
		this.steamAchievementsList = steamAchievementsList;
		this.playerAvatarIconURL = playerAvatarIconURL;
		this.messages = messages;
	}

	@Override
	protected ImageIcon doInBackground() throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(playerAvatarIconURL);
        publish("IconPaneReader Executing request " + httpget.getRequestLine());

        try {
            return httpclient.execute(httpget, new ImageIconResponseHandler());
        } finally {
            httpclient.close();
        }
	}

	/*/
	 * (non-Javadoc)(
	 * @see javax.swing.SwingWorker#done()
	 */
	@Override
	protected void done() {
		try {
			ImageIcon icon = get();
			if (exception != null) {
				tee.printStackTrace(exception);
			} else if (icon != null && icon.getImage() != null && icon.getIconHeight() >= 0 && icon.getIconWidth() >= 0) {
				steamAchievementsList.setPlayerAvatarIcon(icon);
			}
		} catch (InterruptedException | ExecutionException e) {
			tee.printStackTrace(e);
		}
	}

	/*/
	 * (non-Javadoc)
	 * @see javax.swing.SwingWorker#process(java.util.List)
	 */
	@Override
    protected void process(List<String> strings) {
		ColoredTee.writeln(tee, strings);
    }

}


text:
package org.siggd;

public class Convert {
	/**
	 * Attempt to dynamically convert an object to target type, as intelligently as possible
	 * @param val  The object
	 * @param type The target type
	 * @return An object in either the target type, or a boxed version of that type
	 */
	public static Object convertTo(Object val, Class<?> type)
	{
		if (type == int.class || type == Integer.class) {
			return getInt(val);
		} else if (type == float.class || type == Float.class) {
			return getFloat(val);
		} else if (type == long.class || type == Long.class) {
			return getLong(val);
		} else if (type == double.class || type == Double.class) {
			return getDouble(val);
		} else if (type == String.class) {
			return val.toString();
		} else {
			return type.cast(val);
		}
	}

	// Get primitive types
	/**
	 * Will return 0 if the requested property is null, and truncate the value
	 * if it is not an integer. These will now return primitive types.
	 *
	 * @param object
	 *            Prop
	 * @return Requested int primitive type
	 */
	public static int getInt(Object prop) {
		if (prop == null)
			return 0;
		if (prop instanceof Float) {
			return (int) (float) (Float) prop;
		}
		if (prop instanceof Long) {
			return (int) (long) (Long) prop;
		}
		if (prop instanceof Double) {
			return (int) (double) (Double) prop;
		}
		if (prop instanceof Integer) {
			return (int) (Integer) prop;
		}
		if (prop instanceof String) {
			try {
				return Integer.parseInt((String) prop);
			} catch (NumberFormatException n) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * Will return 0 if the requested property is null, and cast the value if it
	 * is not float. These will now return primitive types.
	 *
	 * @param object
	 *            Prop
	 * @return Requested float primitive type
	 */
	public static float getFloat(Object prop) {
		if (prop == null)
			return 0;
		if (prop instanceof Integer) {
			return (float) (int) (Integer) prop;
		}
		if (prop instanceof Long) {
			return (float) (long) (Long) prop;
		}
		if (prop instanceof Double) {
			return (float) (double) (Double) prop;
		}
		if (prop instanceof Float) {
			return (float) (Float) prop;
		}
		if (prop instanceof String) {
			try {
				return Float.parseFloat((String) prop);
			} catch (NumberFormatException n) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * Will return 0 if the requested property is null, and truncate the value
	 * if it is not long. These will now return primitive types.
	 *
	 * @param object
	 *            Prop
	 * @return Requested long primitive type
	 */
	public static long getLong(Object prop) {
		if (prop == null)
			return 0;
		if (prop instanceof Integer) {
			return (long) (int) (Integer) prop;
		}
		if (prop instanceof Float) {
			return (long) (float) (Float) prop;
		}
		if (prop instanceof Double) {
			return (long) (double) (Double) prop;
		}
		if (prop instanceof Long) {
			return (long) (Long) prop;
		}
		if (prop instanceof String) {
			try {
				return Long.parseLong((String) prop);
			} catch (NumberFormatException n) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * Will return 0 if the requested property is null, and cast the value if it
	 * is not double. These will now return primitive types.
	 *
	 * @param object
	 *            Prop
	 * @return Requested double primitive type
	 */
	public static double getDouble(Object prop) {
		if (prop == null)
			return 0;
		if (prop instanceof Integer) {
			return (double) (int) (Integer) prop;
		}
		if (prop instanceof Float) {
			return (double) (float) (Float) prop;
		}
		if (prop instanceof Long) {
			return (double) (Long) (Long) prop;
		}
		if (prop instanceof Double) {
			return (double) (Double) prop;
		}
		if (prop instanceof String) {
			try {
				return Double.parseDouble((String) prop);
			} catch (NumberFormatException n) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * Converts radians to degrees
	 *
	 * @param r
	 *            angle in radians
	 * @return
	 */
	public static float getDegrees(float r) {
		return (float) (r * 180f / (Math.PI));
	}

	/**
	 * Converts degrees to radians
	 *
	 * @param d
	 *            angle in degrees
	 * @return
	 */
	public static float getRadians(float d) {
		return (float) (d * Math.PI / 180f);
	}
}


text:
{% extends "tests/base.html" %}
{% load wagtailcore_tags %}

{% block content %}

{{ greeting }}

    {{ self.thank_you_text|richtext }}

User email: {{ form_submission.get_data.useremail }}

{% endblock %}


text:
HOST = '127.0.0.1'
PORT = 8080

from Tkinter import *
import tkColorChooser

import socket
import thread
import spots

################################################################################

def main():
    global hold, fill, draw, look
    hold = []
    fill = '#000000'
    connect()
    root = Tk()
    root.title('Paint 2.0')
    root.resizable(False, False)
    upper = LabelFrame(root, text='Your Canvas')
    lower = LabelFrame(root, text='Their Canvas')
    draw = Canvas(upper, bg='#ffffff', width=400, height=300, highlightthickness=0)
    look = Canvas(lower, bg='#ffffff', width=400, height=300, highlightthickness=0)
    cursor = Button(upper, text='Cursor Color', command=change_cursor)
    canvas = Button(upper, text='Canvas Color', command=change_canvas)
    draw.bind('<Motion>', motion)
    draw.bind('<ButtonPress-1>', press)
    draw.bind('<ButtonRelease-1>', release)
    draw.bind('<Button-3>', delete)
    upper.grid(padx=5, pady=5)
    lower.grid(padx=5, pady=5)
    draw.grid(row=0, column=0, padx=5, pady=5, columnspan=2)
    look.grid(padx=5, pady=5)
    cursor.grid(row=1, column=0, padx=5, pady=5, sticky=EW)
    canvas.grid(row=1, column=1, padx=5, pady=5, sticky=EW)
    root.mainloop()

################################################################################

def connect():
    try:
        start_client()
    except:
        start_server()
    thread.start_new_thread(processor, ())

def start_client():
    global ZSP
    server = socket.socket()
    server.connect((HOST, PORT))
    ZSP = spots.ZSP(server)

def start_server():
    global ZSP
    server = socket.socket()
    server.bind(('', PORT))
    server.listen(1)
    ZSP = spots.ZSP(server.accept()[0])

def processor():
    while True:
        func, args, kwargs = ZSP.recv()
        getattr(look, func)(*args, **kwargs)

def call(func, *args, **kwargs):
    ZSP.send((func, args, kwargs))

################################################################################

def change_cursor():
    global fill
    color = tkColorChooser.askcolor(color=fill)[1]
    if color is not None:
        fill = color

def change_canvas():
    color = tkColorChooser.askcolor(color=draw['bg'])[1]
    if color is not None:
        draw.config(bg=color)
        call('config', bg=color)

################################################################################

def motion(event):
    if hold:
        hold.extend([event.x, event.y])
        event.widget.create_line(hold[-4:], fill=fill, tag='TEMP')
        call('create_line', hold[-4:], fill=fill, tag='TEMP')

def press(event):
    global hold
    hold = [event.x, event.y]

def release(event):
    global hold
    if len(hold) > 2:
        event.widget.delete('TEMP')
        event.widget.create_line(hold, fill=fill, smooth=True)
        call('delete', 'TEMP')
        call('create_line', hold, fill=fill, smooth=True)
    hold = []

def delete(event):
    event.widget.delete(ALL)
    call('delete', ALL)

################################################################################

if __name__ == '__main__':
    main()


text:
namespace Norma.Delta.Migrations.Base
{
    internal interface IMigration
    {
        string MigrationId { get; }

        string UpSql();

        string DownSql();
    }
}


text:
package org.apache.cassandra.repair.consistent;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.cql3.statements.CreateTableStatement;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.repair.messages.FailSession;
import org.apache.cassandra.repair.messages.FinalizeCommit;
import org.apache.cassandra.repair.messages.FinalizePromise;
import org.apache.cassandra.repair.messages.FinalizePropose;
import org.apache.cassandra.repair.messages.PrepareConsistentRequest;
import org.apache.cassandra.repair.messages.PrepareConsistentResponse;
import org.apache.cassandra.repair.messages.RepairMessage;
import org.apache.cassandra.repair.messages.StatusRequest;
import org.apache.cassandra.repair.messages.StatusResponse;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.UUIDGen;

import static org.apache.cassandra.repair.consistent.ConsistentSession.State.*;

public class LocalSessionTest extends AbstractConsistentSessionTest
{

    static LocalSession.Builder createBuilder()
    {
        LocalSession.Builder builder = LocalSession.builder();
        builder.withState(PREPARING);
        builder.withSessionID(UUIDGen.getTimeUUID());
        builder.withCoordinator(COORDINATOR);
        builder.withUUIDTableIds(Sets.newHashSet(UUIDGen.getTimeUUID(), UUIDGen.getTimeUUID()));
        builder.withRepairedAt(System.currentTimeMillis());
        builder.withRanges(Sets.newHashSet(RANGE1, RANGE2, RANGE3));
        builder.withParticipants(Sets.newHashSet(PARTICIPANT1, PARTICIPANT2, PARTICIPANT3));

        int now = FBUtilities.nowInSeconds();
        builder.withStartedAt(now);
        builder.withLastUpdate(now);

        return builder;
    }

    static LocalSession createSession()
    {
        return createBuilder().build();
    }

    private static void assertValidationFailure(Consumer<LocalSession.Builder> consumer)
    {
        try
        {
            LocalSession.Builder builder = createBuilder();
            consumer.accept(builder);
            builder.build();
            Assert.fail("Expected assertion error");
        }
        catch (IllegalArgumentException e)
        {
            // expected
        }
    }

    private static void assertNoMessagesSent(InstrumentedLocalSessions sessions, InetAddress to)
    {
        Assert.assertNull(sessions.sentMessages.get(to));
    }

    private static void assertMessagesSent(InstrumentedLocalSessions sessions, InetAddress to, RepairMessage... expected)
    {
        Assert.assertEquals(Lists.newArrayList(expected), sessions.sentMessages.get(to));
    }

    static class InstrumentedLocalSessions extends LocalSessions
    {
        Map<InetAddress, List<RepairMessage>> sentMessages = new HashMap<>();
        protected void sendMessage(InetAddress destination, RepairMessage message)
        {
            if (!sentMessages.containsKey(destination))
            {
                sentMessages.put(destination, new ArrayList<>());
            }
            sentMessages.get(destination).add(message);
        }

        SettableFuture<Object> pendingAntiCompactionFuture = null;
        boolean submitPendingAntiCompactionCalled = false;
        ListenableFuture submitPendingAntiCompaction(LocalSession session, ExecutorService executor)
        {
            submitPendingAntiCompactionCalled = true;
            if (pendingAntiCompactionFuture != null)
            {
                return pendingAntiCompactionFuture;
            }
            else
            {
                return super.submitPendingAntiCompaction(session, executor);
            }
        }

        boolean failSessionCalled = false;
        public void failSession(UUID sessionID, boolean sendMessage)
        {
            failSessionCalled = true;
            super.failSession(sessionID, sendMessage);
        }

        public LocalSession prepareForTest(UUID sessionID)
        {
            pendingAntiCompactionFuture = SettableFuture.create();
            handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));
            pendingAntiCompactionFuture.set(new Object());
            sentMessages.clear();
            return getSession(sessionID);
        }

        protected InetAddress getBroadcastAddress()
        {
            return PARTICIPANT1;
        }

        protected boolean isAlive(InetAddress address)
        {
            return true;
        }

        protected boolean isNodeInitialized()
        {
            return true;
        }
    }

    private static TableMetadata cfm;
    private static ColumnFamilyStore cfs;

    @BeforeClass
    public static void setupClass()
    {
        SchemaLoader.prepareServer();
        cfm = CreateTableStatement.parse("CREATE TABLE tbl (k INT PRIMARY KEY, v INT)", "localsessiontest").build();
        SchemaLoader.createKeyspace("localsessiontest", KeyspaceParams.simple(1), cfm);
        cfs = Schema.instance.getColumnFamilyStoreInstance(cfm.id);
    }

    @Before
    public void setup()
    {
        // clear out any data from previous test runs
        ColumnFamilyStore repairCfs = Keyspace.open(SchemaConstants.SYSTEM_KEYSPACE_NAME).getColumnFamilyStore(SystemKeyspace.REPAIRS);
        repairCfs.truncateBlocking();
    }

    private static UUID registerSession()
    {
        return registerSession(cfs);
    }

    @Test
    public void validation()
    {
        assertValidationFailure(b -> b.withState(null));
        assertValidationFailure(b -> b.withSessionID(null));
        assertValidationFailure(b -> b.withCoordinator(null));
        assertValidationFailure(b -> b.withTableIds(null));
        assertValidationFailure(b -> b.withTableIds(new HashSet<>()));
        assertValidationFailure(b -> b.withRepairedAt(0));
        assertValidationFailure(b -> b.withRepairedAt(-1));
        assertValidationFailure(b -> b.withRanges(null));
        assertValidationFailure(b -> b.withRanges(new HashSet<>()));
        assertValidationFailure(b -> b.withParticipants(null));
        assertValidationFailure(b -> b.withParticipants(new HashSet<>()));
        assertValidationFailure(b -> b.withStartedAt(0));
        assertValidationFailure(b -> b.withLastUpdate(0));
    }

    /**
     * Test that sessions are loaded and saved properly
     */
    @Test
    public void persistence()
    {
        LocalSessions sessions = new LocalSessions();
        LocalSession expected = createSession();
        sessions.save(expected);
        LocalSession actual = sessions.loadUnsafe(expected.sessionID);
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void prepareSuccessCase()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        // replacing future so we can inspect state before and after anti compaction callback
        sessions.pendingAntiCompactionFuture = SettableFuture.create();
        Assert.assertFalse(sessions.submitPendingAntiCompactionCalled);
        sessions.handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));
        Assert.assertTrue(sessions.submitPendingAntiCompactionCalled);
        Assert.assertTrue(sessions.sentMessages.isEmpty());

        // anti compaction hasn't finished yet, so state in memory and on disk should be PREPARING
        LocalSession session = sessions.getSession(sessionID);
        Assert.assertNotNull(session);
        Assert.assertEquals(PREPARING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));

        // anti compaction has now finished, so state in memory and on disk should be PREPARED
        sessions.pendingAntiCompactionFuture.set(new Object());
        session = sessions.getSession(sessionID);
        Assert.assertNotNull(session);
        Assert.assertEquals(PREPARED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));

        // ...and we should have sent a success message back to the coordinator
        assertMessagesSent(sessions, COORDINATOR, new PrepareConsistentResponse(sessionID, PARTICIPANT1, true));
    }

    /**
     * If anti compactionn fails, we should fail the session locally,
     * and send a failure message back to the coordinator
     */
    @Test
    public void prepareAntiCompactFailure()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        // replacing future so we can inspect state before and after anti compaction callback
        sessions.pendingAntiCompactionFuture = SettableFuture.create();
        Assert.assertFalse(sessions.submitPendingAntiCompactionCalled);
        sessions.handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));
        Assert.assertTrue(sessions.submitPendingAntiCompactionCalled);
        Assert.assertTrue(sessions.sentMessages.isEmpty());

        // anti compaction hasn't finished yet, so state in memory and on disk should be PREPARING
        LocalSession session = sessions.getSession(sessionID);
        Assert.assertNotNull(session);
        Assert.assertEquals(PREPARING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));

        // anti compaction has now finished, so state in memory and on disk should be PREPARED
        sessions.pendingAntiCompactionFuture.setException(new RuntimeException());
        session = sessions.getSession(sessionID);
        Assert.assertNotNull(session);
        Assert.assertEquals(FAILED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));

        // ...and we should have sent a success message back to the coordinator
        assertMessagesSent(sessions, COORDINATOR, new FailSession(sessionID));

    }

    /**
     * If a ParentRepairSession wasn't previously created, we shouldn't
     * create a session locally, but we should send a failure message to
     * the coordinator.
     */
    @Test
    public void prepareWithNonExistantParentSession()
    {
        UUID sessionID = UUIDGen.getTimeUUID();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));
        Assert.assertNull(sessions.getSession(sessionID));
        assertMessagesSent(sessions, COORDINATOR, new FailSession(sessionID));
    }

    @Test
    public void maybeSetRepairing()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());

        sessions.sentMessages.clear();
        sessions.maybeSetRepairing(sessionID);
        Assert.assertEquals(REPAIRING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    /**
     * Multiple calls to maybeSetRepairing shouldn't cause any problems
     */
    @Test
    public void maybeSetRepairingDuplicates()
    {

        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());

        // initial set
        sessions.sentMessages.clear();
        sessions.maybeSetRepairing(sessionID);
        Assert.assertEquals(REPAIRING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());

        // repeated call 1
        sessions.maybeSetRepairing(sessionID);
        Assert.assertEquals(REPAIRING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());

        // repeated call 2
        sessions.maybeSetRepairing(sessionID);
        Assert.assertEquals(REPAIRING, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    /**
     * We shouldn't fail if we don't have a session for the given session id
     */
    @Test
    public void maybeSetRepairingNonExistantSession()
    {
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        UUID fakeID = UUIDGen.getTimeUUID();
        sessions.maybeSetRepairing(fakeID);
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    /**
     * In the success case, session state should be set to FINALIZE_PROMISED and
     * persisted, and a FinalizePromise message should be sent back to the coordinator
     */
    @Test
    public void finalizeProposeSuccessCase()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        // create session and move to preparing
        LocalSession session = sessions.prepareForTest(sessionID);
        sessions.maybeSetRepairing(sessionID);

        //
        Assert.assertEquals(REPAIRING, session.getState());

        // should send a promised message to coordinator and set session state accordingly
        sessions.sentMessages.clear();
        sessions.handleFinalizeProposeMessage(COORDINATOR, new FinalizePropose(sessionID));
        Assert.assertEquals(FINALIZE_PROMISED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        assertMessagesSent(sessions, COORDINATOR, new FinalizePromise(sessionID, PARTICIPANT1, true));
    }

    /**
     * Trying to propose finalization when the session isn't in the repaired
     * state should fail the session and send a failure message to the proposer
     */
    @Test
    public void finalizeProposeInvalidStateFailure()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());

        // should fail the session and send a failure message to the coordinator
        sessions.sentMessages.clear();
        sessions.handleFinalizeProposeMessage(COORDINATOR, new FinalizePropose(sessionID));
        Assert.assertEquals(FAILED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        assertMessagesSent(sessions, COORDINATOR, new FailSession(sessionID));
    }

    @Test
    public void finalizeProposeNonExistantSessionFailure()
    {
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        UUID fakeID = UUIDGen.getTimeUUID();
        sessions.handleFinalizeProposeMessage(COORDINATOR, new FinalizePropose(fakeID));
        Assert.assertNull(sessions.getSession(fakeID));
        assertMessagesSent(sessions, COORDINATOR, new FailSession(fakeID));
    }

    /**
     * Session state should be set to finalized, sstables should be promoted
     * to repaired. No messages should be sent to the coordinator
     */
    @Test
    public void finalizeCommitSuccessCase()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        // create session and move to finalized promised
        sessions.prepareForTest(sessionID);
        sessions.maybeSetRepairing(sessionID);
        sessions.handleFinalizeProposeMessage(COORDINATOR, new FinalizePropose(sessionID));

        sessions.sentMessages.clear();
        LocalSession session = sessions.getSession(sessionID);
        sessions.handleFinalizeCommitMessage(PARTICIPANT1, new FinalizeCommit(sessionID));

        Assert.assertEquals(FINALIZED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(sessionID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    @Test
    public void finalizeCommitNonExistantSession()
    {
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        UUID fakeID = UUIDGen.getTimeUUID();
        sessions.handleFinalizeCommitMessage(PARTICIPANT1, new FinalizeCommit(fakeID));
        Assert.assertNull(sessions.getSession(fakeID));
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    @Test
    public void failSession()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());
        sessions.sentMessages.clear();

        // fail session
        sessions.failSession(sessionID);
        Assert.assertEquals(FAILED, session.getState());
        assertMessagesSent(sessions, COORDINATOR, new FailSession(sessionID));
    }

    /**
     * Session should be failed, but no messages should be sent
     */
    @Test
    public void handleFailMessage()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());
        sessions.sentMessages.clear();

        sessions.handleFailSessionMessage(PARTICIPANT1, new FailSession(sessionID));
        Assert.assertEquals(FAILED, session.getState());
        Assert.assertTrue(sessions.sentMessages.isEmpty());
    }

    @Test
    public void sendStatusRequest() throws Exception
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        LocalSession session = sessions.prepareForTest(sessionID);

        sessions.sentMessages.clear();
        sessions.sendStatusRequest(session);

        assertNoMessagesSent(sessions, PARTICIPANT1);
        StatusRequest expected = new StatusRequest(sessionID);
        assertMessagesSent(sessions, PARTICIPANT2, expected);
        assertMessagesSent(sessions, PARTICIPANT3, expected);
    }

    @Test
    public void handleStatusRequest() throws Exception
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        LocalSession session = sessions.prepareForTest(sessionID);
        Assert.assertEquals(PREPARED, session.getState());

        sessions.sentMessages.clear();
        sessions.handleStatusRequest(PARTICIPANT2, new StatusRequest(sessionID));
        assertNoMessagesSent(sessions, PARTICIPANT1);
        assertMessagesSent(sessions, PARTICIPANT2, new StatusResponse(sessionID, PREPARED));
        assertNoMessagesSent(sessions, PARTICIPANT3);
    }

    @Test
    public void handleStatusRequestNoSession() throws Exception
    {
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        sessions.sentMessages.clear();
        UUID sessionID = UUIDGen.getTimeUUID();
        sessions.handleStatusRequest(PARTICIPANT2, new StatusRequest(sessionID));
        assertNoMessagesSent(sessions, PARTICIPANT1);
        assertMessagesSent(sessions, PARTICIPANT2, new StatusResponse(sessionID, FAILED));
        assertNoMessagesSent(sessions, PARTICIPANT3);
    }

    @Test
    public void handleStatusResponseFinalized() throws Exception
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        LocalSession session = sessions.prepareForTest(sessionID);
        session.setState(FINALIZE_PROMISED);

        sessions.handleStatusResponse(PARTICIPANT1, new StatusResponse(sessionID, FINALIZED));
        Assert.assertEquals(FINALIZED, session.getState());
    }

    @Test
    public void handleStatusResponseFailed() throws Exception
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        LocalSession session = sessions.prepareForTest(sessionID);
        session.setState(FINALIZE_PROMISED);

        sessions.handleStatusResponse(PARTICIPANT1, new StatusResponse(sessionID, FAILED));
        Assert.assertEquals(FAILED, session.getState());
    }

    @Test
    public void handleStatusResponseNoop() throws Exception
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        LocalSession session = sessions.prepareForTest(sessionID);
        session.setState(REPAIRING);

        sessions.handleStatusResponse(PARTICIPANT1, new StatusResponse(sessionID, FINALIZE_PROMISED));
        Assert.assertEquals(REPAIRING, session.getState());
    }

    @Test
    public void handleStatusResponseNoSession() throws Exception
    {
        UUID sessionID = UUIDGen.getTimeUUID();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        sessions.handleStatusResponse(PARTICIPANT1, new StatusResponse(sessionID, FINALIZE_PROMISED));
        Assert.assertNull(sessions.getSession(sessionID));
    }

    /**
     * Check all states (except failed)
     */
    @Test
    public void isSessionInProgress()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        sessions.pendingAntiCompactionFuture = SettableFuture.create();  // prevent moving to prepared
        sessions.handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));

        LocalSession session = sessions.getSession(sessionID);
        Assert.assertNotNull(session);
        Assert.assertEquals(PREPARING, session.getState());
        Assert.assertTrue(sessions.isSessionInProgress(sessionID));

        session.setState(PREPARED);
        Assert.assertTrue(sessions.isSessionInProgress(sessionID));

        session.setState(REPAIRING);
        Assert.assertTrue(sessions.isSessionInProgress(sessionID));

        session.setState(FINALIZE_PROMISED);
        Assert.assertTrue(sessions.isSessionInProgress(sessionID));

        session.setState(FINALIZED);
        Assert.assertFalse(sessions.isSessionInProgress(sessionID));
    }

    @Test
    public void isSessionInProgressFailed()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        sessions.pendingAntiCompactionFuture = SettableFuture.create();
        sessions.handlePrepareMessage(PARTICIPANT1, new PrepareConsistentRequest(sessionID, COORDINATOR, PARTICIPANTS));
        sessions.pendingAntiCompactionFuture.set(new Object());

        Assert.assertTrue(sessions.isSessionInProgress(sessionID));
        sessions.failSession(sessionID);
        Assert.assertFalse(sessions.isSessionInProgress(sessionID));
    }

    @Test
    public void isSessionInProgressNonExistantSession()
    {
        UUID fakeID = UUIDGen.getTimeUUID();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        Assert.assertFalse(sessions.isSessionInProgress(fakeID));
    }

    @Test
    public void finalRepairedAtFinalized()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        sessions.prepareForTest(sessionID);
        sessions.maybeSetRepairing(sessionID);
        sessions.handleFinalizeProposeMessage(COORDINATOR, new FinalizePropose(sessionID));
        sessions.handleFinalizeCommitMessage(PARTICIPANT1, new FinalizeCommit(sessionID));

        LocalSession session = sessions.getSession(sessionID);
        Assert.assertTrue(session.repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE);
        Assert.assertEquals(session.repairedAt, sessions.getFinalSessionRepairedAt(sessionID));
    }

    @Test
    public void finalRepairedAtFailed()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        sessions.prepareForTest(sessionID);
        sessions.failSession(sessionID);

        LocalSession session = sessions.getSession(sessionID);
        Assert.assertTrue(session.repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE);
        long repairedAt = sessions.getFinalSessionRepairedAt(sessionID);
        Assert.assertEquals(ActiveRepairService.UNREPAIRED_SSTABLE, repairedAt);
    }

    @Test
    public void finalRepairedAtNoSession()
    {
        UUID fakeID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        long repairedAt = sessions.getFinalSessionRepairedAt(fakeID);
        Assert.assertEquals(ActiveRepairService.UNREPAIRED_SSTABLE, repairedAt);
    }

    @Test(expected = IllegalStateException.class)
    public void finalRepairedAtInProgress()
    {
        UUID sessionID = registerSession();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();
        sessions.prepareForTest(sessionID);

        sessions.getFinalSessionRepairedAt(sessionID);
    }

    /**
     * Startup happy path
     */
    @Test
    public void startup() throws Exception
    {
        InstrumentedLocalSessions initialSessions = new InstrumentedLocalSessions();
        initialSessions.start();
        Assert.assertEquals(0, initialSessions.getNumSessions());
        UUID id1 = registerSession();
        UUID id2 = registerSession();

        initialSessions.prepareForTest(id1);
        initialSessions.prepareForTest(id2);
        Assert.assertEquals(2, initialSessions.getNumSessions());
        LocalSession session1 = initialSessions.getSession(id1);
        LocalSession session2 = initialSessions.getSession(id2);

        // subsequent startups should load persisted sessions
        InstrumentedLocalSessions nextSessions = new InstrumentedLocalSessions();
        Assert.assertEquals(0, nextSessions.getNumSessions());
        nextSessions.start();
        Assert.assertEquals(2, nextSessions.getNumSessions());

        Assert.assertEquals(session1, nextSessions.getSession(id1));
        Assert.assertEquals(session2, nextSessions.getSession(id2));
    }

    /**
     * If LocalSessions.start is called more than
     * once, an exception should be thrown
     */
    @Test (expected = IllegalArgumentException.class)
    public void multipleStartupFailure() throws Exception
    {
        InstrumentedLocalSessions initialSessions = new InstrumentedLocalSessions();
        initialSessions.start();
        initialSessions.start();
    }

    /**
     * If there are problems with the rows we're reading out of the repair table, we should
     * do the best we can to repair them, but not refuse to startup.
     */
    @Test
    public void loadCorruptRow() throws Exception
    {
        LocalSessions sessions = new LocalSessions();
        LocalSession session = createSession();
        sessions.save(session);

        sessions = new LocalSessions();
        sessions.start();
        Assert.assertNotNull(sessions.getSession(session.sessionID));

        QueryProcessor.instance.executeInternal("DELETE participants FROM system.repairs WHERE parent_id=?", session.sessionID);

        sessions = new LocalSessions();
        sessions.start();
        Assert.assertNull(sessions.getSession(session.sessionID));
    }

    private static LocalSession sessionWithTime(int started, int updated)
    {
        LocalSession.Builder builder = createBuilder();
        builder.withStartedAt(started);
        builder.withLastUpdate(updated);
        return builder.build();
    }

    /**
     * Sessions that shouldn't be failed or deleted are left alone
     */
    @Test
    public void cleanupNoOp() throws Exception
    {
        LocalSessions sessions = new LocalSessions();
        sessions.start();

        int time = FBUtilities.nowInSeconds() - LocalSessions.AUTO_FAIL_TIMEOUT + 60;
        LocalSession session = sessionWithTime(time - 1, time);

        sessions.putSessionUnsafe(session);
        Assert.assertNotNull(sessions.getSession(session.sessionID));

        sessions.cleanup();

        Assert.assertNotNull(sessions.getSession(session.sessionID));
    }

    /**
     * Sessions past the auto fail cutoff should be failed
     */
    @Test
    public void cleanupFail() throws Exception
    {
        LocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        int time = FBUtilities.nowInSeconds() - LocalSessions.AUTO_FAIL_TIMEOUT - 1;
        LocalSession session = sessionWithTime(time - 1, time);
        session.setState(REPAIRING);

        sessions.putSessionUnsafe(session);
        Assert.assertNotNull(sessions.getSession(session.sessionID));

        sessions.cleanup();

        Assert.assertNotNull(sessions.getSession(session.sessionID));
        Assert.assertEquals(FAILED, session.getState());
        Assert.assertEquals(session, sessions.loadUnsafe(session.sessionID));
    }

    /**
     * Sessions past the auto delete cutoff should be deleted
     */
    @Test
    public void cleanupDelete() throws Exception
    {
        LocalSessions sessions = new InstrumentedLocalSessions();
        sessions.start();

        int time = FBUtilities.nowInSeconds() - LocalSessions.AUTO_FAIL_TIMEOUT - 1;
        LocalSession failed = sessionWithTime(time - 1, time);
        failed.setState(FAILED);

        LocalSession finalized = sessionWithTime(time - 1, time);
        finalized.setState(FINALIZED);

        sessions.putSessionUnsafe(failed);
        sessions.putSessionUnsafe(finalized);
        Assert.assertNotNull(sessions.getSession(failed.sessionID));
        Assert.assertNotNull(sessions.getSession(finalized.sessionID));

        sessions.cleanup();

        Assert.assertNull(sessions.getSession(failed.sessionID));
        Assert.assertNull(sessions.getSession(finalized.sessionID));

        Assert.assertNull(sessions.loadUnsafe(failed.sessionID));
        Assert.assertNull(sessions.loadUnsafe(finalized.sessionID));
    }

    /**
     * Sessions should start checking the status of their participants if
     * there hasn't been activity for the CHECK_STATUS_TIMEOUT period
     */
    @Test
    public void cleanupStatusRequest() throws Exception
    {
        AtomicReference<LocalSession> checkedSession = new AtomicReference<>();
        InstrumentedLocalSessions sessions = new InstrumentedLocalSessions() {
            public void sendStatusRequest(LocalSession session)
            {
                Assert.assertTrue(checkedSession.compareAndSet(null, session));
            }
        };
        sessions.start();

        int time = FBUtilities.nowInSeconds() - LocalSessions.CHECK_STATUS_TIMEOUT - 1;
        LocalSession session = sessionWithTime(time - 1, time);
        session.setState(REPAIRING);

        sessions.putSessionUnsafe(session);
        Assert.assertNotNull(sessions.getSession(session.sessionID));

        sessions.cleanup();

        Assert.assertEquals(session, checkedSession.get());
    }
}


text:
#ifndef PG_SHDEPEND_H
#define PG_SHDEPEND_H

/* ----------------
 *		postgres.h contains the system type definitions and the
 *		CATALOG(), BKI_BOOTSTRAP and DATA() sugar words so this file
 *		can be read by both genbki.sh and the C compiler.
 * ----------------
 */

/* ----------------
 *		pg_shdepend definition.  cpp turns this into
 *		typedef struct FormData_pg_shdepend
 * ----------------
 */
#define SharedDependRelationId	1214
CATALOG(pg_shdepend,1214) BKI_SHARED_RELATION BKI_WITHOUT_OIDS
{
	/*
	 * Identification of the dependent (referencing) object.
	 *
	 * These fields are all zeroes for a DEPENDENCY_PIN entry.	Also, dbid can
	 * be zero to denote a shared object.
	 */
	Oid			dbid;			/* OID of database containing object */
	Oid			classid;		/* OID of table containing object */
	Oid			objid;			/* OID of object itself */

	/*
	 * Identification of the independent (referenced) object.  This is always
	 * a shared object, so we need no database ID field.
	 */
	Oid			refclassid;		/* OID of table containing object */
	Oid			refobjid;		/* OID of object itself */

	/*
	 * Precise semantics of the relationship are specified by the deptype
	 * field.  See SharedDependencyType in catalog/dependency.h.
	 */
	char		deptype;		/* see codes in dependency.h */
} FormData_pg_shdepend;

/* ----------------
 *		Form_pg_shdepend corresponds to a pointer to a row with
 *		the format of pg_shdepend relation.
 * ----------------
 */
typedef FormData_pg_shdepend *Form_pg_shdepend;

/* ----------------
 *		compiler constants for pg_shdepend
 * ----------------
 */
#define Natts_pg_shdepend			6
#define Anum_pg_shdepend_dbid		1
#define Anum_pg_shdepend_classid	2
#define Anum_pg_shdepend_objid		3
#define Anum_pg_shdepend_refclassid 4
#define Anum_pg_shdepend_refobjid	5
#define Anum_pg_shdepend_deptype	6

/*
 * pg_shdepend has no preloaded contents; system-defined dependencies are
 * loaded into it during a late stage of the initdb process.
 *
 * NOTE: we do not represent all possible dependency pairs in pg_shdepend;
 * for example, there's not much value in creating an explicit dependency
 * from a relation to its database.  Currently, only dependencies on roles
 * are explicitly stored in pg_shdepend.
 */

#endif   /* PG_SHDEPEND_H */


text:
<android.support.design.widget.TabLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/background_actionbar"
    app:tabMode="scrollable"
    app:tabSelectedTextColor="?attr/font_actionbar_selected"
    app:tabTextColor="?attr/font_actionbar"
    app:tabIndicatorColor="?attr/font_actionbar_selected"/>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Living Well Seniors Communities</title>

<meta name="language" content="en" />
<meta content='width=910' name='viewport' />

<meta name="Description" content="" />

<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link href="style-v2.css" rel="stylesheet" media="all" type="text/css" />
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/style4.css" />

Contact

INDONESIAN

ENGLISH

Vision

Mission

Values

Seniors Focused Residences & Communities

Team

Management

Advisors

Market Knowledge

Seniors Care in Asia

Indonesia's Economy

Indonesia's Social Demographics

Indonesia's Healthcare

Indonesia's Real Estate

Projects

Cipayung Jakarta

Lifestyle

Philosophy

Individual Residence Features

Community Facilities

Care Team

Services Delivered

Activities for Residents

Community

ASLI

Kampung Kids

HomeMarket KnowledgeIndonesia's Healthcare

Print

Market Knowledge

Seniors Care in Asia

Indonesia's Economy

Indonesia's Social Demographics

Indonesia's Healthcare

Indonesia's Real Estate

Indonesia's Healthcare

Public spending on healthcare is currently low by regional and global standards and provides enormous opportunities for the private sector.

A report from KPMG in 2012 found that there are only 0.6 hospital beds per 1000 people in Indonesia, compared to 2.1 in Thailand, 1.8 in Malaysia, a global average of 3.0 and an average of 5.0 for OECD countries. Healthcare expenditure accounted for 2.8% of GDP in 2009, compared to 3.3% in Thailand, 3.9% in The Philippines, 5.8% in China and a global average of 8.7%.

Under investment in the health sector has led to an $8 billion (USD) industry in the provision of Singaporean health care services to Indonesians each year.

  Living Well Seniors Communities ™


text:
<!DOCTYPE html>

    <title>Young Turks @ Multunus</title>
    <link rel="icon" type="image/png" href="images/favicon.ico">
    <meta property="og:image" content="http://multunus.herokuapp.com/youngturks/images/young_turks_collage.jpg"/>
    <meta property="og:description" content="See the timelines of our
    young turks: Manoj, Tamil, Akshay, Sreenath, Anup, Ernest,
    Abhilash and KP" />

    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/timeliner.css">
    <link rel="stylesheet" type="text/css" href="css/application.css">
    <link href='http://fonts.googleapis.com/css?family=Orbitron:900,700' rel='stylesheet' type='text/css'>

rock      /’räk/

		Verb:

Speak at a public event.

Blog on technical subjects.

Contribute to open source.

Build awesome products.

Steer and Grow the organization.

Go home satisfied. Everyday.


text:
require 'sclust/util/filters'

describe 'document' do

  it 'filter terms out' do
    f = SClust::Util::DocumentTermFilter.new()

    f.apply("aba").should == "aba"
  end

  it 'tokenizes' do
    f = SClust::Util::TokenizerFilter.new()

    f.apply("hi bye").should == [ "hi", "bye" ]
    f.apply("hi \r\n\n\rbye").should == [ "hi", "bye" ]
  end
end # describe 'document'


text:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web version="8.0" xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/schema/jbossas/jboss-web_8_0.xsd">
  <context-root>/post-redirect-get</context-root>
</jboss-web>


text:
  { tilebank, offset, mapbank, reg_bg, prio }

typedef struct {    // Background font using 30x20 grid.
  Uint16 tilebank;  // The tilebank to copy the font tiles into.
  Uint16 offset;    // How many tiles to skip before copying font tiles.
  Uint16 mapbank;   // Which map bank to print to (uses 32x32 map).
  Uint16 reg_bg;    // The background register to use.
  Uint16 prio;      // Background draw priority 0 - 3.
} FontBG4;

void font_bg4_init(const FontBG4* font); // init sys regs and map
void font_bg4_cptiles(const FontBG4* font, const Tile4* tiles); // cp tiles vram
void font_bg4_clear(const FontBG4* font); // remove all chars from map
void font_bg4_print(const FontBG4* font, Uint16 palbank,
                    Vec pos, const char* str);
void font_bg4_printf(const FontBG4* font, Uint16 palbank,
                     Vec pos, const char* format, ...);

void font_bg4_printu(const FontBG4* font, Uint16 palbank, Vec pos, Uint16 num);

////////////////////////////////////////////////////////////////////////////////
//                FONT BG 8                   //
////////////////////////////////////////////////////////////////////////////////

#define FONTBG8(tilebank, offset, mapbank, reg_bg, prio) \
  { tilebank, offset, mapbank, reg_bg, prio }

typedef struct {    // Background font using 30x20 grid.
  Uint16 tilebank;  // The tilebank to copy the font tiles into.
  Uint16 offset;    // How many tiles to skip before copying font tiles.
  Uint16 mapbank;   // Which map bank to print to (uses 32x32 map).
  Uint16 reg_bg;    // The background register to use.
  Uint16 prio;      // Background draw priority 0 - 3.
} FontBG8;

void font_bg8_init(const FontBG8* font); // init sys regs and map
void font_bg8_cptiles(const FontBG8* font, const Tile8* tiles); // cp tiles vram
void font_bg8_clear(const FontBG8* font); // remove all chars from map
void font_bg8_print(const FontBG8* font, Vec pos, const char* str);
void font_bg8_printf(const FontBG8* font, Vec pos, const char* format, ...);
void font_bg8_printu(const FontBG8* font, Vec pos, Uint16 num);

#endif


text:
import * as Preact from '../../../src/preact';
import * as styles from './base-carousel.css';
import {dict} from '../../../src/utils/object';

/**
 * @param {!JsonObject} props
 * @return {PreactDef.Renderable}
 */
export function Arrow(props) {
  const {
    'customArrow': customArrow,
    'dir': dir,
    'advance': advance,
    'disabled': disabled,
  } = props;
  const button = customArrow
    ? customArrow
    : renderDefaultArrow(dict({'dir': dir}));
  const {
    'children': children,
    'disabled': customDisabled,
    'onClick': onCustomClick,
    ...rest
  } = button.props;
  const isDisabled = disabled || customDisabled;
  const onClick = (e) => {
    if (onCustomClick) {
      onCustomClick(e);
    }
    advance();
  };
  return (
    <div
      style={{
        ...styles.arrowPlacement,
        // Offset button from the edge.
        [dir < 0 ? 'left' : 'right']: '0px',
      }}
    >
      {Preact.cloneElement(
        button,
        {
          'onClick': onClick,
          'disabled': isDisabled,
          'aria-disabled': isDisabled,
          ...rest,
        },
        children
      )}
    </div>
  );
}

/**
 * @param {!JsonObject} props
 * @return {PreactDef.Renderable}
 */
function renderDefaultArrow(props) {
  return (
    <button style={styles.defaultArrowButton}>
      {props['dir'] < 0 ? '<<' : '>>'}
    </button>
  );
}


text:
@interface BasetabbarViewController ()<UITabBarControllerDelegate>

@end

@implementation BasetabbarViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    self.tabBar.barTintColor = [UIColor whiteColor];
    self.delegate=self;
    [self addViewControllers];

    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(refreshInterface) name:@"refreshInterface" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(exitLogin) name:@"exitLogin" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(shopingCar) name:@"shopingCar" object:nil];

}
//完善资料退出跳转登录
-(void)exitLogin{
    self.selectedIndex = 0;
}

- (void)addViewControllers {

    //米劵商城
    LBIntegralMallViewController *IntegralMallvc = [[LBIntegralMallViewController alloc] init];
    BaseNavigationViewController *IntegralMallnav = [[BaseNavigationViewController alloc] initWithRootViewController:IntegralMallvc];
    IntegralMallvc.tabBarItem = [self barTitle:@"米券商城" image:@"public_welfare_consumption_normal" selectImage:@"public_welfare_consumption_select"];

    //我的
    LBMineViewController *minevc = [[LBMineViewController alloc] init];
    BaseNavigationViewController *minenav = [[BaseNavigationViewController alloc] initWithRootViewController:minevc];
    minevc.tabBarItem = [self barTitle:@"我的" image:@"wd_icon" selectImage:@"wd_selected_icon"];

    //搜附近
    GLNearbyViewController *nearbyVC = [[GLNearbyViewController alloc] init];
    BaseNavigationViewController *nearbyNav = [[BaseNavigationViewController alloc] initWithRootViewController:nearbyVC];
    nearbyNav.tabBarItem = [self barTitle:@"逛逛" image:@"sfj_icon" selectImage:@"sfj_selected_icon"];

    //购物车
    GLShoppingCartController *ShoppingVC = [[GLShoppingCartController alloc] init];
    BaseNavigationViewController *ShoppingNav = [[BaseNavigationViewController alloc] initWithRootViewController:ShoppingVC];
    ShoppingNav.tabBarItem = [self barTitle:@"购物车" image:@"购物车未点中" selectImage:@"购物车点中"];

    self.viewControllers = @[IntegralMallnav,nearbyNav,ShoppingNav, minenav];

    self.selectedIndex=0;

}

- (UITabBarItem *)barTitle:(NSString *)title image:(NSString *)image selectImage:(NSString *)selectImage {
    UITabBarItem *item = [[UITabBarItem alloc] init];

    item.title = title;
    item.image = [[UIImage imageNamed:image] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item.selectedImage = [[UIImage imageNamed:selectImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor grayColor]} forState:UIControlStateNormal];
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName : YYSRGBColor(102, 139, 255, 1)} forState:UIControlStateSelected];
    item.titlePositionAdjustment = UIOffsetMake(0, -4);
    return item;
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{

    if (viewController == [tabBarController.viewControllers objectAtIndex:3] || viewController == [tabBarController.viewControllers objectAtIndex:2]) {

        if ([UserModel defaultUser].loginstatus == YES) {

            return YES;
        }
        GLLoginController *loginVC = [[GLLoginController alloc] init];
        BaseNavigationViewController *nav = [[BaseNavigationViewController alloc]initWithRootViewController:loginVC];
        nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:nav animated:YES completion:nil];
        return NO;

    }

    return YES;
}
//刷新界面
-(void)refreshInterface{

   [self.viewControllers reverseObjectEnumerator];
    [self addViewControllers];

}

- (void)pushToHome{

     self.selectedIndex = 0;
}

-(void)shopingCar{

    self.selectedIndex = 2;

}

@end


text:
title: React Chip component
components: Chip
githubLabel: 'component: Chip'
materialDesign: https://material.io/components/chips
---

# Chip

Chips are compact elements that represent an input, attribute, or action.

Chips allow users to enter information, make selections, filter content, or trigger actions.

While included here as a standalone component, the most common use will
be in some form of input, so some of the behavior demonstrated here is
not shown in context.

{{"component": "modules/components/ComponentLinkHeader.js"}}

## Basic chip

The `Chip` component supports outlined and filled styling.

{{"demo": "pages/components/chips/BasicChips.js"}}

## Chip actions

You can use the following actions.

- Chips with the `onClick` prop defined change appearance on focus, hover, and click.
- Chips with the `onDelete` prop defined will display a delete icon which changes appearance on hover.

### Clickeable

{{"demo": "pages/components/chips/ClickeableChips.js"}}

### Deleteable

{{"demo": "pages/components/chips/DeleteableChips.js"}}

### Clickeable and deleteable

{{"demo": "pages/components/chips/ClickeableAndDeleteableChips.js"}}

### Clickeable link

{{"demo": "pages/components/chips/ClickeableLinkChips.js"}}

### Custom delete icon

{{"demo": "pages/components/chips/CustomDeleteIconChips.js"}}

## Chip adornments

You can add ornaments to the beginning of the component.

Use the `avatar` prop to added a avatar or use the `icon` prop to added a icon.

### Avatar chip

{{"demo": "pages/components/chips/AvatarChips.js"}}

### Icon chip

{{"demo": "pages/components/chips/IconChips.js"}}

## Color chip

You can use the `color` prop to define a color from theme palette.

{{"demo": "pages/components/chips/ColorChips.js"}}

## Sizes chip

You can use the `size` prop to define a small Chip.

{{"demo": "pages/components/chips/SizesChips.js"}}

## Chip array

An example of rendering multiple chips from an array of values.
Deleting a chip removes it from the array. Note that since no
`onClick` prop is defined, the `Chip` can be focused, but does not
gain depth while clicked or touched.

{{"demo": "pages/components/chips/ChipsArray.js", "bg": true}}

## Chip playground

{{"demo": "pages/components/chips/ChipsPlayground.js", "hideToolbar": true}}

## Accessibility

If the Chip is deletable or clickable then it is a button in tab order. When the Chip is focused (e.g. when tabbing) releasing (`keyup` event) `Backspace` or `Delete` will call the `onDelete` handler while releasing `Escape` will blur the Chip.


text:
A simple waterflow wrapper for seneca microservices

# Idea

Chain microservices based on business workflow.

# To Use

var _seneca = require('seneca')()

	.use('seneca-wflow', {

  	filename:'./workflow/yourflow',// module that contains the business flow

  	sequence:['process1', 'process2',...]

  	});

# Examples:

### Example 1 :

	run with flow without seneca

	$ node example/example1 --seneca.log.all | grep flowEngine

### Example 2:

	Example of creating a new workflow using the create command.

	$ node example/example2

	Add loging to your plugin

	$ node example/example2 --seneca.log.all | grep example2

### Example 3:
	Using the append command will append a sequence with number of times to execute the sequence.  Used to make loops.

	$ node example/example3

### Example 4:
	Use pre-workflow flag to modify workflow prior to execute.

	var options={

	filename:"example4_seneca", // module
	sequence:["hello","preWF:generateLoop"]
	}

	$ node example/example4


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis.Semantics
{
    /// <summary>
    /// Represents a VB Stop statement.
    /// </summary>
    /// <remarks>
    /// This interface is reserved for implementation by its associated APIs. We reserve the right to
    /// change it in the future.
    /// </remarks>
    public interface IStopStatement : IOperation
    {
    }
}


text:
import pygame
import random
from viewer_ng.image_creator import create_tiles
from tca_ng import cells, models, example_maps, cars
from pygame import locals

#tca = models.Automaton()
#topo = example_maps.grid_2lane_map(width=2, height=2)
#tca.topology = topo
#topo.automaton = tca

#tca.update()
#car = topo.cars[0]
#lista = [0]
#speeds = [0]
#for _ in range(1000):
#    if car in topo.cars:
#        lista.append(car.cell.id)
#        speeds.append(car.speed)
#    else:
#        break
#    tca.update()
#    print(_)
#cells.Cell.id = 0
#
#for s in speeds:
#    print(s)
#
#print (len(speeds))

def get_color(cell):
    if isinstance(cell, cells.StreetCell):
        color = 'street'
    elif isinstance(cell, cells.IntersectionCell):
        color = 'intersection'
    elif isinstance(cell, cells.EndpointEntranceCell):
        color = 'entrance'
    elif isinstance(cell, cells.EndpointExitCell):
        color = 'exit'
    elif isinstance(cell, models.Light):
        color = 'green' if cell.free else 'red'
#        color = 'oob'
    else:
        color = 'oob'

    if isinstance(cell, cells.Cell):
        if cell.car is not None:
            color = 'special_car' if cell.car.id % 10 == 0 else 'car'
#            color = 'car'
#
#    if isinstance(cell, cells.Cell) and cell.id in lista:
#        color = 'exit'

    return color

class Cell:
    location = None
    aut_cell = None
    color = 'oob'

    def absolute_location(self, square_size):
        x = self.location[0] * square_size
        y = self.location[1] * square_size
        return (x, y)

class Board:
    automaton = None
    cells = []
    size = None

    def __init__(self, automaton):
        self.automaton = automaton
        self.cells = []
        self.map_cells()

    def map_cells(self):
        max_x = 0
        max_y = 0

        def map_(aut_cell, max_x, max_y):
            max_x = max(max_x, aut_cell.viewer_address[0] + 1)
            max_y = max(max_y, aut_cell.viewer_address[1] + 1)
            cell = Cell()
            cell.aut_cell = aut_cell
            cell.location = aut_cell.viewer_address
            cell.color = get_color(aut_cell)
            self.cells.append(cell)
            return max_x, max_y

        for aut_cell in self.automaton.topology.cells:
            max_x, max_y = map_(aut_cell, max_x, max_y)
        for light in self.automaton.topology.lights:
            max_x, max_y = map_(light, max_x, max_y)
        self.size = (max_x, max_y)

    def update(self):
        for cell in self.cells:
            cell.color = get_color(cell.aut_cell)

    def draw(self, screen, tiles):
        for cell in self.cells:
            screen.blit(
                tiles[cell.color],
                cell.absolute_location(self.square_size)
            )

def test():
    create_tiles(square_size)
    pygame.init()

    tca = models.Automaton()
#    topo = example_maps.generate_wide_street(60, 4)
#    topo = example_maps.grid_2lane_map()
    topo = example_maps.totito_map(10)
#    topo = example_maps.generate_street(25)
    tca.topology = topo
    topo.automaton = tca
    board = Board(tca)

#    topo.cells[0].connection = topo.cells[-1]
#    topo.cells[-1].connection = topo.cells[0]
#    topo.cells[-1].front_cell = topo.cells[0]
#    m_cells = [c for c in topo.cells]
#    for _ in range(5):
#        cell = random.choice(m_cells)
#        car = cars.Car()
#        car.cell = cell
#        car.speed = 0
#        car.v_max = 1
#        cell.car = car
#        cell.street.car_entry(car)
#        topo.cars.append(car)
#        m_cells.remove(cell)

    width = board.size[0] * square_size
    height = board.size[1] * square_size
    screen_size = (width, height)

    screen = pygame.display.set_mode(screen_size)
    clock = pygame.time.Clock()

    tiles = {
        'red': pygame.image.load('viewer_ng/res/red_%s.png' % square_size).convert(),
        'green': pygame.image.load('viewer_ng/res/green_%s.png' % square_size).convert(),
        'entrance': pygame.image.load('viewer_ng/res/entrance_%s.png' % square_size).convert(),
        'exit': pygame.image.load('viewer_ng/res/exit_%s.png' % square_size).convert(),
        'street': pygame.image.load('viewer_ng/res/street_%s.png' % square_size).convert(),
        'oob': pygame.image.load('viewer_ng/res/oob_%s.png' % square_size).convert(),
        'car': pygame.image.load('viewer_ng/res/car_%s.png' % square_size).convert(),
        'special_car': pygame.image.load('viewer_ng/res/special_car_%s.png' % square_size).convert(),
        'intersection': pygame.image.load('viewer_ng/res/intersection_%s.png' % square_size).convert(),
    }

    elapsed = 0
    run = False
    done = False

    board.draw(screen, tiles)
    pygame.display.flip()

    def update():
        tca.update()
        board.update()
        board.draw(screen, tiles)

    while done == False:

        elapsed += clock.tick(60)

        for event in pygame.event.get():
            if event.type == locals.QUIT:
                done = True
            if event.type == locals.KEYDOWN:
                if event.key == locals.K_SPACE:
                    run = not run
            if event.type == locals.KEYUP:
                if event.key == locals.K_q:
                    done = True
                elif event.key == locals.K_n:
                    run = False
                    update()

        if run and elapsed >= 1000 / speed:
            elapsed = 0
            update()

        pygame.display.set_caption('%s' % tca.generation)
        pygame.display.flip()

    pygame.quit()

def start_viewer(topology, square_size=16, speed=10):
    pygame.init()

    tca = models.Automaton()
    tca.topology = topology
    topology.automaton = tca
    board = Board(tca)

    info = pygame.display.Info()

    square_size = min(
        square_size,
        info.current_w // board.size[0],
        info.current_h // board.size[1]
    )

    width = board.size[0] * square_size
    height = board.size[1] * square_size
    screen_size = (width, height)

    create_tiles(square_size)

    board.square_size = square_size

    screen = pygame.display.set_mode(screen_size, locals.FULLSCREEN | locals.NOFRAME)
    clock = pygame.time.Clock()

    tiles = {
        'red': pygame.image.load('viewer_ng/res/red_%s.png' % square_size).convert(),
        'green': pygame.image.load('viewer_ng/res/green_%s.png' % square_size).convert(),
        'entrance': pygame.image.load('viewer_ng/res/entrance_%s.png' % square_size).convert(),
        'exit': pygame.image.load('viewer_ng/res/exit_%s.png' % square_size).convert(),
        'street': pygame.image.load('viewer_ng/res/street_%s.png' % square_size).convert(),
        'oob': pygame.image.load('viewer_ng/res/oob_%s.png' % square_size).convert(),
        'car': pygame.image.load('viewer_ng/res/car_%s.png' % square_size).convert(),
        'special_car': pygame.image.load('viewer_ng/res/special_car_%s.png' % square_size).convert(),
        'intersection': pygame.image.load('viewer_ng/res/intersection_%s.png' % square_size).convert(),
    }

    elapsed = 0
    run = False
    done = False

    board.draw(screen, tiles)
    pygame.display.flip()

    def update():
        tca.update()
        board.update()
        board.draw(screen, tiles)

    while done == False:
        elapsed += clock.tick(60)
        for event in pygame.event.get():
            if event.type == locals.QUIT:
                done = True
            if event.type == locals.KEYDOWN:
                if event.key == locals.K_SPACE:
                    run = not run
            if event.type == locals.KEYUP:
                if event.key == locals.K_q:
                    done = True
                elif event.key == locals.K_n:
                    run = False
                    update()

        if run and elapsed >= 1000 / speed:
            elapsed = 0
            update()

        pygame.display.set_caption('%s' % tca.generation)
        pygame.display.flip()

    pygame.quit()


text:
@class LZCartModel;
typedef void(^LZNumberChangedBlock)(NSInteger number);
typedef void(^LZCellSelectedBlock)(BOOL select);
@interface LZCartTableViewCell : UITableViewCell
//商品数量
@property (assign,nonatomic)NSInteger lzNumber;
@property (assign,nonatomic)BOOL lzSelected;

- (void)LZReloadDataWithModel:(LZCartModel*)model;
- (void)LZNumberAddWithBlock:(LZNumberChangedBlock)block;
- (void)LZNumberCutWithBlock:(LZNumberChangedBlock)block;
- (void)LZCellSelectedWithBlock:(LZCellSelectedBlock)block;
@end


text:
typedef struct CombatButtonWindow CombatButtonWindow;
struct CombatButtonWindow {
        int32_t unknown[0];
};


text:
package gosockjs

import (
	"bytes"
	"code.google.com/p/gorilla/mux"
	"errors"
	"io"
	"net/http"
	"sync"
)

func xhrProlog(w http.ResponseWriter, req *http.Request) bool {
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	h := req.Header.Get("Access-Control-Request-Headers")
	if h != "" {
		w.Header().Set("Access-Control-Allow-Headers", h)
	}
	if req.Method == "OPTIONS" {
		writeCacheAndExpires(w, req)
		writeOptionsAccess(w, req, "POST")
		w.WriteHeader(http.StatusNoContent)
		return true
	}
	writeCorsHeaders(w, req)
	writeNoCache(w, req)
	return false
}

type xhrTransport struct {
	receiver *xhrReceiver
	s        *session
	opts     xhrOptions
	lock     sync.RWMutex
}

func (t *xhrTransport) writeFrame(w io.Writer, frame []byte) error {
	return t.opts.writeFrame(w, frame)
}

func (t *xhrTransport) sendFrame(frame []byte) error {
	t.lock.RLock()
	defer t.lock.RUnlock()
	if t.receiver != nil {
		return t.receiver.opts.writeFrame(t.receiver, frame)
	}
	return errors.New("No receiver")
}

func (t *xhrTransport) closeTransport() {
	t.lock.RLock()
	defer t.lock.RUnlock()
	if t.receiver != nil {
		t.receiver.Close()
	}
}

func (t *xhrTransport) setReceiver(r *xhrReceiver) error {
	t.lock.Lock()
	if t.receiver != nil {
		defer t.lock.Unlock()
		// Nyet.
		t.writeFrame(r, closeFrame(2010, "Another connection still open"))
		return errors.New("Another connection still open")
	}
	t.receiver = r
	r.t = t
	t.lock.Unlock()
	t.s.newReceiver()
	return nil
}

func (t *xhrTransport) clearReceiver() {
	t.lock.Lock()
	t.receiver = nil
	defer t.lock.Unlock()
	t.s.disconnectReceiver()
}

type xhrReceiver struct {
	t        *xhrTransport
	w        io.WriteCloser
	opts     xhrOptions
	closed   chan bool // When closed the receiver closes this channel.
	nwritten int
	lock     sync.Mutex
}

func (r *xhrReceiver) Write(data []byte) (int, error) {
	r.lock.Lock()
	defer r.lock.Unlock()
	if r.closed == nil {
		return 0, errors.New("Closed")
	}
	if len(data) == 0 {
		return 0, nil
	}
	n, err := r.w.Write(data)
	r.nwritten += n
	if r.nwritten > r.opts.maxBytes() {
		r.internalClose()
	}
	return n, err
}

func (r *xhrReceiver) Close() error {
	r.lock.Lock()
	defer r.lock.Unlock()
	return r.internalClose()
}

func (r *xhrReceiver) internalClose() error {
	if r.closed != nil {
		close(r.closed)
		r.closed = nil
		return nil
	}
	return errors.New("Closed")
}

// differentiate between XhrPolling and XhrStreaming
type xhrOptions interface {
	maxBytes() int
	writeFrame(w io.Writer, frame []byte) error
	writePrelude(w io.Writer) error
	streaming() bool
	contentType() string
}

type xhrBaseOptions struct {
}

func (o xhrBaseOptions) writeFrame(w io.Writer, frame []byte) error {
	_, err := w.Write(append(frame, '\n'))
	return err
}

func (o xhrBaseOptions) contentType() string {
	return "application/javascript; charset=UTF-8"
}

type xhrPollingOptions struct {
	xhrBaseOptions
}

func (o xhrPollingOptions) maxBytes() int {
	return 1
}

func (o xhrPollingOptions) writePrelude(io.Writer) error {
	return nil
}

func (o xhrPollingOptions) streaming() bool {
	return false
}

type xhrStreamingOptions struct {
	xhrBaseOptions
}

func (o xhrStreamingOptions) maxBytes() int {
	return 4096 // r.maxBytes
}

func (o xhrStreamingOptions) writePrelude(w io.Writer) error {
	prelude := make([]byte, 2049)
	for i, _ := range prelude {
		prelude[i] = 'h'
	}
	prelude[2048] = '\n'
	_, err := w.Write(prelude)
	return err
}

func (o xhrStreamingOptions) streaming() bool {
	return true
}

func xhrJsessionid(r *Router, w http.ResponseWriter, req *http.Request) {
	c, err := req.Cookie("JSESSIONID")
	if err == nil && c != nil {
		if len(c.Path) == 0 {
			c.Path = "/"
		}
		http.SetCookie(w, c)
	} else if r.CookieNeeded {
		c := &http.Cookie{
			Name:  "JSESSIONID",
			Value: "dummy",
			Path:  "/",
		}
		http.SetCookie(w, c)
	}
}

// BUG(mrlauer): xhr connections cannot be reused.

// The handlers
func xhrHandlerBase(opts xhrOptions, r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	xhrJsessionid(r, w, req)
	w.Header().Set("Content-type", opts.contentType())
	// For CORS, if the server sent Access-Control-Request-Headers, we
	// echo it back.
	acrh := req.Header.Get("Access-Control-Request-Headers")
	if acrh != "" {
		w.Header().Set("Access-Control-Allow-Headers", acrh)
	}
	sessionId := mux.Vars(req)["sessionid"]

	w.WriteHeader(http.StatusOK)
	opts.writePrelude(w)
	hijackAndContinue(w, func(w io.WriteCloser, done chan struct{}) {
		defer w.Close()
		var trans *xhrTransport
		// Find the session
		s, _ := r.getOrCreateSession(sessionId)
		s.sessionLock.Lock()
		// TODO: encapsulate this logic
		var sessionUnlocked bool
		defer func() {
			if !sessionUnlocked {
				s.sessionLock.Unlock()
			}
		}()
		if s.trans != nil {
			if s.closed {
				s.trans.writeFrame(w, closeFrame(3000, "Go away!"))
				return
			}
			var ok bool
			trans, ok = s.trans.(*xhrTransport)
			if !ok {
				s.trans.writeFrame(w, closeFrame(1001, "Another kind of connection is using this session"))
				return
			}
		} else {
			trans = new(xhrTransport)
			trans.opts = opts
			s.trans = trans
			trans.s = s
			trans.writeFrame(w, openFrame())
			conn := &Conn{s}
			go r.handler(conn)
			if !opts.streaming() {
				w.Close()
				return
			}
		}
		s.sessionLock.Unlock()
		sessionUnlocked = true
		var leavingVoluntarily bool
		loopDone := make(chan bool)
		recvDone := make(chan bool)
		go func() {
			defer close(loopDone)
			defer w.Close()
			select {
			case <-recvDone:
				leavingVoluntarily = true
				return
			case <-done:
				return
			}
		}()
		err := trans.setReceiver(&xhrReceiver{t: trans, w: w, opts: opts, closed: recvDone})
		if err != nil {
			return
		}
		defer trans.clearReceiver()
		// The session may already have closed from underneath us!
		// If so, die now
		if s.closed {
			return
		}
		<-loopDone
		// If the session isn't closed, and we're not closing voluntarily, then
		// assume the client closed us and close the session.
		if !leavingVoluntarily && !s.closed {
			trans.clearReceiver()
			s.Close()
			r.removeSession(sessionId, s)
		}
	})
}

func xhrSendHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	w.Header().Set("Content-type", "text/plain; charset=UTF-8")
	sessionId := mux.Vars(req)["sessionid"]
	// Find the session
	s := r.getSession(sessionId)
	if s == nil {
		http.NotFoundHandler().ServeHTTP(w, req)
		return
	}
	// Synchronization? What if an xhr request is still creating this?
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, req.Body)
	req.Body.Close()
	if buf.Len() == 0 {
		http.Error(w, EmptyPayload.Error(), http.StatusInternalServerError)
		return
	}
	err := s.fromClient(message(buf.Bytes()))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-length", "0")
	w.WriteHeader(http.StatusNoContent)
}

func xhrHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	xhrHandlerBase(xhrPollingOptions{}, r, w, req)
}

func xhrStreamingHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	xhrHandlerBase(xhrStreamingOptions{}, r, w, req)
}


text:
<?php

namespace ApiPlatform\Core\tests\Metadata\Extractor;

use ApiPlatform\Core\Metadata\Extractor\YamlExtractor;

/**
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class YamlExtractorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \ApiPlatform\Core\Exception\InvalidArgumentException
     * @expectedExceptionMessage The property "shortName" must be a "string", "integer" given.
     */
    public function testInvalidProperty()
    {
        (new YamlExtractor([__DIR__.'/../../Fixtures/FileConfigurations/badpropertytype.yml']))->getResources();
    }
}


text:
$(document).ready(function() {
	var grid = new Grid();
});


text:
<?php

namespace bonavall\BancdeltempsBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use bonavall\BancdeltempsBundle\Entity\TipusServei;
use bonavall\BancdeltempsBundle\Form\TipusServeiType;

/**
 * TipusServei controller.
 *
 * @Route("/admin/tipusservei")
 */
class TipusServeiController extends Controller
{

    /**
     * Lists all TipusServei entities.
     *
     * @Route("/", name="admin_tipusservei")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('bonavallBancdeltempsBundle:TipusServei')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new TipusServei entity.
     *
     * @Route("/", name="admin_tipusservei_create")
     * @Method("POST")
     * @Template("bonavallBancdeltempsBundle:TipusServei:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new TipusServei();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_tipusservei_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a TipusServei entity.
    *
    * @param TipusServei $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(TipusServei $entity)
    {
        $form = $this->createForm(new TipusServeiType(), $entity, array(
            'action' => $this->generateUrl('admin_tipusservei_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new TipusServei entity.
     *
     * @Route("/new", name="admin_tipusservei_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new TipusServei();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a TipusServei entity.
     *
     * @Route("/{id}", name="admin_tipusservei_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('bonavallBancdeltempsBundle:TipusServei')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipusServei entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing TipusServei entity.
     *
     * @Route("/{id}/edit", name="admin_tipusservei_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('bonavallBancdeltempsBundle:TipusServei')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipusServei entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a TipusServei entity.
    *
    * @param TipusServei $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(TipusServei $entity)
    {
        $form = $this->createForm(new TipusServeiType(), $entity, array(
            'action' => $this->generateUrl('admin_tipusservei_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing TipusServei entity.
     *
     * @Route("/{id}", name="admin_tipusservei_update")
     * @Method("PUT")
     * @Template("bonavallBancdeltempsBundle:TipusServei:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('bonavallBancdeltempsBundle:TipusServei')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipusServei entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('admin_tipusservei_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a TipusServei entity.
     *
     * @Route("/{id}", name="admin_tipusservei_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('bonavallBancdeltempsBundle:TipusServei')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find TipusServei entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_tipusservei'));
    }

    /**
     * Creates a form to delete a TipusServei entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_tipusservei_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php

namespace Publiux\laravelcdn\Validators;

use Publiux\laravelcdn\Validators\Contracts\ValidatorInterface;

/**
 * Class Validator
 * Main Validator Class.
 *
 * @category Main Validator
 *
 * @author  Mahmoud Zalt <mahmoud@vinelab.com>
 */
class Validator implements ValidatorInterface
{
}


text:
package com.google.idea.sdkcompat.kotlin;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import org.jetbrains.kotlin.cli.common.arguments.Freezable;
import org.jetbrains.kotlin.idea.configuration.KotlinJavaModuleConfigurator;
import org.jetbrains.kotlin.idea.configuration.NotificationMessageCollector;

/** Provides SDK compatibility shims for Kotlin classes, available to IntelliJ CE & UE. */
public class KotlinCompat {
  private KotlinCompat() {}

  /** #api213 inline in BlazeKotlinSyncPlugin using FreezableKt.unfrozen() */
  public static <T extends Freezable> Freezable unfreezeSettings(T settings) {
    return settings.unfrozen();
  }

  /**
   * We want to configure only a single module, without a user-facing dialog (the configuration
   * process takes O(seconds) per module, on the EDT, and there can be 100s of modules for Android
   * Studio).
   *
   *
The single-module configuration method isn't exposed though, so we need to subclass the
   * configurator.
   *
   *
TODO(brendandouglas): remove this hack as soon as there's an appropriate upstream method. *
   *
   *
#api213: directly call KotlinJavaModuleConfigurator$configureModule from {@link
   * BlazeKotlinSyncPlugin}
   */
  private static class KotlinLibraryConfigurator extends KotlinJavaModuleConfigurator {
    static final KotlinLibraryConfigurator INSTANCE = new KotlinLibraryConfigurator();

    void configureModule(Project project, Module module) {
      configureModule(
          module,
          getDefaultPathToJarFile(project),
          null,
          new NotificationMessageCollector(project, "Configuring Kotlin", "Configuring Kotlin"));
    }
  }

  /* #api213: directly call KotlinJavaModuleConfigurator$configureModule from {@link
   * BlazeKotlinSyncPlugin}*/
  public static void configureModule(Project project, Module module) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      // do not invoke it later since serviceContainer may be disposed before it get completed
      ApplicationManager.getApplication()
          .invokeAndWait(() -> KotlinLibraryConfigurator.INSTANCE.configureModule(project, module));
    } else {
      ApplicationManager.getApplication()
          .invokeLater(() -> KotlinLibraryConfigurator.INSTANCE.configureModule(project, module));
    }
  }
}


text:
#pragma once

#include <string>
#include <vector>
#include <fstream>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <Utility/Log.hpp>
#include "../linking.hpp"

namespace Animation {
    struct Bone;
    struct Animation;
}

namespace Animation {
    /// An animation loaded from a file.
    class AnimationClip {
        public:
            /// Default constructor.
            AnimationClip() = default;

            /// Load.
            /**
             * @param name Name of animation.
             */
            ENGINE_API void Load(const std::string& name);

            Animation* animation = nullptr;

            /// Path of animation clip.
            std::string path;

            /// Name of animation clip.
            std::string name;
    };
}