text:
package org.egov.service;

import org.egov.entity.AppNumberFormat;
import org.egov.repository.AppNumberFormatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.apache.commons.lang3.StringUtils.EMPTY;

@Service
public class AppNumberFormatService {

    private static final Pattern formatPattern = Pattern.compile("\\{(.*?)\\}");
    public static final String SEQ_FORMAT_PREFIX = "{seq(";
    public static final String FORMAT_SUFFIX = ")}";
    public static final String EXPL_FORMAT_PREFIX = "{expl(";
    public static final String RANDOM_FORMAT_PREFIX = "{rnd(";
    public static final String DATE_FORMAT_PREFIX = "{date(";

    @Autowired
    private AppNumberFormatRepository appNumberFormatRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public String generateApplicationNumber(String name, Object ... objects) {
        AppNumberFormat appNumberFormat = appNumberFormatRepository.findByName(name);
        String appNumber = appNumberFormat.getFormat();
        Matcher formatMatcher = formatPattern.matcher(appNumberFormat.getFormat());
        while(formatMatcher.find()) {
            String currentValue = formatMatcher.group();
            if(currentValue.contains(SEQ_FORMAT_PREFIX)) {
                String[] seq_exp = currentValue.replace(SEQ_FORMAT_PREFIX,EMPTY).replace(FORMAT_SUFFIX,EMPTY).trim().split(",");
                appNumber = appNumber.replace(currentValue, String.format("%0"+seq_exp[1]+"d",
                        (Serializable)entityManager.createNativeQuery("SELECT "+seq_exp[0]+".nextval from DUAL").getSingleResult()));
            } else if(currentValue.contains(EXPL_FORMAT_PREFIX)) {
                String [] expression = currentValue.replace(EXPL_FORMAT_PREFIX,EMPTY).replace(FORMAT_SUFFIX,EMPTY).trim().split(",");
                appNumber = appNumber.replace(currentValue, new SpelExpressionParser().parseExpression(expression[0])
                        .getValue(objects[Integer.valueOf(expression[1])]).toString());
            } else if (currentValue.contains(RANDOM_FORMAT_PREFIX)) {
                String [] random = currentValue.replace(RANDOM_FORMAT_PREFIX,EMPTY).replace(FORMAT_SUFFIX,EMPTY).trim().split(",");
                Integer size = Integer.valueOf(random[1]);
                appNumber = appNumber.replace(currentValue, random[0].equals("n") ? randomNumeric(size) :
                        random[0].equals("a") ? randomAlphabetic(size) : randomAlphanumeric(size));
            } else if(currentValue.contains(DATE_FORMAT_PREFIX)) {
                appNumber = appNumber.replace(currentValue, LocalDate.now().format(DateTimeFormatter
                        .ofPattern(currentValue.replace(DATE_FORMAT_PREFIX,EMPTY).replace(FORMAT_SUFFIX,EMPTY))));
            }
        }

        return appNumber;
    }

}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "default", {
  enumerable: true,
  get: function get() {
    return _ButtonGroup.default;
  }
});

var _ButtonGroup = _interopRequireDefault(require("./ButtonGroup"));


text:
package org.openfact.representations.idm;

/**
 *
 * @author Stan Silvert ssilvert@sistcoop.com (C) 2016 Red Hat Inc.
 */
public class AuthDetailsRepresentation {

    private String organizationId;
    private String userId;
    private String ipAddress;

    public String getOrganizationId() {
        return organizationId;
    }

    public void setOrganizationId(String organizationId) {
        this.organizationId = organizationId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

}


text:
module.exports = function(messages) {
    function initialize() {
        var eventList = document.getElementById('event-list');
        var events = ['deviceready', 'backbutton', 'menubutton', 'pause', 'resume', 'searchbutton', 'online', 'offline'];
        events.forEach(function (event) {
            var option = document.createElement('option');
            option.value = event;
            var caption = document.createTextNode(event);
            option.appendChild(caption);
            eventList.appendChild(option);
        });
    }

    function fireEvent() {
        var eventList = document.getElementById('event-list');
        var option = eventList.options[eventList.selectedIndex];
        messages.emit('event', option.value, function (result, err) {
            if (err) {
                window.alert('Firing event failed: ' + err);
            } else {
                window.alert('Fired event: ' + result);
            }
        });
    }

    return {
        initialize: initialize,
        fireEvent: fireEvent
    };
};


text:
#include <stdnoreturn.h>

#include "aontaskfw/ish_aon_share.h"
#include "console.h"
#include "hwtimer.h"
#include "interrupts.h"
#include "ish_dma.h"
#include "ish_persistent_data.h"
#include "power_mgt.h"
#include "system.h"
#include "task.h"
#include "util.h"
#include "watchdog.h"

#define CPUTS(outstr) cputs(CC_SYSTEM, outstr)
#define CPRINTS(format, args...) cprints(CC_SYSTEM, format, ##args)
#define CPRINTF(format, args...) cprintf(CC_SYSTEM, format, ##args)

/* defined in link script: core/minute-ia/ec.lds.S */
extern uint32_t __aon_ro_start;
extern uint32_t __aon_ro_end;
extern uint32_t __aon_rw_start;
extern uint32_t __aon_rw_end;

static void pg_exit_restore_hw(void)
{
	lapic_restore();
	i2c_port_restore();

	CCU_RST_HST = CCU_RST_HST;
	CCU_TCG_ENABLE = 0;
	CCU_BCG_ENABLE = 0;

	CCU_BCG_MIA = 0;
	CCU_BCG_DMA = 0;
	CCU_BCG_I2C = 0;
	CCU_BCG_SPI = 0;
	CCU_BCG_UART = 0;
	CCU_BCG_GPIO = 0;
}

/**
 * on ISH, uart interrupt can only wakeup ISH from low power state via
 * CTS pin, but most ISH platforms only have Rx and Tx pins, no CTS pin
 * exposed, so, we need block ISH enter low power state for a while when
 * console is in use.
 * fixed amount of time to keep the console in use flag true after boot in
 * order to give a permanent window in which the low speed clock is not used.
 */
#define CONSOLE_IN_USE_ON_BOOT_TIME (15 * SECOND)

/* power management internal context data structure */
struct pm_context {
	/* aontask image valid flag */
	int aon_valid;
	/* point to the aon shared data in aontask */
	struct ish_aon_share *aon_share;
	/* TSS segment selector for task switching */
	int aon_tss_selector[2];
	/* console expire time */
	timestamp_t console_expire_time;
	/* console in use timeout */
	int console_in_use_timeout_sec;
} __packed;

static struct pm_context pm_ctx = {
	.aon_valid = 0,
	/* aon shared data located in the start of aon memory */
	.aon_share = (struct ish_aon_share *)CONFIG_AON_RAM_BASE,
	.console_in_use_timeout_sec = 60
};

/* D0ix statistics data, including each state's count and total stay time */
struct pm_stat {
	uint64_t count;
	uint64_t total_time_us;
};

struct pm_statistics {
	struct pm_stat d0i0;
	struct pm_stat d0i1;
	struct pm_stat d0i2;
	struct pm_stat d0i3;
	struct pm_stat pg;
};

static struct pm_statistics pm_stats;

/*
 * Log a new statistic
 *
 * t0: start time, in us
 * t1: end time, in us
 */
static void log_pm_stat(struct pm_stat *stat, uint32_t t0, uint32_t t1)
{
	stat->total_time_us += t1 - t0;
	stat->count++;
}

#ifdef CONFIG_ISH_PM_AONTASK

/* The GDT which initialized in init.S */
extern struct gdt_entry __gdt[];
extern struct gdt_header __gdt_ptr[];

/* TSS desccriptor for saving main FW's cpu context during aontask switching */
static struct tss_entry main_tss;

/**
 * add new entry in GDT
 * if defined 'CONFIG_ISH_PM_AONTASK', the GDT which defined in init.S will
 * have 3 more empty placeholder entries, this function is help to update
 * these entries which needed by x86's HW task switching method
 *
 * @param desc_lo	lower DWORD of the entry descriptor
 * @param desc_up	upper DWORD of the entry descriptor
 *
 * @return		the descriptor selector index of the added entry
 */
static uint32_t add_gdt_entry(uint32_t desc_lo, uint32_t desc_up)
{
	int index;

	/**
	 * get the first empty entry of GDT which defined in init.S
	 * each entry has a fixed size of 8 bytes
	 */
	index = __gdt_ptr[0].limit >> 3;

	/* add the new entry descriptor to the GDT */
	__gdt[index].dword_lo = desc_lo;
	__gdt[index].dword_up = desc_up;

	/* update GDT's limit size */
	__gdt_ptr[0].limit += sizeof(struct gdt_entry);

	return __gdt_ptr[0].limit - sizeof(struct gdt_entry);
}

static void init_aon_task(void)
{
	uint32_t desc_lo, desc_up;
	struct ish_aon_share *aon_share = pm_ctx.aon_share;
	struct tss_entry *aon_tss = aon_share->aon_tss;

	if (aon_share->magic_id != AON_MAGIC_ID) {
		pm_ctx.aon_valid = 0;
		return;
	}

	pm_ctx.aon_valid = 1;

	pm_ctx.aon_tss_selector[0] = 0;

	/* fill in the 3 placeholder GDT entries */

	/* TSS's limit specified as 0x67, to allow the task has permission to
	 * access I/O port using IN/OUT instructions,'iomap_base_addr' field
	 * must be greater than or equal to TSS' limit
	 * see 'I/O port permissions' on
	 *	https://en.wikipedia.org/wiki/Task_state_segment
	 */
	main_tss.iomap_base_addr = GDT_DESC_TSS_LIMIT;

	/* set GDT entry 3 for TSS descriptor of main FW
	 * limit: 0x67
	 * Present = 1, DPL = 0
	 */
	desc_lo = GEN_GDT_DESC_LO((uint32_t)&main_tss, GDT_DESC_TSS_LIMIT,
				  GDT_DESC_TSS_FLAGS);
	desc_up = GEN_GDT_DESC_UP((uint32_t)&main_tss, GDT_DESC_TSS_LIMIT,
				  GDT_DESC_TSS_FLAGS);
	add_gdt_entry(desc_lo, desc_up);

	/* set GDT entry 4 for TSS descriptor of aontask
	 * limit: 0x67
	 * Present = 1, DPL = 0, Accessed = 1
	 */
	desc_lo = GEN_GDT_DESC_LO((uint32_t)aon_tss, GDT_DESC_TSS_LIMIT,
				  GDT_DESC_TSS_FLAGS);
	desc_up = GEN_GDT_DESC_UP((uint32_t)aon_tss, GDT_DESC_TSS_LIMIT,
				  GDT_DESC_TSS_FLAGS);
	pm_ctx.aon_tss_selector[1] = add_gdt_entry(desc_lo, desc_up);

	/* set GDT entry 5 for LDT descriptor of aontask
	 * Present = 1, DPL = 0, Readable = 1
	 */
	desc_lo = GEN_GDT_DESC_LO((uint32_t)aon_share->aon_ldt,
				  aon_share->aon_ldt_size, GDT_DESC_LDT_FLAGS);
	desc_up = GEN_GDT_DESC_UP((uint32_t)aon_share->aon_ldt,
				  aon_share->aon_ldt_size, GDT_DESC_LDT_FLAGS);
	aon_tss->ldt_seg_selector = add_gdt_entry(desc_lo, desc_up);

	/* update GDT register and set current TSS as main_tss (GDT entry 3) */
	__asm__ volatile("lgdt __gdt_ptr;\n"
			 "push %eax;\n"
			 "movw $0x18, %ax;\n"
			 "ltr %ax;\n"
			 "pop %eax;");

	aon_share->main_fw_ro_addr = (uint32_t)&__aon_ro_start;
	aon_share->main_fw_ro_size =
		(uint32_t)&__aon_ro_end - (uint32_t)&__aon_ro_start;

	aon_share->main_fw_rw_addr = (uint32_t)&__aon_rw_start;
	aon_share->main_fw_rw_size =
		(uint32_t)&__aon_rw_end - (uint32_t)&__aon_rw_start;

	aon_share->uma_msb = IPC_UMA_RANGE_LOWER_1;

	ish_dma_init();
}

static inline void check_aon_task_status(void)
{
	struct ish_aon_share *aon_share = pm_ctx.aon_share;

	if (aon_share->last_error != AON_SUCCESS) {
		CPRINTF("aontask has errors:\n");
		CPRINTF("    last error:   %d\n", aon_share->last_error);
		CPRINTF("    error counts: %d\n", aon_share->error_count);
	}
}

static void switch_to_aontask(void)
{
	interrupt_disable();

	__sync_synchronize();

	/* disable cache and flush cache */
	__asm__ volatile("movl %%cr0, %%eax;\n"
			 "orl $0x60000000, %%eax;\n"
			 "movl %%eax, %%cr0;\n"
			 "wbinvd;"
			 :
			 :
			 : "eax");

	/* switch to aontask through a far call with aontask's TSS selector */
	__asm__ volatile("lcall *%0;" ::"m"(*pm_ctx.aon_tss_selector) :);

	/* clear TS (Task Switched) flag and enable cache */
	__asm__ volatile("clts;\n"
			 "movl %%cr0, %%eax;\n"
			 "andl $0x9FFFFFFF, %%eax;\n"
			 "movl %%eax, %%cr0;"
			 :
			 :
			 : "eax");

	interrupt_enable();
}

noreturn static void handle_reset_in_aontask(enum ish_pm_state pm_state)
{
	pm_ctx.aon_share->pm_state = pm_state;

	/* only enable PMU wakeup interrupt */
	disable_all_interrupts();
	task_enable_irq(ISH_PMU_WAKEUP_IRQ);

	if (IS_ENABLED(CONFIG_ISH_PM_RESET_PREP))
		task_enable_irq(ISH_RESET_PREP_IRQ);

	/* enable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 1;

	/* enable power gating of RF(Cache) and ROMs */
	PMU_RF_ROM_PWR_CTRL = 1;

	switch_to_aontask();

	__builtin_unreachable();
}

#endif

static void enter_d0i0(void)
{
	uint32_t t0, t1;

	t0 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0I0;

	/* halt ISH cpu, will wakeup from any interrupt */
	ish_mia_halt();

	t1 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0;
	log_pm_stat(&pm_stats.d0i0, t0, t1);
}

/**
 * ISH PMU does not support both-edge interrupt triggered gpio configuration.
 * If both edges are configured, then the ISH can't stay in low poer mode
 * because it will exit immediately.
 *
 * As a workaround, we scan all gpio pins which have been configured as
 * both-edge triggered, and then temporarily set each gpio pin to the single
 * edge trigger that is opposite of its value, then restore the both-edge
 * trigger configuration immediately after exiting low power mode.
 */
static uint32_t convert_both_edge_gpio_to_single_edge(void)
{
	uint32_t both_edge_pins = 0;
	int i = 0;

	/**
	 * scan GPIO GFER, GRER and GIMR registers to find the both edge
	 * interrupt trigger mode enabled pins.
	 */
	for (i = 0; i < 32; i++) {
		if (ISH_GPIO_GIMR & BIT(i) && ISH_GPIO_GRER & BIT(i) &&
		    ISH_GPIO_GFER & BIT(i)) {
			/* Record the pin so we can restore it later */
			both_edge_pins |= BIT(i);

			if (ISH_GPIO_GPLR & BIT(i)) {
				/* pin is high, just keep falling edge mode */
				ISH_GPIO_GRER &= ~BIT(i);
			} else {
				/* pin is low, just keep rising edge mode */
				ISH_GPIO_GFER &= ~BIT(i);
			}
		}
	}

	return both_edge_pins;
}

static void restore_both_edge_gpio_config(uint32_t both_edge_pin_map)
{
	ISH_GPIO_GRER |= both_edge_pin_map;
	ISH_GPIO_GFER |= both_edge_pin_map;
}

static void enter_d0i1(void)
{
	uint64_t current_irq_map;
	uint32_t both_edge_gpio_pins;
	uint32_t t0, t1;

	/* only enable PMU wakeup interrupt */
	current_irq_map = disable_all_interrupts();
	task_enable_irq(ISH_PMU_WAKEUP_IRQ);

	if (IS_ENABLED(CONFIG_ISH_PM_RESET_PREP))
		task_enable_irq(ISH_RESET_PREP_IRQ);

	t0 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0I1;

	both_edge_gpio_pins = convert_both_edge_gpio_to_single_edge();

	/* enable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 1;

	/* halt ISH cpu, will wakeup from PMU wakeup interrupt */
	ish_mia_halt();

	if (IS_ENABLED(CONFIG_ISH_NEW_PM))
		clear_fabric_error();

	/* disable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 0;

	restore_both_edge_gpio_config(both_edge_gpio_pins);

	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0;
	t1 = __hw_clock_source_read();
	log_pm_stat(&pm_stats.d0i1, t0, t1);

	/* Reload watchdog before enabling interrupts again */
	watchdog_reload();

	/* restore interrupts */
	task_disable_irq(ISH_PMU_WAKEUP_IRQ);
	restore_interrupts(current_irq_map);
}

static void enter_d0i2(void)
{
	uint64_t current_irq_map;
	uint32_t both_edge_gpio_pins;
	uint32_t t0, t1;

	/* only enable PMU wakeup interrupt */
	current_irq_map = disable_all_interrupts();
	task_enable_irq(ISH_PMU_WAKEUP_IRQ);

	if (IS_ENABLED(CONFIG_ISH_PM_RESET_PREP))
		task_enable_irq(ISH_RESET_PREP_IRQ);

	t0 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0I2;

	both_edge_gpio_pins = convert_both_edge_gpio_to_single_edge();

	/* enable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 1;

	/* enable power gating of RF(Cache) and ROMs */
	PMU_RF_ROM_PWR_CTRL = 1;

	switch_to_aontask();

	/* returned from aontask */

	if (IS_ENABLED(CONFIG_ISH_IPAPG)) {
		if (pm_ctx.aon_share->pg_exit)
			pg_exit_restore_hw();
	}

	if (IS_ENABLED(CONFIG_ISH_NEW_PM))
		clear_fabric_error();

	/* disable power gating of RF(Cache) and ROMs */
	PMU_RF_ROM_PWR_CTRL = 0;

	/* disable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 0;

	restore_both_edge_gpio_config(both_edge_gpio_pins);

	t1 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0;
	log_pm_stat(&pm_stats.d0i2, t0, t1);
	if (IS_ENABLED(CONFIG_ISH_IPAPG)) {
		if (pm_ctx.aon_share->pg_exit)
			log_pm_stat(&pm_stats.pg, t0, t1);
	}

	/* Reload watchdog before enabling interrupts again */
	watchdog_reload();

	/* restore interrupts */
	task_disable_irq(ISH_PMU_WAKEUP_IRQ);
	restore_interrupts(current_irq_map);
}

static void enter_d0i3(void)
{
	uint64_t current_irq_map;
	uint32_t both_edge_gpio_pins;
	uint32_t t0, t1;

	/* only enable PMU wakeup interrupt */
	current_irq_map = disable_all_interrupts();
	task_enable_irq(ISH_PMU_WAKEUP_IRQ);

	if (IS_ENABLED(CONFIG_ISH_PM_RESET_PREP))
		task_enable_irq(ISH_RESET_PREP_IRQ);

	t0 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0I3;

	both_edge_gpio_pins = convert_both_edge_gpio_to_single_edge();

	/* enable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 1;

	/* enable power gating of RF(Cache) and ROMs */
	PMU_RF_ROM_PWR_CTRL = 1;

	switch_to_aontask();

	/* returned from aontask */

	if (IS_ENABLED(CONFIG_ISH_IPAPG)) {
		if (pm_ctx.aon_share->pg_exit)
			pg_exit_restore_hw();
	}

	if (IS_ENABLED(CONFIG_ISH_NEW_PM))
		clear_fabric_error();

	/* disable power gating of RF(Cache) and ROMs */
	PMU_RF_ROM_PWR_CTRL = 0;

	/* disable Trunk Clock Gating (TCG) of ISH */
	CCU_TCG_EN = 0;

	restore_both_edge_gpio_config(both_edge_gpio_pins);

	t1 = __hw_clock_source_read();
	pm_ctx.aon_share->pm_state = ISH_PM_STATE_D0;
	log_pm_stat(&pm_stats.d0i3, t0, t1);
	if (IS_ENABLED(CONFIG_ISH_IPAPG)) {
		if (pm_ctx.aon_share->pg_exit)
			log_pm_stat(&pm_stats.pg, t0, t1);
	}

	/* Reload watchdog before enabling interrupts again */
	watchdog_reload();

	/* restore interrupts */
	task_disable_irq(ISH_PMU_WAKEUP_IRQ);
	restore_interrupts(current_irq_map);
}

static int d0ix_decide(timestamp_t cur_time, uint32_t idle_us)
{
	int pm_state = ISH_PM_STATE_D0I0;

	if (DEEP_SLEEP_ALLOWED) {
		/* check if the console use has expired. */
		if (sleep_mask & SLEEP_MASK_CONSOLE) {
			if (cur_time.val > pm_ctx.console_expire_time.val) {
				enable_sleep(SLEEP_MASK_CONSOLE);
				ccprints("Disabling console in deep sleep");
			} else {
				return pm_state;
			}
		}

		if (IS_ENABLED(CONFIG_ISH_PM_D0I3) &&
		    idle_us >= CONFIG_ISH_D0I3_MIN_USEC && pm_ctx.aon_valid)
			pm_state = ISH_PM_STATE_D0I3;

		else if (IS_ENABLED(CONFIG_ISH_PM_D0I2) &&
			 idle_us >= CONFIG_ISH_D0I2_MIN_USEC &&
			 pm_ctx.aon_valid)
			pm_state = ISH_PM_STATE_D0I2;

		else if (IS_ENABLED(CONFIG_ISH_PM_D0I1))
			pm_state = ISH_PM_STATE_D0I1;
	}

	return pm_state;
}

static void pre_setting_d0ix(void)
{
	if (IS_ENABLED(CONFIG_ISH_NEW_PM)) {
		PMU_VNN_REQ = PMU_VNN_REQ;
		uart_to_idle();
	}
}

static void post_setting_d0ix(void)
{
	if (IS_ENABLED(CONFIG_ISH_NEW_PM))
		uart_port_restore();
}

static void pm_process(timestamp_t cur_time, uint32_t idle_us)
{
	int decide;

	decide = d0ix_decide(cur_time, idle_us);

	switch (decide) {
	case ISH_PM_STATE_D0I1:
		pre_setting_d0ix();
		enter_d0i1();
		post_setting_d0ix();
		break;
	case ISH_PM_STATE_D0I2:
		pre_setting_d0ix();
		enter_d0i2();
		post_setting_d0ix();
		check_aon_task_status();
		break;
	case ISH_PM_STATE_D0I3:
		pre_setting_d0ix();
		enter_d0i3();
		post_setting_d0ix();
		check_aon_task_status();
		break;
	default:
		enter_d0i0();
		break;
	}
}

static void reset_bcg(void)
{
	if (IS_ENABLED(CONFIG_ISH_NEW_PM)) {
		CCU_BCG_MIA = 0;
		CCU_BCG_DMA = 0;
		CCU_BCG_I2C = 0;
		CCU_BCG_SPI = 0;
		CCU_BCG_UART = 0;
		CCU_BCG_GPIO = 0;
	} else {
		CCU_BCG_EN = 0;
	}
}

static void enable_d3bme_irqs(void)
{
	task_enable_irq(ISH_D3_RISE_IRQ);
	if (!IS_ENABLED(CONFIG_ISH_NEW_PM)) {
		task_enable_irq(ISH_D3_FALL_IRQ);
		task_enable_irq(ISH_BME_RISE_IRQ);
		task_enable_irq(ISH_BME_FALL_IRQ);
	}
}

void ish_pm_init(void)
{
	/* clear reset bit */
	ISH_RST_REG = 0;

	/* clear reset history register in CCU */
	CCU_RST_HST = CCU_RST_HST;

#if defined(CHIP_VARIANT_ISH5P4)
	if (IS_ENABLED(CONFIG_ISH_NEW_PM))
		PMU_D3_STATUS_1 = 0xffffffff;
#endif

	/* disable TCG and disable BCG */
	CCU_TCG_ENABLE = 0;
	CCU_BCG_ENABLE = 0;

	/* Disable power gate of CACHE and ROM */
	PMU_RF_ROM_PWR_CTRL = 0;

	reset_bcg();

	if (IS_ENABLED(CONFIG_ISH_PM_AONTASK))
		init_aon_task();

	if (IS_ENABLED(CONFIG_ISH_NEW_PM)) {
		PMU_GPIO_WAKE_MASK0 = 0;
		PMU_GPIO_WAKE_MASK1 = 0;
	}

	/* Unmask all wake up events in event1 */
	PMU_MASK_EVENT = ~PMU_MASK_EVENT_BIT_ALL;
	/* Mask events in event2 */
	PMU_MASK_EVENT2 = PMU_MASK2_ALL_EVENTS;

#if defined(CHIP_VARIANT_ISH5P4)
	SBEP_REG_CLK_GATE_ENABLE =
		(SB_CLK_GATE_EN_LOCAL_CLK_GATE | SB_CLK_GATE_EN_TRUNK_CLK_GATE);
#endif

	if (IS_ENABLED(CONFIG_ISH_NEW_PM)) {
		PMU_ISH_FABRIC_CNT = (PMU_ISH_FABRIC_CNT & 0xffff0000) |
				     FABRIC_IDLE_COUNT;
		PMU_PGCB_CLKGATE_CTRL = TRUNK_CLKGATE_COUNT;
	}

	if (IS_ENABLED(CONFIG_ISH_PM_RESET_PREP)) {
		/* unmask reset prep avail interrupt */
		PMU_RST_PREP = 0;

		task_enable_irq(ISH_RESET_PREP_IRQ);
	}

	if (IS_ENABLED(CONFIG_ISH_PM_D3)) {
		/* unmask D3 and BME interrupts */
		PMU_D3_STATUS &= (PMU_D3_BIT_SET | PMU_BME_BIT_SET);

		if ((!(PMU_D3_STATUS & PMU_D3_BIT_SET)) &&
		    (PMU_D3_STATUS & PMU_BME_BIT_SET))
			PMU_D3_STATUS = PMU_D3_STATUS;

#if defined(CHIP_VARIANT_ISH5P4)
		if (IS_ENABLED(CONFIG_ISH_NEW_PM)) {
			/* Mask all function1 */
			PMU_REG_MASK_D3_RISE = 0x2;
			PMU_REG_MASK_D3_FALL = 0x2;
			PMU_REG_MASK_BME_RISE = 0x2;
			PMU_REG_MASK_BME_FALL = 0x2;
		}
#endif
		enable_d3bme_irqs();
	}
}

noreturn void ish_pm_reset(enum ish_pm_state pm_state)
{
	if (IS_ENABLED(CONFIG_ISH_PM_AONTASK) && pm_ctx.aon_valid) {
		handle_reset_in_aontask(pm_state);
	} else {
		ish_mia_reset();
	}

	__builtin_unreachable();
}

void __idle(void)
{
	timestamp_t t0;
	int next_delay = 0;

	/**
	 * initialize console in use to true and specify the console expire
	 * time in order to give a fixed window on boot
	 */
	disable_sleep(SLEEP_MASK_CONSOLE);
	pm_ctx.console_expire_time.val =
		get_time().val + CONSOLE_IN_USE_ON_BOOT_TIME;

	while (1) {
		t0 = get_time();
		next_delay = __hw_clock_event_get() - t0.le.lo;

		/*
		 * Most of the time, 'next_delay' will be positive. But, due to
		 * interrupt latency, it's possible that get_time() returns
		 * the value bigger than the one from __hw_clock_event_get()
		 * which is supposed to be updated by ISR before control reaches
		 * to the get_time().
		 *
		 * Here, we handle the delayed update by changing negative to 0.
		 */
		pm_process(t0, MAX(0, next_delay));
	}
}

/*
 * helper for command_idle_stats
 */
static void print_stats(const char *name, const struct pm_stat *stat)
{
	if (stat->count)
		ccprintf("    %s:\n"
			 "        counts: %llu\n"
			 "        time:   %.6llus\n",
			 name, stat->count, stat->total_time_us);
}

/**
 * Print low power idle statistics
 */
static int command_idle_stats(int argc, const char **argv)
{
	struct ish_aon_share *aon_share = pm_ctx.aon_share;

	ccprintf("Aontask exists: %s\n", pm_ctx.aon_valid ? "Yes" : "No");
	ccprintf("Total time on: %.6llus\n", get_time().val);
	ccprintf("Idle sleep:\n");
	print_stats("D0i0", &pm_stats.d0i0);

	ccprintf("Deep sleep:\n");
	print_stats("D0i1", &pm_stats.d0i1);
	print_stats("D0i2", &pm_stats.d0i2);
	print_stats("D0i3", &pm_stats.d0i3);
	if (IS_ENABLED(CONFIG_ISH_IPAPG))
		print_stats("IPAPG", &pm_stats.pg);

	if (pm_ctx.aon_valid) {
		ccprintf("    Aontask status:\n");
		ccprintf("        last error:   %u\n", aon_share->last_error);
		ccprintf("        error counts: %u\n", aon_share->error_count);
	}

	return EC_SUCCESS;
}

DECLARE_CONSOLE_COMMAND(idlestats, command_idle_stats, "",
			"Print power management statistics");

/**
 * main FW only need handle PMU wakeup interrupt for D0i1 state, aontask will
 * handle PMU wakeup interrupt for other low power states
 */
__maybe_unused static void pmu_wakeup_isr(void)
{
	/* at current nothing need to do */
}

#ifdef CONFIG_ISH_PM_D0I1
DECLARE_IRQ(ISH_PMU_WAKEUP_IRQ, pmu_wakeup_isr);
#endif

/**
 * from ISH5.0, when system doing S0->Sx transition, will receive reset prep
 * interrupt, will switch to aontask for handling
 *
 */

__maybe_unused noreturn static void reset_prep_isr(void)
{
	/* mask reset prep avail interrupt */
	PMU_RST_PREP = PMU_RST_PREP_INT_MASK;

	/*
	 * Indicate completion of servicing the interrupt to IOAPIC first
	 * then indicate completion of servicing the interrupt to LAPIC
	 */
	IOAPIC_EOI_REG = ISH_RESET_PREP_VEC;
	LAPIC_EOI_REG = 0x0;

	system_reset(0);
	__builtin_unreachable();
}

#ifdef CONFIG_ISH_PM_RESET_PREP
DECLARE_IRQ(ISH_RESET_PREP_IRQ, reset_prep_isr);
#endif

__maybe_unused static void handle_d3(uint32_t irq_vec)
{
	PMU_D3_STATUS = PMU_D3_STATUS;

	if (PMU_D3_STATUS & (PMU_D3_BIT_RISING_EDGE_STATUS | PMU_D3_BIT_SET)) {
		/*
		 * Indicate completion of servicing the interrupt to IOAPIC
		 * first then indicate completion of servicing the interrupt
		 * to LAPIC
		 */
		IOAPIC_EOI_REG = irq_vec;
		LAPIC_EOI_REG = 0x0;

		ish_persistent_data_commit();
		ish_pm_reset(ISH_PM_STATE_D3);
	}
}

static void d3_rise_isr(void)
{
	handle_d3(ISH_D3_RISE_VEC);
}

static __maybe_unused void d3_fall_isr(void)
{
	handle_d3(ISH_D3_FALL_VEC);
}

static __maybe_unused void bme_rise_isr(void)
{
	handle_d3(ISH_BME_RISE_VEC);
}

static __maybe_unused void bme_fall_isr(void)
{
	handle_d3(ISH_BME_FALL_VEC);
}

#ifdef CONFIG_ISH_PM_D3
DECLARE_IRQ(ISH_D3_RISE_IRQ, d3_rise_isr);
#ifndef CONFIG_ISH_NEW_PM
DECLARE_IRQ(ISH_D3_FALL_IRQ, d3_fall_isr);
DECLARE_IRQ(ISH_BME_RISE_IRQ, bme_rise_isr);
DECLARE_IRQ(ISH_BME_FALL_IRQ, bme_fall_isr);
#endif
#endif

void ish_pm_refresh_console_in_use(void)
{
	disable_sleep(SLEEP_MASK_CONSOLE);

	/* Set console in use expire time. */
	pm_ctx.console_expire_time = get_time();
	pm_ctx.console_expire_time.val +=
		pm_ctx.console_in_use_timeout_sec * SECOND;
}


text:
goog.provide('gmfapp.objecteditinghub');

goog.require('goog.asserts');
/** @suppress {extraRequire} */
goog.require('ngeo.proj.EPSG21781');
goog.require('gmf.ObjectEditingManager');
goog.require('gmf.Themes');
goog.require('gmf.XSDAttributes');
goog.require('ol.format.WFS');

/** @type {!angular.Module} **/
gmfapp.module = angular.module('gmfapp', ['gmf']);

gmfapp.module.value('gmfTreeUrl',
    'https://geomapfish-demo.camptocamp.net/2.1/wsgi/themes?version=2&background=background');

gmfapp.module.value('gmfLayersUrl',
    'https://geomapfish-demo.camptocamp.net/2.1/wsgi/layers/');

/**
 * @param {angular.$http} $http Angular $http service.
 * @param {angular.$q} $q Angular $q service.
 * @param {!angular.Scope} $scope Angular scope.
 * @param {gmf.Themes} gmfThemes The gmf themes service.
 * @param {gmf.XSDAttributes} gmfXSDAttributes The gmf XSDAttributes service.
 * @constructor
 * @ngInject
 */
gmfapp.MainController = function($http, $q, $scope, gmfThemes, gmfXSDAttributes) {

  /**
   * @type {angular.$http}
   * @private
   */
  this.http_ = $http;

  /**
   * @type {angular.$q}
   * @private
   */
  this.q_ = $q;

  /**
   * @type {gmf.Themes}
   * @private
   */
  this.gmfThemes_ = gmfThemes;

  /**
   * @type {gmf.XSDAttributes}
   * @private
   */
  this.gmfXSDAttributes_ = gmfXSDAttributes;

  /**
   * @type {Array.<string>} List of example and application urls that contain
   *     ObjectEditing tools.
   * @export
   */
  this.urls = [
    {
      'name': 'oeedit app. (hosted)',
      'url': 'apps/oeedit/'
    },
    {
      'name': 'oeedit app. (dev)',
      'url': '../apps/oeedit/'
    },
    {
      'name': 'example',
      'url': 'objectediting.html'
    }
  ];

  /**
   * @type {string} OE viewer application base url when developping.
   * @private
   */
  this.viewerUrlDev_ = '../apps/oeview/';

  /**
   * @type {string} OE viewer application base url when hosted.
   * @private
   */
  this.viewerUrlHosted_ = 'apps/oeview/';

  /**
   * @type {Object.<string, string>}
   * @export
   */
  this.selectedUrl = this.urls[0];

  /**
   * @type {gmfThemes.GmfOgcServers} ogcServers OGC servers.
   * @private
   */
  this.gmfServers_;

  /**
   * @type {gmfThemes.GmfOgcServer} ogcServer OGC server to use.
   * @private
   */
  this.gmfServer_;

  /**
   * @type {Array.<gmfThemes.GmfLayerWMS>}
   * @export
   */
  this.gmfLayerNodes = [];

  /**
   * @type {?gmfThemes.GmfLayerWMS}
   * @export
   */
  this.selectedGmfLayerNode = null;

  /**
   * @type {Object.<number, Array.<ol.Feature>>}
   * @export
   */
  this.featuresCache_ = {};

  /**
   * @type {Array.<ol.Feature>}
   * @export
   */
  this.features = null;

  /**
   * @type {?ol.Feature}
   * @export
   */
  this.selectedFeature = null;

  /**
   * @type {Object.<number, string>}
   * @private
   */
  this.geomTypeCache_ = {};

  /**
   * @type {?string}
   * @export
   */
  this.selectedGeomType = null;

  $scope.$watch(
    function() {
      return this.selectedGmfLayerNode;
    }.bind(this),
    function(newVal, oldVal) {
      this.selectedFeature = null;

      if (newVal) {
        this.getFeatures_(newVal).then(
          this.handleGetFeatures_.bind(this, newVal)
        );
        this.getGeometryType_(newVal).then(
          this.handleGetGeometryType_.bind(this, newVal)
        );
      }
    }.bind(this)
  );

  /**
   * @type {string}
   * @export
   */
  this.themeName = 'ObjectEditing';

  this.gmfThemes_.loadThemes();

  this.gmfThemes_.getOgcServersObject().then(function(ogcServers) {

    // (1) Set OGC servers
    this.gmfServers_ = ogcServers;

    this.gmfThemes_.getThemesObject().then(function(themes) {
      if (!themes) {
        return;
      }

      var i, ii;

      // (2) Find OE theme
      var theme;
      for (i = 0, ii = themes.length; i < ii; i++) {
        if (themes[i].name === this.themeName) {
          theme = themes[i];
          break;
        }
      }

      if (!theme) {
        return;
      }

      // (3) Get first group node
      var groupNode = theme.children[0];

      // (4) Set OGC server, which must support WFS for this example to work
      var gmfServer = this.gmfServers_[groupNode.ogcServer];
      if (gmfServer && gmfServer.wfsSupport === true && gmfServer.urlWfs) {
        this.gmfServer_ = gmfServer;
      } else {
        return;
      }

      var gmfLayerNodes = [];
      for (i = 0, ii = groupNode.children.length; i < ii; i++) {
        if (groupNode.children[i].metadata.identifierAttributeField) {
          gmfLayerNodes.push(groupNode.children[i]);
        }
      }

      // (5) Set layer nodes
      this.gmfLayerNodes = gmfLayerNodes;

      // (6) Select 'polygon' for the purpose of simplifying the demo
      this.selectedGmfLayerNode = this.gmfLayerNodes[1];

    }.bind(this));
  }.bind(this));

};

/**
 * @export
 */
gmfapp.MainController.prototype.runEditor = function() {

  var geomType = this.selectedGeomType;
  var feature = this.selectedFeature;
  var layer = this.selectedGmfLayerNode.id;
  var property = this.selectedGmfLayerNode.metadata.identifierAttributeField;
  goog.asserts.assert(property !== undefined);
  var id = feature.get(property);

  var params = {};
  params[gmf.ObjectEditingManager.Param.GEOM_TYPE] = geomType;
  params[gmf.ObjectEditingManager.Param.ID] = id;
  params[gmf.ObjectEditingManager.Param.LAYER] = layer;
  params[gmf.ObjectEditingManager.Param.THEME] = this.themeName;
  params[gmf.ObjectEditingManager.Param.PROPERTY] = property;

  var url = gmfapp.MainController.appendParams(this.selectedUrl['url'], params);
  window.open(url);
};

/**
 * @export
 */
gmfapp.MainController.prototype.runViewerDev = function() {
  this.runViewer_(this.viewerUrlDev_);
};

/**
 * @export
 */
gmfapp.MainController.prototype.runViewerHosted = function() {
  this.runViewer_(this.viewerUrlHosted_);
};

/**
 * @param {string} baseUrl Base url of the viewer.
 * @private
 */
gmfapp.MainController.prototype.runViewer_ = function(baseUrl) {

  var node = this.selectedGmfLayerNode;
  var nodeId = node.id;
  var nodeName = node.name;
  var nodeIdAttrFieldName = node.metadata.identifierAttributeField;
  goog.asserts.assert(nodeIdAttrFieldName !== undefined);
  var ids = [];

  var features = this.featuresCache_[nodeId];
  for (var i = 0, ii = features.length; i < ii; i++) {
    ids.push(
      features[i].get(nodeIdAttrFieldName)
    );
  }

  var params = {};
  params['wfs_layer'] = nodeName;
  params['wfs_' + nodeIdAttrFieldName] = ids.join(',');

  var url = gmfapp.MainController.appendParams(baseUrl, params);
  window.open(url);
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @return {angular.$q.Promise} The promise attached to the deferred object.
 * @private
 */
gmfapp.MainController.prototype.getFeatures_ = function(gmfLayerNode) {

  this.getFeaturesDeferred_ = this.q_.defer();

  var features = this.getFeaturesFromCache_(gmfLayerNode);

  if (features) {
    this.getFeaturesDeferred_.resolve();
  } else {
    this.issueGetFeatures_(gmfLayerNode);
  }

  return this.getFeaturesDeferred_.promise;
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @private
 */
gmfapp.MainController.prototype.issueGetFeatures_ = function(gmfLayerNode) {

  var id = gmfLayerNode.id;

  var url = gmfapp.MainController.appendParams(
    this.gmfServer_.urlWfs,
    {
      'SERVICE': 'WFS',
      'REQUEST': 'GetFeature',
      'VERSION': '1.1.0',
      'TYPENAME': gmfLayerNode.layers
    }
  );

  this.http_.get(url).then(function(response) {
    var features = new ol.format.WFS().readFeatures(response.data);
    this.featuresCache_[id] = features;
    this.getFeaturesDeferred_.resolve();
  }.bind(this));
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @private
 */
gmfapp.MainController.prototype.handleGetFeatures_ = function(gmfLayerNode) {
  var features = /** @type Array.<ol.Feature> */ (
    this.getFeaturesFromCache_(gmfLayerNode));
  this.features = features;
  this.selectedFeature = this.features[0];
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @return {?Array.<ol.Feature>} List of features
 * @private
 */
gmfapp.MainController.prototype.getFeaturesFromCache_ = function(gmfLayerNode) {
  var id = gmfLayerNode.id;
  var features = this.featuresCache_[id] || null;
  return features;
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @return {angular.$q.Promise} The promise attached to the deferred object.
 * @private
 */
gmfapp.MainController.prototype.getGeometryType_ = function(gmfLayerNode) {

  this.getGeometryTypeDeferred_ = this.q_.defer();

  var geomType = this.getGeometryTypeFromCache_(gmfLayerNode);

  if (geomType) {
    this.getGeometryTypeDeferred_.resolve();
  } else {
    this.issueGetAttributesRequest_(gmfLayerNode);
  }

  return this.getGeometryTypeDeferred_.promise;
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @private
 */
gmfapp.MainController.prototype.issueGetAttributesRequest_ = function(
  gmfLayerNode
) {

  this.gmfXSDAttributes_.getAttributes(gmfLayerNode.id).then(
    function(gmfLayerNode, attributes) {
      // Get geom type from attributes and set
      var geomAttr = ngeo.format.XSDAttribute.getGeometryAttribute(attributes);
      if (geomAttr && geomAttr.geomType) {
        this.geomTypeCache_[gmfLayerNode.id] = geomAttr.geomType;
        this.getGeometryTypeDeferred_.resolve();
      }
    }.bind(this, gmfLayerNode)
  );

};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @private
 */
gmfapp.MainController.prototype.handleGetGeometryType_ = function(gmfLayerNode) {
  var geomType = /** @type {string} */ (
    this.getGeometryTypeFromCache_(gmfLayerNode));
  this.selectedGeomType = geomType;
};

/**
 * @param {gmfThemes.GmfLayerWMS} gmfLayerNode Layer node.
 * @return {?string} The type of geometry.
 * @private
 */
gmfapp.MainController.prototype.getGeometryTypeFromCache_ = function(
  gmfLayerNode
) {
  var id = gmfLayerNode.id;
  var geomType = this.geomTypeCache_[id] || null;
  return geomType;
};

/**
 * Appends query parameters to a URI.
 *
 * @param {string} uri The original URI, which may already have query data.
 * @param {!Object} params An object where keys are URI-encoded parameter keys,
 *     and the values are arbitrary types or arrays.
 * @return {string} The new URI.
 */
gmfapp.MainController.appendParams = function(uri, params) {
  var keyParams = [];
  // Skip any null or undefined parameter values
  Object.keys(params).forEach(function(k) {
    if (params[k] !== null && params[k] !== undefined) {
      keyParams.push(k + '=' + encodeURIComponent(params[k]));
    }
  });
  var qs = keyParams.join('&');
  // remove any trailing ? or &
  uri = uri.replace(/[?&]$/, '');
  // append ? or & depending on whether uri has existing parameters
  uri = uri.indexOf('?') === -1 ? uri + '?' : uri + '&';
  return uri + qs;
};

gmfapp.module.controller('MainController', gmfapp.MainController);


text:
package cli

import "strings"

// Context is the context is which an Action is ran.
type Context struct {
	// Action is the context wrapped function to be evaluated.
	Action func() error

	flagSet map[string]struct{}
}

// NewContext initializes a new context for the Action to run in.
func NewContext(app *App, args []string) (*Context, error) {
	// Parse the flags first
	flagSet := ParseFlags(app.Flags, args)

	// Parse the commands
	action := ParseCommands(app.Action, app.Commands, args[len(flagSet):])

	// No appropriate action found, so we return ErrIncorrectUsage
	if action == nil {
		return nil, ErrIncorrectUsage
	}

	context := &Context{
		flagSet: flagSet,
	}

	context.Action = func() error {
		// Wrap the action call with context
		return action(context)
	}

	return context, nil
}

// IsSet returns whether flag with name is enabled.
func (c *Context) IsSet(name string) bool {
	_, ok := c.flagSet[name]
	return ok
}

// ParseFlags parses the args and returns a map of flags set.
func ParseFlags(flags Flags, args []string) map[string]struct{} {
	flagSet := make(map[string]struct{})

	for _, arg := range args {
		if !strings.HasPrefix(arg, "--") {
			break
		}

		alias := strings.TrimLeft(arg, "--")
		name := flags.NameForAlias(alias)
		if name != "" {
			flagSet[name] = struct{}{}
		}
	}

	return flagSet
}

// ParseCommands parses the args and returns the Action to invoke.
func ParseCommands(defaultAction Action, commands Commands, args []string) Action {
	var action func(ctx *Context) error

	if len(args) == 0 {
		// Default to application's default action if no commands are found
		action = defaultAction
	} else if len(args) == 1 {
		// Subcommands not supported, so only if there is one command, take that
		// command's Action
		action = commands.ActionForName(args[0])
	}

	return action
}


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>Hello World</title>

Hello World!


text:
#include <aws/ce/model/CreateCostCategoryDefinitionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CostExplorer::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateCostCategoryDefinitionRequest::CreateCostCategoryDefinitionRequest() :
    m_nameHasBeenSet(false),
    m_ruleVersion(CostCategoryRuleVersion::NOT_SET),
    m_ruleVersionHasBeenSet(false),
    m_rulesHasBeenSet(false),
    m_defaultValueHasBeenSet(false),
    m_splitChargeRulesHasBeenSet(false),
    m_resourceTagsHasBeenSet(false)
{
}

Aws::String CreateCostCategoryDefinitionRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_ruleVersionHasBeenSet)
  {
   payload.WithString("RuleVersion", CostCategoryRuleVersionMapper::GetNameForCostCategoryRuleVersion(m_ruleVersion));
  }

  if(m_rulesHasBeenSet)
  {
   Array<JsonValue> rulesJsonList(m_rules.size());
   for(unsigned rulesIndex = 0; rulesIndex < rulesJsonList.GetLength(); ++rulesIndex)
   {
     rulesJsonList[rulesIndex].AsObject(m_rules[rulesIndex].Jsonize());
   }
   payload.WithArray("Rules", std::move(rulesJsonList));

  }

  if(m_defaultValueHasBeenSet)
  {
   payload.WithString("DefaultValue", m_defaultValue);

  }

  if(m_splitChargeRulesHasBeenSet)
  {
   Array<JsonValue> splitChargeRulesJsonList(m_splitChargeRules.size());
   for(unsigned splitChargeRulesIndex = 0; splitChargeRulesIndex < splitChargeRulesJsonList.GetLength(); ++splitChargeRulesIndex)
   {
     splitChargeRulesJsonList[splitChargeRulesIndex].AsObject(m_splitChargeRules[splitChargeRulesIndex].Jsonize());
   }
   payload.WithArray("SplitChargeRules", std::move(splitChargeRulesJsonList));

  }

  if(m_resourceTagsHasBeenSet)
  {
   Array<JsonValue> resourceTagsJsonList(m_resourceTags.size());
   for(unsigned resourceTagsIndex = 0; resourceTagsIndex < resourceTagsJsonList.GetLength(); ++resourceTagsIndex)
   {
     resourceTagsJsonList[resourceTagsIndex].AsObject(m_resourceTags[resourceTagsIndex].Jsonize());
   }
   payload.WithArray("ResourceTags", std::move(resourceTagsJsonList));

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection CreateCostCategoryDefinitionRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSInsightsIndexService.CreateCostCategoryDefinition"));
  return headers;

}


text:
#include <zephyr/kernel.h>
#include <zephyr/fff.h>
#include <tinycrypt/hmac_prng.h>
#include <tinycrypt/constants.h>

/* List of fakes used by this unit tester */
#define HMAC_PRNG_FFF_FAKES_LIST(FAKE)         \
		FAKE(tc_hmac_prng_init)                \
		FAKE(tc_hmac_prng_reseed)              \
		FAKE(tc_hmac_prng_generate)

DECLARE_FAKE_VALUE_FUNC(int, tc_hmac_prng_init, TCHmacPrng_t, const uint8_t *, unsigned int);
DECLARE_FAKE_VALUE_FUNC(int, tc_hmac_prng_reseed, TCHmacPrng_t, const uint8_t *, unsigned int,
			const uint8_t *, unsigned int);
DECLARE_FAKE_VALUE_FUNC(int, tc_hmac_prng_generate, uint8_t *, unsigned int, TCHmacPrng_t);


text:
package io.opentelemetry.opencensusshim;

import io.opencensus.common.Function;
import io.opencensus.trace.BlankSpan;
import io.opencensus.trace.Span;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.SpanId;
import io.opencensus.trace.TraceId;
import io.opencensus.trace.TraceOptions;
import io.opencensus.trace.Tracestate;
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.TraceFlags;
import io.opentelemetry.api.trace.TraceState;
import io.opentelemetry.api.trace.TraceStateBuilder;
import javax.annotation.Nullable;

final class SpanConverter {
  static final String MESSAGE_EVENT_ATTRIBUTE_KEY_TYPE = "message.event.type";
  static final String MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_UNCOMPRESSED =
      "message.event.size.uncompressed";
  static final String MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_COMPRESSED = "message.event.size.compressed";

  private SpanConverter() {}

  static SpanKind mapKind(@Nullable io.opencensus.trace.Span.Kind ocKind) {
    if (ocKind == null) {
      return SpanKind.INTERNAL;
    }
    switch (ocKind) {
      case CLIENT:
        return SpanKind.CLIENT;
      case SERVER:
        return SpanKind.SERVER;
    }
    return SpanKind.INTERNAL;
  }

  static Span fromOtelSpan(@Nullable io.opentelemetry.api.trace.Span otSpan) {
    if (otSpan == null) {
      return BlankSpan.INSTANCE;
    }
    return new OpenTelemetrySpanImpl(otSpan);
  }

  static SpanContext mapSpanContext(io.opentelemetry.api.trace.SpanContext otelSpanContext) {
    return SpanContext.create(
        TraceId.fromLowerBase16(otelSpanContext.getTraceId()),
        SpanId.fromLowerBase16(otelSpanContext.getSpanId()),
        TraceOptions.builder().setIsSampled(otelSpanContext.isSampled()).build(),
        mapTracestate(otelSpanContext.getTraceState()));
  }

  static io.opentelemetry.api.trace.SpanContext mapSpanContext(SpanContext ocSpanContext) {
    return io.opentelemetry.api.trace.SpanContext.create(
        ocSpanContext.getTraceId().toLowerBase16(),
        ocSpanContext.getSpanId().toLowerBase16(),
        ocSpanContext.getTraceOptions().isSampled()
            ? TraceFlags.getSampled()
            : TraceFlags.getDefault(),
        mapTracestate(ocSpanContext.getTracestate()));
  }

  private static TraceState mapTracestate(Tracestate tracestate) {
    TraceStateBuilder builder = TraceState.builder();
    tracestate.getEntries().forEach(entry -> builder.put(entry.getKey(), entry.getValue()));
    return builder.build();
  }

  static Tracestate mapTracestate(TraceState traceState) {
    Tracestate.Builder tracestateBuilder = Tracestate.builder();
    traceState.forEach(tracestateBuilder::set);
    return tracestateBuilder.build();
  }

  static Function<String, Void> setStringAttribute(AttributesBuilder builder, String key) {
    return arg -> {
      builder.put(key, arg);
      return null;
    };
  }

  static Function<Boolean, Void> setBooleanAttribute(AttributesBuilder builder, String key) {
    return arg -> {
      builder.put(key, arg);
      return null;
    };
  }

  static Function<Long, Void> setLongAttribute(AttributesBuilder builder, String key) {
    return arg -> {
      builder.put(key, arg);
      return null;
    };
  }

  static Function<Double, Void> setDoubleAttribute(AttributesBuilder builder, String key) {
    return arg -> {
      builder.put(key, arg);
      return null;
    };
  }
}


text:
package de.madcyph3r.materialnavigationdrawer.menu.item.style;

import android.view.View;

import de.madcyph3r.materialnavigationdrawer.menu.item.MaterialMenuItem;
import de.madcyph3r.materialnavigationdrawer.listener.Selectable;

public class MaterialItemDevisor extends MaterialMenuItem implements Selectable {

/*    public MaterialItemDevisor() {
        setBottom(false);
    }

    public MaterialItemDevisor(boolean bottom) {
        setBottom(bottom);
    }*/

    @Override
    public void select() {

    }

    @Override
    public void unSelect() {

    }

    @Override
    public boolean isSelected() {
        return false;
    }

    @Override
    public View getView() {
        return null;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fiddler;
using Grabacr07.KanColleWrapper.Internal;
using Grabacr07.KanColleWrapper.Models.Raw;

namespace Grabacr07.KanColleWrapper.Models
{
	/// <summary>
	/// 母港に所属している艦娘を表します。
	/// </summary>
	public class Ship : RawDataWrapper<kcsapi_ship2>, IIdentifiable
	{
		private readonly Homeport homeport;

		/// <summary>
		/// この艦娘を識別する ID を取得します。
		/// </summary>
		public int Id
		{
			get { return this.RawData.api_id; }
		}

		/// <summary>
		/// 艦娘の種類に基づく情報を取得します。
		/// </summary>
		public ShipInfo Info { get; private set; }

		public int SortNumber
		{
			get { return this.RawData.api_sortno; }
		}

		/// <summary>
		/// 艦娘の現在のレベルを取得します。
		/// </summary>
		public int Level
		{
			get { return this.RawData.api_lv; }
		}

		/// <summary>
		/// 艦娘がロックされているかどうかを示す値を取得します。
		/// </summary>
		public bool IsLocked
		{
			get { return this.RawData.api_locked == 1; }
		}

		/// <summary>
		/// 艦娘の現在の累積経験値を取得します。
		/// </summary>
		public int Exp
		{
			get { return this.RawData.api_exp.Get(0) ?? 0; }
		}

		/// <summary>
		/// この艦娘が次のレベルに上がるために必要な経験値を取得します。
		/// </summary>
		public int ExpForNextLevel
		{
			get { return this.RawData.api_exp.Get(1) ?? 0; }
		}

		#region HP 変更通知プロパティ

		private LimitedValue _HP;

		/// <summary>
		/// 耐久値を取得します。
		/// </summary>
		public LimitedValue HP
		{
			get { return this._HP; }
			private set
			{
				this._HP = value;
				this.RaisePropertyChanged();
			}
		}

		#endregion

		#region Fuel 変更通知プロパティ

		private LimitedValue _Fuel;

		/// <summary>
		/// 燃料を取得します。
		/// </summary>
		public LimitedValue Fuel
		{
			get { return this._Fuel; }
			private set
			{
				this._Fuel = value;
				this.RaisePropertyChanged();
			}
		}

		#endregion

		#region Bull 変更通知プロパティ

		private LimitedValue _Bull;

		public LimitedValue Bull
		{
			get { return this._Bull; }
			private set
			{
				this._Bull = value;
				this.RaisePropertyChanged();
			}
		}

		#endregion

		#region Firepower 変更通知プロパティ

		private ModernizableStatus _Firepower;

		/// <summary>
		/// 火力ステータス値を取得します。
		/// </summary>
		public ModernizableStatus Firepower
		{
			get { return this._Firepower; }
			private set
			{
				this._Firepower = value;
				this.RaisePropertyChanged();

			}
		}

		#endregion

		#region Torpedo 変更通知プロパティ

		private ModernizableStatus _Torpedo;

		/// <summary>
		/// 雷装ステータス値を取得します。
		/// </summary>
		public ModernizableStatus Torpedo
		{
			get { return this._Torpedo; }
			private set
			{
				this._Torpedo = value;
				this.RaisePropertyChanged();

			}
		}

		#endregion

		#region AA 変更通知プロパティ

		private ModernizableStatus _AA;

		/// <summary>
		/// 対空ステータス値を取得します。
		/// </summary>
		public ModernizableStatus AA
		{
			get { return this._AA; }
			private set
			{
				this._AA = value;
				this.RaisePropertyChanged();
			}

		}

		#endregion

		#region Armer 変更通知プロパティ

		private ModernizableStatus _Armer;

		/// <summary>
		/// 装甲ステータス値を取得します。
		/// </summary>
		public ModernizableStatus Armer
		{
			get { return this._Armer; }
			private set
			{
				this._Armer = value;
				this.RaisePropertyChanged();

			}
		}

		#endregion

		#region Luck 変更通知プロパティ

		private ModernizableStatus _Luck;

		/// <summary>
		/// 運のステータス値を取得します。
		/// </summary>
		public ModernizableStatus Luck
		{
			get { return this._Luck; }
			private set
			{
				this._Luck = value;
				this.RaisePropertyChanged();
			}
		}

		#endregion

		/// <summary>
		/// 装備によるボーナスを含めた索敵ステータス値を取得します。
		/// </summary>
		public int ViewRange
		{
			get { return this.RawData.api_sakuteki.Get(0) ?? 0; }
		}

		/// <summary>
		/// 火力・雷装・対空・装甲のすべてのステータス値が最大値に達しているかどうかを示す値を取得します。
		/// </summary>
		public bool IsMaxModernized
		{
			get { return this.Firepower.IsMax && this.Torpedo.IsMax && this.AA.IsMax && this.Armer.IsMax; }
		}

		/// <summary>
		/// 現在のコンディション値を取得します。
		/// </summary>
		public int Condition
		{
			get { return this.RawData.api_cond; }
		}

		/// <summary>
		/// コンディションの種類を示す <see cref="ConditionType" /> 値を取得します。
		/// </summary>
		public ConditionType ConditionType
		{
			get { return ConditionTypeHelper.ToConditionType(this.RawData.api_cond); }
		}

		public SlotItem[] SlotItems { get; private set; }

		#region OnSlot 変更通知プロパティ

		private int[] _OnSlot;

		/// <summary>
		/// 各装備スロットの艦載機数を取得します。
		/// </summary>
		public int[] OnSlot
		{
			get { return this._OnSlot; }
			private set
			{
				if (this._OnSlot != value)
				{
					this._OnSlot = value;
					this.RaisePropertyChanged();
				}
			}
		}

		#endregion

		#region IsInRepairing 変更通知プロパティ

		private bool _IsInRepairing;

		/// <summary>
		/// この艦が入渠中かどうかを示す値を取得します。
		/// </summary>
		public bool IsInRepairing
		{
			get { return this._IsInRepairing; }
			internal set
			{
				if (this._IsInRepairing != value)
				{
					this._IsInRepairing = value;
					this.RaisePropertyChanged();
				}
			}
		}

		#endregion

		/// <summary>
		/// この艦が出撃した海域を識別する整数値を取得します。
		/// </summary>
		public int SallyArea
		{
			get { return this.RawData.api_sally_area; }
		}

		internal Ship(Homeport parent, kcsapi_ship2 rawData)
			: base(rawData)
		{
			this.homeport = parent;
			this.Update(rawData);
		}

		internal void Update(kcsapi_ship2 rawData)
		{
			this.UpdateRawData(rawData);

			this.Info = KanColleClient.Current.Master.Ships[rawData.api_ship_id] ?? ShipInfo.Dummy;
			this.HP = new LimitedValue(this.RawData.api_nowhp, this.RawData.api_maxhp, 0);
			this.Fuel = new LimitedValue(this.RawData.api_fuel, this.Info.RawData.api_fuel_max, 0);
			this.Bull = new LimitedValue(this.RawData.api_bull, this.Info.RawData.api_bull_max, 0);

			if (this.RawData.api_kyouka.Length >= 5)
			{
				this.Firepower = new ModernizableStatus(this.Info.RawData.api_houg, this.RawData.api_kyouka[0]);
				this.Torpedo = new ModernizableStatus(this.Info.RawData.api_raig, this.RawData.api_kyouka[1]);
				this.AA = new ModernizableStatus(this.Info.RawData.api_tyku, this.RawData.api_kyouka[2]);
				this.Armer = new ModernizableStatus(this.Info.RawData.api_souk, this.RawData.api_kyouka[3]);
				this.Luck = new ModernizableStatus(this.Info.RawData.api_luck, this.RawData.api_kyouka[4]);
			}

			this.SlotItems = this.RawData.api_slot.Select(id => this.homeport.Itemyard.SlotItems[id]).Where(x => x != null).ToArray();
			this.OnSlot = this.RawData.api_onslot;
		}

		internal void Charge(int fuel, int bull, int[] onslot)
		{
			this.Fuel = this.Fuel.Update(fuel);
			this.Bull = this.Bull.Update(bull);
			this.OnSlot = onslot;
		}

		internal void Repair()
		{
			var max = this.HP.Maximum;
			this.HP = this.HP.Update(max);
		}

		public override string ToString()
		{
			return string.Format("ID = {0}, Name = \"{1}\", ShipType = \"{2}\", Level = {3}", this.Id, this.Info.Name, this.Info.ShipType.Name, this.Level);
		}
	}
}


text:
package com.andreitoledo.financeiro.compras.controller.cadastros;

import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.andreitoledo.financeiro.compras.model.cadastros.TipoObjeto;
import com.andreitoledo.financeiro.compras.service.CadastroTipoObjetoService;
import com.andreitoledo.financeiro.compras.service.NegocioException;
import com.andreitoledo.financeiro.compras.util.jsf.FacesMessages;

@Named
@ViewScoped
public class CadastroTipoObjetoBean implements Serializable{

	private static final long serialVersionUID = 1L;

	@Inject
	private CadastroTipoObjetoService cadastroTipoObjetoService;

	private TipoObjeto tipoObjeto;

	@Inject
	private FacesMessages facesMessages;

	public void inicializar(){
		if(this.tipoObjeto == null){
			limpar();

		}
	}

	private void limpar() {
		this.tipoObjeto = new TipoObjeto();

	}

	public void salvar(){
		try {
			this.cadastroTipoObjetoService.salvar(tipoObjeto);
			facesMessages.info("Tipo Objeto salvo com sucesso !");

			limpar();

		} catch (NegocioException e) {
			facesMessages.error(e.getMessage());

		}

	}

	public TipoObjeto getTipoObjeto() {
		return tipoObjeto;
	}

	public void setTipoObjeto(TipoObjeto tipoObjeto) {
		this.tipoObjeto = tipoObjeto;
	}

	public boolean isEditando(){
		return this.tipoObjeto.getCodigo() != null;
	}

}


text:
package io.cattle.platform.iaas.api.auth.dao.impl;

import static io.cattle.platform.core.model.tables.AuthTokenTable.AUTH_TOKEN;

import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.model.AuthToken;
import io.cattle.platform.core.model.tables.records.AuthTokenRecord;
import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao;
import io.cattle.platform.iaas.api.auth.SecurityConstants;
import io.cattle.platform.iaas.api.auth.dao.AuthTokenDao;
import io.cattle.platform.iaas.api.filter.apikey.ApiKeyFilter;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;

import java.util.Date;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

public class AuthTokenDaoImpl extends AbstractJooqDao implements AuthTokenDao{

    @Inject
    GenericResourceDao resourceDao;
    @Inject
    ObjectManager objectManager;
    @Inject
    ObjectProcessManager objectProcessManager;

    @Override
    public AuthTokenRecord getTokenByKey(String key) {
        return create()
                .selectFrom(AUTH_TOKEN)
                .where(AUTH_TOKEN.KEY.eq(key))
                        .and(AUTH_TOKEN.VERSION.eq(SecurityConstants.TOKEN_VERSION))
                        .and(AUTH_TOKEN.EXPIRES.greaterThan(new Date()))
                                .orderBy(AUTH_TOKEN.ID.asc()).fetchOne();
    }

    @Override
    public AuthToken createToken(String jwt, String provider, long accountId, long authenticatedAsAccountId) {
        if (StringUtils.isBlank(jwt)){
            throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "NoJwtToSave", "Cannot save a null jwt.",
                    null);
        }
        AuthTokenRecord authTokenRecord = new AuthTokenRecord();
        authTokenRecord.setAccountId(accountId);
        authTokenRecord.setValue(jwt);
        authTokenRecord.setKey(ApiKeyFilter.generateKeys()[1]);
        authTokenRecord.setVersion(SecurityConstants.TOKEN_VERSION);
        authTokenRecord.setProvider(provider);
        authTokenRecord.setAuthenticatedAsAccountId(authenticatedAsAccountId);
        Date expiry = new Date(System.currentTimeMillis() + SecurityConstants.TOKEN_EXPIRY_MILLIS.get());
        authTokenRecord.setCreated(new Date());
        authTokenRecord.setExpires(expiry);
        int result = create().executeInsert(authTokenRecord);
        if (result == 0){
            throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR,
                    "AuthTokenCreation", "Failed to create auth token.", null);
        }
        return authTokenRecord;
    }

    @Override
    public AuthToken getTokenByAccountId(long accountId) {
        return create()
                .selectFrom(AUTH_TOKEN)
                .where(AUTH_TOKEN.ACCOUNT_ID.eq(accountId))
                        .and(AUTH_TOKEN.VERSION.eq(SecurityConstants.TOKEN_VERSION))
                        .and(AUTH_TOKEN.PROVIDER.eq(SecurityConstants.AUTH_PROVIDER.get()))
                        .and(AUTH_TOKEN.EXPIRES.greaterThan(new Date()))
                .orderBy(AUTH_TOKEN.EXPIRES.desc()).fetchAny();
    }

    @Override
    public boolean deleteToken(String key) {
        return create().executeDelete(getTokenByKey(key)) == 1;
    }

    @Override
    public void deletePreviousTokens(long authenticatedAsAccountId, long tokenAccountId) {
        create().delete(AUTH_TOKEN)
                .where(AUTH_TOKEN.AUTHENTICATED_AS_ACCOUNT_ID.eq(authenticatedAsAccountId))
                        .and(AUTH_TOKEN.ACCOUNT_ID.eq(tokenAccountId))
                        .and(AUTH_TOKEN.EXPIRES.greaterThan(new Date()))
                .execute();

    }
}


text:
    <md-icon (click)="collapsed=!collapsed" *ngIf="collapsed">keyboard_arrow_right</md-icon>
    <md-icon (click)="collapsed=!collapsed" *ngIf="!collapsed">keyboard_arrow_down</md-icon>

{{data.key}}

      Boolean

    <md-icon class="option-menu" [mdMenuTriggerFor]="appMenu">more_vert</md-icon>

    <md-menu #appMenu="mdMenu">
      <button md-menu-item (click)="deleteProperty()">Remove</button>
      <button md-menu-item [mdMenuTriggerFor]="appMenu2">Add Field</button>
    </md-menu>

    <md-menu #appMenu2="mdMenu">
      <button (click)="addField(field)" md-menu-item *ngFor="let field of fields">{{field}}</button>
    </md-menu>

    <md-input-container>
      <input mdInput placeholder="Description" [(ngModel)]="data.data.description">
    </md-input-container>
    <md-icon (click)="deleteField('description')">remove_circle</md-icon>

    <md-select placeholder="Format" [(ngModel)]="data.data.format">
      <md-option *ngFor="let format of formats" [value]="format">{{ format }}</md-option>
    </md-select>
    <md-icon (click)="deleteField('format')">remove_circle</md-icon>


text:
package leap.oauth2.server.endpoint.authorize;

import java.util.Map;

import leap.oauth2.server.authc.AuthzAuthentication;
import leap.web.Request;
import leap.web.Response;

/**
 * Created by kael on 2017/1/5.
 */
public interface Oauth2RedirectHandler {
    /**
     * before redirect on oauth2 login success
     * @param request
     * @param response
     * @param authc
     * @param qs
     * @return true if want to go to redirect, otherwise false
     */
    boolean onOauth2LoginSuccessRedirect(Request request, Response response, AuthzAuthentication authc, Map<String,String> qs);
}


text:
FROM cleawing/zulu-openjdk:8u45

MAINTAINER Cleawing Dockerfile <dockerfile@cleawing.com>

RUN export MARATHON_VERSION="0.9.0" && apt-key adv --keyserver keyserver.ubuntu.com --recv E56151BF && \
  DISTRO=$(lsb_release -is | tr '[:upper:]' '[:lower:]') && \
  CODENAME=$(lsb_release -cs) && \
  echo "deb http://repos.mesosphere.io/${DISTRO} ${CODENAME} main" | tee /etc/apt/sources.list.d/mesosphere.list && \
  apt-get -yq update && \
  apt-get -yq install --no-install-recommends mesos=0.23.0-1.0.ubuntu1404 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* && \
  rm /etc/mesos/zk && \
    rm /etc/mesos-master/quorum && \
  curl -L -o /tmp/marathon.tgz https://downloads.mesosphere.io/marathon/v${MARATHON_VERSION}/marathon-${MARATHON_VERSION}.tgz && \
  mkdir -p /opt/marathon && tar xzf /tmp/marathon.tgz -C /opt/marathon --strip=1 && rm -f /tmp/marathon.tgz

WORKDIR /opt/marathon

EXPOSE 8080

CMD ["--help"]
ENTRYPOINT ["./bin/start"]


text: Runs a child JON Server container


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO.Abstractions;
using System.Linq;
using System.Windows.Input;

using Autofac;

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PicklesDoc.Pickles.ObjectModel;
using PicklesDoc.Pickles.UserInterface.Mvvm;
using PicklesDoc.Pickles.UserInterface.Settings;

namespace PicklesDoc.Pickles.UserInterface.ViewModel
{
    ///
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the mvvminpc snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    ///
    public class MainViewModel : ViewModelBase
    {
        private readonly MultiSelectableCollection<DocumentationFormat> documentationFormats;

        private readonly TestResultsFormat[] testResultsFormats;

        private readonly RelayCommand browseForFeatureFolderCommand;

        private readonly RelayCommand browseForOutputFolderCommand;

        private readonly RelayCommand browseForTestResultsFileCommand;

        private readonly RelayCommand generateCommand;

        private readonly RelayCommand openOutputDirectory;

        private readonly IMainModelSerializer mainModelSerializer;

        private readonly IFileSystem fileSystem;

        private readonly CultureInfo[] neutralCultures;

        private string picklesVersion = typeof(Feature).Assembly.GetName().Version.ToString();

        private string featureFolder;

        private string outputFolder;

        private string projectName;

        private string projectVersion;

        private string testResultsFile;

        private CultureInfo selectedLanguage;

        private bool includeTests;

        private bool isRunning;

        private bool isFeatureDirectoryValid;

        private bool isOutputDirectoryValid;

        private bool isProjectNameValid;

        private bool isProjectVersionValid;

        private bool isTestResultsFileValid;

        private bool isTestResultsFormatValid;

        private bool isLanguageValid = true;

        private bool createDirectoryForEachOutputFormat;

        private bool isDocumentationFormatValid;

        private TestResultsFormat selectedTestResultsFormat;

        private bool includeExperimentalFeatures;

        public MainViewModel(IMainModelSerializer mainModelSerializer, IFileSystem fileSystem)
        {
            this.documentationFormats =
                new MultiSelectableCollection<DocumentationFormat>(
                    Enum.GetValues(typeof(DocumentationFormat)).Cast<DocumentationFormat>());
            this.documentationFormats.First().IsSelected = true;
            this.documentationFormats.SelectionChanged += this.DocumentationFormatsOnCollectionChanged;

            this.testResultsFormats = Enum.GetValues(typeof(TestResultsFormat)).Cast<TestResultsFormat>().ToArray();
            this.selectedTestResultsFormat = TestResultsFormat.NUnit;

            this.browseForFeatureFolderCommand = new RelayCommand(this.DoBrowseForFeature);
            this.browseForOutputFolderCommand = new RelayCommand(this.DoBrowseForOutputFolder);
            this.browseForTestResultsFileCommand = new RelayCommand(this.DoBrowseForTestResultsFile);
            this.generateCommand = new RelayCommand(this.DoGenerate, this.CanGenerate);
            this.openOutputDirectory = new RelayCommand(this.DoOpenOutputDirectory, this.CanOpenOutputDirectory);

            this.PropertyChanged += this.MainWindowViewModelPropertyChanged;
            this.neutralCultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
            this.selectedLanguage = CultureInfo.GetCultureInfo("en");

            this.mainModelSerializer = mainModelSerializer;
            this.fileSystem = fileSystem;
        }

        public string PicklesVersion
        {
            get { return this.picklesVersion; }
            set { this.Set(() => this.PicklesVersion, ref this.picklesVersion, value); }
        }

        public string FeatureFolder
        {
            get { return this.featureFolder; }
            set { this.Set(() => this.FeatureFolder, ref this.featureFolder, value); }
        }

        public string OutputFolder
        {
            get { return this.outputFolder; }
            set { this.Set(() => this.OutputFolder, ref this.outputFolder, value); }
        }

        public MultiSelectableCollection<DocumentationFormat> DocumentationFormatValues
        {
            get { return this.documentationFormats; }
        }

        public string ProjectName
        {
            get { return this.projectName; }
            set { this.Set(() => this.ProjectName, ref this.projectName, value); }
        }

        public string ProjectVersion
        {
            get { return this.projectVersion; }
            set { this.Set(() => this.ProjectVersion, ref this.projectVersion, value); }
        }

        public string TestResultsFile
        {
            get { return this.testResultsFile; }

            set { this.Set(() => this.TestResultsFile, ref this.testResultsFile, value); }
        }

        public IEnumerable<TestResultsFormat> TestResultsFormatValues
        {
            get { return this.testResultsFormats; }
        }

        public TestResultsFormat SelectedTestResultsFormat
        {
            get { return this.selectedTestResultsFormat; }
            set { this.Set(() => this.SelectedTestResultsFormat, ref this.selectedTestResultsFormat, value); }
        }

        public CultureInfo SelectedLanguage
        {
            get { return this.selectedLanguage; }
            set { this.Set(() => this.SelectedLanguage, ref this.selectedLanguage, value); }
        }

        public IEnumerable<CultureInfo> LanguageValues
        {
            get { return this.neutralCultures; }
        }

        public bool IncludeTests
        {
            get { return this.includeTests; }
            set { this.Set(() => this.IncludeTests, ref this.includeTests, value); }
        }

        public ICommand GeneratePickles
        {
            get { return this.generateCommand; }
        }

        public ICommand BrowseForFeatureFolder
        {
            get { return this.browseForFeatureFolderCommand; }
        }

        public ICommand BrowseForOutputFolder
        {
            get { return this.browseForOutputFolderCommand; }
        }

        public ICommand BrowseForTestResultsFile
        {
            get { return this.browseForTestResultsFileCommand; }
        }

        public RelayCommand OpenOutputDirectory
        {
            get { return this.openOutputDirectory; }
        }

        public bool IsRunning
        {
            get { return this.isRunning; }
            set { this.Set(() => this.IsRunning, ref this.isRunning, value); }
        }

        public bool IsFeatureDirectoryValid
        {
            get { return this.isFeatureDirectoryValid; }

            set { this.Set(() => this.IsFeatureDirectoryValid, ref this.isFeatureDirectoryValid, value); }
        }

        public bool IsDocumentationFormatValid
        {
            get { return this.isDocumentationFormatValid; }

            set { this.Set(() => this.IsDocumentationFormatValid, ref this.isDocumentationFormatValid, value); }
        }

        public bool IsOutputDirectoryValid
        {
            get { return this.isOutputDirectoryValid; }
            set { this.Set(() => this.IsOutputDirectoryValid, ref this.isOutputDirectoryValid, value); }
        }

        public bool IsProjectNameValid
        {
            get { return this.isProjectNameValid; }
            set { this.Set(() => this.IsProjectNameValid, ref this.isProjectNameValid, value); }
        }

        public bool IsProjectVersionValid
        {
            get { return this.isProjectVersionValid; }
            set { this.Set(() => this.IsProjectVersionValid, ref this.isProjectVersionValid, value); }
        }

        public bool IsTestResultsFileValid
        {
            get { return this.isTestResultsFileValid; }
            set { this.Set(() => this.IsTestResultsFileValid, ref this.isTestResultsFileValid, value); }
        }

        public bool IsTestResultsFormatValid
        {
            get { return this.isTestResultsFormatValid; }
            set { this.Set(() => this.IsTestResultsFormatValid, ref this.isTestResultsFormatValid, value); }
        }

        public bool IsLanguageValid
        {
            get { return this.isLanguageValid; }
            set { this.Set(() => this.IsLanguageValid, ref this.isLanguageValid, value); }
        }

        public bool CreateDirectoryForEachOutputFormat
        {
            get { return this.createDirectoryForEachOutputFormat; }
            set { this.Set(() => this.CreateDirectoryForEachOutputFormat, ref this.createDirectoryForEachOutputFormat, value); }
        }

        public bool IncludeExperimentalFeatures
        {
            get { return this.includeExperimentalFeatures; }
            set { this.Set(nameof(this.IncludeExperimentalFeatures), ref this.includeExperimentalFeatures, value); }
        }

        public void SaveToSettings()
        {
            MainModel mainModel = new MainModel
            {
                FeatureDirectory = this.featureFolder,
                OutputDirectory = this.outputFolder,
                ProjectName = this.projectName,
                ProjectVersion = this.projectVersion,
                IncludeTestResults = this.includeTests,
                TestResultsFile = this.testResultsFile,
                TestResultsFormat = this.SelectedTestResultsFormat,
                SelectedLanguageLcid = this.selectedLanguage.LCID,
                DocumentationFormats =
                    this.documentationFormats.Where(item => item.IsSelected).Select(item => item.Item).ToArray(),
                CreateDirectoryForEachOutputFormat = this.createDirectoryForEachOutputFormat,
                IncludeExperimentalFeatures = this.includeExperimentalFeatures
            };

            this.mainModelSerializer.Write(mainModel);
        }

        public void LoadFromSettings()
        {
            MainModel mainModel = this.mainModelSerializer.Read();

            if (mainModel == null)
            {
                return;
            }

            this.FeatureFolder = mainModel.FeatureDirectory;
            this.OutputFolder = mainModel.OutputDirectory;
            this.ProjectName = mainModel.ProjectName;
            this.ProjectVersion = mainModel.ProjectVersion;
            this.IncludeTests = mainModel.IncludeTestResults;
            this.TestResultsFile = mainModel.TestResultsFile;

            this.SelectedTestResultsFormat =
                this.testResultsFormats.Where(tf => tf == mainModel.TestResultsFormat).FirstOrDefault();

            this.SelectedLanguage =
                this.neutralCultures.Where(lv => lv.LCID == mainModel.SelectedLanguageLcid).FirstOrDefault();

            foreach (var item in this.documentationFormats)
            {
                item.IsSelected = mainModel.DocumentationFormats.Contains(item.Item);
            }

            this.CreateDirectoryForEachOutputFormat = mainModel.CreateDirectoryForEachOutputFormat;
            this.IncludeExperimentalFeatures = mainModel.IncludeExperimentalFeatures;
        }

        private void DocumentationFormatsOnCollectionChanged(object sender, EventArgs notifyCollectionChangedEventArgs)
        {
            this.IsDocumentationFormatValid = this.documentationFormats.Selected.Any();
        }

        private void MainWindowViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "FeatureFolder":
                {
                    if (this.fileSystem.Directory.Exists(this.featureFolder))
                    {
                        this.IsFeatureDirectoryValid = true;
                    }
                    else
                    {
                        this.IsFeatureDirectoryValid = false;
                    }

                    break;
                }

                case "OutputFolder":
                {
                    if (this.fileSystem.Directory.Exists(this.outputFolder))
                    {
                        this.IsOutputDirectoryValid = true;
                    }
                    else
                    {
                        this.IsOutputDirectoryValid = false;
                    }

                    this.openOutputDirectory.RaiseCanExecuteChanged();

                    break;
                }

                case "TestResultsFile":
                {
                    if (this.testResultsFile == null ||
                        this.testResultsFile.Split(';').All(trf => this.fileSystem.File.Exists(trf)))
                    {
                        this.IsTestResultsFileValid = true;
                    }
                    else
                    {
                        this.IsTestResultsFileValid = false;
                    }

                    break;
                }

                case "ProjectName":
                {
                    this.IsProjectNameValid = !string.IsNullOrWhiteSpace(this.projectName);
                    break;
                }

                case "ProjectVersion":
                {
                    this.IsProjectVersionValid = !string.IsNullOrWhiteSpace(this.projectVersion);
                    break;
                }

                case "SelectedTestResultsFormat":
                {
                    this.IsTestResultsFormatValid = Enum.IsDefined(typeof(TestResultsFormat), this.selectedTestResultsFormat);
                    break;
                }

                case "IsRunning":
                case "IsFeatureDirectoryValid":
                case "IsOutputDirectoryValid":
                case "IsProjectNameValid":
                case "IsProjectVersionValid":
                case "IsTestResultsFileValid":
                case "IsTestResultsFormatValid":
                case "IsLanguageValid":
                case "IncludeTests":
                case "IsDocumentationFormatValid":
                {
                    this.generateCommand.RaiseCanExecuteChanged();
                    break;
                }
            }
        }

        private bool CanGenerate()
        {
            return !this.isRunning
                   && this.isFeatureDirectoryValid
                   && this.isOutputDirectoryValid
                   && this.isProjectNameValid
                   && this.isProjectVersionValid
                   && (this.isTestResultsFileValid || !this.includeTests)
                   && (this.isTestResultsFormatValid || !this.includeTests)
                   && this.isDocumentationFormatValid
                   && this.isLanguageValid;
        }

        private void DoGenerate()
        {
            this.IsRunning = true;

            var backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += (sender, args) => this.DoWork();
            backgroundWorker.RunWorkerCompleted += (sender, args) =>
            {
                this.IsRunning = false;
            };
            backgroundWorker.RunWorkerAsync();
        }

        private void DoWork()
        {
            foreach (DocumentationFormat documentationFormat in this.documentationFormats.Selected)
            {
                var builder = new ContainerBuilder();
                builder.RegisterAssemblyTypes(typeof(Runner).Assembly);
                builder.Register<IFileSystem>(_ => this.fileSystem).SingleInstance();
                builder.RegisterModule<PicklesModule>();
                var container = builder.Build();

                var configuration = container.Resolve<IConfiguration>();

                configuration.FeatureFolder = this.fileSystem.DirectoryInfo.FromDirectoryName(this.featureFolder);

                if (this.createDirectoryForEachOutputFormat)
                {
                    configuration.OutputFolder =
                        this.fileSystem.DirectoryInfo.FromDirectoryName(
                            this.fileSystem.Path.Combine(
                                this.outputFolder,
                                documentationFormat.ToString("G")));
                }
                else
                {
                    configuration.OutputFolder = this.fileSystem.DirectoryInfo.FromDirectoryName(this.outputFolder);
                }

                configuration.SystemUnderTestName = this.projectName;
                configuration.SystemUnderTestVersion = this.projectVersion;
                configuration.AddTestResultFiles(this.IncludeTests
                    ? this.testResultsFile.Split(';').Select(trf => this.fileSystem.FileInfo.FromFileName(trf)).ToArray()
                    : null);
                configuration.TestResultsFormat = this.selectedTestResultsFormat;
                configuration.Language = this.selectedLanguage != null
                    ? this.selectedLanguage.TwoLetterISOLanguageName
                    : CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;

                configuration.DocumentationFormat = documentationFormat;

                if (this.includeExperimentalFeatures)
                {
                    configuration.EnableExperimentalFeatures();
                }
                else
                {
                    configuration.DisableExperimentalFeatures();
                }

                var runner = container.Resolve<Runner>();
                runner.Run(container);
            }
        }

        private void DoBrowseForTestResultsFile()
        {
            var dlg = new Ookii.Dialogs.Wpf.VistaOpenFileDialog();
            dlg.Multiselect = true;
            var result = dlg.ShowDialog();
            if (result == true)
            {
                this.TestResultsFile = string.Join(";", dlg.FileNames);
            }
        }

        private void DoBrowseForFeature()
        {
            var dlg = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
            var result = dlg.ShowDialog();
            if (result == true)
            {
                this.FeatureFolder = dlg.SelectedPath;
            }
        }

        private void DoBrowseForOutputFolder()
        {
            var dlg = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
            var result = dlg.ShowDialog();
            if (result == true)
            {
                this.OutputFolder = dlg.SelectedPath;
            }
        }

        private void DoOpenOutputDirectory()
        {
            Process.Start(this.outputFolder);
        }

        private bool CanOpenOutputDirectory()
        {
            return this.isOutputDirectoryValid;
        }
    }
}


text:
module Sql.Sessions where

import Data.List (intersperse)
import Data.Time.Clock
import Database.HDBC
import Database.HDBC.Sqlite3
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe

import Types
import Sql.Utils

newSession :: Connection -> UID -> Token -> UTCTime -> IO (Maybe SessionToken)
newSession c uid token time = do
    run c "INSERT INTO \
        \sessions (uid,token,expiration_date) \
        \VALUES (?,?,?)"
        [toSql uid, toSql token, toSql time]
    runMaybeT $ do
        sid <- MaybeT $ lastRowId c
        lift $ commit c
        return $ SessionToken sid token

updateSession :: Connection -> SID -> String -> UTCTime -> IO ()
updateSession c sid token expiration = do
    run c "UPDATE sessions \
        \SET token=?,expiration_date=? \
        \WHERE id=?"
        [toSql token,toSql expiration,toSql sid]
    commit c

openSessions :: Connection -> UID -> IO [(SID,UTCTime)]
openSessions c uid = do
    res <- quickQuery c "SELECT id, expiration_date \
        \FROM sessions \
        \WHERE uid=?"
        [toSql uid]
    return $ map (\[sid,time] -> (fromSql sid,fromSql time)) res

deleteSessions :: Connection -> [SID] -> IO (Maybe ())
deleteSessions c sids = runMaybeT $ do
    guard . not . null $ sids
    s <- return $   "DELETE FROM sessions WHERE "
            ++ (concat $
            intersperse "OR" [" id=? " | sid <- sids])
    lift $ run c s (map toSql sids)
    lift $ commit c

getUIDAndExpiration :: Connection -> SessionToken -> IO (Maybe (UID,UTCTime))
getUIDAndExpiration c (SessionToken sid token) = do
    res <- fetch c "SELECT uid,expiration_date \
        \FROM sessions \
        \WHERE id=? AND token=?"
        [toSql sid,toSql token]
    return $ fmap (\[uid,t] -> (fromSql uid, fromSql t)) res

getExpiration :: Connection -> SessionToken -> IO (Maybe UTCTime)
getExpiration c (SessionToken sid token) = do
    res <- fetch c "SELECT expiration_date \
            \FROM sessions \
            \WHERE id=? AND token=?"
            [toSql sid, toSql token]
    case res of
        Just [time] -> return $ Just (fromSql time)
        _ -> return Nothing


text:
package api

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/muka/redzilla/docker"
	"github.com/muka/redzilla/model"
	"github.com/muka/redzilla/storage"
	"github.com/sirupsen/logrus"
)

const instanceCollection = "instances"

var instancesCache = make(map[string]*Instance)

//ListInstances list available instances
func ListInstances(cfg *model.Config) (*[]model.Instance, error) {

	store := storage.GetStore(instanceCollection, cfg)

	jsonlist, err := store.List()
	if err != nil {
		return nil, fmt.Errorf("store.List: %s", err)
	}

	list := make([]model.Instance, 0)
	for _, jsonstr := range jsonlist {
		item := new(model.Instance)
		err = json.Unmarshal([]byte(jsonstr), item)
		if err != nil {
			return nil, err
		}
		list = append(list, *item)
	}

	logrus.Debugf("Found %d instances", len(list))
	return &list, err
}

// GetInstance return a instance from the cache if available
func GetInstance(name string, cfg *model.Config) *Instance {
	if _, ok := instancesCache[name]; !ok {
		instancesCache[name] = NewInstance(name, cfg)
	}
	return instancesCache[name]
}

// NewInstance new instance api
func NewInstance(name string, cfg *model.Config) *Instance {

	datadir := storage.GetInstancesDataPath(name, cfg)
	storage.CreateDir(datadir)

	instanceLogger, err := NewInstanceLogger(name, datadir)
	if err != nil {
		logrus.Errorf("Failed to initialize instance %s logger at %s", name, datadir)
		panic(err)
	}

	i := Instance{
		instance:   model.NewInstance(name),
		cfg:        cfg,
		store:      storage.GetStore(instanceCollection, cfg),
		logger:     instanceLogger,
		logContext: NewInstanceContext(),
	}

	// TODO add support to port mapping (eg. MQTT)
	i.instance.Port = NodeRedPort

	return &i
}

//NewInstanceContext craeate a new instance context
func NewInstanceContext() *InstanceContext {
	ctx, cancel := context.WithCancel(context.Background())
	return &InstanceContext{
		context: ctx,
		cancel:  cancel,
	}
}

//InstanceContext tracks internal context for the instance
type InstanceContext struct {
	context context.Context
	cancel  context.CancelFunc
}

//Cancel the instance level context
func (c *InstanceContext) Cancel() {
	c.cancel()
}

//GetContext return the real context reference
func (c *InstanceContext) GetContext() context.Context {
	return c.context
}

//Instance API
type Instance struct {
	instance   *model.Instance
	cfg        *model.Config
	store      *storage.Store
	logger     *InstanceLogger
	logContext *InstanceContext
}

//Save instance status
func (i *Instance) Save() error {

	logrus.Debugf("Saving instance state %s", i.instance.Name)

	err := i.store.Save(i.instance.Name, i.instance)
	if err != nil {
		return err
	}

	return nil
}

//Create instance without starting
func (i *Instance) Create() error {

	logrus.Debugf("Creating instance %s", i.instance.Name)

	err := i.Save()
	if err != nil {
		return err
	}

	return nil
}

//Start an instance creating a record for if it does not exists
func (i *Instance) Start() error {

	logrus.Debugf("Starting instance %s", i.instance.Name)

	err := i.Save()
	if err != nil {
		return err
	}

	err = docker.StartContainer(i.instance.Name, i.cfg)
	if err != nil {
		return fmt.Errorf("StartContainer: %s", err)
	}

	_, err = i.GetIP()
	if err != nil {
		return fmt.Errorf("GetIP: %s", err)
	}

	return nil
}

//Remove instance and stop it if running
func (i *Instance) Remove() error {

	err := i.Stop()
	if err != nil {
		return err
	}

	err = i.store.Delete(i.instance.Name)
	if err != nil {
		return err
	}

	return nil
}

//Stop instance without removing
func (i *Instance) Stop() error {

	logrus.Debugf("Stopping instance %s", i.instance.Name)

	err := docker.StopContainer(i.instance.Name, false)
	if err != nil {
		return err
	}

	return nil
}

//GetStatus return the current instance known status
func (i *Instance) GetStatus() *model.Instance {
	return i.instance
}

//Exists check if the instance has been stored
func (i *Instance) Exists() (bool, error) {

	logrus.Debugf("Check if instance %s exists", i.instance.Name)

	dbInstance := new(model.Instance)
	err := i.store.Load(i.instance.Name, dbInstance)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}

	return true, nil
}

//IsRunning check if the instance is running
func (i *Instance) IsRunning() (bool, error) {

	if i.instance.Status == model.InstanceStarted {
		return true, nil
	}

	info, err := docker.GetContainer(i.instance.Name)
	if err != nil {
		return false, err
	}

	running := info.ContainerJSONBase != nil
	if running {
		i.instance.Status = model.InstanceStarted
	} else {
		i.instance.Status = model.InstanceStopped
	}

	return running, nil
}

//Restart instance
func (i *Instance) Restart() error {
	err := i.Stop()
	if err != nil {
		return fmt.Errorf("Stop: %s", err)
	}
	return i.Start()
}

//Reset reset container runtime information
func (i *Instance) Reset() error {

	i.instance.IP = ""
	i.instance.Status = model.InstanceStopped

	return nil
}


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, The University of Chicago -
*  Argonne National Laboratory, Emory University, SemanticBits LLC,
*  and Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.notification;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;

/**
 * Base Events based notifier class.
 * Implemtntations will handle specefic event types
 * <p/>
 * User: kherm
 *
 * @author kherm manav.kher@semanticbits.com
 */
public abstract class AbstractNotifier implements ApplicationListener {

    private NotificationSender notificationSender;

    protected final Log logger = LogFactory
            .getLog(getClass());

    public NotificationSender getNotificationSender() {
        return notificationSender;
    }

    public void setNotificationSender(NotificationSender notificationSender) {
        this.notificationSender = notificationSender;
    }
}


text:
module ActiveAdmin

  class Resource
    module Attributes

      def default_attributes
        resource_class.columns.each_with_object({}) do |c, attrs|
          unless reject_col?(c)
            name = c.name.to_sym
            attrs[name] = (method_for_column(name) || name)
          end
        end
      end

      def method_for_column(c)
        resource_class.respond_to?(:reflect_on_all_associations) && foreign_methods.has_key?(c) && foreign_methods[c].name.to_sym
      end

      def foreign_methods
        @foreign_methods ||= resource_class.reflect_on_all_associations.
          select { |r| r.macro == :belongs_to }.
          reject { |r| r.chain.length > 2 && !r.options[:polymorphic] }.
          index_by { |r| r.foreign_key.to_sym }
      end

      def reject_col?(c)
        primary_col?(c) || sti_col?(c) || counter_cache_col?(c) || filtered_col?(c)
      end

      def primary_col?(c)
        c.name == resource_class.primary_key
      end

      def sti_col?(c)
        c.name == resource_class.inheritance_column
      end

      def counter_cache_col?(c)
        c.name.end_with?('_count')
      end

      def filtered_col?(c)
        ActiveAdmin.application.filter_attributes.include?(c.name.to_sym)
      end
    end
  end
end


text:
set -e
set -u

if [ -e ../../configure.sh ]; then
    source ../../configure.sh
elif [ -e ../configure.sh ]; then
    source ../configure.sh
elif [ -e ./configure.sh ]; then
    source ./configure.sh
else
    echo "Error: Could not find 'configure.sh'!"
    exit 1
fi

if check_number $1; then
    echo "Usage: run-debug.sh <image ID> [<architecture>]"
    exit 1
fi
IID=${1}

if [ $# -gt 1 ]; then
    if check_arch "${2}"; then
        echo "Error: Invalid architecture!"
        exit 1
    fi

    ARCH=${2}
else
    echo -n "Querying database for architecture... "
    ARCH=$(psql -d firmware -U firmadyne -h 127.0.0.1 -t -q -c "SELECT arch from image WHERE id=${1};")
    ARCH="${ARCH#"${ARCH%%[![:space:]]*}"}"
    echo "${ARCH}"
    if [ -z "${ARCH}" ]; then
        echo "Error: Unable to lookup architecture. Please specify {armel,mipseb,mipsel} as the second argument!"
        exit 1
    fi
fi

${VM_SCRIPT_DIR}/run.${ARCH}-debug.sh ${IID}


text:
<?php
/* @var $this yii\web\View */
$this->title = 'SMA Taman Harapan MALANG - Sekolah Standart Nasional Akreditasi A';

//use common\models\ProductStock;
use common\models\Article;

$session = Yii::$app->session;
?>

                    <?php $sambutan = Article::findOne(['id' => 19]); ?>

                                <?= $sambutan->title ?>

                                    <button class="button-xs b-btn-title-real-estate f-primary-b">SMA Taman Harapan</button>
                                    IBU SUTIANI, S.Pd, MM

                            <img src="<?php echo Yii::$app->homeUrl . 'images/article/' . $sambutan->primary_image; ?>" align="left" style="width:170px; margin-right:10px" class="img-thumbnail"/>
                            <?php echo $sambutan->content; ?>

Informasi Terbaru

                            <?php
                            $news = Article::find()
                                    ->where([
                                        'publish' => 1,
                                        'article_category_id' => ['14','10']
                                    ])
                                    ->orderBy('created DESC')
                                    ->limit(5)
                                    ->all();

                            foreach ($news as $item) {
                                ?>

                                        <img data-retina="" src="<?=$item->imgSmall?>" alt="">

<a href="<?= Yii::$app->urlManager->createUrl('article/' . $item->id) ?>"><?= $item->title ?>

                                            <?= substr(strip_tags($item->content), 0, 25); ?>

                                            <a href="<?= Yii::$app->urlManager->createUrl('article/' . $item->id) ?>" class="b-btn f-btn b-btn-sm f-btn-sm b-btn-default f-primary-b">Selanjutnya

                            <?php } ?>

Sarana & Prasarana

Lapangan Basket

Fasilitas Lapangan basket luas dan bersih

 Kantin

Kantin yang berada di dalam sekolah dengan makanan segar dan fresh

Perpustakaan

Perpustakaan dengan koleksi buku yang lengkap dan mendidik

Taman Hijau

taman hijau dan asri serta nyaman membuat susana menjadi teduh

Lab Bahasa

Lab Bahasa dengan fasilitas lengkap berguna mendukung siswa belajar

Lab Biologi

                                Lab yang ada cukup komplit peralatannya untuk melaksanakan praktek yang akan di ajarkan ke siswa-siswi sehingga mereka dapat mengetahui ilmu biology yang sempurna dengan peralatan-peralatan yang tersedia.

Lab Fisika

Lab. Fisika lengkap beserta alat-alat fisika yang memadai berguna untuk mendukung siswa praktikum

Toilet bersih & nyaman

Toilet di jamin bersih dan nyaman

Ruang UKS

Ruang UKS dengan perlatan P3k lengkap berguna buat penangan pertolongan pertama untuk siswa yang lagi sakit

Majalah Dinding

Majalah Dinding yang selalu update berita dan pengumuman untuk siswa yang di kelolah oleh para siswa sendiri

Ruang Tunggu

Ruang Tunggu yang nyaman berfungsi supaya para tamu bisa nyaman dan tenang

Ruang Fotokopi

Ruang Fotokopi milik sekolah agar siswa tidak perlu keluar sekolah untuk memfoto kopi tugasnya

Ruang Tata Usaha

Sebagai pusat layanan Administrasi sekolah yang mencakup Surat menyurat, Pengarsipan, Layanan tamu dan lain sebagainya

Ruang BP/BK

Ruang BP/BK dibuat senyaman mungkin agar siswa dan guru dapat melakukan konsultasi dengan nyaman juga. Dan Fasilitas Guru BP/BK dapat berfungsi dengan semestinya

Ruang Kelas

                                    Ruang Kelas bersih dan nyaman, seluruh ruang kelas juga dilengkapi dengan fasilitas LCD

Ruang Kepala Sekolah

Ruang Kepala Sekolah baru yang menunjang aktivitas pendidikan.

Ruang Guru

                                Keadaan ruang guru dibuat senyaman mungkin. Bagian depan di berikan fasilitas Meja dan Kursi Tamu, Kemudian Meja Guru seluruhnya menghadap ke depan

                                Contact

                                            SMA Taman Harapan

                                            Jalan Mojopahit no. 1 Malang
(Selatan Balai Kota Malang)

                                            Kode Pos 65119
Jawa Timur

                                            info@smatamanharapan.sch.id

                                            (0341) 362 400


text:
'use strict';

angular.module('myApp.home', ['ngRoute','firebase'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/home', {
    templateUrl: 'home/home.html',
    controller: 'HomeCtrl'
  });
}])

.controller('HomeCtrl', ['$scope','$location','CommonProp','$firebaseAuth',function($scope,$location,CommonProp,$firebaseAuth) {

  var firebaseObj = new Firebase("https://event-manager-app.firebaseio.com/");
  var loginObj = $firebaseAuth(firebaseObj);
  $scope.EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i;

  var login = {};
  $scope.login = login;

  $scope.user = {};
  $scope.SignIn = function(e) {
    e.preventDefault();
    var username = $scope.user.email;
    var password = $scope.user.password;
    login.loading = true;
    loginObj.$authWithPassword({
            email: username,
            password: password
        })
        .then(function(user) {
            //Success callback
            console.log('Authentication successful');
            login.loading = false;
	          CommonProp.setUser(user.password.email);
		        $location.path('/welcome');
        }, function(error) {
            //Failure callback
            login.loading = false;
            console.log('Authentication failure');
        });
};
}])
.service('CommonProp', ['$location','$firebaseAuth', function($location, $firebaseAuth) {
    var user = '';
    var firebaseObj = new Firebase("https://event-manager-app.firebaseio.com/Events");
    var loginObj = $firebaseAuth(firebaseObj);

    return {
        getUser: function() {
          if(user === ''){
            console.log(user);
            user = localStorage.getItem('userEmail');
          }
          return user;
        },
        setUser: function(value) {
          localStorage.setItem("userEmail", value);
          user = value;
        },
        logoutUser:function(){
          loginObj.$unauth();
          user = '';
          localStorage.clear();
          console.log('done logout');
          $location.path('/home');
        }
    };
}]);
// .directive('valid', function() {
//   var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
//   return {
//     link: function(scope, elm) {
//       elm.on("keyup",function(){
//             var isMatchRegex = EMAIL_REGEXP.test(elm.val());
//             if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
//               elm.removeClass('warning');
//             }else if(isMatchRegex == false && !elm.hasClass('warning')){
//               elm.addClass('warning');
//             }
//       });
//     }
//   }
// });


text:
package io.cucumber.gherkin;

class GherkinLineSpan {
    // One-based line position
    public final int column;

    // text part of the line
    public final String text;

    public GherkinLineSpan(int column, String text) {
        this.column = column;
        this.text = text;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GherkinLineSpan that = (GherkinLineSpan) o;
        return column == that.column && text.equals(that.text);
    }

    @Override
    public int hashCode() {
        int result = column;
        result = 31 * result + text.hashCode();
        return result;
    }
}