text:
/*************************************************************************/
/*  joypad_linux.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef JOYDEV_ENABLED

#include "joypad_linux.h"

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>

#ifdef UDEV_ENABLED
#include "libudev-so_wrap.h"
#endif

#define LONG_BITS (sizeof(long) * 8)
#define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
#define NBITS(x) ((((x)-1) / LONG_BITS) + 1)

#ifdef UDEV_ENABLED
static const char *ignore_str = "/dev/input/js";
#endif

JoypadLinux::Joypad::~Joypad() {
	for (int i = 0; i < MAX_ABS; i++) {
		if (abs_info[i]) {
			memdelete(abs_info[i]);
		}
	}
}

void JoypadLinux::Joypad::reset() {
	dpad = 0;
	fd = -1;

	Input::JoyAxisValue jx;
	jx.min = -1;
	jx.value = 0.0f;
	for (int i = 0; i < MAX_ABS; i++) {
		abs_map[i] = -1;
		curr_axis[i] = jx;
	}
}

JoypadLinux::JoypadLinux(Input *in) {
#ifdef UDEV_ENABLED
#ifdef DEBUG_ENABLED
	int dylibloader_verbose = 1;
#else
	int dylibloader_verbose = 0;
#endif
	use_udev = initialize_libudev(dylibloader_verbose) == 0;
	if (use_udev) {
		print_verbose("JoypadLinux: udev enabled and loaded successfully.");
	} else {
		print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads.");
	}
#else
	print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads.");
#endif
	input = in;
	joy_thread.start(joy_thread_func, this);
}

JoypadLinux::~JoypadLinux() {
	exit_monitor.set();
	joy_thread.wait_to_finish();
	close_joypad();
}

void JoypadLinux::joy_thread_func(void *p_user) {
	if (p_user) {
		JoypadLinux *joy = (JoypadLinux *)p_user;
		joy->run_joypad_thread();
	}
}

void JoypadLinux::run_joypad_thread() {
#ifdef UDEV_ENABLED
	if (use_udev) {
		udev *_udev = udev_new();
		if (!_udev) {
			use_udev = false;
			ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input.");
			monitor_joypads();
		} else {
			enumerate_joypads(_udev);
			monitor_joypads(_udev);
			udev_unref(_udev);
		}
	} else {
		monitor_joypads();
	}
#else
	monitor_joypads();
#endif
}

#ifdef UDEV_ENABLED
void JoypadLinux::enumerate_joypads(udev *p_udev) {
	udev_enumerate *enumerate;
	udev_list_entry *devices, *dev_list_entry;
	udev_device *dev;

	enumerate = udev_enumerate_new(p_udev);
	udev_enumerate_add_match_subsystem(enumerate, "input");

	udev_enumerate_scan_devices(enumerate);
	devices = udev_enumerate_get_list_entry(enumerate);
	udev_list_entry_foreach(dev_list_entry, devices) {
		const char *path = udev_list_entry_get_name(dev_list_entry);
		dev = udev_device_new_from_syspath(p_udev, path);
		const char *devnode = udev_device_get_devnode(dev);

		if (devnode) {
			String devnode_str = devnode;
			if (devnode_str.find(ignore_str) == -1) {
				MutexLock lock(joy_mutex);
				open_joypad(devnode);
			}
		}
		udev_device_unref(dev);
	}
	udev_enumerate_unref(enumerate);
}

void JoypadLinux::monitor_joypads(udev *p_udev) {
	udev_device *dev = nullptr;
	udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
	udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr);
	udev_monitor_enable_receiving(mon);
	int fd = udev_monitor_get_fd(mon);

	while (!exit_monitor.is_set()) {
		fd_set fds;
		struct timeval tv;
		int ret;

		FD_ZERO(&fds);
		FD_SET(fd, &fds);
		tv.tv_sec = 0;
		tv.tv_usec = 0;

		ret = select(fd + 1, &fds, nullptr, nullptr, &tv);

		/* Check if our file descriptor has received data. */
		if (ret > 0 && FD_ISSET(fd, &fds)) {
			/* Make the call to receive the device.
			   select() ensured that this will not block. */
			dev = udev_monitor_receive_device(mon);

			if (dev && udev_device_get_devnode(dev) != nullptr) {
				MutexLock lock(joy_mutex);
				String action = udev_device_get_action(dev);
				const char *devnode = udev_device_get_devnode(dev);
				if (devnode) {
					String devnode_str = devnode;
					if (devnode_str.find(ignore_str) == -1) {
						if (action == "add") {
							open_joypad(devnode);
						} else if (String(action) == "remove") {
							close_joypad(get_joy_from_path(devnode));
						}
					}
				}

				udev_device_unref(dev);
			}
		}
		usleep(50000);
	}
	udev_monitor_unref(mon);
}
#endif

void JoypadLinux::monitor_joypads() {
	while (!exit_monitor.is_set()) {
		{
			MutexLock lock(joy_mutex);

			DIR *input_directory;
			input_directory = opendir("/dev/input");
			if (input_directory) {
				struct dirent *current;
				char fname[64];

				while ((current = readdir(input_directory)) != nullptr) {
					if (strncmp(current->d_name, "event", 5) != 0) {
						continue;
					}
					sprintf(fname, "/dev/input/%.*s", 16, current->d_name);
					if (attached_devices.find(fname) == -1) {
						open_joypad(fname);
					}
				}
			}
			closedir(input_directory);
		}
		usleep(1000000); // 1s
	}
}

int JoypadLinux::get_joy_from_path(String p_path) const {
	for (int i = 0; i < JOYPADS_MAX; i++) {
		if (joypads[i].devpath == p_path) {
			return i;
		}
	}
	return -2;
}

void JoypadLinux::close_joypad(int p_id) {
	if (p_id == -1) {
		for (int i = 0; i < JOYPADS_MAX; i++) {
			close_joypad(i);
		};
		return;
	} else if (p_id < 0) {
		return;
	}

	Joypad &joy = joypads[p_id];

	if (joy.fd != -1) {
		close(joy.fd);
		joy.fd = -1;
		attached_devices.remove(attached_devices.find(joy.devpath));
		input->joy_connection_changed(p_id, false, "");
	};
}

static String _hex_str(uint8_t p_byte) {
	static const char *dict = "0123456789abcdef";
	char ret[3];
	ret[2] = 0;

	ret[0] = dict[p_byte >> 4];
	ret[1] = dict[p_byte & 0xF];

	return ret;
}

void JoypadLinux::setup_joypad_properties(int p_id) {
	Joypad *joy = &joypads[p_id];

	unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
	unsigned long absbit[NBITS(ABS_MAX)] = { 0 };

	int num_buttons = 0;
	int num_axes = 0;

	if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
			(ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
		return;
	}
	for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
		if (test_bit(i, keybit)) {
			joy->key_map[i] = num_buttons++;
		}
	}
	for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
		if (test_bit(i, keybit)) {
			joy->key_map[i] = num_buttons++;
		}
	}
	for (int i = 0; i < ABS_MISC; ++i) {
		/* Skip hats */
		if (i == ABS_HAT0X) {
			i = ABS_HAT3Y;
			continue;
		}
		if (test_bit(i, absbit)) {
			joy->abs_map[i] = num_axes++;
			joy->abs_info[i] = memnew(input_absinfo);
			if (ioctl(joy->fd, EVIOCGABS(i), joy->abs_info[i]) < 0) {
				memdelete(joy->abs_info[i]);
				joy->abs_info[i] = nullptr;
			}
		}
	}

	joy->force_feedback = false;
	joy->ff_effect_timestamp = 0;
	unsigned long ffbit[NBITS(FF_CNT)];
	if (ioctl(joy->fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
		if (test_bit(FF_RUMBLE, ffbit)) {
			joy->force_feedback = true;
		}
	}
}

void JoypadLinux::open_joypad(const char *p_path) {
	int joy_num = input->get_unused_joy_id();
	int fd = open(p_path, O_RDWR | O_NONBLOCK);
	if (fd != -1 && joy_num != -1) {
		unsigned long evbit[NBITS(EV_MAX)] = { 0 };
		unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
		unsigned long absbit[NBITS(ABS_MAX)] = { 0 };

		// add to attached devices so we don't try to open it again
		attached_devices.push_back(String(p_path));

		if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
				(ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
				(ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
			close(fd);
			return;
		}

		// Check if the device supports basic gamepad events
		if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
					test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) {
			close(fd);
			return;
		}

		char uid[128];
		char namebuf[128];
		String name = "";
		input_id inpid;
		if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
			name = namebuf;
		}

		if (ioctl(fd, EVIOCGID, &inpid) < 0) {
			close(fd);
			return;
		}

		joypads[joy_num].reset();

		Joypad &joy = joypads[joy_num];
		joy.fd = fd;
		joy.devpath = String(p_path);
		setup_joypad_properties(joy_num);
		sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
		if (inpid.vendor && inpid.product && inpid.version) {
			uint16_t vendor = BSWAP16(inpid.vendor);
			uint16_t product = BSWAP16(inpid.product);
			uint16_t version = BSWAP16(inpid.version);

			sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
			input->joy_connection_changed(joy_num, true, name, uid);
		} else {
			String uidname = uid;
			int uidlen = MIN(name.length(), 11);
			for (int i = 0; i < uidlen; i++) {
				uidname = uidname + _hex_str(name[i]);
			}
			uidname += "00";
			input->joy_connection_changed(joy_num, true, name, uidname);
		}
	}
}

void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
	Joypad &joy = joypads[p_id];
	if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
		return;
	}
	if (joy.ff_effect_id != -1) {
		joypad_vibration_stop(p_id, p_timestamp);
	}

	struct ff_effect effect;
	effect.type = FF_RUMBLE;
	effect.id = -1;
	effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
	effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
	effect.replay.length = floor(p_duration * 1000);
	effect.replay.delay = 0;

	if (ioctl(joy.fd, EVIOCSFF, &effect) < 0) {
		return;
	}

	struct input_event play;
	play.type = EV_FF;
	play.code = effect.id;
	play.value = 1;
	if (write(joy.fd, (const void *)&play, sizeof(play)) == -1) {
		print_verbose("Couldn't write to Joypad device.");
	}

	joy.ff_effect_id = effect.id;
	joy.ff_effect_timestamp = p_timestamp;
}

void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
	Joypad &joy = joypads[p_id];
	if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
		return;
	}

	if (ioctl(joy.fd, EVIOCRMFF, joy.ff_effect_id) < 0) {
		return;
	}

	joy.ff_effect_id = -1;
	joy.ff_effect_timestamp = p_timestamp;
}

Input::JoyAxisValue JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
	int min = p_abs->minimum;
	int max = p_abs->maximum;
	Input::JoyAxisValue jx;

	if (min < 0) {
		jx.min = -1;
		if (p_value < 0) {
			jx.value = (float)-p_value / min;
		} else {
			jx.value = (float)p_value / max;
		}
	} else if (min == 0) {
		jx.min = 0;
		jx.value = 0.0f + (float)p_value / max;
	}
	return jx;
}

void JoypadLinux::process_joypads() {
	if (joy_mutex.try_lock() != OK) {
		return;
	}
	for (int i = 0; i < JOYPADS_MAX; i++) {
		if (joypads[i].fd == -1) {
			continue;
		}

		input_event events[32];
		Joypad *joy = &joypads[i];

		int len;

		while ((len = read(joy->fd, events, (sizeof events))) > 0) {
			len /= sizeof(events[0]);
			for (int j = 0; j < len; j++) {
				input_event &ev = events[j];

				// ev may be tainted and out of MAX_KEY range, which will cause
				// joy->key_map[ev.code] to crash
				if (ev.code >= MAX_KEY) {
					return;
				}

				switch (ev.type) {
					case EV_KEY:
						input->joy_button(i, joy->key_map[ev.code], ev.value);
						break;

					case EV_ABS:

						switch (ev.code) {
							case ABS_HAT0X:
								if (ev.value != 0) {
									if (ev.value < 0) {
										joy->dpad = (joy->dpad | Input::HAT_MASK_LEFT) & ~Input::HAT_MASK_RIGHT;
									} else {
										joy->dpad = (joy->dpad | Input::HAT_MASK_RIGHT) & ~Input::HAT_MASK_LEFT;
									}
								} else {
									joy->dpad &= ~(Input::HAT_MASK_LEFT | Input::HAT_MASK_RIGHT);
								}

								input->joy_hat(i, joy->dpad);
								break;

							case ABS_HAT0Y:
								if (ev.value != 0) {
									if (ev.value < 0) {
										joy->dpad = (joy->dpad | Input::HAT_MASK_UP) & ~Input::HAT_MASK_DOWN;
									} else {
										joy->dpad = (joy->dpad | Input::HAT_MASK_DOWN) & ~Input::HAT_MASK_UP;
									}
								} else {
									joy->dpad &= ~(Input::HAT_MASK_UP | Input::HAT_MASK_DOWN);
								}

								input->joy_hat(i, joy->dpad);
								break;

							default:
								if (ev.code >= MAX_ABS) {
									return;
								}
								if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
									Input::JoyAxisValue value = axis_correct(joy->abs_info[ev.code], ev.value);
									joy->curr_axis[joy->abs_map[ev.code]] = value;
								}
								break;
						}
						break;
				}
			}
		}
		for (int j = 0; j < MAX_ABS; j++) {
			int index = joy->abs_map[j];
			if (index != -1) {
				input->joy_axis(i, index, joy->curr_axis[index]);
			}
		}
		if (len == 0 || (len < 0 && errno != EAGAIN)) {
			close_joypad(i);
		};

		if (joy->force_feedback) {
			uint64_t timestamp = input->get_joy_vibration_timestamp(i);
			if (timestamp > joy->ff_effect_timestamp) {
				Vector2 strength = input->get_joy_vibration_strength(i);
				float duration = input->get_joy_vibration_duration(i);
				if (strength.x == 0 && strength.y == 0) {
					joypad_vibration_stop(i, timestamp);
				} else {
					joypad_vibration_start(i, strength.x, strength.y, duration, timestamp);
				}
			}
		}
	}
	joy_mutex.unlock();
}
#endif


text:
title:  Keluarga
date:  03/10/2020
---

### Bacaan Untuk Pelajaran Minggu Ini
Kejadian 3:1–15, 2 Korintus 4:6, Lukas 1:26–38, Matius 1:18–24, Efesus 4:15, 1 Yohanes 3:18, Ulangan 6.

>
Ayat Hafalan

> "Hai anakku, dengarkanlah didikan ayahmu, dan jangan menyia-nyiakan ajaran ibumu" (Amsal 1:8) .

Sebagai manusia, kita sentiasa (secara idealnya) belajar. Sebenarnya, kehidupan itu sendiri adalah sebuah sekolah.

"Sejak awal orang Israel  yang setia telah memberikan banyak perhatian terhadap pendidikan para muda-mudi. Tuhan telah memerintahkan bahawa sejak kecil lagi anak-anak harus diajar tentang kebaikan dan kebesaran-Nya, terutama seperti yang dinyatakan dalam hukum-Nya dan dinyatakan di dalam sejarah Israel. Nyanyian dan doa serta pelajaran dari Kitab Suci harus disesuaikan dengan pembukaan minda. Bapa dan ibu harus mengajarkan kepada anak-anak mereka bahawa hukum Tuhan adalah satu pernyataan keperibadian-Nya, dan bahawa ketika mereka menerima prinsip hukum itu ke dalam hati, gambaran Tuhan ditelusuri di dalam fikiran dan jiwa. Sebilangan besar cara pengajaran adalah secara lisan; tetapi para pemuda juga belajar membaca tulisan Ibrani; dan gulungan tulisan dari Kitab Perjanjian Lama terbuka untuk kajian mereka. "- Ellen G. White, The Desire of Ages, ms. 69.

Bagi sebahagian besar sejarah manusia, pendidikan banyak berlaku di rumah, terutama pada tahun-tahun awal. Apakah yang Alkitab katakan tentang pendidikan dalam keluarga, dan prinsip apakah yang dapat kita ambil dari situ untuk diri kita sendiri, di dalam apapun keadaan keluarga kita?

_*Sila kaji pelajaran minggu ini untuk persediaan Sabat, Oktober 10._

redpajama_set_name: RedPajamaGithub


text:
package controllers;

import static org.fest.assertions.Assertions.assertThat;
import static play.mvc.Http.Status.*;
import static play.test.Helpers.*;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import models.Project;
import models.PullRequest;
import models.PushedBranch;
import models.User;
import models.enumeration.State;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.RefSpec;
import org.junit.*;

import org.junit.rules.TestWatcher;
import play.mvc.Result;
import play.test.FakeApplication;
import play.test.Helpers;
import support.ExecutionTimeWatcher;
import playRepository.GitRepository;

public class PullRequestAppTest {
    protected static FakeApplication app;

    private String ownerLoginId;
    private String projectName;
    private Long pullRequestNumber;
    private static PullRequest pullRequest;
    private static boolean isInit = false;

    @Rule
    public TestWatcher watcher = new ExecutionTimeWatcher();

    @BeforeClass
    public static void beforeClass() {
        app = support.Helpers.makeTestApplication();
        Helpers.start(app);
    }

    @Before
    public void before() {
        GitRepository.setRepoPrefix("resources/test/repo/git/");
    }

    @AfterClass
    public static void afterClase(){
        Helpers.stop(app);
    }

    @After
    public void after() {
        support.Files.rm_rf(new File(GitRepository.getRepoPrefix()));
    }

    @Test
    public void testCloseAnonymous() throws Exception {
        initParameters("alecsiel", "sample", 10L);
        Result result = callAction(
                controllers.routes.ref.PullRequestApp.close(ownerLoginId, projectName, pullRequestNumber)
        );

        assertThat(status(result)).isEqualTo(SEE_OTHER);
    }

    @Test
    public void testCloseNotExistProject() throws Exception {
        initParameters("alecsiel", "sample", 10L);
        User currentUser = User.findByLoginId("admin");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.close(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
              );

        assertThat(status(result)).isEqualTo(FORBIDDEN);
    }

    @Test
    public void testCloseNotExistPullRequest() throws Exception {
        initParameters("yobi", "projectYobi-1", 10L);
        User currentUser = User.findByLoginId("admin");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.close(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
              );

        assertThat(status(result)).isEqualTo(NOT_FOUND);
    }

    @Test
    public void testClosePullRequest() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("admin");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.close(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        assertThat(status(result)).isEqualTo(SEE_OTHER);
        assertThat(PullRequest.findById(pullRequestNumber).state).isEqualTo(State.CLOSED);
    }

    @Test
    public void testClosePullRequestNotAllow() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("alecsiel");
        User projectOwner = User.findByLoginId("yobi");

        callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                        .withSession(UserApp.SESSION_USERID, projectOwner.id.toString())
        );

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.close(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
              );

        assertThat(status(result)).isEqualTo(FORBIDDEN);
        assertThat(PullRequest.findById(pullRequestNumber).state).isEqualTo(State.OPEN);
    }

    @Test
    public void testOpenAnonymous() throws Exception {
        initParameters("alecsiel", "sample", 10L);
        Result result = callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber)
        );

        assertThat(status(result)).isEqualTo(SEE_OTHER);
    }

    @Test
    public void testOpenPullRequestBadRequest() throws Exception {
        //Given
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("admin");

        User projectOwner = User.findByLoginId("yobi");

        final String uri = "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber;
        callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", uri).withSession(UserApp.SESSION_USERID, projectOwner.id.toString())
        );

        //When
        Result result = callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", uri).withSession(UserApp.SESSION_USERID, currentUser.id.toString())
              );

        //Then
        assertThat(status(result)).isEqualTo(BAD_REQUEST).describedAs("open already opened");
    }

    @Test
    public void testOpenPullRequest() throws Exception {
        // Given
        initParameters("yobi", "HelloSocialApp", 1L);
        User currentUser = User.findByLoginId("admin");
        Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName);
        PullRequest pullRequest = PullRequest.findOne(project, pullRequestNumber);
        PushedBranch pushedBranch = new PushedBranch(new Date(), pullRequest.fromBranch,
                pullRequest.fromProject);
        pushedBranch.save();

        // When
        Result result = callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
              );

        // Then
        assertThat(status(result)).isEqualTo(SEE_OTHER);
        assertThat(PullRequest.findOne(project, pullRequestNumber).state).isEqualTo(State.OPEN);
        assertThat(
                PushedBranch.find.where().eq("project", pullRequest.fromProject)
                        .eq("name", pullRequest.fromBranch).findUnique()).isNull();
    }

    @Test
    public void testAcceptAnonymous() throws Exception {
        initParameters("alecsiel", "sample", 10L);
        Result result = callAction(
                controllers.routes.ref.PullRequestApp.accept(ownerLoginId, projectName, pullRequestNumber)
        );

        assertThat(status(result)).isEqualTo(SEE_OTHER);
    }

    @Test
    public void testNewForkByAdmin() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("admin");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.newFork(ownerLoginId, projectName, null),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/newFork")
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        assertThat(status(result)).isEqualTo(OK);
    }

    @Test
    public void testNewForkByMember() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("yobi");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.newFork(ownerLoginId, projectName, null),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/newFork")
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        assertThat(status(result)).isEqualTo(OK);

    }

    @Test
    public void testNewForkByNotMember() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("alecsiel");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.newFork(ownerLoginId, projectName, null),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/newFork")
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        assertThat(status(result)).isEqualTo(OK);
    }

    @Test
    public void testNewForkPrivateProjectAndNotMember() throws Exception {
        initParameters("laziel", "Jindo", 1L);
        User currentUser = User.findByLoginId("alecsiel");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.newFork(ownerLoginId, projectName, null),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/newFork")
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        assertThat(status(result)).isEqualTo(FORBIDDEN);
    }

    @Test
    public void testForkAlreadyExistForkProject() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("yobi");

        Map<String,String> data = new HashMap<>();
        data.put("owner", "yobi");
        data.put("name", "projectYobi-2");
        data.put("projectScope", "PUBLIC");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.fork(ownerLoginId, projectName),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/fork")
                        .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
                        .withFormUrlEncodedBody(data)
        );

        assertThat(status(result)).isEqualTo(OK);
    }

    @Test
    public void testForkSampleName() throws Exception {
        initParameters("yobi", "TestApp", 1L);
        User currentUser = User.findByLoginId("yobi");

        Map<String,String> data = new HashMap<>();
        data.put("name", "HelloSocialApp-1");

        Result result = callAction(
                controllers.routes.ref.PullRequestApp.fork(ownerLoginId, projectName),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/fork")
                .withSession(UserApp.SESSION_USERID, currentUser.id.toString())
                .withFormUrlEncodedBody(data)
              );

        assertThat(status(result)).isEqualTo(SEE_OTHER);
    }
    @Test
    public void testNewForkRoute() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        String url = "/" + ownerLoginId + "/" + projectName + "/newFork";
        User currentUser = User.findByLoginId("yobi");

        Result result = route(
            fakeRequest(GET, url).withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );
        assertThat(status(result)).isEqualTo(OK);
    }

    @Test
    public void testCloseRoute() throws Exception {
        initParameters("yobi", "projectYobi", 1L);
        String url = "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber + "/close";
        User currentUser = User.findByLoginId("yobi");

        Result result = route(
            fakeRequest(POST, url).withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );
        assertThat(status(result)).isEqualTo(SEE_OTHER);

        Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName);
        PullRequest pullRequest = PullRequest.findOne(project, pullRequestNumber);

        assertThat(pullRequest.state).isEqualTo(State.CLOSED);
    }

    @Test
    public void testOpenRoute() throws Exception {
        //Given
        initParameters("yobi", "projectYobi", 1L);
        User currentUser = User.findByLoginId("yobi");
        User projectOwner = User.findByLoginId("yobi");

        String url = "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber + "/open";
        callAction(
                controllers.routes.ref.PullRequestApp.open(ownerLoginId, projectName, pullRequestNumber),
                fakeRequest("GET", "/" + ownerLoginId + "/" + projectName + "/pullRequest/" + pullRequestNumber)
                        .withSession(UserApp.SESSION_USERID, projectOwner.id.toString())
        );

        //When
        Result result = route(
            fakeRequest(POST, url).withSession(UserApp.SESSION_USERID, currentUser.id.toString())
        );

        //Then
        assertThat(status(result)).isEqualTo(BAD_REQUEST);

        Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName);
        PullRequest pullRequest = PullRequest.findOne(project, pullRequestNumber);

        assertThat(pullRequest.state).isEqualTo(State.OPEN);
    }

    private void initParameters(String ownerLoginId, String projectName, Long pullRequestNumber)
            throws Exception {
        this.ownerLoginId = ownerLoginId;
        this.projectName = projectName;
        this.pullRequestNumber = pullRequestNumber;
    }

}


text:
<?php

namespace Blog\Form;

use Zend\Form\Form;
//use Zend\Stdlib\Hydrator\ClassMethods;

use Blog\Model\BlogPost;

class BlogPostForm extends Form
{
	public function __construct($name = null, $options = array())
	{
		parent::__construct($name, $options);

		// Set the form object
		$this->setObject(new BlogPost());

		// Set the form hydrator
		//$this->setHydrator(new ClassMethods());

		// Set the form method
		$this->setAttribute('method', 'post');

		// Add the title field
		$this->add(array(
			'name' => 'title',
			'attributes' => array(
				'type' => 'text',
			),
			'options' => array(
				'label' => 'Title',
			),
		));

		// Add the post text field
		$this->add(array(
			'name' => 'text',
			'attributes' => array(
				'type' => 'textarea',
			),
			'options' => array(
				'label' => 'Body',
			),
		));

		// Add the post id field
		/*$this->add(array(
			'name' => 'id',
			'attributes' => array(
				'type'  => 'hidden',
			),
		));*/

		// Add the submit button
		$this->add(array(
			'name' => 'submit',
			'attributes' => array(
				'type'  => 'submit',
				'value' => 'Submit',
			),
		));
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>Nameitlater</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,900"/>
  <link rel="stylesheet" href="/css/main.css"/>

{{ html|safe }}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace WGSharpAPI.Entities.PlayerDetails
{
    public class Player
    {
        public Player()
        {
            Achievements = new List<Achievement>();
            Tanks = new List<Tank>();
        }

        /// <summary>
        /// Player account ID
        /// </summary>
        [JsonProperty("account_id")]
        public long AccountId { get; set; }

        /// <summary>
        /// Player name
        /// </summary>
        [JsonProperty("nickname")]
        public string Nickname { get; set; }

        /// <summary>
        /// Date when player's account was created
        /// </summary>
        [JsonProperty("created_at")]
        public long CreatedAt { get; set; }

        /// <summary>
        /// Personal rating
        /// </summary>
        [JsonProperty("global_rating")]
        public decimal GlobalRating { get; set; }

        /// <summary>
        /// Last battle time
        /// </summary>
        [JsonProperty("last_battle_time")]
        public long LastBattleTime { get; set; }

        /// <summary>
        /// End time of last game session
        /// </summary>
        [JsonProperty("logout_at")]
        public long LastLogout { get; set; }

        /// <summary>
        /// Date when player details were updated
        /// </summary>
        [JsonProperty("updated_at")]
        public long UpdatedAt { get; set; }

        /// <summary>
        /// Player's achievements
        /// </summary>
        [JsonProperty("achievements")]
        [Obsolete("This field will be removed.")]
        public Achievements AchievementsOld { get; set; }

        /// <summary>
        /// Player's private data
        /// </summary>
        [JsonProperty("private")]
        public PrivateData Private { get; set; }

        /// <summary>
        /// Player statistics
        /// </summary>
        [JsonProperty("statistics")]
        public Statistics Statistics { get; set; }

        /// <summary>
        /// Player's achievements
        /// </summary>
        public List<Achievement> Achievements { get; set; }

        /// <summary>
        /// List of tanks
        /// </summary>
        public List<Tank> Tanks { get; set; }

        #region Overrides

        public override string ToString()
        {
            var result = string.Empty;

            if (!string.IsNullOrWhiteSpace(Nickname))
                result = Nickname;
            else if (AccountId != 0)
                result = AccountId.ToString();
            else
                result = base.ToString();

            return result;
        }

        #endregion Overrides
    }
}


text:
module ActiveRecord
  module Associations
    class Preloader
      class HasManyThrough < CollectionAssociation #:nodoc:
        include ThroughAssociation

        def associated_records_by_owner
          records_by_owner = super

          if reflection_scope.distinct_value
            records_by_owner.each_value { |records| records.uniq! }
          end

          records_by_owner
        end
      end
    end
  end
end


text:
#include "src/compiler/objective_c_generator.h"

#include <map>
#include <set>
#include <sstream>

#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>

#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator_helpers.h"

using ::google::protobuf::compiler::objectivec::ClassName;
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::MethodDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::grpc::protobuf::io::Printer;
using ::std::map;
using ::std::set;

namespace grpc_objective_c_generator {
namespace {

void PrintProtoRpcDeclarationAsPragma(Printer* printer,
                                      const MethodDescriptor* method,
                                      map< ::std::string, ::std::string> vars) {
  vars["client_stream"] = method->client_streaming() ? "stream " : "";
  vars["server_stream"] = method->server_streaming() ? "stream " : "";

  printer->Print(vars,
                 "#pragma mark $method_name$($client_stream$$request_type$)"
                 " returns ($server_stream$$response_type$)\n\n");
}

template <typename DescriptorType>
static void PrintAllComments(const DescriptorType* desc, Printer* printer,
                             bool deprecated = false) {
  std::vector<std::string> comments;
  grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,
                             &comments);
  grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING,
                             &comments);
  grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING,
                             &comments);
  if (comments.empty()) {
    return;
  }
  printer->Print("/**\n");
  for (auto it = comments.begin(); it != comments.end(); ++it) {
    printer->Print(" * ");
    size_t start_pos = it->find_first_not_of(' ');
    if (start_pos != std::string::npos) {
      printer->PrintRaw(it->c_str() + start_pos);
    }
    printer->Print("\n");
  }
  if (deprecated) {
    printer->Print(" *\n");
    printer->Print(
        " * This method belongs to a set of APIs that have been deprecated. "
        "Using"
        " the v2 API is recommended.\n");
  }
  printer->Print(" */\n");
}

void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
                          const map< ::std::string, ::std::string>& vars) {
  // Print comment
  PrintAllComments(method, printer, true);

  printer->Print(vars, "- ($return_type$)$method_name$With");
  if (method->client_streaming()) {
    printer->Print("RequestsWriter:(GRXWriter *)requestWriter");
  } else {
    printer->Print(vars, "Request:($request_class$ *)request");
  }

  // TODO(jcanizales): Put this on a new line and align colons.
  if (method->server_streaming()) {
    printer->Print(vars,
                   " eventHandler:(void(^)(BOOL done, "
                   "$response_class$ *_Nullable response, NSError *_Nullable "
                   "error))eventHandler");
  } else {
    printer->Print(vars,
                   " handler:(void(^)($response_class$ *_Nullable response, "
                   "NSError *_Nullable error))handler");
  }
}

void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,
                          map< ::std::string, ::std::string> vars) {
  vars["method_name"] =
      grpc_generator::LowercaseFirstLetter(vars["method_name"]);
  vars["return_type"] = "void";
  PrintMethodSignature(printer, method, vars);
}

void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,
                            map< ::std::string, ::std::string> vars) {
  vars["method_name"] = "RPCTo" + vars["method_name"];
  vars["return_type"] = "GRPCProtoCall *";
  PrintMethodSignature(printer, method, vars);
}

void PrintV2Signature(Printer* printer, const MethodDescriptor* method,
                      map< ::std::string, ::std::string> vars) {
  if (method->client_streaming()) {
    vars["return_type"] = "GRPCStreamingProtoCall *";
  } else {
    vars["return_type"] = "GRPCUnaryProtoCall *";
  }
  vars["method_name"] =
      grpc_generator::LowercaseFirstLetter(vars["method_name"]);

  PrintAllComments(method, printer);

  printer->Print(vars, "- ($return_type$)$method_name$With");
  if (method->client_streaming()) {
    printer->Print("ResponseHandler:(id<GRPCProtoResponseHandler>)handler");
  } else {
    printer->Print(vars,
                   "Message:($request_class$ *)message "
                   "responseHandler:(id<GRPCProtoResponseHandler>)handler");
  }
  printer->Print(" callOptions:(GRPCCallOptions *_Nullable)callOptions");
}

inline map< ::std::string, ::std::string> GetMethodVars(
    const MethodDescriptor* method) {
  map< ::std::string, ::std::string> res;
  res["method_name"] = method->name();
  res["request_type"] = method->input_type()->name();
  res["response_type"] = method->output_type()->name();
  res["request_class"] = ClassName(method->input_type());
  res["response_class"] = ClassName(method->output_type());
  return res;
}

void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {
  if (!ShouldIncludeMethod(method)) return;

  map< ::std::string, ::std::string> vars = GetMethodVars(method);

  PrintProtoRpcDeclarationAsPragma(printer, method, vars);

  PrintSimpleSignature(printer, method, vars);
  printer->Print(";\n\n");
  PrintAdvancedSignature(printer, method, vars);
  printer->Print(";\n\n\n");
}

void PrintV2MethodDeclarations(Printer* printer,
                               const MethodDescriptor* method) {
  if (!ShouldIncludeMethod(method)) return;

  map< ::std::string, ::std::string> vars = GetMethodVars(method);

  PrintProtoRpcDeclarationAsPragma(printer, method, vars);

  PrintV2Signature(printer, method, vars);
  printer->Print(";\n\n");
}

void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,
                               map< ::std::string, ::std::string> vars) {
  printer->Print("{\n");
  printer->Print(vars, "  [[self RPCTo$method_name$With");
  if (method->client_streaming()) {
    printer->Print("RequestsWriter:requestWriter");
  } else {
    printer->Print("Request:request");
  }
  if (method->server_streaming()) {
    printer->Print(" eventHandler:eventHandler] start];\n");
  } else {
    printer->Print(" handler:handler] start];\n");
  }
  printer->Print("}\n");
}

void PrintAdvancedImplementation(Printer* printer,
                                 const MethodDescriptor* method,
                                 map< ::std::string, ::std::string> vars) {
  printer->Print("{\n");
  printer->Print(vars, "  return [self RPCToMethod:@\"$method_name$\"\n");

  printer->Print("            requestsWriter:");
  if (method->client_streaming()) {
    printer->Print("requestWriter\n");
  } else {
    printer->Print("[GRXWriter writerWithValue:request]\n");
  }

  printer->Print(vars, "             responseClass:[$response_class$ class]\n");

  printer->Print("        responsesWriteable:[GRXWriteable ");
  if (method->server_streaming()) {
    printer->Print("writeableWithEventHandler:eventHandler]];\n");
  } else {
    printer->Print("writeableWithSingleHandler:handler]];\n");
  }

  printer->Print("}\n");
}

void PrintV2Implementation(Printer* printer, const MethodDescriptor* method,
                           map< ::std::string, ::std::string> vars) {
  printer->Print(" {\n");
  if (method->client_streaming()) {
    printer->Print(vars, "  return [self RPCToMethod:@\"$method_name$\"\n");
    printer->Print("           responseHandler:handler\n");
    printer->Print("               callOptions:callOptions\n");
    printer->Print(
        vars, "             responseClass:[$response_class$ class]];\n}\n\n");
  } else {
    printer->Print(vars, "  return [self RPCToMethod:@\"$method_name$\"\n");
    printer->Print("                   message:message\n");
    printer->Print("           responseHandler:handler\n");
    printer->Print("               callOptions:callOptions\n");
    printer->Print(
        vars, "             responseClass:[$response_class$ class]];\n}\n\n");
  }
}

void PrintMethodImplementations(Printer* printer,
                                const MethodDescriptor* method,
                                const Parameters& generator_params) {
  if (!ShouldIncludeMethod(method)) return;

  map< ::std::string, ::std::string> vars = GetMethodVars(method);

  PrintProtoRpcDeclarationAsPragma(printer, method, vars);

  if (!generator_params.no_v1_compatibility) {
    // TODO(jcanizales): Print documentation from the method.
    PrintSimpleSignature(printer, method, vars);
    PrintSimpleImplementation(printer, method, vars);

    printer->Print("// Returns a not-yet-started RPC object.\n");
    PrintAdvancedSignature(printer, method, vars);
    PrintAdvancedImplementation(printer, method, vars);
  }

  PrintV2Signature(printer, method, vars);
  PrintV2Implementation(printer, method, vars);
}

}  // namespace

::std::string GetAllMessageClasses(const FileDescriptor* file) {
  ::std::string output;
  set< ::std::string> classes;
  for (int i = 0; i < file->service_count(); i++) {
    const auto service = file->service(i);
    for (int i = 0; i < service->method_count(); i++) {
      const auto method = service->method(i);
      if (ShouldIncludeMethod(method)) {
        classes.insert(ClassName(method->input_type()));
        classes.insert(ClassName(method->output_type()));
      }
    }
  }
  for (auto one_class : classes) {
    output += "@class " + one_class + ";\n";
  }

  return output;
}

::std::string GetProtocol(const ServiceDescriptor* service,
                          const Parameters& generator_params) {
  ::std::string output;

  if (generator_params.no_v1_compatibility) return output;

  // Scope the output stream so it closes and finalizes output to the string.
  grpc::protobuf::io::StringOutputStream output_stream(&output);
  Printer printer(&output_stream, '$');

  map< ::std::string, ::std::string> vars = {
      {"service_class", ServiceClassName(service)}};

  printer.Print(vars,
                "/**\n"
                " * The methods in this protocol belong to a set of old APIs "
                "that have been deprecated. They do not\n"
                " * recognize call options provided in the initializer. Using "
                "the v2 protocol is recommended.\n"
                " */\n");
  printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
  for (int i = 0; i < service->method_count(); i++) {
    PrintMethodDeclarations(&printer, service->method(i));
  }
  printer.Print("@end\n\n");

  return output;
}

::std::string GetV2Protocol(const ServiceDescriptor* service) {
  ::std::string output;

  // Scope the output stream so it closes and finalizes output to the string.
  grpc::protobuf::io::StringOutputStream output_stream(&output);
  Printer printer(&output_stream, '$');

  map< ::std::string, ::std::string> vars = {
      {"service_class", ServiceClassName(service) + "2"}};

  printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
  for (int i = 0; i < service->method_count(); i++) {
    PrintV2MethodDeclarations(&printer, service->method(i));
  }
  printer.Print("@end\n\n");

  return output;
}

::std::string GetInterface(const ServiceDescriptor* service,
                           const Parameters& generator_params) {
  ::std::string output;

  // Scope the output stream so it closes and finalizes output to the string.
  grpc::protobuf::io::StringOutputStream output_stream(&output);
  Printer printer(&output_stream, '$');

  map< ::std::string, ::std::string> vars = {
      {"service_class", ServiceClassName(service)}};

  printer.Print(vars,
                "/**\n"
                " * Basic service implementation, over gRPC, that only does\n"
                " * marshalling and parsing.\n"
                " */\n");
  printer.Print(vars,
                "@interface $service_class$ :"
                " GRPCProtoService<$service_class$2");
  if (!generator_params.no_v1_compatibility) {
    printer.Print(vars, ", $service_class$");
  }
  printer.Print(">\n");
  printer.Print(
      "- (instancetype)initWithHost:(NSString *)host "
      "callOptions:(GRPCCallOptions "
      "*_Nullable)callOptions"
      " NS_DESIGNATED_INITIALIZER;\n");
  printer.Print(
      "+ (instancetype)serviceWithHost:(NSString *)host "
      "callOptions:(GRPCCallOptions *_Nullable)callOptions;\n");
  if (!generator_params.no_v1_compatibility) {
    printer.Print(
        "// The following methods belong to a set of old APIs that have been "
        "deprecated.\n");
    printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
    printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
  }
  printer.Print("@end\n");

  return output;
}

::std::string GetSource(const ServiceDescriptor* service,
                        const Parameters& generator_params) {
  ::std::string output;
  {
    // Scope the output stream so it closes and finalizes output to the string.
    grpc::protobuf::io::StringOutputStream output_stream(&output);
    Printer printer(&output_stream, '$');

    map< ::std::string, ::std::string> vars = {
        {"service_name", service->name()},
        {"service_class", ServiceClassName(service)},
        {"package", service->file()->package()}};

    printer.Print(vars,
                  "@implementation $service_class$\n\n"
                  "#pragma clang diagnostic push\n"
                  "#pragma clang diagnostic ignored "
                  "\"-Wobjc-designated-initializers\"\n\n"
                  "// Designated initializer\n"
                  "- (instancetype)initWithHost:(NSString *)host "
                  "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
                  "  return [super initWithHost:host\n"
                  "                 packageName:@\"$package$\"\n"
                  "                 serviceName:@\"$service_name$\"\n"
                  "                 callOptions:callOptions];\n"
                  "}\n\n");
    if (!generator_params.no_v1_compatibility) {
      printer.Print(vars,
                    "- (instancetype)initWithHost:(NSString *)host {\n"
                    "  return [super initWithHost:host\n"
                    "                 packageName:@\"$package$\"\n"
                    "                 serviceName:@\"$service_name$\"];\n"
                    "}\n\n");
    }
    printer.Print("#pragma clang diagnostic pop\n\n");

    if (!generator_params.no_v1_compatibility) {
      printer.Print(
          "// Override superclass initializer to disallow different"
          " package and service names.\n"
          "- (instancetype)initWithHost:(NSString *)host\n"
          "                 packageName:(NSString *)packageName\n"
          "                 serviceName:(NSString *)serviceName {\n"
          "  return [self initWithHost:host];\n"
          "}\n\n");
    }
    printer.Print(
        "- (instancetype)initWithHost:(NSString *)host\n"
        "                 packageName:(NSString *)packageName\n"
        "                 serviceName:(NSString *)serviceName\n"
        "                 callOptions:(GRPCCallOptions *)callOptions {\n"
        "  return [self initWithHost:host callOptions:callOptions];\n"
        "}\n\n");

    printer.Print("#pragma mark - Class Methods\n\n");
    if (!generator_params.no_v1_compatibility) {
      printer.Print(
          "+ (instancetype)serviceWithHost:(NSString *)host {\n"
          "  return [[self alloc] initWithHost:host];\n"
          "}\n\n");
    }
    printer.Print(
        "+ (instancetype)serviceWithHost:(NSString *)host "
        "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
        "  return [[self alloc] initWithHost:host callOptions:callOptions];\n"
        "}\n\n");

    printer.Print("#pragma mark - Method Implementations\n\n");

    for (int i = 0; i < service->method_count(); i++) {
      PrintMethodImplementations(&printer, service->method(i),
                                 generator_params);
    }

    printer.Print("@end\n");
  }
  return output;
}

}  // namespace grpc_objective_c_generator


text:
/**
 * ReportDefinitionServiceInterface.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201502.cm;

public interface ReportDefinitionServiceInterface extends java.rmi.Remote {

    /**
     * Returns the available report fields for a given report type.
     *
     *
     * @param reportType The type of report.
     *
     * @return The list of available report fields. Each
     *         {@link ReportDefinitionField} encapsulates the field name,
     * the
     *         field data type, and the enum values (if the field's type
     * is
     *         {@code enum}).
     *
     * @throws ApiException if a problem occurred while fetching the
     *         ReportDefinitionField information.
     */
    public com.google.api.ads.adwords.axis.v201502.cm.ReportDefinitionField[] getReportFields(com.google.api.ads.adwords.axis.v201502.cm.ReportDefinitionReportType reportType) throws java.rmi.RemoteException, com.google.api.ads.adwords.axis.v201502.cm.ApiException;
}


text:
// 04. Write a program, that reads from the console an array of N integers and an integer K, sorts the array
//     and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.

using System;
using System.Collections.Generic;
using System.Linq;

class UsingBinSearchToFindLargestElement
{
    //String.Join(", ", array)
    static int partitionSizeForQuickSort = 3;

    static void Main(string[] args)
    {
        //First sort the array with Quicksort algorithm. After the current partition size get smaller than "partitionSizeForQuickSort"
        //Sort the array with Insertionsort algorithm.
        //We can directly use "Array.Sort()", but after all, we have to practice

        int givenN;
        int givenK;
        int[] givenArray;
        int indexFromBinarySearch;

        //Validate input data, using method "ValidateSequenceLengthInteger(string textToDisplay)"
        givenN = ValidateSequenceLengthInteger("Please enter number N: ");

        //Validate input data, using method "ValidateInputInteger(string textToDisplay)"
        givenK = ValidateInputInteger("Please enter number K: ");

        givenArray = new int[givenN]; //Set the array length to "givenN"

        //Assign values to the array, using "ValidateInputIntegerArray(int arrayLengrh)"
        givenArray = ValidateInputIntegerArray(givenN);

        Console.WriteLine(new string('=', 50));

        //Sort the array using Quicksort algorithm, with method "QuickSortArray(int[] arrayToSort, int leftIndex, int rightIndex)"
        QuickSortArray(givenArray, 0, (givenArray.Length - 1));

        //Print the sorted array, using method "PrintArray(int[] arrayToPrint, string textToDisplay)"
        PrintArray(givenArray, "Sorted array, after using \"Quicksort\" algorithm");

        Console.WriteLine(new string('=', 50));

        //Sort the array using Insertionsort algorithm, with method "InsertionSortArray(int[] arrayToSort)"
        InsertionSortArray(givenArray);

        //Print the sorted array, using method "PrintArray(int[] arrayToPrint, string textToDisplay)"
        PrintArray(givenArray, "Sorted array, after using \"Insertionsort\" algorithm");

        Console.WriteLine(new string('=', 50));

        //Using "Array.BinarySearch()" to find the wanted number "givenK"
        indexFromBinarySearch = Array.BinarySearch(givenArray, givenK);

        //"Array.BinarySearch()" returns negative integer if the number is Not found. That negative integer is the index where is supposed to be the wanted number, plus 1
        if (indexFromBinarySearch < 0)
        {
            //Make the negative returned integer to positive.
            indexFromBinarySearch *= -1;

            //Check if that integer, after we make it positive, is less than 2, if so the supposed index of the wanted number is 0, This means that there is no lower number in the array!
            if (indexFromBinarySearch < 2)
            {
                Console.WriteLine("There is neither {0}, nor lower number!", givenK);
            }
            else //If the integer is 2 or greather, we subtract 2 to find the index of the number that is closest to wanted number and less than it.
            {
                indexFromBinarySearch -= 2;
                Console.WriteLine("Lower number closest to {0} is: number {1} on index: {2}", givenK, givenArray[indexFromBinarySearch], indexFromBinarySearch);
            }
        }
        else //If number is found "Array.BinarySearch()" returns integer 0 or greather, and we print it
        {
            Console.WriteLine("Number {0} is on index: {1}", givenK, indexFromBinarySearch);
        }
    }

    //Method to sort the different parts of the array, using Quicksort algorithm
    static int Partition(int[] arrayToSort, int leftIndex, int rightIndex, int pivotIndex)
    {
        int pivotValue = arrayToSort[pivotIndex];
        int storeIndex = leftIndex;
        int buffer;

        // Swap the values of the pivot index and right(last) index
        arrayToSort[pivotIndex] ^= arrayToSort[rightIndex];
        arrayToSort[rightIndex] ^= arrayToSort[pivotIndex];
        arrayToSort[pivotIndex] ^= arrayToSort[rightIndex];

        for (int i = leftIndex; i < rightIndex; i++) //Iterate through the array to sort the lower numbers to the left and greather remain to the right
        {
            if (arrayToSort[i] <= pivotValue)
            {
                //Swap the values of the current index and the stored index
                buffer = arrayToSort[i];
                arrayToSort[i] = arrayToSort[storeIndex];
                arrayToSort[storeIndex] = buffer;

                storeIndex++;
            }
        }

        // Swap the values of the stored index index and right(last) index, where is the pivot value
        buffer = arrayToSort[storeIndex];
        arrayToSort[storeIndex] = arrayToSort[rightIndex];
        arrayToSort[rightIndex] = buffer;

        return storeIndex;
    }

    //Method to set the bounds of the different parts of the array to be sorted
    static void QuickSortArray(int[] arrayToSort, int leftIndex, int rightIndex)
    {
        if (partitionSizeForQuickSort < (rightIndex - leftIndex)) //Quicksort is used while the current partition is larger than "partitionSizeForQuickSort", when it get smaller, insertion sort is used
        {
            int pivotNewIndex;
            int pivotIndex = leftIndex + ((rightIndex - leftIndex) / 2); //Set the position of the pivot

            pivotNewIndex = Partition(arrayToSort, leftIndex, rightIndex, pivotIndex);

            QuickSortArray(arrayToSort, leftIndex, pivotNewIndex - 1); // Recursively call "QuickSortArray" for the left part of the current partition.
            QuickSortArray(arrayToSort, pivotNewIndex + 1, rightIndex); //We exclude the previous pivot index, because it is already on its place
        }
    }

    static void InsertionSortArray(int[] arrayToSort) //Insertion sort algorithm is used after Quicksort sort the array for partition with size larger than "partitionSizeForQuickSort"
    {
        for (int i = 1; i < arrayToSort.Length; i++)
        {
            for (int j = i; j > 0; j--)
            {
                //If previous element is lower, swap current and previous element values
                if (arrayToSort[j - 1] > arrayToSort[j])
                {
                    arrayToSort[j - 1] ^= arrayToSort[j];
                    arrayToSort[j] ^= arrayToSort[j - 1];
                    arrayToSort[j - 1] ^= arrayToSort[j];
                }
            }
        }
    }

    static int ValidateSequenceLengthInteger(string textToDisplay) //Method to validate the input data
    {
        int validatedInteger;

        Console.Write(textToDisplay);

        while (true) //If number is invalide or is less than 1, the input will no be accepted
        {
            while (!int.TryParse(Console.ReadLine(), out validatedInteger))
            {
                Console.WriteLine("Please enter a correct integer number!");
            }

            if (validatedInteger > 0) //Array index can Not be negative! Also there is no point to set 0
            {
                break;
            }
            else
            {
                Console.WriteLine("Please enter positive integer, greather than 0!");
            }
        }

        return validatedInteger;
    }

    static int ValidateInputInteger(string textToDisplay) //Method to validate the input integer
    {
        int validatedInteger;

        Console.Write(textToDisplay);

        while (!int.TryParse(Console.ReadLine(), out validatedInteger))
        {
            Console.WriteLine("Please enter a correct integer number!");
        }

        return validatedInteger;
    }

    static int[] ValidateInputIntegerArray(int arrayLengrh) //Method to validate the input integer array
    {
        int[] arrayValidatedArray = new int[arrayLengrh];

        for (int i = 0; i < arrayValidatedArray.Length; i++)
        {
            Console.Write("Please enter array element {0}: ", i);
            arrayValidatedArray[i] = ValidateInputInteger(""); //Using another method - "ValidateInputInteger(string textToDisplay)"
        }

        return arrayValidatedArray;
    }

    static void PrintArray(int[] arrayToPrint, string textToDisplay) //Print given array
    {
        Console.WriteLine(textToDisplay);

        Console.Write('{');
        Console.Write(String.Join(", ", arrayToPrint));
        Console.WriteLine('}');
    }
}


text:
package com.microsoft.azure.spring.integration.eventhub;

import com.azure.messaging.eventhubs.EventData;
import com.azure.messaging.eventhubs.EventDataBatch;
import com.azure.messaging.eventhubs.EventHubProducerAsyncClient;
import com.azure.messaging.eventhubs.models.CreateBatchOptions;
import com.microsoft.azure.spring.integration.eventhub.api.EventHubClientFactory;
import com.microsoft.azure.spring.integration.eventhub.api.EventHubOperation;
import com.microsoft.azure.spring.integration.eventhub.impl.EventHubRuntimeException;
import com.microsoft.azure.spring.integration.eventhub.impl.EventHubTemplate;
import com.microsoft.azure.spring.integration.test.support.reactor.SendOperationTest;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import reactor.core.publisher.Mono;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class EventHubTemplateSendTest extends SendOperationTest<EventHubOperation> {

    @Mock
    EventDataBatch eventDataBatch;
    @Mock
    private EventHubClientFactory mockClientFactory;
    @Mock
    private EventHubProducerAsyncClient mockProducerClient;

    @Before
    public void setUp() {
        when(this.mockClientFactory.getOrCreateProducerClient(eq(this.destination)))
            .thenReturn(this.mockProducerClient);
        when(this.mockProducerClient.createBatch(any(CreateBatchOptions.class)))
            .thenReturn(Mono.just(this.eventDataBatch));
        when(this.mockProducerClient.send(any(EventDataBatch.class))).thenReturn(this.mono);
        when(this.eventDataBatch.tryAdd(any(EventData.class))).thenReturn(true);

        this.sendOperation = new EventHubTemplate(mockClientFactory);
    }

    @Override
    protected void verifySendCalled(int times) {
        verify(this.mockProducerClient, times(times)).send(any(EventDataBatch.class));
    }

    @Override
    protected void whenSendWithException() {
        when(this.mockClientFactory.getOrCreateProducerClient(this.destination))
            .thenThrow(EventHubRuntimeException.class);
    }

    @Override
    protected void verifyGetClientCreator(int times) {
        verify(this.mockClientFactory, times(times)).getOrCreateProducerClient(this.destination);
    }

    @Override
    protected void setupError(String errorMessage) {
        when(this.mockProducerClient.send(any(EventDataBatch.class)))
            .thenReturn(Mono.error(new IllegalArgumentException("Send failed.")));
    }
}


text:
import time
import sys
import zookeeper
import threading
from optparse import OptionParser

parser = OptionParser(usage="usage: %prog [options]")
parser.add_option("", "--server", dest="server", default="localhost:2181",
                  help="zookeeper server (default %default)")
parser.add_option("", "--root_znode", dest="root_znode",
                  default="/zk-benchmark-zkpy",
                  help="root znode for the evaluation")
parser.add_option("", "--znode_data_size", dest="znode_data_size",
                  type="int", default=20,
                  help="data size for each znode (default %default)")
parser.add_option("", "--count", dest="count",
                  type="int", default=10000,
                  help="the number of znodes in each test run")
parser.add_option("", "--sync",
                  action="store_false", dest="async", default=True,
                  help="using synchronous api")
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="verbose logging")
parser.add_option("-q", "--quiet",
                  action="store_true", dest="quiet", default=False,
                  help="quiet output, basically just success/failure")
(options, args) = parser.parse_args()

acl = [{"perms": 0x1f, "scheme": "world", "id": "anyone"}]

class Operation():
    create = "create"
    get = "get"
    set = "set"
    delete = "delete"
    NOT_SUPPORT_MSG = "NOT SUPPORTED"

class Callback(object):

    def __init__(self):
        self.cv = threading.Condition()
        self.callback_flag = False
        self.rc = -1
        self.cv.acquire()

    def callback(self, rc):
        self.cv.acquire()
        self.callback_flag = True
        self.rc = rc
        self.cv.notify()
        self.cv.release()

    def wait(self):
        while not self.callback_flag:
            self.cv.wait()
        self.cv.release()

        if self.callback_flag is not True:
            sys.stderr.write("callback timeout")
        if not self.rc == zookeeper.OK:
            sys.stderr.write("async call failed with error code %d" % self.rc)

class GetCallback(Callback):

    def __call__(self, handle, rc, value, stat):
        self.callback(rc)

class SetCallback(Callback):

    def __call__(self, handle, rc, stat):
        self.callback(rc)

class CreateCallback(Callback):

    def __call__(self, handle, rc, path):
        self.callback(rc)

class DeleteCallback(Callback):

    def __call__(self, handle, rc):
        self.callback(rc)

def timed(f):
    def wrapper(*args, **kwargs):
        start = time.time()
        msg = f(*args, **kwargs)
        elapsed = (time.time() - start) * 1000
        if msg.find(Operation.NOT_SUPPORT_MSG) != -1:
            print "%s" % msg
        else:
            print "%s took %8d ms (%5d/sec)" % \
                  (msg, int(elapsed), kwargs["count"] / (elapsed / 1000))
    return wrapper

def child_path(root, i):
    return "%s/session_%d" % (root, i)

@timed
def do_operation(op, s, root, async, count, ephemeral=True, data=None):
    async_results = []
    for i in range(count):
        path = child_path(root, i)
        if async:
            if op == Operation.create:
                cb = CreateCallback()
                zookeeper.acreate(s, path, data, acl,
                                  zookeeper.EPHEMERAL if ephemeral else 0, cb)
            elif op == Operation.get:
                cb = GetCallback()
                zookeeper.aget(s, path, None, cb)
            elif op == Operation.set:
                cb = SetCallback()
                zookeeper.aset(s, path, data, -1, cb)
            elif op == Operation.delete:
                cb = DeleteCallback()
                zookeeper.adelete(s, path, -1, cb)
            async_results.append(cb)
        else:
            if op == Operation.create:
                zookeeper.create(s, path, data, acl,
                                 zookeeper.EPHEMERAL if ephemeral else 0)
            elif op == Operation.get:
                zookeeper.get(s, path)
            elif op == Operation.set:
                zookeeper.set(s, path, data)
            elif op == Operation.delete:
                zookeeper.delete(s, path)

    for cb in async_results:
        cb.wait()

    # only print node type for creation operation
    node_type = ""
    if op == Operation.create:
        node_type = "ephemeral" if ephemeral else "permanent"

    return "%5s %6s %8d %10s znodes " % \
           ("async" if async else "sync", op, count, node_type)

def evaluation(s, root, data, options):
    # create znodes (permanent)
    do_operation(Operation.create, s, root, options.async,
                 count=options.count, ephemeral=False, data=data)

    # set znodes
    do_operation(Operation.set, s, root, options.async,
                 count=options.count, data=data)

    # get znodes
    do_operation(Operation.get, s, root, options.async, count=options.count)

    # delete znodes
    do_operation(Operation.delete, s, root, options.async, count=options.count)

    # create znodes (ephemeral)
    do_operation(Operation.create, s, root, options.async,
                 count=options.count, data=data)

    # set znodes
    do_operation(Operation.set, s, root, options.async,
                 count=options.count, data=data)

    # get znodes
    do_operation(Operation.get, s, root, options.async, count=options.count)

    # delete znodes
    do_operation(Operation.delete, s, root, options.async, count=options.count)

def main():
    data = options.znode_data_size * "D"

    zookeeper.set_debug_level(zookeeper.LOG_LEVEL_WARN)
    s = zookeeper.init(options.server)

    if zookeeper.exists(s, options.root_znode, None):
        children = zookeeper.get_children(s, options.root_znode, None)
        print "delete old entries: %d" % len(children)
        for child in children:
            zookeeper.delete(s, "%s/%s" % (options.root_znode, child))
    else:
        zookeeper.create(s, options.root_znode, "zkpy root znode", acl, 0)

    evaluation(s, options.root_znode, data, options)

    zookeeper.close(s)

    print("Performance test complete")

if __name__ == "__main__":
    sys.exit(main())


text:
package br.recomende.infra.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(SpringScope.PROTOTYPE)
public class DateConversionHelper {

	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public String toXML(Date date) {
		return simpleDateFormat.format(date);
	}

}


text:
#ifndef GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H
#define GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H

#include <grpc++/security/auth_context.h>

struct grpc_auth_context;

namespace grpc {

class SecureAuthContext final : public AuthContext {
 public:
  SecureAuthContext(grpc_auth_context* ctx, bool take_ownership);

  ~SecureAuthContext() override;

  bool IsPeerAuthenticated() const override;

  std::vector<grpc::string_ref> GetPeerIdentity() const override;

  grpc::string GetPeerIdentityPropertyName() const override;

  std::vector<grpc::string_ref> FindPropertyValues(
      const grpc::string& name) const override;

  AuthPropertyIterator begin() const override;

  AuthPropertyIterator end() const override;

  void AddProperty(const grpc::string& key,
                   const grpc::string_ref& value) override;

  virtual bool SetPeerIdentityPropertyName(const grpc::string& name) override;

 private:
  grpc_auth_context* ctx_;
  bool take_ownership_;
};

}  // namespace grpc

#endif  // GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright 2013 - 2014 Jerome Leleu

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

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

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>7</version>
    </parent>

    <groupId>org.pac4j</groupId>
    <artifactId>gae-pac4j</artifactId>
    <packaging>jar</packaging>
    <name>GAE pac4j</name>
    <version>1.0.3-SNAPSHOT</version>
    <description>GAE multi protocols (CAS, OAuth, OpenID, HTTP...) client</description>
    <url>https://github.com/pac4j/gae-pac4j</url>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <url>https://github.com/pac4j/gae-pac4j.git</url>
        <connection>scm:git:git@github.com:pac4j/gae-pac4j.git</connection>
        <developerConnection>scm:git:git@github.com:pac4j/gae-pac4j.git</developerConnection>
    </scm>

    <developers>
        <developer>
            <id>patou</id>
            <name>Patrice de Saint Steban</name>
            <email>patrice@desaintsteban.fr</email>
        </developer>
    </developers>

    <properties>
		<gae.version>1.9.0</gae.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.pac4j</groupId>
            <artifactId>pac4j-core</artifactId>
            <version>1.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-api-1.0-sdk</artifactId>
            <version>${gae.version}</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jsr107cache</groupId>
            <artifactId>jsr107cache</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-jsr107cache</artifactId>
            <version>${gae.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.8.1</version>
                <configuration>
                    <charset>UTF-8</charset>
                    <encoding>UTF-8</encoding>
                    <docencoding>UTF-8</docencoding>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.1</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
=pod

=head1 NAME

DirectedGraph - module for creating and manipulating directed graphs

=head1 SYNOPSIS

Use HPI::Graph::DirectedGraph;
my $graph = HPI::Graph::DirectedGraph("prop1"=>val1, "prop2"=>val2, ...);

=head1 DESCRIPTION

=head2 Description

A module for creating and manipuating directed graphs and hypergraphs. This
module uses HPI::Graph::Graph as its base. Directedness-independent methods can
be found in HPI::Graph::Graph.

As with all modules that inherit from HPI::Graph::Element, you can add prop=val
pairs, or string tags, or both. (prop=val pairs can be passed as arguments to
the constructor, or set using the setprop method. tags must be added after
instantiation. see HPI::Graph::Element for more info.)

=head2 Routines

=item empty

Clears all data from this graph, except the id. That includes the links to
any children of this graph. (if a child is linked somewhere else, though, it
is not destroyed - only the parent-child relationship to this graph object.)
Overrides the routine in the base class in order to reset data specific to
directed graphs (e.g., MAXINDEGREE, MAXOUTDEGREE, etc.).

=item directed

Returns 1 to indicate this graph is directed.

=item is_tree

Returns 1 if this graph can be considered a polytree: a directed acyclic graph
in which there are no undirected cycles as well. Otherwise, returns 0.

=item is_dag

Returns 1 if this graph is a directed acyclic graph with a single connected
component. Otherwise, returns 0.

=item deg($id)

Returns the degree of the node with the given $id (k, or how may edges are
incident on the node).

=item outdeg($sid)

Returns the number of edges that originate from a given node $sid. Note: this
is equivalent to the simple degree of a node in an undirected graph. This
method runs in constant time; it simply finds the length of the adjacency
list for the given node $sid.

=item indeg

Returns the number of edges incident upon a given node $sid; in other words,
directed edges that end in $sid.

=item sources

Returns an array of source node ids for this graph. Source nodes have no
incoming edges (indegree = 0). This method runs in O(m+n) time. It first
queries all edges in the graph for their target node, counting the number of
times each node acts as a target. Then it queries all nodes for those that are
never targets.

=item sinks

Returns an array of sink node ids for this graph. Sink nodes have no exiting
edges (outdegree = 0). This method runs in O(n) time. It simply examines the
length of the adjacency list for each node in the graph, and returns the nodes
that have empty adjacency lists.

=head1 AUTHOR AND COPYRIGHT

Timothy Driscoll <driscoll451@gmail.com>

=head1 LICENSE

This module is licensed under the same terms as Perl itself.

=cut


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

using mtinfo;
using mtsuite.shared.CommandLine;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using tests.FileSystemHelpers;
using mtsuite.CoreFileSystem;

namespace tests {
  [TestClass]
  public class MtInfoTest {
    private FileSystemSetup _fileSystemSetup;

    [TestInitialize]
    public void Setup() {
      _fileSystemSetup = new FileSystemSetup();
    }

    [TestCleanup]
    public void Cleanup() {
      _fileSystemSetup.Dispose();
      _fileSystemSetup = null;
    }

    [TestMethod]
    [ExpectedException(typeof(CommandLineReturnValueException))]
    public void MtInfoShouldThrowWithNonExistingFolder() {
      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);
      mtinfo.DoCollect(_fileSystemSetup.Root.Path.Combine("fake"), new MtInfo.CollectOptions { LevelCount = 3});
    }

    [TestMethod]
    public void MtInfoShouldWorkWithEmptyFolder() {
      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);
      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3}).Summary;
      Assert.AreEqual(0, summary.Stats.DirectoryCount);
      Assert.AreEqual(0, summary.Stats.FileCount);
      Assert.AreEqual(0, summary.Stats.FileBytesTotal);
    }

    [TestMethod]
    public void MtInfoShouldWorkWithFiles() {
      _fileSystemSetup.Root.CreateFile("a", 10);
      _fileSystemSetup.Root.CreateFile("b", 11);
      _fileSystemSetup.Root.CreateFile("c", 12);
      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);

      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3 }).Summary;
      Assert.AreEqual(0, summary.Stats.DirectoryCount);
      Assert.AreEqual(3, summary.Stats.FileCount);
      Assert.AreEqual(33, summary.Stats.FileBytesTotal);
    }

    [TestMethod]
    public void MtInfoShouldWorkWithDirectories() {
      var dir1 = _fileSystemSetup.Root.CreateDirectory("a");
      dir1.CreateFile("a", 10);
      dir1.CreateFile("b", 11);
      dir1.CreateFile("c", 12);
      var dir2 = _fileSystemSetup.Root.CreateDirectory("b");
      dir2.CreateFile("b", 11);
      dir2.CreateFile("c", 12);
      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);

      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3 }).Summary;
      Assert.AreEqual(2, summary.Stats.DirectoryCount);
      Assert.AreEqual(5, summary.Stats.FileCount);
      Assert.AreEqual(56, summary.Stats.FileBytesTotal);
    }

    [TestMethod]
    public void MtInfoShouldWorkWithNestedDirectories() {
      _fileSystemSetup.Root.CreateDirectory("a").CreateDirectory("b").CreateDirectory("c").CreateDirectory("d");
      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);

      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3 }).Summary;
      Assert.AreEqual(4, summary.Stats.DirectoryCount);
      Assert.AreEqual(0, summary.Stats.FileCount);
      Assert.AreEqual(0, summary.Stats.FileBytesTotal);
    }

    [TestMethod]
    public void MtInfoShouldWorkWithLinks() {
      if (!_fileSystemSetup.SupportsSymbolicLinkCreation()) {
        Assert.Inconclusive("Symbolic links are not supported. Try running test (or Visual Studio) as Administrator.");
      }
      var dir = _fileSystemSetup.Root.CreateDirectory("a");
      dir.CreateFile("a", 10);
      dir.CreateFileLink("b", "a");

      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);

      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3 }).Summary;
      Assert.AreEqual(1, summary.Stats.DirectoryCount);
      Assert.AreEqual(1, summary.Stats.FileCount);
      Assert.AreEqual(1, summary.Stats.SymlinkCount);
      Assert.AreEqual(10, summary.Stats.FileBytesTotal);
    }

    [TestMethod]
    public void MtInfoShouldWorkWithJunctionPoints() {
      // [root]
      //   [file] topdir-file.txt
      //   [dir ] subdir
      //     [file] subdir-file.txt
      //   [jpt]  j1 <==> subdir
      //   [jpt]  j2 <==> subdir
      //   [jpt]  j3 <==> subdir
      var root = _fileSystemSetup.Root;
      root.CreateFile("topdir-file.txt", 10);
      var subdir = root.CreateDirectory("subdir");
      subdir.CreateFile("subdir-file.txt", 20);
      var j1 = root.CreateJunctionPoint("j1", "subdir");
      var j2 = root.CreateJunctionPoint("j2", ".\\subdir");
      var j3 = root.CreateJunctionPoint("j3", root.Path.Combine("subdir").FullName);

      var mtinfo = new MtInfo(_fileSystemSetup.FileSystem);

      var summary = mtinfo.DoCollect(_fileSystemSetup.Root.Path, new MtInfo.CollectOptions { LevelCount = 3 }).Summary;
      Assert.AreEqual(1, summary.Stats.DirectoryCount);
      Assert.AreEqual(2, summary.Stats.FileCount);
      Assert.AreEqual(3, summary.Stats.SymlinkCount);
      Assert.AreEqual(30, summary.Stats.FileBytesTotal);

      // TODO: Move this to a test class related to FileSystem tests.
      var j1Info = _fileSystemSetup.FileSystem.GetReparsePointInfo(j1.Path);
      Assert.AreEqual(true, j1Info.IsJunctionPoint);
      Assert.AreEqual(false, j1Info.IsTargetRelative);
      Assert.AreEqual(subdir.Path.FullName, j1Info.Target);

      var j2Info = _fileSystemSetup.FileSystem.GetReparsePointInfo(j2.Path);
      Assert.AreEqual(true, j2Info.IsJunctionPoint);
      Assert.AreEqual(false, j2Info.IsTargetRelative);
      Assert.AreEqual(subdir.Path.FullName, j2Info.Target);
    }
  }
}


text:
module A {}
#pragma clang module contents
#pragma clang module begin A
template<typename T> struct ct { friend auto operator-(ct, ct) { struct X {}; return X(); } void x(); };
#pragma clang module end
#pragma clang module endbuild

#pragma clang module build B
module B {}
#pragma clang module contents
#pragma clang module begin B
template<typename T> struct ct { friend auto operator-(ct, ct) { struct X{}; return X(); } void x(); };
inline auto f() { return ct<float>() - ct<float>(); }
#pragma clang module end
#pragma clang module endbuild

// Force the definition of ct in module A to be the primary definition.
#pragma clang module import A
template<typename T> void ct<T>::x() {}

// Attempt to cause the definition of operator- in the ct primary template in
// module B to be the primary definition of that function. If that happens,
// we'll be left with a class template ct that appears to not contain a
// definition of the inline friend function.
#pragma clang module import B
auto v = f();

ct<int> make();
void h() {
  make() - make();
}


text:
Simple angular.js app using custom php mvc 'framework'

This was project was made for school purposes. It contains a simple facebook/twitter clone. Powered by angular.js and custom php 'framework'.


text:
Alto Guisso allows connecting your application with Guisso (Instedd's Single Sign On).

It allows OAuth and Basic authentication with Guisso credentials.

## Installation

Add this line to your application's Gemfile:

    gem 'alto_guisso', github: "instedd/alto_guisso", branch: 'master'

And this ones if you are missing any of them:

* ruby-openid
* rack-oauth2
* omniauth
* omniauth-openid

And then execute:

    $ bundle

## Usage

You can get a rest client with:

    Guisso.trusted_resource(url, user_email).get(path)
    Guisso.trusted_resource(url, user_email).post(path, body)  {|response, request, result| response }

And get a bearer token with:

    Guisso.generate_bearer_token(user_email)

## Config File

Alto Guisso expects a config file named `guisso.yml` on Rails config path, but it can be initialized with an optional hash:

    Guisso.setup! "enabled" => true, "url" => "www.example.com", "client_id" => "...", "client_secret" => "..."


text:
<?php
namespace MonologModuleTest\Handler\Factory;

use Laminas\ServiceManager\ServiceLocatorInterface;
use MonologModule\Exception\RuntimeException;
use MonologModule\Handler\Factory\GelfHandlerFactory;
use Monolog\Handler\GelfHandler;
use PHPUnit\Framework\TestCase;

class GelfHandlerFactoryTest extends TestCase
{
    public function testInstantiateGelfHandler()
    {
        $serviceLocator = $this->createMock(ServiceLocatorInterface::class);

        $gelfHandlerFactory = new GelfHandlerFactory();
        $gelfHandler = ($gelfHandlerFactory)($serviceLocator, GelfHandler::class, [
            'host' => 'domain.com',
            'port' => 123,
        ]);

        $this->assertInstanceOf(GelfHandler::class, $gelfHandler);
    }

    public function testInstantiateGelfHandlerWithoutHost()
    {
        $this->expectException(RuntimeException::class);

        $serviceLocator = $this->createMock(ServiceLocatorInterface::class);

        $gelfHandlerFactory = new GelfHandlerFactory();
        ($gelfHandlerFactory)($serviceLocator, GelfHandler::class, ['port' => 123]);
    }

    public function testInstantiateGelfHandlerWithoutPort()
    {
        $this->expectException(RuntimeException::class);

        $serviceLocator = $this->createMock(ServiceLocatorInterface::class);

        $gelfHandlerFactory = new GelfHandlerFactory();
        ($gelfHandlerFactory)($serviceLocator, GelfHandler::class, ['host' => 'domain.com']);
    }
}


text:
"""Tests for image transformation functionalities."""

from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from tensorflow_addons import image as tfa_image

from tensorflow_graphics.image import transformer
from tensorflow_graphics.util import test_case

class TransformerTest(test_case.TestCase, parameterized.TestCase):

  @parameterized.parameters(
      ((None, 1, 2, None), (None, 3, 3)),
      ((1, 2, 3, 4), (1, 3, 3)),
  )
  def test_perspective_transform_exception_not_raised(self, *shape):
    """Tests that the shape exceptions are not raised."""

    self.assert_exception_is_not_raised(transformer.perspective_transform,
                                        shape)

  @parameterized.parameters(
      ("must have a rank of 4.", (1, 1, 1), (1, 3, 3)),
      ("must have a rank of 3.", (1, 1, 1, 1), (3, 3)),
      ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 3, 3)),
  )
  def test_perspective_transform_exception_raised(self, error_msg, *shape):
    """Tests that the shape exceptions are properly raised."""

    self.assert_exception_is_raised(transformer.perspective_transform,
                                    error_msg, shape)

  @parameterized.parameters(
      (tf.float32, "NEAREST"),
      (tf.float64, "NEAREST"),
      (tf.float32, "BILINEAR"),
      (tf.float64, "BILINEAR"),
  )
  def test_perspective_transform_half_integer_centers_preset(
      self, dtype, interpolation):
    """Tests that we can reproduce the results of tf.image.resize."""
    image = tf.constant(
        ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)),
        dtype=dtype)
    scale = 3
    transformation = tf.constant(
        ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)),
        dtype=dtype)

    image_shape = tf.shape(input=image)
    image_resized_shape = image_shape * scale
    image = image[tf.newaxis, ..., tf.newaxis]
    transformation = transformation[tf.newaxis, ...]
    image_resized = tf.image.resize(
        image,
        size=image_resized_shape,
        method=tf.image.ResizeMethod.NEAREST_NEIGHBOR
        if interpolation == "NEAREST" else tf.image.ResizeMethod.BILINEAR)
    image_transformed = transformer.perspective_transform(
        image,
        transformation,
        resampling_type=transformer.ResamplingType.NEAREST
        if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR,
        border_type=transformer.BorderType.DUPLICATE,
        output_shape=image_resized_shape)

    self.assertAllClose(image_resized, image_transformed)

  @parameterized.parameters(
      (tf.float32, "NEAREST"),
      (tf.float64, "NEAREST"),
      (tf.float32, "BILINEAR"),
      (tf.float64, "BILINEAR"),
  )
  def test_perspective_transform_integer_centers_preset(self, dtype,
                                                        interpolation):
    """Tests that we can reproduce the results of tfa_image.transform."""
    image = tf.constant(
        ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)),
        dtype=dtype)
    scale = 3
    transformation = tf.constant(
        ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)),
        dtype=dtype)

    image_shape = tf.shape(input=image)
    image_resized_shape = image_shape * scale
    image = image[tf.newaxis, ..., tf.newaxis]
    transformation = transformation[tf.newaxis, ...]
    image_resized = tfa_image.transform(
        tf.cast(image, tf.float32),
        tf.cast(
            tfa_image.transform_ops.matrices_to_flat_transforms(transformation),
            tf.float32),
        interpolation=interpolation,
        output_shape=image_resized_shape)
    image_transformed = transformer.perspective_transform(
        image,
        transformation,
        resampling_type=transformer.ResamplingType.NEAREST
        if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR,
        pixel_type=transformer.PixelType.INTEGER,
        output_shape=image_resized_shape)

    self.assertAllClose(image_resized, image_transformed)

  def test_perspective_transform_jacobian_random(self):
    """Tests the Jacobian of the transform function."""
    tensor_shape = np.random.randint(2, 4, size=4)
    image_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist())
    transformation_init = np.random.uniform(
        0.0, 1.0, size=(tensor_shape[0], 3, 3))

    self.assert_jacobian_is_correct_fn(
        lambda x: transformer.perspective_transform(x, transformation_init),
        [image_init])
    self.assert_jacobian_is_correct_fn(
        lambda x: transformer.perspective_transform(image_init, x),
        [transformation_init])

  @parameterized.parameters(
      ((None, 1, 2, None), (None, 2)),
      ((1, 3, 2, 4), (1, 2)),
  )
  def test_sample_exception_not_raised(self, *shape):
    """Tests that the shape exceptions are not raised."""

    self.assert_exception_is_not_raised(transformer.sample, shape)

  @parameterized.parameters(
      ("must have a rank of 4.", (1, 1, 1), (1, 2)),
      ("must have a rank greater than 1", (1, 1, 1, 1), (2,)),
      ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 2)),
  )
  def test_sample_exception_raised(self, error_msg, *shape):
    """Tests that the shape exceptions are properly raised."""

    self.assert_exception_is_raised(transformer.sample, error_msg, shape)

if __name__ == "__main__":
  test_case.main()


text:
{-# LANGUAGE OverloadedStrings #-}
module Data.Attoparsec.Text.ParsecSpec (main, spec) where

import           Test.Hspec
import           Test.QuickCheck

import           Prelude hiding (take, takeWhile)
import           Control.Applicative
import qualified Data.Text as Text

import           Data.Attoparsec.Text.Parsec

main :: IO ()
main = hspec spec

{-# ANN spec ("HLint: ignore Redundant do"::String) #-}
spec :: Spec
spec = do

  describe "IsString instance for Parser" $ do
    it "recognizes a given string" $ do
      parseOnly "foo" "foo" `shouldBe` Right "foo"

    it "works without explicit type signature" $ do
      parseOnly ("foo" >> "bar") "foobar" `shouldBe` Right "bar"

  describe "atEnd" $ do
    it "parses an empty string to True" $ do
      parseOnly atEnd "" `shouldBe` Right True

    it "parses an non-empty string to False" $ do
      parseOnly atEnd "foo" `shouldBe` Right False

    it "does not consume any input" $ do
      parseOnly (atEnd *> takeWhile (const True) <* endOfInput) "foo" `shouldBe` Right "foo"

  describe "takeText" $ do
    it "consumes all remaining input" $ do
      parseOnly takeText "foo" `shouldBe` Right "foo"

  describe "takeLazyText" $ do
    it "consumes all remaining input" $ do
      parseOnly takeText "foo" `shouldBe` Right "foo"

  describe "take" $ do
    it "consumes exactly a given number n characters of input" $ do
      parseOnly (take 3) "foobar" `shouldBe` Right "foo"

    it "consumes nothing, if n is negative" $ do
      parseOnly ((,) <$> take (-3) <*> takeText) "foobar" `shouldBe` Right ("", "foobar")

  describe "peekChar" $ do
    it "returns the next found character" $ do
      parseOnly peekChar "foobar" `shouldBe` Right (Just 'f')

    it "does not consume the input" $ do
      parseOnly (peekChar >> takeText) "foobar" `shouldBe` Right "foobar"

    it "returns nothing for null input" $ do
      parseOnly peekChar "" `shouldBe` Right Nothing

  describe "stringCI" $ do
    it "ignores case" $ do
      parseOnly (stringCI "fooBAR") "FOObar" `shouldBe` Right "FOObar"

    it "does proper case folding" $ (const . pendingWith) "ignored" $ do
      parseOnly (stringCI "dass") "da\223" `shouldBe` Right "da\223"

  describe "decimal" $ do
    it "parses 23" $ do
      parseOnly decimal "23" `shouldBe` Right (23 :: Int)

    it "parses any postive decimal number" $ property $
      \(Positive n) -> parseOnly decimal (Text.pack $ show n) == Right (n :: Int)

  describe "hexadecimal" $ do
    it "parses 0xAB" $ do
      parseOnly hexadecimal "aB" `shouldBe` Right (171 :: Int)

  describe "Efficient string handling" $ do

    describe "string" $ do
      it "parses a given string" $ do
        parseOnly (string "foobar") "foobar" `shouldBe` Right "foobar"


text:
Notes for myself so I can remember what I did

## 01 Gaussaian Naive Bayes Deployment on Terrain Data

Can only be run on udacity. I did not take the time to get all the imports working. Best run on udacity

## 02 Calculating Naive Bayes Accuracy

Commented out imports and removed files not needed to allow example to run in command line vs only on udacity. "app.py" can be run directly from python as long as you have all the libraries installed or run the Docker image

## 03 Author ID Accuracy

I cloned https://github.com/udacity/ud120-projects to a completely separate directory structure. I've copied the tools directory from ud120-project here to get each assignment to work. I've excluded uploading maildir/* as that is a waste of space and time.

To get Docker to work, need to mount tools and maildir into Docker image. See https://docs.docker.com/docker-for-mac/osxfs/

* tools is located here ~/Documents/Udacity/ud120 Intro to Machine Learning/tools
* maildir is located here ~/Documents/Udacity/ud120 Intro to Machine Learning/maildir

And the run file in the directory shows how I ran it. This start with assignment 3