code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* linux/drivers/media/video/samsung/tv20/s5pv210/hdcp_s5pv210.c * * hdcp raw ftn file for Samsung TVOut driver * * Copyright (c) 2010 Samsung Electronics * http://www.samsungsemi.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/wait.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/irq.h> #include <linux/io.h> #include <plat/gpio-cfg.h> #include <mach/regs-gpio.h> #include <mach/gpio.h> #include <plat/regs-hdmi.h> #include "../ddc.h" #include "tv_out_s5pv210.h" /* for Operation check */ #ifdef CONFIG_TVOUT_RAW_DBG #define S5P_HDCP_DEBUG 1 #define S5P_HDCP_AUTH_DEBUG 1 #endif #ifdef S5P_HDCP_DEBUG #define HDCPPRINTK(fmt, args...) \ printk(KERN_INFO "\t\t[HDCP] %s: " fmt, __func__ , ## args) #else #define HDCPPRINTK(fmt, args...) #endif /* for authentication key check */ #ifdef S5P_HDCP_AUTH_DEBUG #define AUTHPRINTK(fmt, args...) \ printk("\t\t\t[AUTHKEY] %s: " fmt, __func__ , ## args) #else #define AUTHPRINTK(fmt, args...) #endif enum hdmi_run_mode { DVI_MODE = 0, HDMI_MODE }; enum hdmi_resolution { SD480P = 0, SD480I, WWSD480P, HD720P, SD576P, WWSD576P, HD1080I }; enum hdmi_color_bar_type { HORIZONTAL = 0, VERTICAL }; enum hdcp_event { /* Stop HDCP */ HDCP_EVENT_STOP = 0, /* Start HDCP*/ HDCP_EVENT_START, /* Start to read Bksv, Bcaps */ HDCP_EVENT_READ_BKSV_START, /* Start to write Aksv, An */ HDCP_EVENT_WRITE_AKSV_START, /* Start to check if Ri is equal to Rj */ HDCP_EVENT_CHECK_RI_START, /* Start 2nd authentication process */ HDCP_EVENT_SECOND_AUTH_START }; enum hdcp_state { NOT_AUTHENTICATED = 0, RECEIVER_READ_READY, BCAPS_READ_DONE, BKSV_READ_DONE, AN_WRITE_DONE, AKSV_WRITE_DONE, FIRST_AUTHENTICATION_DONE, SECOND_AUTHENTICATION_RDY, RECEIVER_FIFOLSIT_READY, SECOND_AUTHENTICATION_DONE, }; /* * Below CSC_TYPE is temporary. CSC_TYPE enum. * may be included in SetSD480pVars_60Hz etc. * * LR : Limited Range (16~235) * FR : Full Range (0~255) */ enum hdmi_intr_src { WAIT_FOR_ACTIVE_RX = 0, WDT_FOR_REPEATER, EXCHANGE_KSV, UPDATE_P_VAL, UPDATE_R_VAL, AUDIO_OVERFLOW, AUTHEN_ACK, UNKNOWN_INT }; struct s5p_hdcp_info { bool is_repeater; bool hpd_status; u32 time_out; u32 hdcp_enable; spinlock_t lock; spinlock_t reset_lock; struct i2c_client *client; wait_queue_head_t waitq; enum hdcp_event event; enum hdcp_state auth_status; struct work_struct work; }; static struct s5p_hdcp_info hdcp_info = { .is_repeater = false, .time_out = 0, .hdcp_enable = false, .client = NULL, .event = HDCP_EVENT_STOP, .auth_status = NOT_AUTHENTICATED, }; #define HDCP_RI_OFFSET 0x08 #define INFINITE 0xffffffff #define HDMI_SYS_ENABLE (1 << 0) #define HDMI_ASP_ENABLE (1 << 2) #define HDMI_ASP_DISABLE (~HDMI_ASP_ENABLE) #define MAX_DEVS_EXCEEDED (0x1 << 7) #define MAX_CASCADE_EXCEEDED (0x1 << 3) #define MAX_CASCADE_EXCEEDED_ERROR (-1) #define MAX_DEVS_EXCEEDED_ERROR (-2) #define REPEATER_ILLEGAL_DEVICE_ERROR (-3) #define REPEATER_TIMEOUT_ERROR (-4) #define AINFO_SIZE 1 #define BCAPS_SIZE 1 #define BSTATUS_SIZE 2 #define SHA_1_HASH_SIZE 20 #define KSV_FIFO_READY (0x1 << 5) /* spmoon for test : it's not in manual */ #define SET_HDCP_KSV_WRITE_DONE (0x1 << 3) #define CLEAR_HDCP_KSV_WRITE_DONE (~SET_HDCP_KSV_WRITE_DONE) #define SET_HDCP_KSV_LIST_EMPTY (0x1 << 2) #define CLEAR_HDCP_KSV_LIST_EMPTY (~SET_HDCP_KSV_LIST_EMPTY) #define SET_HDCP_KSV_END (0x1 << 1) #define CLEAR_HDCP_KSV_END (~SET_HDCP_KSV_END) #define SET_HDCP_KSV_READ (0x1 << 0) #define CLEAR_HDCP_KSV_READ (~SET_HDCP_KSV_READ) #define SET_HDCP_SHA_VALID_READY (0x1 << 1) #define CLEAR_HDCP_SHA_VALID_READY (~SET_HDCP_SHA_VALID_READY) #define SET_HDCP_SHA_VALID (0x1 << 0) #define CLEAR_HDCP_SHA_VALID (~SET_HDCP_SHA_VALID) #define TRANSMIT_EVERY_VSYNC (0x1 << 1) /* must be checked */ static bool g_sw_reset; static bool g_is_dvi; static bool g_av_mute; static bool g_audio_en; /* * 1st Authentication step func. * Write the Ainfo data to Rx */ static bool write_ainfo(void) { int ret = 0; u8 ainfo[2]; ainfo[0] = HDCP_Ainfo; ainfo[1] = 0; ret = ddc_write(ainfo, 2); if (ret < 0) { pr_err("%s::Can't write ainfo data through i2c bus\n", __func__); } return (ret < 0) ? false : true; } /* * Write the An data to Rx */ static bool write_an(void) { int ret = 0; u8 an[AN_SIZE+1]; an[0] = HDCP_An; an[1] = readb(g_hdmi_base + S5P_HDCP_An_0_0); an[2] = readb(g_hdmi_base + S5P_HDCP_An_0_1); an[3] = readb(g_hdmi_base + S5P_HDCP_An_0_2); an[4] = readb(g_hdmi_base + S5P_HDCP_An_0_3); an[5] = readb(g_hdmi_base + S5P_HDCP_An_1_0); an[6] = readb(g_hdmi_base + S5P_HDCP_An_1_1); an[7] = readb(g_hdmi_base + S5P_HDCP_An_1_2); an[8] = readb(g_hdmi_base + S5P_HDCP_An_1_3); ret = ddc_write(an, AN_SIZE + 1); if (ret < 0) { pr_err("%s::Can't write an data through i2c bus\n", __func__); } #ifdef S5P_HDCP_AUTH_DEBUG { u16 i = 0; for (i = 1; i < AN_SIZE + 1; i++) AUTHPRINTK("HDCPAn[%d]: 0x%x\n", i, an[i]); } #endif return (ret < 0) ? false : true; } /* * Write the Aksv data to Rx */ static bool write_aksv(void) { int ret = 0; u8 aksv[AKSV_SIZE+1]; aksv[0] = HDCP_Aksv; aksv[1] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_0); aksv[2] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_1); aksv[3] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_2); aksv[4] = readb(g_hdmi_base + S5P_HDCP_AKSV_0_3); aksv[5] = readb(g_hdmi_base + S5P_HDCP_AKSV_1); if (aksv[1] == 0 && aksv[2] == 0 && aksv[3] == 0 && aksv[4] == 0 && aksv[5] == 0) return false; ret = ddc_write(aksv, AKSV_SIZE + 1); if (ret < 0) { pr_err("%s::Can't write aksv data through i2c bus\n", __func__); } #ifdef S5P_HDCP_AUTH_DEBUG { u16 i = 0; for (i = 1; i < AKSV_SIZE + 1; i++) AUTHPRINTK("HDCPAksv[%d]: 0x%x\n", i, aksv[i]); } #endif return (ret < 0) ? false : true; } static bool read_bcaps(void) { int ret = 0; u8 bcaps[BCAPS_SIZE] = {0}; ret = ddc_read(HDCP_Bcaps, bcaps, BCAPS_SIZE); if (ret < 0) { pr_err("%s::Can't read bcaps data from i2c bus\n", __func__); return false; } writel(bcaps[0], g_hdmi_base + S5P_HDCP_BCAPS); HDCPPRINTK("BCAPS(from i2c) : 0x%08x\n", bcaps[0]); if (bcaps[0] & REPEATER_SET) hdcp_info.is_repeater = true; else hdcp_info.is_repeater = false; HDCPPRINTK("attached device type : %s !!\n", hdcp_info.is_repeater ? "REPEATER" : "SINK"); HDCPPRINTK("BCAPS(from sfr) = 0x%08x\n", readl(g_hdmi_base + S5P_HDCP_BCAPS)); return true; } static bool read_again_bksv(void) { u8 bk_sv[BKSV_SIZE] = {0, 0, 0, 0, 0}; u8 i = 0; u8 j = 0; u32 no_one = 0; u32 no_zero = 0; u32 result = 0; int ret = 0; ret = ddc_read(HDCP_Bksv, bk_sv, BKSV_SIZE); if (ret < 0) { pr_err("%s::Can't read bk_sv data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("i2c read : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif for (i = 0; i < BKSV_SIZE; i++) { for (j = 0; j < 8; j++) { result = bk_sv[i] & (0x1 << j); if (result == 0) no_zero += 1; else no_one += 1; } } if ((no_zero == 20) && (no_one == 20)) { HDCPPRINTK("Suucess: no_zero, and no_one is 20\n"); writel(bk_sv[0], g_hdmi_base + S5P_HDCP_BKSV_0_0); writel(bk_sv[1], g_hdmi_base + S5P_HDCP_BKSV_0_1); writel(bk_sv[2], g_hdmi_base + S5P_HDCP_BKSV_0_2); writel(bk_sv[3], g_hdmi_base + S5P_HDCP_BKSV_0_3); writel(bk_sv[4], g_hdmi_base + S5P_HDCP_BKSV_1); #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("set reg : Bksv[%d]: 0x%x\n", i, bk_sv[i]); /* writel(HDCP_ENC_ENABLE, g_hdmi_base + S5P_ENC_EN); */ #endif return true; } else { pr_err("%s::no_zero or no_one is NOT 20\n", __func__); return false; } } static bool read_bksv(void) { u8 bk_sv[BKSV_SIZE] = {0, 0, 0, 0, 0}; int i = 0; int j = 0; u32 no_one = 0; u32 no_zero = 0; u32 result = 0; u32 count = 0; int ret = 0; ret = ddc_read(HDCP_Bksv, bk_sv, BKSV_SIZE); if (ret < 0) { pr_err("%s::Can't read bk_sv data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("i2c read : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif for (i = 0; i < BKSV_SIZE; i++) { for (j = 0; j < 8; j++) { result = bk_sv[i] & (0x1 << j); if (result == 0) no_zero++; else no_one++; } } if ((no_zero == 20) && (no_one == 20)) { writel(bk_sv[0], g_hdmi_base + S5P_HDCP_BKSV_0_0); writel(bk_sv[1], g_hdmi_base + S5P_HDCP_BKSV_0_1); writel(bk_sv[2], g_hdmi_base + S5P_HDCP_BKSV_0_2); writel(bk_sv[3], g_hdmi_base + S5P_HDCP_BKSV_0_3); writel(bk_sv[4], g_hdmi_base + S5P_HDCP_BKSV_1); #ifdef S5P_HDCP_AUTH_DEBUG for (i = 0; i < BKSV_SIZE; i++) AUTHPRINTK("set reg : Bksv[%d]: 0x%x\n", i, bk_sv[i]); #endif HDCPPRINTK("Success: no_zero, and no_one is 20\n"); } else { HDCPPRINTK("Failed: no_zero or no_one is NOT 20\n"); while (!read_again_bksv()) { count++; mdelay(200); if (count == 14) return false; } } return true; } /* * Compare the R value of Tx with that of Rx */ static bool compare_r_val(void) { int ret = 0; u8 ri[2] = {0, 0}; u8 rj[2] = {0, 0}; u16 i; for (i = 0; i < R_VAL_RETRY_CNT; i++) { if (hdcp_info.auth_status < AKSV_WRITE_DONE) { ret = false; break; } /* Read R value from Tx */ ri[0] = readl(g_hdmi_base + S5P_HDCP_Ri_0); ri[1] = readl(g_hdmi_base + S5P_HDCP_Ri_1); /* Read R value from Rx */ ret = ddc_read(HDCP_Ri, rj, 2); if (ret < 0) { pr_err("%s::Can't read r data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_AUTH_DEBUG AUTHPRINTK("retries :: %d\n", i); printk("\t\t\t Rx(ddc)\t ->"); printk("rj[0]: 0x%02x, rj[1]: 0x%02x\n", rj[0], rj[1]); printk("\t\t\t Tx(register)\t ->"); printk("ri[0]: 0x%02x, ri[1]: 0x%02x\n", ri[0], ri[1]); #endif /* Compare R value */ if ((ri[0] == rj[0]) && (ri[1] == rj[1]) && (ri[0] | ri[1])) { writel(Ri_MATCH_RESULT__YES, g_hdmi_base + S5P_HDCP_CHECK_RESULT); HDCPPRINTK("R0, R0' is matched!!\n"); /* for simplay test */ mdelay(1); ret = true; break; } else { writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); HDCPPRINTK("R0, R0' is not matched!!\n"); ret = false; } ri[0] = 0; ri[1] = 0; rj[0] = 0; rj[1] = 0; } if (!ret) { hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; } return ret ? true : false; } /* * Enable/Disable Software HPD control */ static void sw_hpd_enable(bool enable) { u8 reg; reg = readb(g_hdmi_base + S5P_HPD); reg &= ~HPD_SW_ENABLE; if (enable) writeb(reg | HPD_SW_ENABLE, g_hdmi_base + S5P_HPD); else writeb(reg, g_hdmi_base + S5P_HPD); } /* * Set Software HPD level * * @param level [in] if 0 - low;othewise, high */ static void set_sw_hpd(bool level) { u8 reg; reg = readb(g_hdmi_base + S5P_HPD); reg &= ~HPD_ON; if (level) writeb(reg | HPD_ON, g_hdmi_base + S5P_HPD); else writeb(reg, g_hdmi_base + S5P_HPD); } /* * Reset Authentication */ static void reset_authentication(void) { u8 reg; spin_lock_irq(&hdcp_info.reset_lock); hdcp_info.time_out = INFINITE; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; /* Disable hdcp */ writeb(0x0, g_hdmi_base + S5P_HDCP_CTRL1); writeb(0x0, g_hdmi_base + S5P_HDCP_CTRL2); s5p_hdmi_mute_en(true); /* Disable encryption */ HDCPPRINTK("Stop Encryption by reset!!\n"); writeb(HDCP_ENC_DIS, g_hdmi_base + S5P_ENC_EN); HDCPPRINTK("Now reset authentication\n"); /* disable hdmi status enable reg. */ reg = readb(g_hdmi_base + S5P_STATUS_EN); reg &= HDCP_STATUS_DIS_ALL; writeb(reg, g_hdmi_base + S5P_STATUS_EN); /* clear all result */ writeb(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); /* * 1. Mask HPD plug and unplug interrupt * disable HPD INT */ g_sw_reset = true; reg = s5p_hdmi_get_enabled_interrupt(); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); /* for simplay test */ mdelay(50); /* 2. Enable software HPD */ sw_hpd_enable(true); /* 3. Make software HPD logical 0 */ set_sw_hpd(false); /* 4. Make software HPD logical 1 */ set_sw_hpd(true); /* 5. Disable software HPD */ sw_hpd_enable(false); /* 6. Unmask HPD plug and unplug interrupt */ if (reg & 1<<HDMI_IRQ_HPD_PLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_PLUG); if (reg & 1<<HDMI_IRQ_HPD_UNPLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_UNPLUG); g_sw_reset = false; /* clear result */ #if 0 writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); writel(readl(g_hdmi_base + S5P_HDMI_CON_0) & HDMI_DIS, g_hdmi_base + S5P_HDMI_CON_0); writel(readl(g_hdmi_base + S5P_HDMI_CON_0) | HDMI_EN, g_hdmi_base + S5P_HDMI_CON_0); #endif writel(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); /* set hdcp_int enable */ reg = readb(g_hdmi_base + S5P_STATUS_EN); reg |= WTFORACTIVERX_INT_OCCURRED | WATCHDOG_INT_OCCURRED | EXCHANGEKSV_INT_OCCURRED | UPDATE_RI_INT_OCCURRED; writeb(reg, g_hdmi_base + S5P_STATUS_EN); /* HDCP Enable */ writeb(CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); spin_unlock_irq(&hdcp_info.reset_lock); } /* * Set the timing parameter for load e-fuse key. */ /* TODO: must use clk_get for pclk rate */ #define PCLK_D_RATE_FOR_HDCP 166000000 static u32 efuse_ceil(u32 val, u32 time) { u32 res; res = val / time; if (val % time) res += 1; return res; } #if 0 static void hdcp_efuse_timing(void) { u32 time, val; /* TODO: must use clk_get for pclk rate */ time = 1000000000/PCLK_D_RATE_FOR_HDCP; val = efuse_ceil(EFUSE_ADDR_WIDTH, time); writeb(val, g_hdmi_base + S5P_EFUSE_ADDR_WIDTH); val = efuse_ceil(EFUSE_SIGDEV_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SIGDEV_ASSERT); val = efuse_ceil(EFUSE_SIGDEV_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SIGDEV_DEASSERT); val = efuse_ceil(EFUSE_PRCHG_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_PRCHG_ASSERT); val = efuse_ceil(EFUSE_PRCHG_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_PRCHG_DEASSERT); val = efuse_ceil(EFUSE_FSET_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_FSET_ASSERT); val = efuse_ceil(EFUSE_FSET_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_FSET_DEASSERT); val = efuse_ceil(EFUSE_SENSING, time); writeb(val, g_hdmi_base + S5P_EFUSE_SENSING); val = efuse_ceil(EFUSE_SCK_ASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SCK_ASSERT); val = efuse_ceil(EFUSE_SCK_DEASSERT, time); writeb(val, g_hdmi_base + S5P_EFUSE_SCK_DEASSERT); val = efuse_ceil(EFUSE_SDOUT_OFFSET, time); writeb(val, g_hdmi_base + S5P_EFUSE_SDOUT_OFFSET); val = efuse_ceil(EFUSE_READ_OFFSET, time); writeb(val, g_hdmi_base + S5P_EFUSE_READ_OFFSET); } #endif /* * load hdcp key from e-fuse mem. */ static int hdcp_loadkey(void) { u8 status; int time_out = HDMI_TIME_OUT; #if 0 hdcp_efuse_timing(); #endif /* read HDCP key from E-Fuse */ writeb(EFUSE_CTRL_ACTIVATE, g_hdmi_base + S5P_EFUSE_CTRL); do { status = readb(g_hdmi_base + S5P_EFUSE_STATUS); time_out--; } while (!(status & EFUSE_ECC_DONE) && time_out); if (readb(g_hdmi_base + S5P_EFUSE_STATUS) & EFUSE_ECC_FAIL) { pr_err("%s::Can't load key from fuse ctrl.\n", __func__); return -EINVAL; } else { HDCPPRINTK("%s::readb S5P_EFUSE_STATUS for EFUSE_ECC_FAIL: 0\n", __func__); } return 0; } /* * Start encryption */ static void start_encryption(void) { int time_out = HDMI_TIME_OUT; if (readl(g_hdmi_base + S5P_HDCP_CHECK_RESULT) == Ri_MATCH_RESULT__YES) { do { if (readl(g_hdmi_base + S5P_STATUS) & AUTHENTICATED) { writel(HDCP_ENC_ENABLE, g_hdmi_base + S5P_ENC_EN); HDCPPRINTK("Encryption start!!\n"); s5p_hdmi_mute_en(false); break; } else { time_out--; mdelay(1); } } while (time_out); if (time_out <= 0) pr_err("%s::readl S5P_STATUS for AUTHENTICATED fail!!\n", __func__); } else { writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); HDCPPRINTK("Encryption stop!!\n"); } } /* * Check whether Rx is repeater or not */ static int check_repeater(void) { int ret = 0; u8 i = 0; u16 j = 0; u8 bcaps[BCAPS_SIZE] = {0}; u8 status[BSTATUS_SIZE] = {0, 0}; u8 rx_v[SHA_1_HASH_SIZE] = {0}; u8 ksv_list[HDCP_MAX_DEVS*HDCP_KSV_SIZE] = {0}; u32 dev_cnt; u32 stat; bool ksv_fifo_ready = false; memset(rx_v, 0x0, SHA_1_HASH_SIZE); memset(ksv_list, 0x0, HDCP_MAX_DEVS * HDCP_KSV_SIZE); while (j <= 50) { ret = ddc_read(HDCP_Bcaps, bcaps, BCAPS_SIZE); if (ret < 0) { pr_err("%s::Can't read bcaps data from i2c bus\n", __func__); return false; } if (bcaps[0] & KSV_FIFO_READY) { HDCPPRINTK("ksv fifo is ready\n"); ksv_fifo_ready = true; writel(bcaps[0], g_hdmi_base + S5P_HDCP_BCAPS); break; } else { HDCPPRINTK("ksv fifo is not ready\n"); ksv_fifo_ready = false; mdelay(100); j++; } bcaps[0] = 0; } if (!ksv_fifo_ready) return REPEATER_TIMEOUT_ERROR; /* * Check MAX_CASCADE_EXCEEDED * or MAX_DEVS_EXCEEDED indicator */ ret = ddc_read(HDCP_BStatus, status, BSTATUS_SIZE); if (ret < 0) { pr_err("%s::Can't read status data from i2c bus\n", __func__); return false; } /* MAX_CASCADE_EXCEEDED || MAX_DEVS_EXCEEDED */ if (status[1] & MAX_CASCADE_EXCEEDED) { HDCPPRINTK("MAX_CASCADE_EXCEEDED\n"); return MAX_CASCADE_EXCEEDED_ERROR; } else if (status[0] & MAX_DEVS_EXCEEDED) { HDCPPRINTK("MAX_CASCADE_EXCEEDED\n"); return MAX_DEVS_EXCEEDED_ERROR; } writel(status[0], g_hdmi_base + S5P_HDCP_BSTATUS_0); writel(status[1], g_hdmi_base + S5P_HDCP_BSTATUS_1); /* Read KSV list */ dev_cnt = status[0] & 0x7f; HDCPPRINTK("status[0] :0x%08x, status[1] :0x%08x!!\n", status[0], status[1]); if (dev_cnt) { u32 val = 0; /* read ksv */ ret = ddc_read(HDCP_KSVFIFO, ksv_list, dev_cnt * HDCP_KSV_SIZE); if (ret < 0) { pr_err("%s::Can't read ksv fifo!!\n", __func__); return false; } /* write ksv */ for (i = 0; i < dev_cnt - 1; i++) { writel(ksv_list[(i*5) + 0], g_hdmi_base + S5P_HDCP_RX_KSV_0_0); writel(ksv_list[(i*5) + 1], g_hdmi_base + S5P_HDCP_RX_KSV_0_1); writel(ksv_list[(i*5) + 2], g_hdmi_base + S5P_HDCP_RX_KSV_0_2); writel(ksv_list[(i*5) + 3], g_hdmi_base + S5P_HDCP_RX_KSV_0_3); writel(ksv_list[(i*5) + 4], g_hdmi_base + S5P_HDCP_RX_KSV_0_4); mdelay(1); writel(SET_HDCP_KSV_WRITE_DONE, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); mdelay(1); stat = readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); if (!(stat & SET_HDCP_KSV_READ)) return false; HDCPPRINTK("HDCP_RX_KSV_1 = 0x%x\n", readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL)); HDCPPRINTK("i : %d, dev_cnt : %d, val = 0x%08x\n", i, dev_cnt, val); } writel(ksv_list[(i*5) + 0], g_hdmi_base + S5P_HDCP_RX_KSV_0_0); writel(ksv_list[(i*5) + 1], g_hdmi_base + S5P_HDCP_RX_KSV_0_1); writel(ksv_list[(i*5) + 2], g_hdmi_base + S5P_HDCP_RX_KSV_0_2); writel(ksv_list[(i*5) + 3], g_hdmi_base + S5P_HDCP_RX_KSV_0_3); writel(ksv_list[(i*5) + 4], g_hdmi_base + S5P_HDCP_RX_KSV_0_4); mdelay(1); /* end of ksv */ val = SET_HDCP_KSV_END|SET_HDCP_KSV_WRITE_DONE; writel(val, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); HDCPPRINTK("HDCP_RX_KSV_1 = 0x%x\n", readl(g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL)); HDCPPRINTK("i : %d, dev_cnt : %d, val = 0x%08x\n", i, dev_cnt, val); } else { /* mdelay(200); */ writel(SET_HDCP_KSV_LIST_EMPTY, g_hdmi_base + S5P_HDCP_RX_KSV_LIST_CTRL); } /* Read SHA-1 from receiver */ ret = ddc_read(HDCP_SHA1, rx_v, SHA_1_HASH_SIZE); if (ret < 0) { pr_err("%s::Can't read sha_1_hash data from i2c bus\n", __func__); return false; } #ifdef S5P_HDCP_DEBUG for (i = 0; i < SHA_1_HASH_SIZE; i++) HDCPPRINTK("SHA_1 rx :: %x\n", rx_v[i]); #endif /* write SHA-1 to register */ writeb(rx_v[0], g_hdmi_base + S5P_HDCP_RX_SHA1_0_0); writeb(rx_v[1], g_hdmi_base + S5P_HDCP_RX_SHA1_0_1); writeb(rx_v[2], g_hdmi_base + S5P_HDCP_RX_SHA1_0_2); writeb(rx_v[3], g_hdmi_base + S5P_HDCP_RX_SHA1_0_3); writeb(rx_v[4], g_hdmi_base + S5P_HDCP_RX_SHA1_1_0); writeb(rx_v[5], g_hdmi_base + S5P_HDCP_RX_SHA1_1_1); writeb(rx_v[6], g_hdmi_base + S5P_HDCP_RX_SHA1_1_2); writeb(rx_v[7], g_hdmi_base + S5P_HDCP_RX_SHA1_1_3); writeb(rx_v[8], g_hdmi_base + S5P_HDCP_RX_SHA1_2_0); writeb(rx_v[9], g_hdmi_base + S5P_HDCP_RX_SHA1_2_1); writeb(rx_v[10], g_hdmi_base + S5P_HDCP_RX_SHA1_2_2); writeb(rx_v[11], g_hdmi_base + S5P_HDCP_RX_SHA1_2_3); writeb(rx_v[12], g_hdmi_base + S5P_HDCP_RX_SHA1_3_0); writeb(rx_v[13], g_hdmi_base + S5P_HDCP_RX_SHA1_3_1); writeb(rx_v[14], g_hdmi_base + S5P_HDCP_RX_SHA1_3_2); writeb(rx_v[15], g_hdmi_base + S5P_HDCP_RX_SHA1_3_3); writeb(rx_v[16], g_hdmi_base + S5P_HDCP_RX_SHA1_4_0); writeb(rx_v[17], g_hdmi_base + S5P_HDCP_RX_SHA1_4_1); writeb(rx_v[18], g_hdmi_base + S5P_HDCP_RX_SHA1_4_2); writeb(rx_v[19], g_hdmi_base + S5P_HDCP_RX_SHA1_4_3); /* SHA write done, and wait for SHA computation being done */ mdelay(1); /* check authentication success or not */ stat = readb(g_hdmi_base + S5P_HDCP_AUTH_STATUS); HDCPPRINTK("auth status %d\n", stat); if (stat & SET_HDCP_SHA_VALID_READY) { stat = readb(g_hdmi_base + S5P_HDCP_AUTH_STATUS); if (stat & SET_HDCP_SHA_VALID) ret = true; else ret = false; } else { pr_err("%s::SHA not ready 0x%x\n", __func__, stat); ret = false; } /* clear all validate bit */ writeb(0x0, g_hdmi_base + S5P_HDCP_AUTH_STATUS); return ret; } static bool try_read_receiver(void) { u16 i = 0; bool ret = false; s5p_hdmi_mute_en(true); for (i = 0; i < 400; i++) { msleep(250); if (hdcp_info.auth_status != RECEIVER_READ_READY) { pr_err("%s::hdcp stat. changed!!\ failed attempt no = %d\n", __func__, i); return false; } ret = read_bcaps(); if (ret) { HDCPPRINTK("succeeded at attempt no= %d\n", i); return true; } else pr_err("%s::can't read bcaps!! \ failed attempt no=%d\n", __func__, i); } return false; } static void s5p_hdcp_reset(void) { s5p_stop_hdcp(); g_hdcp_protocol_status = 2; HDCPPRINTK("HDCP ftn. reset!!\n"); } static void bksv_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_READ_BKSV_START bh\n"); hdcp_info.auth_status = RECEIVER_READ_READY; ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) { pr_err("%s::Can't read bcaps!! retry failed!!\ hdcp ftn. will be stopped\n", __func__); reset_authentication(); return; } } hdcp_info.auth_status = BCAPS_READ_DONE; ret = read_bksv(); if (!ret) { pr_err("%s::Can't read bksv!!\ hdcp ftn. will be reset\n", __func__); reset_authentication(); return; } hdcp_info.auth_status = BKSV_READ_DONE; HDCPPRINTK("authentication status : bksv is done (0x%08x)\n", hdcp_info.auth_status); } static void second_auth_start_bh(void) { u8 count = 0; int reg; bool ret = false; int ret_err; u32 bcaps; HDCPPRINTK("HDCP_EVENT_SECOND_AUTH_START bh\n"); ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) { pr_err("%s::Can't read bcaps!! retry failed!!\ hdcp ftn. will be stopped\n", __func__); reset_authentication(); return; } } bcaps = readl(g_hdmi_base + S5P_HDCP_BCAPS); bcaps &= (KSV_FIFO_READY); if (!bcaps) { HDCPPRINTK("ksv fifo is not ready\n"); do { count++; ret = read_bcaps(); if (!ret) { ret = try_read_receiver(); if (!ret) reset_authentication(); return; } bcaps = readl(g_hdmi_base + S5P_HDCP_BCAPS); bcaps &= (KSV_FIFO_READY); if (bcaps) { HDCPPRINTK("bcaps retries : %d\n", count); break; } mdelay(100); if (!hdcp_info.hdcp_enable) { reset_authentication(); return; } } while (count <= 50); /* wait times exceeded 5 seconds */ if (count > 50) { hdcp_info.time_out = INFINITE; /* * time-out (This bit is only available in a REPEATER) */ writel(readl(g_hdmi_base + S5P_HDCP_CTRL1) | 0x1 << 2, g_hdmi_base + S5P_HDCP_CTRL1); reset_authentication(); return; } } HDCPPRINTK("ksv fifo ready\n"); ret_err = check_repeater(); if (ret_err == true) { u32 flag; hdcp_info.auth_status = SECOND_AUTHENTICATION_DONE; HDCPPRINTK("second authentication done!!\n"); flag = readb(g_hdmi_base + S5P_STATUS); HDCPPRINTK("hdcp state : %s authenticated!!\n", flag & AUTHENTICATED ? "" : "not not"); start_encryption(); } else if (ret_err == false) { /* i2c error */ pr_err("%s::repeater check error!!\n", __func__); reset_authentication(); } else { if (ret_err == REPEATER_ILLEGAL_DEVICE_ERROR) { /* * No need to start the HDCP * in case of invalid KSV (revocation case) */ pr_err("%s::illegal dev. error!!\n", __func__); reg = readl(g_hdmi_base + S5P_HDCP_CTRL2); reg = 0x1; writel(reg, g_hdmi_base + S5P_HDCP_CTRL2); reg = 0x0; writel(reg, g_hdmi_base + S5P_HDCP_CTRL2); hdcp_info.auth_status = NOT_AUTHENTICATED; } else if (ret_err == REPEATER_TIMEOUT_ERROR) { reg = readl(g_hdmi_base + S5P_HDCP_CTRL1); reg |= SET_REPEATER_TIMEOUT; writel(reg, g_hdmi_base + S5P_HDCP_CTRL1); reg &= ~SET_REPEATER_TIMEOUT; writel(reg, g_hdmi_base + S5P_HDCP_CTRL1); hdcp_info.auth_status = NOT_AUTHENTICATED; } else { /* * MAX_CASCADE_EXCEEDED_ERROR * MAX_DEVS_EXCEEDED_ERROR */ pr_err("%s::repeater check error(MAX_EXCEEDED)!!\n", __func__); reset_authentication(); } } } static bool write_aksv_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_WRITE_AKSV_START bh\n"); if (hdcp_info.auth_status != BKSV_READ_DONE) { pr_err("%s::bksv is not ready!!\n", __func__); return false; } ret = write_an(); if (!ret) return false; hdcp_info.auth_status = AN_WRITE_DONE; HDCPPRINTK("an write done!!\n"); ret = write_aksv(); if (!ret) return false; /* * Wait for 100ms. Transmitter must not read * Ro' value sooner than 100ms after writing * Aksv */ mdelay(100); hdcp_info.auth_status = AKSV_WRITE_DONE; HDCPPRINTK("aksv write done!!\n"); return ret; } static bool check_ri_start_bh(void) { bool ret = false; HDCPPRINTK("HDCP_EVENT_CHECK_RI_START bh\n"); if (hdcp_info.auth_status == AKSV_WRITE_DONE || hdcp_info.auth_status == FIRST_AUTHENTICATION_DONE || hdcp_info.auth_status == SECOND_AUTHENTICATION_DONE) { ret = compare_r_val(); if (ret) { if (hdcp_info.auth_status == AKSV_WRITE_DONE) { /* * Check whether HDMI receiver is * repeater or not */ if (hdcp_info.is_repeater) hdcp_info.auth_status = SECOND_AUTHENTICATION_RDY; else { hdcp_info.auth_status = FIRST_AUTHENTICATION_DONE; start_encryption(); } } } else { HDCPPRINTK("authentication reset\n"); reset_authentication(); } HDCPPRINTK("auth_status = 0x%08x\n", hdcp_info.auth_status); return true; } else reset_authentication(); HDCPPRINTK("aksv_write or first/second" " authentication is not done\n"); return false; } /* * bottom half for hdmi interrupt * */ static void hdcp_work(void *arg) { /* HDCPPRINTK("event : 0x%08x\n", hdcp_info.event); */ /* * I2C int. was occurred * for reading Bksv and Bcaps */ if (hdcp_info.event & (1 << HDCP_EVENT_READ_BKSV_START)) { bksv_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_READ_BKSV_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * Watchdog timer int. was occurred * for checking repeater */ if (hdcp_info.event & (1 << HDCP_EVENT_SECOND_AUTH_START)) { second_auth_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_SECOND_AUTH_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * An_Write int. was occurred * for writing Ainfo, An and Aksv */ if (hdcp_info.event & (1 << HDCP_EVENT_WRITE_AKSV_START)) { write_aksv_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_WRITE_AKSV_START); /* spin_unlock_bh(&hdcp_info.lock); */ } /* * Ri int. was occurred * for comparing Ri and Ri'(from HDMI sink) */ if (hdcp_info.event & (1 << HDCP_EVENT_CHECK_RI_START)) { check_ri_start_bh(); /* clear event */ /* spin_lock_bh(&hdcp_info.lock); */ hdcp_info.event &= ~(1 << HDCP_EVENT_CHECK_RI_START); /* spin_unlock_bh(&hdcp_info.lock); */ } } irqreturn_t s5p_hdcp_irq_handler(int irq, void *dev_id) { u32 event = 0; u8 flag; unsigned long spin_flags; event = 0; /* check HDCP Status */ flag = readb(g_hdmi_base + S5P_STATUS); HDCPPRINTK("irq_status : 0x%08x\n", readb(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("hdcp state : %s authenticated!!\n", flag & AUTHENTICATED ? "" : "not"); spin_lock_irqsave(&hdcp_info.lock, spin_flags); /* * processing interrupt * interrupt processing seq. is firstly set event for workqueue, * and interrupt pending clear. 'flag|' was used for preventing * to clear AUTHEN_ACK.- it caused many problem. be careful. */ /* I2C INT */ if (flag & WTFORACTIVERX_INT_OCCURRED) { event |= (1 << HDCP_EVENT_READ_BKSV_START); writeb(flag | WTFORACTIVERX_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_I2C_INT); } /* AN INT */ if (flag & EXCHANGEKSV_INT_OCCURRED) { event |= (1 << HDCP_EVENT_WRITE_AKSV_START); writeb(flag | EXCHANGEKSV_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_AN_INT); } /* RI INT */ if (flag & UPDATE_RI_INT_OCCURRED) { event |= (1 << HDCP_EVENT_CHECK_RI_START); writeb(flag | UPDATE_RI_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_RI_INT); } /* WATCHDOG INT */ if (flag & WATCHDOG_INT_OCCURRED) { event |= (1 << HDCP_EVENT_SECOND_AUTH_START); writeb(flag | WATCHDOG_INT_OCCURRED, g_hdmi_base + S5P_STATUS); writeb(0x0, g_hdmi_base + S5P_HDCP_WDT_INT); } if (!event) { pr_err("%s::unknown irq.\n", __func__); spin_unlock_irqrestore(&hdcp_info.lock, spin_flags); return IRQ_HANDLED; } hdcp_info.event |= event; schedule_work(&hdcp_info.work); spin_unlock_irqrestore(&hdcp_info.lock, spin_flags); return IRQ_HANDLED; } static int s5p_hdcp_is_reset(void) { int ret = 0; if (spin_is_locked(&hdcp_info.reset_lock)) return 1; return ret; } static bool s5p_set_hpd_detection(bool detection, bool hdcp_enabled, struct i2c_client *client) { u32 hpd_reg_val = 0; if (detection) hpd_reg_val = CABLE_PLUGGED; else hpd_reg_val = CABLE_UNPLUGGED; writel(hpd_reg_val, g_hdmi_base + S5P_HPD); HDCPPRINTK("HPD status :: 0x%08x\n", readl(g_hdmi_base + S5P_HPD)); return true; } int s5p_hdcp_init(void) { HDCPPRINTK("HDCP ftn. Init!!\n"); g_is_dvi = false; g_av_mute = false; g_audio_en = true; /* for bh */ INIT_WORK(&hdcp_info.work, (work_func_t)hdcp_work); init_waitqueue_head(&hdcp_info.waitq); /* for dev_dbg err. */ spin_lock_init(&hdcp_info.lock); spin_lock_init(&hdcp_info.reset_lock); s5p_hdmi_register_isr((hdmi_isr)s5p_hdcp_irq_handler, (u8)HDMI_IRQ_HDCP); return 0; } /* * start - start functions are only called under stopping HDCP */ bool s5p_start_hdcp(void) { u8 reg; u32 sfr_val; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.time_out = INFINITE; hdcp_info.auth_status = NOT_AUTHENTICATED; HDCPPRINTK("HDCP ftn. Start!!\n"); g_sw_reset = true; reg = s5p_hdmi_get_enabled_interrupt(); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); /* 2. Enable software HPD */ sw_hpd_enable(true); /* 3. Make software HPD logical */ set_sw_hpd(false); /* 4. Make software HPD logical */ set_sw_hpd(true); /* 5. Disable software HPD */ sw_hpd_enable(false); set_sw_hpd(false); /* 6. Unmask HPD plug and unplug interrupt */ if (reg & 1<<HDMI_IRQ_HPD_PLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_PLUG); if (reg & 1<<HDMI_IRQ_HPD_UNPLUG) s5p_hdmi_enable_interrupts(HDMI_IRQ_HPD_UNPLUG); g_sw_reset = false; HDCPPRINTK("Stop Encryption by Start!!\n"); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); g_hdcp_protocol_status = 1; if (hdcp_loadkey() < 0) return false; /* for av mute */ writel(DO_NOT_TRANSMIT, g_hdmi_base + S5P_GCP_CON); /* * 1-1. set hdmi status enable reg. * Update_Ri_int_en should be enabled after * s/w gets ExchangeKSV_int. */ writel(HDCP_STATUS_EN_ALL, g_hdmi_base + S5P_STATUS_EN); /* * 3. set hdcp control reg. * Disable advance cipher option, Enable CP(Content Protection), * Disable time-out (This bit is only available in a REPEATER) * Disable XOR shift, Disable Pj port update, Use external key */ sfr_val = 0; sfr_val |= CP_DESIRED_EN; writel(sfr_val, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_enable_interrupts(HDMI_IRQ_HDCP); if (!read_bcaps()) { pr_err("%s::can't read ddc port!\n", __func__); reset_authentication(); } hdcp_info.hdcp_enable = true; HDCPPRINTK("\tSTATUS \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("\tSTATUS_EN \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS_EN)); HDCPPRINTK("\tHPD \t0x%08x\n", readl(g_hdmi_base + S5P_HPD)); HDCPPRINTK("\tHDCP_CTRL \t0x%08x\n", readl(g_hdmi_base + S5P_HDCP_CTRL1)); HDCPPRINTK("\tMODE_SEL \t0x%08x\n", readl(g_hdmi_base + S5P_MODE_SEL)); HDCPPRINTK("\tENC_EN \t0x%08x\n", readl(g_hdmi_base + S5P_ENC_EN)); HDCPPRINTK("\tHDMI_CON_0 \t0x%08x\n", readl(g_hdmi_base + S5P_HDMI_CON_0)); return true; } /* * stop - stop functions are only called under running HDCP */ bool s5p_stop_hdcp(void) { u32 sfr_val = 0; HDCPPRINTK("HDCP ftn. Stop!!\n"); /* s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_PLUG); s5p_hdmi_disable_interrupts(HDMI_IRQ_HPD_UNPLUG); */ s5p_hdmi_disable_interrupts(HDMI_IRQ_HDCP); g_hdcp_protocol_status = 0; hdcp_info.time_out = INFINITE; hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; hdcp_info.hdcp_enable = false; /* hdcp_info.client = NULL; */ /* 3. disable hdcp control reg. */ sfr_val = readl(g_hdmi_base + S5P_HDCP_CTRL1); sfr_val &= (ENABLE_1_DOT_1_FEATURE_DIS & CLEAR_REPEATER_TIMEOUT & EN_PJ_DIS & CP_DESIRED_DIS); writel(sfr_val, g_hdmi_base + S5P_HDCP_CTRL1); /* 1-3. disable hdmi hpd reg. */ sw_hpd_enable(false); /* 1-2. disable hdmi status enable reg. */ sfr_val = readl(g_hdmi_base + S5P_STATUS_EN); sfr_val &= HDCP_STATUS_DIS_ALL; writel(sfr_val, g_hdmi_base + S5P_STATUS_EN); /* 1-1. clear all status pending */ sfr_val = readl(g_hdmi_base + S5P_STATUS); sfr_val |= HDCP_STATUS_EN_ALL; writel(sfr_val, g_hdmi_base + S5P_STATUS); /* disable encryption */ HDCPPRINTK("Stop Encryption by Stop!!\n"); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); /* clear result */ writel(Ri_MATCH_RESULT__NO, g_hdmi_base + S5P_HDCP_CHECK_RESULT); writel(CLEAR_ALL_RESULTS, g_hdmi_base + S5P_HDCP_CHECK_RESULT); #if 0 /* hdmi disable */ sfr_val = readl(g_hdmi_base + S5P_HDMI_CON_0); sfr_val &= ~(PWDN_ENB_NORMAL | HDMI_EN | ASP_EN); writel(sfr_val, g_hdmi_base + S5P_HDMI_CON_0); */ HDCPPRINTK("\tSTATUS \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS)); HDCPPRINTK("\tSTATUS_EN \t0x%08x\n", readl(g_hdmi_base + S5P_STATUS_EN)); HDCPPRINTK("\tHPD \t0x%08x\n", readl(g_hdmi_base + S5P_HPD)); HDCPPRINTK("\tHDCP_CTRL \t0x%08x\n", readl(g_hdmi_base + S5P_HDCP_CTRL1)); HDCPPRINTK("\tMODE_SEL \t0x%08x\n", readl(g_hdmi_base + S5P_MODE_SEL)); HDCPPRINTK("\tENC_EN \t0x%08x\n", readl(g_hdmi_base + S5P_ENC_EN)); HDCPPRINTK("\tHDMI_CON_0 \t0x%08x\n", readl(g_hdmi_base + S5P_HDMI_CON_0)); writel(sfr_val, g_hdmi_base + S5P_HDMI_CON_0); #endif return true; } /* called by hpd */ int s5p_hdcp_encrypt_stop(bool on) { u32 reg; if (hdcp_info.hdcp_enable) { /* clear interrupt pending all */ writeb(0x0, g_hdmi_base + S5P_HDCP_I2C_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_AN_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_RI_INT); writeb(0x0, g_hdmi_base + S5P_HDCP_WDT_INT); writel(HDCP_ENC_DISABLE, g_hdmi_base + S5P_ENC_EN); s5p_hdmi_mute_en(true); if (!g_sw_reset) { reg = readl(g_hdmi_base + S5P_HDCP_CTRL1); if (on) { writel(reg | CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_enable_interrupts(HDMI_IRQ_HDCP); } else { hdcp_info.event = HDCP_EVENT_STOP; hdcp_info.auth_status = NOT_AUTHENTICATED; writel(reg & ~CP_DESIRED_EN, g_hdmi_base + S5P_HDCP_CTRL1); s5p_hdmi_disable_interrupts(HDMI_IRQ_HDCP); } } HDCPPRINTK("Stop Encryption by HPD Event!!\n"); } return 0; } int s5p_hdmi_set_dvi(bool en) { if (en) g_is_dvi = true; else g_is_dvi = false; return 0; } void s5p_hdmi_set_audio(bool en) { if (en) g_audio_en = true; else g_audio_en = false; } int s5p_hdmi_audio_enable(bool en) { u8 reg; if (!g_is_dvi) { reg = readl(g_hdmi_base + S5P_HDMI_CON_0); if (en) { reg |= ASP_EN; writel(HDMI_TRANS_EVERY_SYNC , g_hdmi_base + S5P_AUI_CON); } else { reg &= ~ASP_EN; writel(HDMI_DO_NOT_TANS , g_hdmi_base + S5P_AUI_CON); } writel(reg, g_hdmi_base + S5P_HDMI_CON_0); } return 0; } int s5p_hdmi_set_mute(bool en) { if (en) g_av_mute = true; else g_av_mute = false; return 0; } int s5p_hdmi_get_mute(void) { return g_av_mute ? true : false; } void s5p_hdmi_mute_en(bool en) { if (!g_av_mute) { if (en) { s5p_hdmi_video_set_bluescreen(true, 128, 0, 128); s5p_hdmi_audio_enable(false); } else { s5p_hdmi_video_set_bluescreen(false, 128, 0, 128); if (g_audio_en) s5p_hdmi_audio_enable(true); } } }
Jolocotroco/android_kernel_samsung_smdkv210
drivers/media/video/samsung/tv20/s5pv210/hdcp_s5pv210.c
C
gpl-2.0
38,054
/** @file esetinternal.h * @brief Xapian::ESet::Internal class */ /* Copyright (C) 2008,2010 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef XAPIAN_INCLUDED_ESETINTERNAL_H #define XAPIAN_INCLUDED_ESETINTERNAL_H #include "xapian/base.h" #include "xapian/enquire.h" #include "xapian/types.h" #include <algorithm> #include <string> #include <vector> namespace Xapian { class Database; class ExpandDecider; namespace Internal { class ExpandWeight; /// Class combining a term and its expand weight. class ExpandTerm { friend class Xapian::ESetIterator; friend class Xapian::ESet::Internal; /// The expand weight calculated for this term. Xapian::weight wt; /// The term. std::string term; public: /// Constructor. ExpandTerm(Xapian::weight wt_, const std::string & term_) : wt(wt_), term(term_) { } /// Implement custom swap for ESet sorting efficiency. void swap(ExpandTerm & o) { std::swap(wt, o.wt); std::swap(term, o.term); } /// Ordering relation for ESet contents. bool operator<(const ExpandTerm & o) const { if (wt > o.wt) return true; if (wt < o.wt) return false; return term > o.term; } /// Return a string describing this object. std::string get_description() const; }; } /// Class which actually implements Xapian::ESet. class ESet::Internal : public Xapian::Internal::RefCntBase { friend class ESet; friend class ESetIterator; /** This is a lower bound on the ESet size if an infinite number of results * were requested. * * It will of course always be true that: ebound >= items.size() */ Xapian::termcount ebound; /// The ExpandTerm objects which represent the items in the ESet. std::vector<Xapian::Internal::ExpandTerm> items; /// Don't allow assignment. void operator=(const Internal &); /// Don't allow copying. Internal(const Internal &); public: /// Construct an empty ESet::Internal. Internal() : ebound(0) { } /// Run the "expand" operation which fills the ESet. void expand(Xapian::termcount max_esize, const Xapian::Database & db, const Xapian::RSet & rset, const Xapian::ExpandDecider * edecider, const Xapian::Internal::ExpandWeight & eweight); /// Return a string describing this object. std::string get_description() const; }; } #endif // XAPIAN_INCLUDED_ESETINTERNAL_H
ystk/debian-xapian-core
common/esetinternal.h
C
gpl-2.0
3,091
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_length=75),), ('message', models.TextField(),), ('date', models.DateField(auto_now=True),)], bases = (models.Model,), options = {}, name = 'Contact', ), migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('date', models.DateTimeField(),), ('title', models.CharField(max_length=255),), ('code', models.CharField(max_length=255),), ('summary', models.TextField(),)], bases = (models.Model,), options = {}, name = 'Commits', ), ]
Nimmard/james-olson.com
main/migrations/0001_initial.py
Python
gpl-2.0
1,003
/****************************************************************************** * File : velocity_tria3.c * * Author : Carlos Rosales Fernandez ([email protected]) * * Date : 01-09-2006 * * Revision : 1.0 * ******************************************************************************* * DESCRIPTION * * Calculates the three components of the flow speed at a given point Xin[] * * and returns the values in array U[]. * * Works for linear interpolation in triangular elements (3-noded triangles). * ******************************************************************************/ /****************************************************************************** * COPYRIGHT & LICENSE INFORMATION * * * * Copyright 2006 Carlos Rosales Fernandez and The Institute of High * * Performance Computing (A*STAR) * * * * This file is part of stkSolver. * * * * stkSolver is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * stkSolver is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with stkSolver; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ******************************************************************************/ #include "constants.h" #include "velocity_tria3.h" int velocity_tria3(double *Xin, double **mNodes, unsigned int **mElems, double *vProbParam, double *vB, double *U) { const unsigned int ELEMS = nElems, NODES_IN_ELEM = 3; unsigned int currentNode, i, j, SinNode, test, xNode, yNode, zNode; double dx, dy, dz, factor; double X[3][3]; double Int[3][3][3]; /* Initialize */ U[0] = U[1] = U[2] = 0.0; factor = 1.0/(8.0*pi*vProbParam[0]); for(i = 0; i < ELEMS; i++){ for(j = 0; j < NODES_IN_ELEM; j++){ currentNode = mElems[i][j] - 1; X[j][0] = mNodes[currentNode][0]; X[j][1] = mNodes[currentNode][1]; X[j][2] = mNodes[currentNode][2]; } /* Check for singular case */ test = 0; for(j = 0; j < NODES_IN_ELEM; j++){ dx = X[j][0] - Xin[0]; dy = X[j][1] - Xin[1]; dz = X[j][2] - Xin[2]; if(dx == 0.0 && dy == 0.0 && dz == 0.0){ test = 1; SinNode = j+1; break; } } if(test == 0) intGStk_tria3(X,Xin,Int); else intSingularGStk_tria3(SinNode,X,Xin,Int); /* Add cotribution from each node j in element i */ for(j = 0; j < NODES_IN_ELEM; j++){ xNode = mElems[i][j] - 1; yNode = xNode + nNodes; zNode = yNode + nNodes; U[0] -= Int[0][0][j]*vB[xNode] + Int[0][1][j]*vB[yNode] + /* Ux */ Int[0][2][j]*vB[zNode]; U[1] -= Int[1][0][j]*vB[xNode] + Int[1][1][j]*vB[yNode] + /* Uy */ Int[1][2][j]*vB[zNode]; U[2] -= Int[2][0][j]*vB[xNode] + Int[2][1][j]*vB[yNode] + /* Uz */ Int[2][2][j]*vB[zNode]; } } U[0] = U[0]*factor; U[1] = U[1]*factor; U[2] = U[2]*factor; return 0; }
carlosrosales/stksolver
src/velocity_tria3.c
C
gpl-2.0
4,564
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\Core\Search\Legacy\Content\Location\Gateway\CriterionHandler; use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriterionHandler; use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter; use eZ\Publish\API\Repository\Values\Content\Query\Criterion; use eZ\Publish\Core\Persistence\Database\SelectQuery; /** * Visits the Ancestor criterion. */ class Ancestor extends CriterionHandler { /** * Check if this criterion handler accepts to handle the given criterion. * * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion * * @return bool */ public function accept(Criterion $criterion) { return $criterion instanceof Criterion\Ancestor; } /** * Generate query expression for a Criterion this handler accepts. * * accept() must be called before calling this method. * * @param \eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter $converter * @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion * @param array $languageSettings * * @return \eZ\Publish\Core\Persistence\Database\Expression */ public function handle( CriteriaConverter $converter, SelectQuery $query, Criterion $criterion, array $languageSettings ) { $idSet = []; foreach ($criterion->value as $value) { foreach (explode('/', trim($value, '/')) as $id) { $idSet[$id] = true; } } return $query->expr->in( $this->dbHandler->quoteColumn('node_id', 'ezcontentobject_tree'), array_keys($idSet) ); } }
ezsystems/ezpublish-kernel
eZ/Publish/Core/Search/Legacy/Content/Location/Gateway/CriterionHandler/Ancestor.php
PHP
gpl-2.0
1,991
using System; using System.Collections.Generic; using System.Management; using System.Security.Principal; using Microsoft.Win32; using PowerPointLabs.ActionFramework.Common.Log; namespace PowerPointLabs.Utils { /// <summary> /// A class that allows watching of Registry Key values. /// </summary> class RegistryWatcher<T> where T : IEquatable<T> { private readonly string path; private readonly string key; private readonly List<T> defaultKey; private ManagementEventWatcher watcher; // returns true if the key started as defaultKey and is not modified, else false public bool IsDefaultKey { get; private set; } public event EventHandler<T> ValueChanged; public RegistryWatcher(string path, string key, List<T> defaultKey) { this.path = path; this.key = key; this.defaultKey = defaultKey; this.IsDefaultKey = true; RegisterKeyChanged(); try { GetKeyAndUpdateKeyStatus(); } catch (Exception) { // There is a possibility no registry entries have been created yet } } /// <summary> /// Fires the event manually /// </summary> public void Fire() { Notify(); } public void Start() { watcher.Start(); } public void Stop() { watcher.Stop(); } public void SetValue(object o) { WindowsIdentity currentUser = WindowsIdentity.GetCurrent(); Registry.SetValue(String.Format("{0}\\{1}", currentUser.User.Value, path), key, o); } private void RegisterKeyChanged() { WindowsIdentity currentUser = WindowsIdentity.GetCurrent(); WqlEventQuery query = new WqlEventQuery( "SELECT * FROM RegistryValueChangeEvent WHERE " + "Hive = 'HKEY_USERS'" + String.Format(@"AND KeyPath = '{0}\\{1}' AND ValueName='{2}'", currentUser.User.Value, path, key)); watcher = new ManagementEventWatcher(query); watcher.EventArrived += (object sender, EventArrivedEventArgs e) => { Notify(); }; } private T GetKeyAndUpdateKeyStatus() { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path)) { object objectValue; if (key == null || (objectValue = key.GetValue(this.key)) == null) { throw new Exceptions.AssumptionFailedException("Key is null"); } T result = (T)objectValue; IsDefaultKey &= defaultKey == null || defaultKey.Contains(result); return result; } } private void Notify() { try { T key = GetKeyAndUpdateKeyStatus(); if (IsDefaultKey) { return; } ValueChanged?.Invoke(this, key); } catch (Exception e) { Logger.LogException(e, nameof(Notify)); } } } }
PowerPointLabs/PowerPointLabs
PowerPointLabs/PowerPointLabs/Utils/RegistryWatcher.cs
C#
gpl-2.0
3,325
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/aspnet/try_razor_cs_011.asp by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:13:45 GMT --> <body> <p>The price is OK.</p> </body> <!-- Mirrored from www.w3schools.com/aspnet/try_razor_cs_011.asp by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:13:45 GMT --> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/aspnet/try_razor_cs_011-2.html
HTML
gpl-2.0
357
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>scipy.special.eval_hermite &mdash; SciPy v0.16.1 Reference Guide</title> <link rel="stylesheet" type="text/css" href="../static_/css/spc-bootstrap.css"> <link rel="stylesheet" type="text/css" href="../static_/css/spc-extend.css"> <link rel="stylesheet" href="../static_/scipy.css" type="text/css" > <link rel="stylesheet" href="../static_/pygments.css" type="text/css" > <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.16.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../static_/jquery.js"></script> <script type="text/javascript" src="../static_/underscore.js"></script> <script type="text/javascript" src="../static_/doctools.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../static_/js/copybutton.js"></script> <link rel="top" title="SciPy v0.16.1 Reference Guide" href="../index.html" > <link rel="up" title="Special functions (scipy.special)" href="../special.html" > <link rel="next" title="scipy.special.eval_hermitenorm" href="scipy.special.eval_hermitenorm.html" > <link rel="prev" title="scipy.special.eval_genlaguerre" href="scipy.special.eval_genlaguerre.html" > </head> <body> <div class="container"> <div class="header"> </div> </div> <div class="container"> <div class="main"> <div class="row-fluid"> <div class="span12"> <div class="spc-navbar"> <ul class="nav nav-pills pull-left"> <li class="active"><a href="../index.html">SciPy v0.16.1 Reference Guide</a></li> <li class="active"><a href="../special.html" accesskey="U">Special functions (<tt class="docutils literal"><span class="pre">scipy.special</span></tt>)</a></li> </ul> <ul class="nav nav-pills pull-right"> <li class="active"> <a href="../genindex.html" title="General Index" accesskey="I">index</a> </li> <li class="active"> <a href="../py-modindex.html" title="Python Module Index" >modules</a> </li> <li class="active"> <a href="../scipy-optimize-modindex.html" title="Python Module Index" >modules</a> </li> <li class="active"> <a href="scipy.special.eval_hermitenorm.html" title="scipy.special.eval_hermitenorm" accesskey="N">next</a> </li> <li class="active"> <a href="scipy.special.eval_genlaguerre.html" title="scipy.special.eval_genlaguerre" accesskey="P">previous</a> </li> </ul> </div> </div> </div> <div class="row-fluid"> <div class="spc-rightsidebar span3"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../index.html"> <img class="logo" src="../static_/scipyshiny_small.png" alt="Logo"> </a></p> <h4>Previous topic</h4> <p class="topless"><a href="scipy.special.eval_genlaguerre.html" title="previous chapter">scipy.special.eval_genlaguerre</a></p> <h4>Next topic</h4> <p class="topless"><a href="scipy.special.eval_hermitenorm.html" title="next chapter">scipy.special.eval_hermitenorm</a></p> </div> </div> <div class="span9"> <div class="bodywrapper"> <div class="body" id="spc-section-body"> <div class="section" id="scipy-special-eval-hermite"> <h1>scipy.special.eval_hermite<a class="headerlink" href="#scipy-special-eval-hermite" title="Permalink to this headline">¶</a></h1> <dl class="data"> <dt id="scipy.special.eval_hermite"> <tt class="descclassname">scipy.special.</tt><tt class="descname">eval_hermite</tt><big>(</big><em>n</em>, <em>x</em>, <em>out=None</em><big>)</big><em class="property"> = &lt;ufunc 'eval_hermite'&gt;</em><a class="headerlink" href="#scipy.special.eval_hermite" title="Permalink to this definition">¶</a></dt> <dd><p>Evaluate Hermite polynomial at a point.</p> </dd></dl> </div> </div> </div> </div> </div> </div> </div> <div class="container container-navbar-bottom"> <div class="spc-navbar"> </div> </div> <div class="container"> <div class="footer"> <div class="row-fluid"> <ul class="inline pull-left"> <li> &copy; Copyright 2008-2014, The Scipy community. </li> <li> Last updated on Oct 24, 2015. </li> <li> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1. </li> </ul> </div> </div> </div> </body> </html>
platinhom/ManualHom
Coding/Python/scipy-html-0.16.1/generated/scipy.special.eval_hermite.html
HTML
gpl-2.0
4,993
<?php /********************************************************** * Lidiun PHP Framework 4.0 - (http://www.lidiun.com) * * @Created in 26/08/2013 * @Author Dyon Enedi <[email protected]> * @Modify in 04/08/2014 * @By Dyon Enedi <[email protected]> * @Contributor Gabriela A. Ayres Garcia <[email protected]> * @Contributor Rodolfo Bulati <[email protected]> * @License: free * **********************************************************/ class Panel { public function __construct() { } }
dyonenedi/lidiun_history
LidiunFramework_5.0/app/repository/render/panel.php
PHP
gpl-2.0
550
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Amelia Valcarcel</title> <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/freelancer.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" class="index"> <!-- Header --> <header> <div class="container"> <div class="row"> <div class="col-lg-12"> <img class="img-responsive" src="img/profile.png" alt=""> <div class="intro-text"> <span class="name">Amelia Valcarcel</span> <hr class="star-light"> <span class="skills">En estos momentos estamos renovando la web, disculpen las molestias</span> </div> </div> </div> </div> </header> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="js/freelancer.js"></script> </body> </html>
sbellver/cerrar-web
close/index.html
HTML
gpl-2.0
2,549
<?php $files = elgg_extract("files", $vars, array()); $folder = elgg_extract("folder", $vars); $folder_content = elgg_view("file_tools/breadcrumb", array("entity" => $folder)); if(!($sub_folders = file_tools_get_sub_folders($folder))){ $sub_folders = array(); } $entities = array_merge($sub_folders, $files) ; if(!empty($entities)) { $params = array( "full_view" => false, "pagination" => false ); elgg_push_context("file_tools_selector"); $files_content = elgg_view_entity_list($entities, $params); elgg_pop_context(); } if(empty($files_content)){ $files_content = elgg_echo("file_tools:list:files:none"); } else { $files_content .= "<div class='clearfix'>"; if(elgg_get_page_owner_entity()->canEdit()) { $files_content .= '<a id="file_tools_action_bulk_delete" href="javascript:void(0);">' . elgg_echo("file_tools:list:delete_selected") . '</a> | '; } $files_content .= "<a id='file_tools_action_bulk_download' href='javascript:void(0);'>" . elgg_echo("file_tools:list:download_selected") . "</a>"; $files_content .= "<a id='file_tools_select_all' class='float-alt' href='javascript:void(0);'>"; $files_content .= "<span>" . elgg_echo("file_tools:list:select_all") . "</span>"; $files_content .= "<span class='hidden'>" . elgg_echo("file_tools:list:deselect_all") . "</span>"; $files_content .= "</a>"; $files_content .= "</div>"; } $files_content .= elgg_view("graphics/ajax_loader"); ?> <div id="file_tools_list_files"> <div id="file_tools_list_files_overlay"></div> <?php echo $folder_content; echo $files_content; ?> </div> <?php $page_owner = elgg_get_page_owner_entity(); if($page_owner->canEdit() || (elgg_instanceof($page_owner, "group") && $page_owner->isMember())) { ?> <script type="text/javascript"> $(function(){ $("#file_tools_list_files .file-tools-file").draggable({ revert: "invalid", opacity: 0.8, appendTo: "body", helper: "clone", start: function(event, ui) { $(this).css("visibility", "hidden"); $(ui.helper).width($(this).width()); }, stop: function(event, ui) { $(this).css("visibility", "visible"); } }); $("#file_tools_list_files .file-tools-folder").droppable({ accept: "#file_tools_list_files .file-tools-file", drop: function(event, ui){ droppable = $(this); draggable = ui.draggable; drop_id = droppable.parent().attr("id").split("-").pop(); drag_id = draggable.parent().attr("id").split("-").pop(); elgg.file_tools.move_file(drag_id, drop_id, draggable); } }); }); </script> <?php }
nachopavon/redprofesional
mod/file_tools/views/default/file_tools/list/files.php
PHP
gpl-2.0
2,690
<?php namespace App\Controller; use App\Controller\AppController; /** * Customers Controller * * @property \App\Model\Table\CustomersTable $Customers */ class CustomersController extends AppController { /** * Index method * * @return void */ public function index() { $this->set('customers', $this->paginate($this->Customers)); $this->set('_serialize', ['customers']); } /** * View method * * @param string|null $id Customer id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function view($id = null) { $customer = $this->Customers->get($id, [ 'contain' => ['Orders'] ]); $this->set('customer', $customer); $this->set('_serialize', ['customer']); } /** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { $customer = $this->Customers->newEntity(); if ($this->request->is('post')) { $customer = $this->Customers->patchEntity($customer, $this->request->data); if ($this->Customers->save($customer)) { $this->Flash->success('The customer has been saved.'); return $this->redirect(['action' => 'index']); } else { $this->Flash->error('The customer could not be saved. Please, try again.'); } } $this->set(compact('customer')); $this->set('_serialize', ['customer']); } /** * Edit method * * @param string|null $id Customer id. * @return void Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $customer = $this->Customers->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $customer = $this->Customers->patchEntity($customer, $this->request->data); if ($this->Customers->save($customer)) { $this->Flash->success('The customer has been saved.'); return $this->redirect(['action' => 'index']); } else { $this->Flash->error('The customer could not be saved. Please, try again.'); } } $this->set(compact('customer')); $this->set('_serialize', ['customer']); } /** * Delete method * * @param string|null $id Customer id. * @return void Redirects to index. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $customer = $this->Customers->get($id); if ($this->Customers->delete($customer)) { $this->Flash->success('The customer has been deleted.'); } else { $this->Flash->error('The customer could not be deleted. Please, try again.'); } return $this->redirect(['action' => 'index']); } }
thinkingwise/cakephp3crm
src/Controller/CustomersController.php
PHP
gpl-2.0
3,197
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": run()
prheenan/BioModel
EnergyLandscapes/Lifetime_Dudko2008/Python/TestExamples/Examples/Example_Dudko_Fit.py
Python
gpl-2.0
889
// Wildebeest Migration Framework // Copyright © 2013 - 2018, Matheson Ventures Pte Ltd // // This file is part of Wildebeest // // Wildebeest is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License v2 as published by the Free // Software Foundation. // // Wildebeest is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with // Wildebeest. If not, see http://www.gnu.org/licenses/gpl-2.0.html package co.mv.wb.plugin.generaldatabase.dom; import co.mv.wb.Asserts; import co.mv.wb.InvalidReferenceException; import co.mv.wb.LoaderFault; import co.mv.wb.ModelExtensions; import co.mv.wb.PluginBuildException; import co.mv.wb.Resource; import co.mv.wb.fixture.Fixtures; import co.mv.wb.impl.ResourceTypeServiceBuilder; import co.mv.wb.plugin.base.dom.DomPlugins; import co.mv.wb.plugin.base.dom.DomResourceLoader; import co.mv.wb.plugin.generaldatabase.AnsiSqlCreateDatabaseMigration; import co.mv.wb.plugin.generaldatabase.AnsiSqlDropDatabaseMigration; import co.mv.wb.plugin.generaldatabase.AnsiSqlTableDoesNotExistAssertion; import co.mv.wb.plugin.generaldatabase.AnsiSqlTableExistsAssertion; import co.mv.wb.plugin.postgresql.PostgreSqlConstants; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.util.Optional; import java.util.UUID; /** * Unit tests for the DOM persistence services for ANSI SQL plugins. * * @since 4.0 */ public class AnsiSqlDomServiceUnitTests { @Test public void ansiSqlCreateDatabaseMigrationLoadFromValidDocument() throws LoaderFault, PluginBuildException, InvalidReferenceException { // Setup UUID migrationId = UUID.randomUUID(); UUID toStateId = UUID.randomUUID(); String xml = Fixtures .resourceXmlBuilder() .resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo") .migration("AnsiSqlCreateDatabase", migrationId, null, toStateId.toString()) .render(); DomResourceLoader loader = DomPlugins.resourceLoader( ResourceTypeServiceBuilder .create() .withFactoryResourceTypes() .build(), xml); // Execute Resource resource = loader.load(new File(".")); // Verify Assert.assertNotNull("resource", resource); Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size()); AnsiSqlCreateDatabaseMigration mT = ModelExtensions.as( resource.getMigrations().get(0), AnsiSqlCreateDatabaseMigration.class); Assert.assertNotNull( "resourceWithPlugin.resource.migrations[0] expected to be of type AnsiSqlCreateDatabaseMigration", mT); Assert.assertEquals( "resourceWithPlugin.resource.migrations[0].id", migrationId, mT.getMigrationId()); Assert.assertEquals( "resourceWithPlugin.resource.migrations[0].fromStateId", Optional.empty(), mT.getFromState()); Assert.assertEquals( "resourceWithPlugin.resource.migrations[0].toStateId", Optional.of(toStateId.toString()), mT.getToState()); } @Test public void ansiSqlDropDatabaseMigrationLoadFromValidDocument() throws LoaderFault, PluginBuildException, InvalidReferenceException { // Setup UUID migrationId = UUID.randomUUID(); String toState = UUID.randomUUID().toString(); String xml = Fixtures .resourceXmlBuilder() .resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo") .migration("AnsiSqlDropDatabase", migrationId, null, toState.toString()) .render(); DomResourceLoader loader = DomPlugins.resourceLoader( ResourceTypeServiceBuilder .create() .withFactoryResourceTypes() .build(), xml); // Execute Resource resource = loader.load(new File(".")); // Verify Assert.assertNotNull("resource", resource); Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size()); AnsiSqlDropDatabaseMigration mT = ModelExtensions.as( resource.getMigrations().get(0), AnsiSqlDropDatabaseMigration.class); Assert.assertNotNull("resource.migrations[0] expected to be of type AnsiSqlDropDatabaseMigration", mT); Assert.assertEquals( "resource.migrations[0].id", migrationId, mT.getMigrationId()); Assert.assertEquals( "resource.migrations[0].fromState", Optional.empty(), mT.getFromState()); Assert.assertEquals( "resource.migrations[0].toState", Optional.of(toState), mT.getToState()); } @Test public void ansiSqlTableExistsAssertionLoadFromValidDocument() throws LoaderFault, PluginBuildException, InvalidReferenceException { // Setup UUID assertionId = UUID.randomUUID(); String xml = Fixtures .resourceXmlBuilder() .resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo") .state(UUID.randomUUID(), null) .assertion("AnsiSqlTableExists", assertionId) .appendInnerXml("<schemaName>sch</schemaName>") .appendInnerXml("<tableName>tbl</tableName>") .build(); DomResourceLoader loader = DomPlugins.resourceLoader( ResourceTypeServiceBuilder .create() .withFactoryResourceTypes() .build(), xml); // Execute Resource resource = loader.load(new File(".")); // Verify Assert.assertNotNull("resource", resource); Assert.assertEquals("resource.states.size", 1, resource.getStates().size()); Assert.assertEquals( "resource.states[0].assertions.size", 1, resource.getStates().get(0).getAssertions().size()); AnsiSqlTableExistsAssertion assertionT = ModelExtensions.as( resource.getStates().get(0).getAssertions().get(0), AnsiSqlTableExistsAssertion.class); Assert.assertNotNull("Expected to be an AnsiSqlTableExistsAssertion", assertionT); Asserts.assertAnsiSqlTableExistsAssertion( assertionId, "sch", "tbl", assertionT, "resource.states[0].assertions[0]"); } @Test public void ansiSqlTableDoesNotExistAssertionLoadFromValidDocument() throws LoaderFault, PluginBuildException, InvalidReferenceException { // Setup UUID assertionId = UUID.randomUUID(); String xml = Fixtures .resourceXmlBuilder() .resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo") .state(UUID.randomUUID(), null) .assertion("AnsiSqlTableDoesNotExist", assertionId) .appendInnerXml("<schemaName>sch</schemaName>") .appendInnerXml("<tableName>tbl</tableName>") .build(); DomResourceLoader loader = DomPlugins.resourceLoader( ResourceTypeServiceBuilder .create() .withFactoryResourceTypes() .build(), xml); // Execute Resource resource = loader.load(new File(".")); // Verify Assert.assertNotNull("resource", resource); Assert.assertEquals("resource.states.size", 1, resource.getStates().size()); Assert.assertEquals( "resource.states[0].assertions.size", 1, resource.getStates().get(0).getAssertions().size()); AnsiSqlTableDoesNotExistAssertion assertionT = ModelExtensions.as( resource.getStates().get(0).getAssertions().get(0), AnsiSqlTableDoesNotExistAssertion.class); Assert.assertNotNull("Expected to be an AnsiSqlTableDoesNotExistAssertion", assertionT); Asserts.assertAnsiSqlTableDoesNotExistAssertion( assertionId, "sch", "tbl", assertionT, "resource.states[0].assertions[0]"); } }
zendigitalstudios/wildebeest
MV.Wildebeest.Core/source/test/java/co/mv/wb/plugin/generaldatabase/dom/AnsiSqlDomServiceUnitTests.java
Java
gpl-2.0
7,441
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # Relative path conversion top directories. SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/robot/bebop_ws/src/navigation_tutorials/navigation_stage") SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/robot/bebop_ws/build/navigation_stage") # Force unix paths in dependencies. SET(CMAKE_FORCE_UNIX_PATHS 1) # The C and CXX include file regular expressions for this directory. SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
nicolasgallardo/TECHLAV_T1-6
bebop_ws/build/navigation_stage/CMakeFiles/CMakeDirectoryInformation.cmake
CMake
gpl-2.0
680
#include <string.h> #include <sys/time.h> #include <sys/resource.h> /////////////////////////////////////// // Function: trim - Remove "\n" // /////////////////////////////////////// int trim(char *line) { int end_pos = strlen(line) - 1; if (line[end_pos] == '\n') { line[end_pos] = '\0'; return 1; } return 0; } /////////////////////////////////////////////////////// // Function: get_time_cpu - Get CPU time // /////////////////////////////////////////////////////// long get_time_cpu() { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return ru.ru_utime.tv_sec; } /////////////////////////////////////////////////////// // Function: get_time - Get time // /////////////////////////////////////////////////////// long get_time() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec; } ///////////////////////////////////////// // Function: count_digit - count digit // ///////////////////////////////////////// int count_digit(long num) { int digit = 1; int quotient; quotient = int(num / 10); while (quotient != 0) { digit ++; quotient = int(quotient / 10); } return digit; } ////////////////////////////////////////////////////// // Function: revcomp - convert to reverse complement// ////////////////////////////////////////////////////// void revcomp(char* str) { int i, len; char c; len = strlen(str); for(i=0; i<len/2; i++) { c = str[i]; str[i] = str[len-i-1]; str[len-i-1] = c; } for(i=0; i<len; i++) { if (str[i] == 'A') { str[i] = 'T'; } else if (str[i] == 'T') { str[i] = 'A'; } else if (str[i] == 'G') { str[i] = 'C'; } else if (str[i] == 'C') { str[i] = 'G'; } } }
pfaucon/PBSIM-PacBio-Simulator
src/helpers.cpp
C++
gpl-2.0
1,764
<?php namespace Jenssegers\Mongodb\Relations; use MongoId; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Collection as BaseCollection; use Jenssegers\Mongodb\Eloquent\Collection; abstract class EmbedsOneOrMany extends Relation { /** * The local key of the parent model. * * @var string */ protected $localKey; /** * The foreign key of the parent model. * * @var string */ protected $foreignKey; /** * The "name" of the relationship. * * @var string */ protected $relation; /** * Create a new embeds many relationship instance. * * @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Model $parent * @param string $localKey * @param string $foreignKey * @param string $relation * @return void */ public function __construct(Builder $query, Model $parent, Model $related, $localKey, $foreignKey, $relation) { $this->query = $query; $this->parent = $parent; $this->related = $related; $this->localKey = $localKey; $this->foreignKey = $foreignKey; $this->relation = $relation; // If this is a nested relation, we need to get the parent query instead. if ($parentRelation = $this->getParentRelation()) { $this->query = $parentRelation->getQuery(); } $this->addConstraints(); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { if (static::$constraints) { $this->query->where($this->getQualifiedParentKeyName(), '=', $this->getParentKey()); } } /** * Set the constraints for an eager load of the relation. * * @param array $models * @return void */ public function addEagerConstraints(array $models) { // There are no eager loading constraints. } /** * Initialize the relation on a set of models. * * @param array $models * @param string $relation * @return void */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setParentRelation($this); $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** * Match the eagerly loaded results to their parents. * * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results * @param string $relation * @return array */ public function match(array $models, BaseCollection $results, $relation) { foreach ($models as $model) { $results = $model->$relation()->getResults(); $model->setParentRelation($this); $model->setRelation($relation, $results); } return $models; } /** * Shorthand to get the results of the relationship. * * @return Jenssegers\Mongodb\Eloquent\Collection */ public function get() { return $this->getResults(); } /** * Get the number of embedded models. * * @return int */ public function count() { return count($this->getEmbedded()); } /** * Attach a model instance to the parent model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Database\Eloquent\Model */ public function save(Model $model) { $model->setParentRelation($this); return $model->save() ? $model : false; } /** * Attach an array of models to the parent instance. * * @param array $models * @return array */ public function saveMany(array $models) { array_walk($models, array($this, 'save')); return $models; } /** * Create a new instance of the related model. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ public function create(array $attributes) { // Here we will set the raw attributes to avoid hitting the "fill" method so // that we do not have to worry about a mass accessor rules blocking sets // on the models. Otherwise, some of these attributes will not get set. $instance = $this->related->newInstance($attributes); $instance->setParentRelation($this); $instance->save(); return $instance; } /** * Create an array of new instances of the related model. * * @param array $records * @return array */ public function createMany(array $records) { $instances = array(); foreach ($records as $record) { $instances[] = $this->create($record); } return $instances; } /** * Transform single ID, single Model or array of Models into an array of IDs * * @param mixed $ids * @return array */ protected function getIdsArrayFrom($ids) { if ( ! is_array($ids)) $ids = array($ids); foreach ($ids as &$id) { if ($id instanceof Model) $id = $id->getKey(); } return $ids; } /** * Get the embedded records array. * * @return array */ protected function getEmbedded() { // Get raw attributes to skip relations and accessors. $attributes = $this->parent->getAttributes(); return isset($attributes[$this->localKey]) ? $attributes[$this->localKey] : null; } /** * Set the embedded records array. * * @param array $records * @return \Illuminate\Database\Eloquent\Model */ protected function setEmbedded($records) { $attributes = $this->parent->getAttributes(); $attributes[$this->localKey] = $records; // Set raw attributes to skip mutators. $this->parent->setRawAttributes($attributes); // Set the relation on the parent. return $this->parent->setRelation($this->relation, $this->getResults()); } /** * Get the foreign key value for the relation. * * @param mixed $id * @return mixed */ protected function getForeignKeyValue($id) { if ($id instanceof Model) { $id = $id->getKey(); } // Convert the id to MongoId if necessary. return $this->getBaseQuery()->convertKey($id); } /** * Convert an array of records to a Collection. * * @param array $records * @return Jenssegers\Mongodb\Eloquent\Collection */ protected function toCollection(array $records = array()) { $models = array(); foreach ($records as $attributes) { $models[] = $this->toModel($attributes); } if (count($models) > 0) { $models = $this->eagerLoadRelations($models); } return new Collection($models); } /** * Create a related model instanced. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Model */ protected function toModel($attributes = array()) { if (is_null($attributes)) return null; $model = $this->related->newFromBuilder((array) $attributes); $model->setParentRelation($this); $model->setRelation($this->foreignKey, $this->parent); // If you remove this, you will get segmentation faults! $model->setHidden(array_merge($model->getHidden(), array($this->foreignKey))); return $model; } /** * Get the relation instance of the parent. * * @return Illuminate\Database\Eloquent\Relations\Relation */ protected function getParentRelation() { return $this->parent->getParentRelation(); } /** * Get the underlying query for the relation. * * @return \Illuminate\Database\Eloquent\Builder */ public function getQuery() { // Because we are sharing this relation instance to models, we need // to make sure we use separate query instances. return clone $this->query; } /** * Get the base query builder driving the Eloquent builder. * * @return \Illuminate\Database\Query\Builder */ public function getBaseQuery() { // Because we are sharing this relation instance to models, we need // to make sure we use separate query instances. return clone $this->query->getQuery(); } /** * Check if this relation is nested in another relation. * * @return boolean */ protected function isNested() { return $this->getParentRelation() != null; } /** * Get the fully qualified local key name. * * @return string */ protected function getPathHierarchy($glue = '.') { if ($parentRelation = $this->getParentRelation()) { return $parentRelation->getPathHierarchy($glue) . $glue . $this->localKey; } return $this->localKey; } /** * Get the parent's fully qualified key name. * * @return string */ protected function getQualifiedParentKeyName() { if ($parentRelation = $this->getParentRelation()) { return $parentRelation->getPathHierarchy() . '.' . $this->parent->getKeyName(); } return $this->parent->getKeyName(); } /** * Get the primary key value of the parent. * * @return string */ protected function getParentKey() { return $this->parent->getKey(); } }
walcott911/easymart
vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php
PHP
gpl-2.0
9,965
require 'spec_helper' feature "Searching Entities" do include CurbHelpers include SearchHelpers scenario 'entities are found by name', js: true, search: true do entity = create(:entity, :with_parent, name: 'Foo bar') index_changed_models expect_entity_api_search_to_find('bar') do|json| json_item = json['entities'].first expect(json_item).to have_key('id').with_value(entity.id.to_s) %w(parent_id name country_code url).each do |key| expect(json_item).to have_key(key).with_value(entity.send(key.to_sym)) end %w(address_line_1 address_line_2 state phone email city).each do |key| expect(json_item).not_to have_key(key) end end end scenario 'the results have relevant metadata', js: true, search: true do entity = create(:entity, name: 'Foo bar') index_changed_models expect_entity_api_search_to_find('bar') do|json| metadata = json['meta'] expect(metadata).to have_key('current_page').with_value(1) expect(metadata).to have_key('query').with_value("term" => "bar") end end def expect_entity_api_search_to_find(term, options = {}) sleep 1 with_curb_get_for_json( "entities/search.json", options.merge(term: term)) do |curb| json = JSON.parse(curb.body_str) yield(json) if block_given? end end end
Domenoth/chillingeffects
spec/integration/entity_search_spec.rb
Ruby
gpl-2.0
1,365
<? if($_GET['action'] == "login") { $conn = mysql_connect("localhost","user","password"); // your MySQL connection data $db = mysql_select_db("DATABASENAME"); //put your database name in here $name = $_POST['user']; $q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'"); ?>
Tieks/php-login
connect.php
PHP
gpl-2.0
286
# TobiiEyetracking This is the repository storing the codes for Tobii eye-tracking cases, including the application of Tobii and corresponding various methods of data analysis. The utility of Tobii for experiment and design is mostly based on Matlab. The data analysis consists of codes based on Matlab and R. I will try to create a consistent work soon.
AoxiangXu/TobiiEyetracking
README.md
Markdown
gpl-2.0
357
<?php namespace Dennis\Tournament\Domain\Model; /*************************************************************** * * Copyright notice * * (c) 2014 * * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Class PlayerKo * * @package Dennis\Tournament\Domain\Model */ class PlayerKo extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity { /** * name * * @var string */ protected $name = ''; /** * Returns the name * * @return string $name */ public function getName() { return $this->name; } /** * Sets the name * * @param string $name * @return self */ public function setName($name) { $this->name = $name; return $this; } }
TildBJ/tournament
Classes/Domain/Model/PlayerKo.php
PHP
gpl-2.0
1,453
#ifndef _INCLUDE_DECODER_H #define _INCLUDE_DECODER_H #include <sys/time.h> #include <string> #include <map> using std::string; using std::map; enum sensor_e { TFA_1=0, // IT+ Klimalogg Pro, 30.3180, 30.3181, 30.3199(?) TFA_2, // IT+ 30.3143, 30.3146(?), 30.3144 TFA_3, // 30.3155 TX22, // LaCrosse TX22 TFA_WHP, // 30.3306 (rain meter), pulse data TFA_WHB, // TFA WeatherHub FIREANGEL=0x20 // ST-630+W2 }; typedef struct { sensor_e type; uint64_t id; double temp; double humidity; int alarm; int flags; int sequence; time_t ts; int rssi; } sensordata_t; class decoder { public: decoder(sensor_e _type); void set_params(char *_handler, int _mode, int _dbg); virtual void store_bit(int bit); virtual void flush(int rssi, int offset=0); virtual void store_data(sensordata_t &d); virtual void execute_handler(sensordata_t &d); virtual void flush_storage(void); virtual int has_sync(void) {return synced;}; int count(void) {return data.size();} sensor_e get_type(void) {return type;} virtual void store_bytes(uint8_t *d, int len); protected: int dbg; int bad; int synced; sensor_e type; uint8_t rdata[256]; int byte_cnt; private: char *handler; int mode; map<uint64_t,sensordata_t> data; }; class demodulator { public: demodulator(decoder *_dec); virtual void start(int len); virtual void reset(void){}; virtual int demod(int thresh, int pwr, int index, int16_t *iq); decoder *dec; protected: int last_bit_idx; }; #endif
baycom/tfrec
decoder.h
C
gpl-2.0
1,500
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL$ // // Version: $Revision$, // $Date$ // $Author$ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source software; you can redistribute it // and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 of the License. // Gurux Device Framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // More information of Gurux products: https://www.gurux.org // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- using Gurux.DLMS.Internal; using Gurux.DLMS.Plc; using Gurux.DLMS.Plc.Enums; using System; using System.Collections.Generic; namespace Gurux.DLMS { /// <summary> /// PLC communication settings. /// </summary> public class GXPlcSettings { byte[] _systemTitle; private GXDLMSSettings settings; /// <summary> /// Initial credit (IC) tells how many times the frame must be repeated. Maximum value is 7. /// </summary> public byte InitialCredit { get; set; } /// <summary> /// The current credit (CC) initial value equal to IC and automatically decremented by the MAC layer after each repetition. /// Maximum value is 7. /// </summary> public byte CurrentCredit { get; set; } /// <summary> /// Delta credit (DC) is used by the system management application entity /// (SMAE) of the Client for credit management, while it has no meaning for a Server or a REPEATER. /// It represents the difference(IC-CC) of the last communication originated by the system identified by the DA address to the system identified by the SA address. /// Maximum value is 3. /// </summary> public byte DeltaCredit { get; set; } /// <summary> /// IEC 61334-4-32 LLC uses 6 bytes long system title. IEC 61334-5-1 uses 8 bytes long system title so we can use the default one. /// </summary> public byte[] SystemTitle { get { if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null) { return settings.Cipher.SystemTitle; } return _systemTitle; } set { if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null) { settings.Cipher.SystemTitle = value; } _systemTitle = value; } } /// <summary> /// Source MAC address. /// </summary> public UInt16 MacSourceAddress { get; set; } /// <summary> /// Destination MAC address. /// </summary> public UInt16 MacDestinationAddress { get; set; } /// <summary> /// Response probability. /// </summary> public byte ResponseProbability { get; set; } /// <summary> /// Allowed time slots. /// </summary> public UInt16 AllowedTimeSlots { get; set; } /// <summary> /// Server saves client system title. /// </summary> public byte[] ClientSystemTitle { get; set; } /// <summary> /// Set default values. /// </summary> public void Reset() { InitialCredit = 7; CurrentCredit = 7; DeltaCredit = 0; //New device addresses are used. if (settings.InterfaceType == Enums.InterfaceType.Plc) { if (settings.IsServer) { MacSourceAddress = (UInt16)PlcSourceAddress.New; MacDestinationAddress = (UInt16)PlcSourceAddress.Initiator; } else { MacSourceAddress = (UInt16)PlcSourceAddress.Initiator; MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical; } } else { if (settings.IsServer) { MacSourceAddress = (UInt16)PlcSourceAddress.New; MacDestinationAddress = (UInt16)PlcHdlcSourceAddress.Initiator; } else { MacSourceAddress = (UInt16)PlcHdlcSourceAddress.Initiator; MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical; } } ResponseProbability = 100; if (settings.InterfaceType == Enums.InterfaceType.Plc) { AllowedTimeSlots = 10; } else { AllowedTimeSlots = 0x14; } } internal GXPlcSettings(GXDLMSSettings s) { settings = s; Reset(); } /// <summary> /// Discover available PLC meters. /// </summary> /// <returns>Generated bytes.</returns> public byte[] DiscoverRequest() { GXByteBuffer bb = new GXByteBuffer(); if (settings.InterfaceType != Enums.InterfaceType.Plc && settings.InterfaceType != Enums.InterfaceType.PlcHdlc) { throw new ArgumentOutOfRangeException("Invalid interface type."); } if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { bb.Set(GXCommon.LLCSendBytes); } bb.SetUInt8((byte)Command.DiscoverRequest); bb.SetUInt8(ResponseProbability); bb.SetUInt16(AllowedTimeSlots); //DiscoverReport initial credit bb.SetUInt8(0); // IC Equal credit bb.SetUInt8(0); int val = 0; int clientAddress = settings.ClientAddress; int serverAddress = settings.ServerAddress; UInt16 da = settings.Plc.MacDestinationAddress; UInt16 sa = settings.Plc.MacSourceAddress; try { //10.4.6.4 Source and destination APs and addresses of CI-PDUs //Client address is No-station in discoverReport. if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { settings.Plc.InitialCredit = 0; settings.Plc.CurrentCredit = 0; settings.Plc.MacSourceAddress = 0xC01; settings.Plc.MacDestinationAddress = 0xFFF; settings.ClientAddress = 0x66; // All-station settings.ServerAddress = 0x33FF; } else { val = settings.Plc.InitialCredit << 5; val |= settings.Plc.CurrentCredit << 2; val |= settings.Plc.DeltaCredit & 0x3; settings.Plc.MacSourceAddress = 0xC00; settings.ClientAddress = 1; settings.ServerAddress = 0; } return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb); } finally { settings.ClientAddress = clientAddress; settings.ServerAddress = serverAddress; settings.Plc.MacDestinationAddress = da; settings.Plc.MacSourceAddress = sa; } } /// <summary> /// Generates discover report. /// </summary> /// <param name="systemTitle">System title</param> /// <param name="newMeter">Is this a new meter.</param> /// <returns>Generated bytes.</returns> public byte[] DiscoverReport(byte[] systemTitle, bool newMeter) { GXByteBuffer bb = new GXByteBuffer(); if (settings.InterfaceType != Enums.InterfaceType.Plc && settings.InterfaceType != Enums.InterfaceType.PlcHdlc) { throw new ArgumentOutOfRangeException("Invalid interface type."); } byte alarmDescription; if (settings.InterfaceType == Enums.InterfaceType.Plc) { alarmDescription = (byte)(newMeter ? 1 : 0x82); } else { alarmDescription = 0; } if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { bb.Set(GXCommon.LLCReplyBytes); } bb.SetUInt8((byte)Command.DiscoverReport); bb.SetUInt8(1); bb.Set(systemTitle); if (alarmDescription != 0) { bb.SetUInt8(1); } bb.SetUInt8(alarmDescription); int clientAddress = settings.ClientAddress; int serverAddress = settings.ServerAddress; UInt16 macSourceAddress = settings.Plc.MacSourceAddress; UInt16 macTargetAddress = settings.Plc.MacDestinationAddress; try { //10.4.6.4 Source and destination APs and addresses of CI-PDUs //Client address is No-station in discoverReport. if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { settings.Plc.MacDestinationAddress = (UInt16) PlcHdlcSourceAddress.Initiator; } else { settings.ClientAddress = 0; settings.ServerAddress = 0xFD; } return GXDLMS.GetMacFrame(settings, 0x13, 0, bb); } finally { settings.ClientAddress = clientAddress; settings.ServerAddress = serverAddress; settings.Plc.MacSourceAddress = macSourceAddress; settings.Plc.MacDestinationAddress = macTargetAddress; } } /// <summary> /// Parse discover reply. /// </summary> /// <param name="value"></param> /// <returns>Array of system titles and alarm descriptor error code</returns> public List<GXDLMSPlcMeterInfo> ParseDiscover(GXByteBuffer value, UInt16 sa, UInt16 da) { List<GXDLMSPlcMeterInfo> list = new List<GXDLMSPlcMeterInfo>(); byte count = value.GetUInt8(); for (int pos = 0; pos != count; ++pos) { GXDLMSPlcMeterInfo info = new GXDLMSPlcMeterInfo(); info.SourceAddress = sa; info.DestinationAddress = da; //Get System title. if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { info.SystemTitle = new byte[8]; } else { info.SystemTitle = new byte[6]; } value.Get(info.SystemTitle); // Alarm descriptor of the reporting system. // Alarm-Descriptor presence flag if (value.GetUInt8() != 0) { //Alarm-Descriptor info.AlarmDescriptor = value.GetUInt8(); } list.Add(info); } return list; } /// <summary> /// Register PLC meters. /// </summary> /// <param name="initiatorSystemTitle">Active initiator systemtitle</param> /// <param name="systemTitle"></param> /// <returns>Generated bytes.</returns> public byte[] RegisterRequest(byte[] initiatorSystemTitle, byte[] systemTitle) { GXByteBuffer bb = new GXByteBuffer(); //Control byte. bb.SetUInt8((byte)Command.RegisterRequest); bb.Set(initiatorSystemTitle); //LEN bb.SetUInt8(0x1); bb.Set(systemTitle); //MAC address. bb.SetUInt16(MacSourceAddress); int val = settings.Plc.InitialCredit << 5; val |= settings.Plc.CurrentCredit << 2; val |= settings.Plc.DeltaCredit & 0x3; int clientAddress = settings.ClientAddress; int serverAddress = settings.ServerAddress; UInt16 macSourceAddress = settings.Plc.MacSourceAddress; UInt16 macTargetAddress = settings.Plc.MacDestinationAddress; try { //10.4.6.4 Source and destination APs and addresses of CI-PDUs //Client address is No-station in discoverReport. if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { settings.Plc.InitialCredit = 0; settings.Plc.CurrentCredit = 0; settings.Plc.MacSourceAddress = 0xC01; settings.Plc.MacDestinationAddress = 0xFFF; settings.ClientAddress = 0x66; // All-station settings.ServerAddress = 0x33FF; } else { settings.ClientAddress = 1; settings.ServerAddress = 0; settings.Plc.MacSourceAddress = 0xC00; settings.Plc.MacDestinationAddress = 0xFFF; } return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb); } finally { settings.ClientAddress = clientAddress; settings.ServerAddress = serverAddress; settings.Plc.MacSourceAddress = macSourceAddress; settings.Plc.MacDestinationAddress = macTargetAddress; } } /// <summary> /// Parse register request. /// </summary> /// <param name="value"></param> /// <returns>System title mac address.</returns> public void ParseRegisterRequest(GXByteBuffer value) { //Get System title. byte[] st; if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { st = new byte[8]; } else { st = new byte[6]; } value.Get(st); byte count = value.GetUInt8(); for (int pos = 0; pos != count; ++pos) { //Get System title. if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc) { st = new byte[8]; } else { st = new byte[6]; } value.Get(st); SystemTitle = st; //MAC address. MacSourceAddress = value.GetUInt16(); } } /// <summary> /// Parse discover request. /// </summary> /// <param name="value"></param> /// <returns></returns> public GXDLMSPlcRegister ParseDiscoverRequest(GXByteBuffer value) { GXDLMSPlcRegister ret = new GXDLMSPlcRegister(); ret.ResponseProbability = value.GetUInt8(); ret.AllowedTimeSlots = value.GetUInt16(); ret.DiscoverReportInitialCredit = value.GetUInt8(); ret.ICEqualCredit = value.GetUInt8(); return ret; } /// <summary> /// Ping PLC meter. /// </summary> /// <returns>Generated bytes.</returns> public byte[] PingRequest(byte[] systemTitle) { GXByteBuffer bb = new GXByteBuffer(); //Control byte. bb.SetUInt8((byte)Command.PingRequest); bb.Set(systemTitle); return GXDLMS.GetMacFrame(settings, 0x13, 0, bb); } /// <summary> /// Parse ping response. /// </summary> /// <param name="value">Received data.</param> public byte[] ParsePing(GXByteBuffer value) { return value.SubArray(1, 6); } /// <summary> /// Repear call request. /// </summary> /// <returns>Generated bytes.</returns> public byte[] RepeaterCallRequest() { GXByteBuffer bb = new GXByteBuffer(); //Control byte. bb.SetUInt8((byte)Command.RepeatCallRequest); //MaxAdrMac. bb.SetUInt16(0x63); //Nb_Tslot_For_New bb.SetUInt8(0); //Reception-Threshold default value bb.SetUInt8(0); return GXDLMS.GetMacFrame(settings, 0x13, 0xFC, bb); } } }
Gurux/Gurux.DLMS.Net
Development/Plc/GXPlcSettings.cs
C#
gpl-2.0
17,732
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script src="js/jquery.min.js"></script> <script type="text/javascript" src="js/js.cookie.js"></script> <title>BenchmarkTest01074</title> </head> <body> <form action="/benchmark/BenchmarkTest01074" method="POST" id="FormBenchmarkTest01074"> <div><label>Please explain your answer:</label></div> <br/> <div><textarea rows="4" cols="50" id="vectorArea" name="vectorArea" value=""></textarea></div> <div><label>Any additional note for the reviewer:</label></div> <div><input type="text" id="answer" name="answer"></input></div> <br/> <div><label>An AJAX request will be sent with a header named vector and value:</label> <input type="text" id="vector" name="vector" value="whatever" class="safe"></input></div> <div><input type="button" id="login-btn" value="Login" /></div> </form> <div id="ajax-form-msg1"></div> <script> $('.safe').keypress(function (e) { if (e.which == 13) { $('#login-btn').trigger('click'); return false; } }); $("#login-btn").click(function(){ var formData = $("#FormBenchmarkTest01074").serializeArray(); var URL = $("#FormBenchmarkTest01074").attr("action"); var text = $("#FormBenchmarkTest01074 input[id=vector]").val(); $.ajax({ url : URL, headers: { 'vector': text }, type: "POST", data : formData, success: function(data, textStatus, jqXHR){ $("#ajax-form-msg1").html('<pre><code class="prettyprint">'+data+'</code></pre>'); }, error: function (jqXHR, textStatus, errorThrown){ alert(errorThrown);} }); }); </script> </body> </html>
ganncamp/Benchmark
src/main/webapp/BenchmarkTest01074.html
HTML
gpl-2.0
1,776
// vim: ts=4 sw=4 expandtab ft=c // Copyright (C) 1998-2012 The University of Melbourne. // This file may only be copied under the terms of the GNU Library General // Public License - see the file COPYING.LIB in the Mercury distribution. #ifndef MERCURY_STACK_LAYOUT_H #define MERCURY_STACK_LAYOUT_H // mercury_stack_layout.h - // // Definitions for stack layout data structures. These are generated by the // compiler, and are used by the parts of the runtime system that need to look // at the stacks (and sometimes the registers) and make sense of their // contents. The parts of the runtime system that need to do this include // exception handling, the debugger, and (eventually) the accurate garbage // collector. // // For a general description of the idea of stack layouts, see the paper // "Run time type information in Mercury" by Tyson Dowd, Zoltan Somogyi, // Fergus Henderson, Thomas Conway and David Jeffery, which is available from // the Mercury web site. The relevant section is section 3.8, but be warned: // while the general principles remain applicable, the details have changed // since that paper was written. // // NOTE: The constants and data-structures used here need to be kept in // sync with the ones generated in the compiler. If you change anything here, // you may need to change stack_layout.m, layout.m, and/or layout_out.m in // the compiler directory as well. #include "mercury_types.h" #include "mercury_std.h" // for MR_VARIABLE_SIZED #include "mercury_tags.h" #include "mercury_type_info.h" // for MR_PseudoTypeInfo #include "mercury_proc_id.h" // for MR_ProcId #include "mercury_goto.h" // for MR_PROC_LAYOUT etc #include "mercury_tabling.h" // for MR_TableTrieStep etc //////////////////////////////////////////////////////////////////////////// // Definitions for MR_Determinism. // The max_soln component of the determinism is encoded in the 1 and 2 bits. // The can_fail component of the determinism is encoded in the 4 bit. // The first_solution component of the determinism is encoded in the 8 bit. // // MR_DETISM_AT_MOST_MANY could also be defined as ((d) & 3) == 3), // but this would be less efficient, since the C compiler does not know // that we do not set the 1 bit unless we also set the 2 bit. // // NOTE: this must match the encoding specified by represent_determinism/1 // in mdbcomp/program_representation.m. typedef MR_int_least16_t MR_Determinism; #define MR_DETISM_DET 6 #define MR_DETISM_SEMI 2 #define MR_DETISM_NON 3 #define MR_DETISM_MULTI 7 #define MR_DETISM_ERRONEOUS 4 #define MR_DETISM_FAILURE 0 #define MR_DETISM_CCNON 10 #define MR_DETISM_CCMULTI 14 #define MR_DETISM_MAX 14 #define MR_DETISM_AT_MOST_ZERO(d) (((d) & 3) == 0) #define MR_DETISM_AT_MOST_ONE(d) (((d) & 3) == 2) #define MR_DETISM_AT_MOST_MANY(d) (((d) & 1) != 0) #define MR_DETISM_CAN_FAIL(d) (((d) & 4) == 0) #define MR_DETISM_FIRST_SOLN(d) (((d) & 8) != 0) #define MR_DETISM_DET_STACK(d) (!MR_DETISM_AT_MOST_MANY(d) \ || MR_DETISM_FIRST_SOLN(d)) //////////////////////////////////////////////////////////////////////////// // Definitions for MR_LongLval and MR_ShortLval. // MR_LongLval is an MR_Unsigned which describes a location. // This includes lvals such as stack slots, general registers, and special // registers such as succip, hp, etc, as well as locations whose address is // given as a typeinfo inside the type class info structure pointed to by an // lval. // // What kind of location an MR_LongLval refers to is encoded using // a low tag with MR_LONG_LVAL_TAGBITS bits; the type MR_LongLvalType // describes the different tag values. The interpretation of the rest of // the word depends on the location type: // // Locn Rest // // MR_r(Num) Num (register number) // MR_f(Num) Num (register number) // MR_stackvar(Num) Num (stack slot number) // MR_framevar(Num) Num (stack slot number) // MR_succip // MR_maxfr // MR_curfr // MR_hp // MR_sp // constant See below // indirect(Base, N) See below // unknown (The location is not known) // // For constants, the rest of the word is a pointer to static data. The // pointer has only two low tag bits free, so we reserve every four-bit tag // which has 00 as its bottom two bits for representing them. // // For indirect references, the word exclusive of the tag consists of // (a) an integer with MR_LONG_LVAL_OFFSETBITS bits giving the index of // the typeinfo inside a type class info (to be interpreted by // MR_typeclass_info_type_info or the predicate // private_builtin.type_info_from_typeclass_info, which calls it) and // (b) a MR_LongLval value giving the location of the pointer to the // type class info. This MR_LongLval value will *not* have an indirect tag. // // This data is generated in stack_layout.represent_locn_as_int, // which must be kept in sync with the constants and macros defined here. typedef MR_Unsigned MR_LongLval; typedef enum { MR_LONG_LVAL_TYPE_CONS_0 = 0, MR_LONG_LVAL_TYPE_R = 1, MR_LONG_LVAL_TYPE_F = 2, MR_LONG_LVAL_TYPE_STACKVAR = 3, MR_LONG_LVAL_TYPE_CONS_1 = 4, MR_LONG_LVAL_TYPE_FRAMEVAR = 5, MR_LONG_LVAL_TYPE_SUCCIP = 6, MR_LONG_LVAL_TYPE_MAXFR = 7, MR_LONG_LVAL_TYPE_CONS_2 = 8, MR_LONG_LVAL_TYPE_CURFR = 9, MR_LONG_LVAL_TYPE_HP = 10, MR_LONG_LVAL_TYPE_SP = 11, MR_LONG_LVAL_TYPE_CONS_3 = 12, MR_LONG_LVAL_TYPE_DOUBLE_STACKVAR = 13, MR_LONG_LVAL_TYPE_DOUBLE_FRAMEVAR = 14, MR_LONG_LVAL_TYPE_INDIRECT = 15, MR_LONG_LVAL_TYPE_CONS_4 = 16, MR_LONG_LVAL_TYPE_UNKNOWN = 17, MR_LONG_LVAL_TYPE_CONS_5 = 20, MR_LONG_LVAL_TYPE_CONS_6 = 24, MR_LONG_LVAL_TYPE_CONS_7 = 28 } MR_LongLvalType; // This must be in sync with stack_layout.long_lval_tag_bits. #define MR_LONG_LVAL_TAGBITS 5 #define MR_LONG_LVAL_CONST_TAGBITS 2 #define MR_LONG_LVAL_TYPE(Locn) \ ((MR_LongLvalType) ((Locn) & ((1 << MR_LONG_LVAL_TAGBITS) - 1))) #define MR_LONG_LVAL_NUMBER(Locn) \ ((int) ((Locn) >> MR_LONG_LVAL_TAGBITS)) #define MR_LONG_LVAL_CONST(Locn) \ (* (MR_Word *) ((Locn) & ~ ((1 << MR_LONG_LVAL_CONST_TAGBITS) - 1))) // This must be in sync with stack_layout.offset_bits. #define MR_LONG_LVAL_OFFSETBITS 6 #define MR_LONG_LVAL_INDIRECT_OFFSET(LocnNumber) \ ((int) ((LocnNumber) & ((1 << MR_LONG_LVAL_OFFSETBITS) - 1))) #define MR_LONG_LVAL_INDIRECT_BASE_LVAL_INT(LocnNumber) \ (((MR_uint_least32_t) (LocnNumber)) >> MR_LONG_LVAL_OFFSETBITS) #define MR_LONG_LVAL_STACKVAR_INT(n) \ (((n) << MR_LONG_LVAL_TAGBITS) + MR_LONG_LVAL_TYPE_STACKVAR) #define MR_LONG_LVAL_FRAMEVAR_INT(n) \ (((n) << MR_LONG_LVAL_TAGBITS) + MR_LONG_LVAL_TYPE_FRAMEVAR) #define MR_LONG_LVAL_R_REG_INT(n) \ (((n) << MR_LONG_LVAL_TAGBITS) + MR_LONG_LVAL_TYPE_R) // MR_ShortLval is a MR_uint_least8_t which describes an location. This // includes lvals such as stack slots and general registers that have small // numbers, and special registers such as succip, hp, etc. // // What kind of location an MR_LongLval refers to is encoded using // a low tag with 2 bits; the type MR_ShortLval_Type describes // the different tag values. The interpretation of the rest of the word // depends on the location type: // // Locn Tag Rest // MR_r(Num) 0 Num (register number) // MR_stackvar(Num) 1 Num (stack slot number) // MR_framevar(Num) 2 Num (stack slot number) // special reg 3 MR_LongLvalType // // This data is generated in stack_layout.represent_locn_as_byte, // which must be kept in sync with the constants and macros defined here. typedef MR_uint_least8_t MR_ShortLval; typedef enum { MR_SHORT_LVAL_TYPE_R, MR_SHORT_LVAL_TYPE_STACKVAR, MR_SHORT_LVAL_TYPE_FRAMEVAR, MR_SHORT_LVAL_TYPE_SPECIAL } MR_ShortLval_Type; // This must be in sync with stack_layout.short_lval_tag_bits. #define MR_SHORT_LVAL_TAGBITS 2 #define MR_SHORT_LVAL_TYPE(Locn) \ ((MR_ShortLval_Type) \ (((MR_Word) Locn) & ((1 << MR_SHORT_LVAL_TAGBITS) - 1))) #define MR_SHORT_LVAL_NUMBER(Locn) \ ((int) (((MR_Word) Locn) >> MR_SHORT_LVAL_TAGBITS)) #define MR_SHORT_LVAL_STACKVAR(n) \ ((MR_ShortLval) (((n) << MR_SHORT_LVAL_TAGBITS) \ + MR_SHORT_LVAL_TYPE_STACKVAR)) #define MR_SHORT_LVAL_FRAMEVAR(n) \ ((MR_ShortLval) (((n) << MR_SHORT_LVAL_TAGBITS) \ + MR_SHORT_LVAL_TYPE_FRAMEVAR)) #define MR_SHORT_LVAL_R_REG(n) \ ((MR_ShortLval) (((n) << MR_SHORT_LVAL_TAGBITS) \ + MR_SHORT_LVAL_TYPE_R)) //////////////////////////////////////////////////////////////////////////// // Definitions for MR_UserEvent and MR_UserEventSpec. // Our layout structures link to information about user events from two places: // the label layout structures of labels that correspond to user events, // and the module layout structures of modules that contain user events. // Label layout structures link to MR_UserEvent structures; module layout // structures link to MR_UserEventSpec structures. Most of the information // is in the MR_UserEventSpec structures; MR_UserEvent structures contain // only information that may differ between two instances of the same event. // The fields of MR_UserEvent: // // The event_number field contains the ordinal number of the event in the // event set the module was compiled with: it gives the identity of the event. // (Event numbers start at zero.) This field is also the link to the rest of // the information about the event, contained in the MR_UserEventSpec structure // linked to by the module layout structure. The MR_user_event_spec macro // follows this link. // // The next two fields all point to arrays whose length is the number of // attributes (which is available in the MR_UserEventSpec structure). // // attr_locns[i] gives the location where we can find the value of the // i'th attribute (the first attribute is attribute zero). This is // meaningful only if the attribute is not a synthesized attribute. // // attr_var_nums[i] gives the variable number of the i'th attribute; // if it contains zero, that means the attribute is synthesized. This field // is used by the debugger to display the associated value just once // (not twice, as both attribute and variable value) with "print *". (Note // that we don't delete the variables that are also attributes from the set of // live variables in layout structures, because that would require any native // garbage collector to look at the list of attributes as well as the list of // other variables, slowing it down.) typedef MR_uint_least16_t MR_HLDSVarNum; struct MR_UserEvent_Struct { MR_uint_least16_t MR_ue_event_number; MR_LongLval *MR_ue_attr_locns; const MR_HLDSVarNum *MR_ue_attr_var_nums; }; // The fields of MR_UserEventSpec: // // The event_name field contains the name of the event. // // The num_attrs field gives the number of attributes. // // The next three fields (attr_names, attr_types and synth_attrs) all point // to arrays whose length is the number of attributes. // // attr_names[i] gives the name of the i'th attribute. // // attr_types[i] is the typeinfo giving the type of the i'th attribute. // // If the i'th attribute is synthesized, synth_attrs[i] points to the // information required to synthesize it: the number of the attribute // containing the synthesis function, the number of arguments of the synthesis // function, and an array of attribute numbers (of length num_arg_attrs) // giving the list of those arguments. The depend_attrs field will point to // a list of numbers of the synthesized attributes whose values must be // materialized before this attribute can be evaluated. (This list will include // the argument attributes, and will be in a feasible evaluation order.) // If the i'th attribute is not synthesized, synth_attrs[i] and depend_attrs[i] // will both be NULL. (For now, depend_attrs[i] will not be filled in for // synthesized attributes either.) // // The synth_attr_order field points to an array of attribute numbers that // gives the order in which the values of the synthesized attributes should be // evaluated. The array is ended by -1 as a sentinel. // // The synth_attrs and synth_attr_order fields will both be NULL for events // that have no synthesized attributes. struct MR_SynthAttr_Struct { MR_int_least16_t MR_sa_func_attr; MR_int_least16_t MR_sa_num_arg_attrs; MR_uint_least16_t *MR_sa_arg_attrs; MR_int_least16_t *MR_sa_depend_attrs; }; struct MR_UserEventSpec_Struct { const char *MR_ues_event_name; MR_uint_least16_t MR_ues_num_attrs; const char **MR_ues_attr_names; MR_TypeInfo *MR_ues_attr_types; MR_SynthAttr *MR_ues_synth_attrs; MR_int_least16_t *MR_ues_synth_attr_order; }; #define MR_user_event_spec(label_layout) \ label_layout->MR_sll_entry->MR_sle_module_layout-> \ MR_ml_user_event_specs[label_layout->MR_sll_user_event-> \ MR_ue_event_number] #define MR_user_event_set_name(label_layout) \ label_layout->MR_sll_entry->MR_sle_module_layout-> \ MR_ml_user_event_set_name //////////////////////////////////////////////////////////////////////////// // Definitions for MR_LabelLayout. // An MR_LabelLayout structure describes the debugging and accurate gc // information available at a given label. // // The MR_sll_entry field points to the proc layout structure of the procedure // in which the label occurs. // // The MR_sll_port field will contain a negative number if there is no // execution tracing port associated with the label. If there is, the // field will contain a value of type MR_TracePort. For labels associated // with events, this will be the port of the event. For return labels, // this port will be exception (since exception events are associated with // the return from the call that raised the exception). // // The MR_sll_hidden field contains a boolean which is meaningful only if the // label corresponds to an execution tracing event. It will be MR_HIDDEN if the // event should have no effects that the user can see (no message printed, no // increment of the event number etc), and MR_NOT_HIDDEN otherwise. Hidden // events are sometimes needed by the declarative debugger to provide the // proper context for other events. // // The MR_sll_goal_path field contains an offset into the module-wide string // table, leading to a string that gives the goal path associated with the // label. If there is no meaningful goal path associated with the label, // the offset will be zero, leading to the empty string. You can use the macro // MR_label_goal_path to convert the value in the MR_sll_goal_path field to a // string. // // A possible alternative would be to represent goal paths using statically // allocated terms of the reverse_goal_path type. An almost-complete diff // making that change was posted to the mercury-reviews mailing list on // 30 Sep 2011, but it was not committed, since it lead to a 4% *increase* // in the size of asm_fast.gc.debug executables. Even though different goal // paths share a tail (the part of the path near the root) with the // static reverse_goal_path term representation but not with the string // representation, the string representation is so much more compact // (usually taking 4 to 6 bytes for most steps) than the Mercury term // representation (1 to 4 words for a step, plus 2 words for the rgp_cons, // totalling at least 24 bytes per step on 64 bit systems), that the string // representation is significantly more compact overall. The Mercury term // representation does have the potential to speed up the implementation of // the operations in the declarative debugger that need to test whether // two goal paths represent two different direct components of the same parent // goal. If the two different goal paths are represented as reverse_goal_paths, // then doing this test on RGPA and RGPB simply requires the test // // RGPA = rgp_cons(ParentRGPA, StepA), // RGPB = rgp_cons(ParentRGPB, StepB), // ParentRGPA = ParentRGPB // // and the last step can be done by a pointer comparison. This test can be done // in constant time, whereas the current implementation of the same test // (the function MR_trace_same_construct in trace/mercury_trace_declarative.c) // works in linear time. // // If the label is the label of a user-defined event, then the // MR_sll_user_event field will point to information about the user event; // otherwise, the field will be NULL. // // The remaining fields give information about the values live at the given // label, if this information is available. If it is available, the // MR_has_valid_var_count macro will return true and the fields after the count // are meaningful; if it is not available, the macro will return false and // those fields are not meaningful (i.e. you are looking at an // MR_LabelLayoutNoVarInfo structure). // // The format in which we store information about the values live at the label // is somewhat complicated, due to our desire to make this information compact. // We can represent a location in one of two ways, as an 8-bit MR_ShortLval // or as a 32-bit MR_LongLval. We prefer representing a location as an // MR_ShortLval, but of course not all locations can be represented in // this way, so those other locations are represented as MR_LongLvals. // // The MR_sll_var_count field, if it is valid, is encoded by the formula // (#Long << MR_SHORT_COUNT_BITS + #Short), where #Short is the number // data items whose descriptions fit into an MR_ShortLval and #Long is the // number of data items whose descriptions do not. (The number of distinct // values that fit into 8 bits also fits into 8 bits, but since some // locations hold the value of more than one variable at a time, not all // the values need to be distinct; this is why MR_SHORT_COUNT_BITS is // more than 8.) // // The MR_sll_types field points to an array of #Long + #Short // MR_PseudoTypeInfos each giving the type of a live data item, with // a small integer instead of a pointer representing a special kind of // live data item (e.g. a saved succip or hp). This field will be null if // #Long + #Short is zero. // // The MR_sll_long_locns field points to an array of #Long MR_LongLvals, // while the MR_sll_short_locns field points to an array of #Short // MR_ShortLvals. The element at index i in the MR_sll_long_locns vector // will have its type described by the element at index i in the MR_sll_types // vector, while the element at index i in the MR_sll_short_locns vector // will have its type described by the element at index #Long + i in the // MR_sll_types vector. MR_sll_long_locns will be NULL if #Long is zero, // and similarly MR_sll_short_locns will be NULL if #Short is zero. // // The MR_sll_var_nums field may be NULL, which means that there is no // information about the variable numbers of the live values. If the field // is not NULL, it points to a vector of variable numbers, which has an element // for each live data item. This is either the live data item's HLDS variable // number, or one of two special values. Zero means that the live data item // is not a variable (e.g. it is a saved copy of succip). The largest possible // 16-bit number on the other hand means "the number of this variable does not // fit into 16 bits". With the exception of these special values, the value // in this slot uniquely identifies the live data item. (Not being able to // uniquely identify nonvariable data items is never a problem. Not being able // to uniquely identify variables is a problem, at the moment, only to the // extent that the debugger cannot print their names.) // // The types of the live variables may or may not have type variables in them. // If they do not, the MR_sll_tvars field will be NULL. If they do, it will // point to an MR_TypeParamLocns structure that gives the locations of the // typeinfos for those type variables. This structure gives the number of type // variables and their locations, so that the code that needs the type // parameters can materialize all the type parameters from their location // descriptions in one go. This is an optimization, since the type parameter // vector could simply be indexed on demand by the type variable's variable // number stored within the MR_PseudoTypeInfos stored inside the vector // pointed to by the MR_sll_types field. // // Since we allocate type variable numbers sequentially, the MR_tp_param_locns // vector will usually be dense. However, after all variables whose types // include e.g. type variable 2 have gone out of scope, variables whose // types include type variable 3 may still be around. In cases like this, // the entry for type variable 2 will be zero; this signals to the code // in the internal debugger that materializes typeinfo structures that // this typeinfo structure need not be materialized. Note that the array // element MR_tp_param_locns[i] describes the location of the typeinfo // structure for type variable i+1, since array offsets start at zero // but type variable numbers start at one. // // The MR_sll_label_num_in_module is used for counting the number of times // the event of this label is executed. It gives the label's index in the // array pointed to by the module layout's MR_ml_label_exec_count field; // whenever the event of this label is executed, the element in that array // indicated by this index will be incremented (when MR_trace_count_enabled // is set). The array element at index zero is ignored. A label layout will // have zero in its MR_sll_label_num_in_module field if the label doesn't // correspond to an event. // // XXX: Presently, inst information is ignored; we assume that all live values // are ground. #define MR_HIDDEN 1 #define MR_NOT_HIDDEN 0 struct MR_TypeParamLocns_Struct { MR_uint_least32_t MR_tp_param_count; MR_LongLval MR_tp_param_locns[MR_VARIABLE_SIZED]; }; struct MR_LabelLayout_Struct { const MR_ProcLayout *MR_sll_entry; MR_int_least8_t MR_sll_port; MR_int_least8_t MR_sll_hidden; MR_uint_least16_t MR_sll_label_num_in_module; MR_uint_least32_t MR_sll_goal_path; const MR_UserEvent *MR_sll_user_event; MR_Integer MR_sll_var_count; // >= 0, encoding Long > 0 const MR_TypeParamLocns *MR_sll_tvars; const MR_PseudoTypeInfo *MR_sll_types; const MR_HLDSVarNum *MR_sll_var_nums; const MR_ShortLval *MR_sll_short_locns; const MR_LongLval *MR_sll_long_locns; }; typedef struct MR_LabelLayoutShort_Struct { const MR_ProcLayout *MR_sll_entry; MR_int_least8_t MR_sll_port; MR_int_least8_t MR_sll_hidden; MR_uint_least16_t MR_sll_label_num_in_module; MR_uint_least32_t MR_sll_goal_path; const MR_UserEvent *MR_sll_user_event; MR_Integer MR_sll_var_count; // >= 0 , encoding Long == 0 const MR_TypeParamLocns *MR_sll_tvars; const MR_PseudoTypeInfo *MR_sll_types; const MR_HLDSVarNum *MR_sll_var_nums; const MR_ShortLval *MR_sll_short_locns; } MR_LabelLayoutShort; typedef struct MR_LabelLayoutNoVarInfo_Struct { const MR_ProcLayout *MR_sll_entry; MR_int_least8_t MR_sll_port; MR_int_least8_t MR_sll_hidden; MR_uint_least16_t MR_sll_label_num_in_module; MR_uint_least32_t MR_sll_goal_path; const MR_UserEvent *MR_sll_user_event; MR_Integer MR_sll_var_count; // < 0 } MR_LabelLayoutNoVarInfo; #define MR_label_goal_path(layout) \ ((MR_PROC_LAYOUT_HAS_EXEC_TRACE((layout)->MR_sll_entry)) ? \ ((layout)->MR_sll_entry->MR_sle_module_layout \ ->MR_ml_string_table \ + ((layout)->MR_sll_goal_path >> 1)) \ : "") #define MR_SHORT_COUNT_BITS 10 #define MR_SHORT_COUNT_MASK ((1 << MR_SHORT_COUNT_BITS) - 1) #define MR_has_valid_var_count(sll) \ (((sll)->MR_sll_var_count) >= 0) #define MR_has_valid_var_info(sll) \ (((sll)->MR_sll_var_count) > 0) #define MR_short_desc_var_count(sll) \ (((sll)->MR_sll_var_count) & MR_SHORT_COUNT_MASK) #define MR_long_desc_var_count(sll) \ (((sll)->MR_sll_var_count) >> MR_SHORT_COUNT_BITS) #define MR_all_desc_var_count(sll) \ (MR_long_desc_var_count(sll) + MR_short_desc_var_count(sll)) #define MR_var_pti(sll, i) \ ((sll)->MR_sll_types[(i)]) #define MR_short_desc_var_locn(sll, i) \ ((sll)->MR_sll_short_locns[(i)]) #define MR_long_desc_var_locn(sll, i) \ ((sll)->MR_sll_long_locns[(i)]) // Define a stack layout for an internal label. // // The only useful information in the structures created by this macro // is the reference to the procedure layout, which allows you to find the // stack frame size and the succip location, thereby enabling stack tracing. // // For the native garbage collector, we will need to add meaningful // live value information as well to these macros. #define MR_LAYOUT_FROM_LABEL(label) \ MR_PASTE2(mercury_data__label_layout__, label) #define MR_LABEL_LAYOUT_REF(label) \ ((const MR_LabelLayout *) &MR_LAYOUT_FROM_LABEL(MR_add_prefix(label))) #define MR_MAKE_USER_INTERNAL_LAYOUT(module, name, arity, mode, label) \ MR_LabelLayoutNoVarInfo \ MR_label_layout_user_name(module, name, arity, mode, label) = { \ (MR_ProcLayout *) & \ MR_proc_layout_user_name(module, name, arity, mode), \ 0, \ -1, \ MR_FALSE, \ 0, \ 0, \ -1 /* No info about live values. */ \ } //////////////////////////////////////////////////////////////////////////// // These macros are used as shorthands in generated C source files // for some fields of MR_LabelLayouts. // // We need to cast the addresses of proc layout structures because there // are several kinds of proc layouts, of different (though compatible) types. #define MR_LL(e, port, num, path) \ MR_PROC_LAYOUT(MR_add_prefix(e)), \ MR_PASTE2(MR_PORT_, port), \ MR_NOT_HIDDEN, (num), (path), NULL #define MR_LL_H(e, port, num, path) \ MR_PROC_LAYOUT(MR_add_prefix(e)), \ MR_PASTE2(MR_PORT_, port), \ MR_HIDDEN, (num), (path), NULL #define MR_LL_U(e, port, num, path, ue) \ MR_PROC_LAYOUT(MR_add_prefix(e)), \ MR_PASTE2(MR_PORT_, port), \ MR_NOT_HIDDEN, (num), (path), (ue) #define MR_LL_H_U(e, port, num, path, ue) \ MR_PROC_LAYOUT(MR_add_prefix(e)), \ MR_PASTE2(MR_PORT_, port), \ MR_HIDDEN, (num), (path), (ue) #define MR_LLVS(m, p, h, s) \ &MR_pseudo_type_infos(m)[p], \ &MR_hlds_var_nums(m)[h], \ &MR_short_locns(m)[s] #define MR_LLVL(m, p, h, s, l) \ &MR_pseudo_type_infos(m)[p], \ &MR_hlds_var_nums(m)[h], \ &MR_short_locns(m)[s], \ &MR_long_locns(m)[l] #define MR_LLVS0(m, p, h, s) \ 0, \ MR_LLVS(m, p, h, s) #define MR_LLVL0(m, p, h, s, l) \ 0, \ MR_LLVL(m, p, h, s, l) #define MR_LLVSC(m, tpt, tpc, p, h, s) \ (const MR_TypeParamLocns *) MR_COMMON(tpt, tpc), \ MR_LLVS(m, p, h, s) #define MR_LLVLC(m, tpt, tpc, p, h, s, l) \ (const MR_TypeParamLocns *) MR_COMMON(tpt, tpc), \ MR_LLVL(m, p, h, s, l) #define MR_cast_to_pti1(r1) \ (MR_PseudoTypeInfo) (r1), #define MR_cast_to_pti2(r1, r2) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), #define MR_cast_to_pti3(r1, r2, r3) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3) #define MR_cast_to_pti4(r1, r2, r3, r4) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), #define MR_cast_to_pti5(r1, r2, r3, r4, r5) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), #define MR_cast_to_pti6(r1, r2, r3, r4, r5, r6) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), \ (MR_PseudoTypeInfo) (r6), #define MR_cast_to_pti7(r1, r2, r3, r4, r5, r6, r7) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), \ (MR_PseudoTypeInfo) (r6), \ (MR_PseudoTypeInfo) (r7), #define MR_cast_to_pti8(r1, r2, r3, r4, r5, r6, r7, r8) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), \ (MR_PseudoTypeInfo) (r6), \ (MR_PseudoTypeInfo) (r7), \ (MR_PseudoTypeInfo) (r8), #define MR_cast_to_pti9(r1, r2, r3, r4, r5, r6, r7, r8, r9) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), \ (MR_PseudoTypeInfo) (r6), \ (MR_PseudoTypeInfo) (r7), \ (MR_PseudoTypeInfo) (r8), \ (MR_PseudoTypeInfo) (r9), #define MR_cast_to_pti10(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10) \ (MR_PseudoTypeInfo) (r1), \ (MR_PseudoTypeInfo) (r2), \ (MR_PseudoTypeInfo) (r3), \ (MR_PseudoTypeInfo) (r4), \ (MR_PseudoTypeInfo) (r5), \ (MR_PseudoTypeInfo) (r6), \ (MR_PseudoTypeInfo) (r7), \ (MR_PseudoTypeInfo) (r8), \ (MR_PseudoTypeInfo) (r9), \ (MR_PseudoTypeInfo) (r10), //////////////////////////////////////////////////////////////////////////// // Definitions for MR_ProcLayout. // The MR_TableIoEntry structure. // // To enable printing and declarative debugging of I/O actions, the compiler // generates one of these structures for each I/O primitive. The compiler // transforms the bodies of those primitives to create a block of memory // (the answerblock, the action's entry in the I/O table), and fill it in with // // - a pointer to the primitive's MR_TableIoEntry structure, and // - the values of some of the primitive's arguments (excluding the // I/O states, which are dummies). // // The arguments in the answerblock will always include the output arguments, // since I/O tabling needs these to make the primitive idempotent. // If the primitive does not have type class constraints, it will include // the values of the input arguments as well, for two reasons: // // - to present them to the user on request, either via mdb's browsing // commands, or via the declarative debugger // // - the input typeinfo arguments are needed to present the value of other // arguments, both inputs and outputs, to the user. // // In the presence of typeclass constraints on the predicate, we cannot // guarantee that we can encode the locations of the typeinfos (which may be // arbitrarily deep inside typeclass_infos) in our fixed size location // descriptions. We therefore set the have_arg_infos field to false, // indicating that none of the following fields contain meaningful information. // // In the absence of typeclass constraints on the predicate, we set the // have_arg_infos field to true. In that case, num_ptis will contain the // number of arguments in the answer block, the ptis field will point to // a vector of num_ptis pseudo-typeinfos (one for each argument in the answer // block), and the type_params field maps the type variables that occur // in the pseudo-typeinfos to the locations of the typeinfos describing // the types bound to them. // // The entry_proc field, which is always meaningful, identifies the procedure // that created the I/O table entry. typedef struct MR_TableIoEntry_Struct { const MR_ProcLayout *MR_table_io_entry_proc; MR_bool MR_table_io_entry_have_arg_infos; MR_Integer MR_table_io_entry_num_ptis; const MR_PseudoTypeInfo *MR_table_io_entry_ptis; const MR_TypeParamLocns *MR_table_io_entry_type_params; } MR_TableIoEntry; // MR_TableInfo: compiler generated information describing the tabling // data structures used by a procedure. // // For I/O tabled procedures, the information is in the io_decl field. // For other kinds of tabled procedures, it is in the gen field. // The init field is used for initialization only. // // The MR_table_proc field is not const because the structure it points to // has fields containing statistics, which are updated at runtime. typedef union { const void *MR_table_init; const MR_TableIoEntry *MR_table_io_entry; const MR_Table_Gen *MR_table_gen; MR_ProcTableInfo *MR_table_proc; } MR_TableInfo; // The MR_StackTraversal structure contains the following fields: // // The code_addr field points to the start of the procedure's code. // This allows the profiler to figure out which procedure a sampled program // counter belongs to, and allows the debugger to implement retry. // // The succip_locn field encodes the location of the saved succip if it is // saved in a general purpose stack slot. If the succip is saved in a special // purpose stack slot (as it is for model_non procedures) or if the procedure // never saves the succip (as in leaf procedures), this field will contain -1. // // The stack_slots field gives the number of general purpose stack slots // in the procedure. // // The detism field encodes the determinism of the procedure. typedef struct MR_StackTraversal_Struct { MR_Code *MR_trav_code_addr; MR_LongLval MR_trav_succip_locn; MR_int_least16_t MR_trav_stack_slots; MR_Determinism MR_trav_detism; } MR_StackTraversal; #define MR_PROC_LAYOUT_IS_UCI(entry) \ MR_PROC_ID_IS_UCI(entry->MR_sle_proc_id) // The MR_ExecTrace structure contains the following fields. // // The call_label field points to the label layout structure for the label // associated with the call event at the entry to the procedure. The purpose // of this field is to allow the debugger to find out which variables // are where on entry, so it can reexecute the procedure if asked to do so // and if the values of the required variables are still available. // // The labels field contains a pointer to an array of pointers to label layout // structures; the size of the array is given by the num_labels field. The // initial part of the array will contain a pointer to the label layout // structure of every interface event in the procedure; the later parts will // contain a pointer to the label layout structure of every internal event. // There is no ordering on the events beyond interface first, internal second. // // The used_var_names field points to an array that contains offsets // into the string table, with the offset at index i-1 giving the name of // variable i (since variable numbers start at one). If a variable has no name // or cannot be referred to from an event, the offset will be zero, at which // offset the string table will contain an empty string. // // The max_named_var_num field gives the number of elements in the // used_var_names table, which is also the number of the highest numbered // named variable. Note that unnamed variables may have numbers higher than // this. // // The max_r_num field tells the debugger which Mercury abstract machine // registers need saving in MR_trace: besides the special registers, it is // the general-purpose registers rN for values of N up to and including the // value of this field. Note that this field contains an upper bound; in // general, there will be calls to MR_trace at which the number of the highest // numbered general purpose (i.e. rN) registers is less than this. However, // storing the upper bound gets us almost all the benefit (of not saving and // restoring all the thousand rN registers) for a small fraction of the static // space cost of storing the actual number in label layout structures. // // If the procedure is compiled with deep tracing, the maybe_from_full field // will contain a negative number. If it is compiled with shallow tracing, // it will contain the number of the stack slot that holds the flag that says // whether this incarnation of the procedure was called from deeply traced code // or not. (The determinism of the procedure decides whether the stack slot // refers to a stackvar or a framevar.) // // If tabling of I/O actions is enabled, the maybe_io_seq field will contain // the number of the stack slot that holds the value the I/O action counter // had on entry to this procedure. Even procedures that do not have I/O state // arguments will have such a slot, since they or their descendants may call // unsafe_perform_io. // // If trailing is not enabled, the maybe_trail field will contain a negative // number. If it is enabled, it will contain number of the first of two stack // slots used for checkpointing the state of the trail on entry to the // procedure. The first contains the trail pointer, the second the ticket. // // If the procedure lives on the nondet stack, or if it cannot create any // temporary nondet stack frames, the maybe_maxfr field will contain a negative // number. If it lives on the det stack, and can create temporary nondet stack // frames, it will contain the number number of the stack slot that contains the // value of maxfr on entry, for use in executing the retry debugger command // from the middle of the procedure. // // The eval_method field contains a representation of the evaluation method // used by the procedure. The retry command needs this information if it is // to reset the call tables of the procedure invocations being retried. // // We cannot put enums into structures as bit fields. To avoid wasting space, // we put MR_EvalMethodInts into structures instead of MR_EvalMethods // themselves. // // If the procedure is compiled with some form of tabling, the maybe_call_table // field contains the number of the stack slot through which we can reach the // call table entry for this call. In forms of tabling which associate a C // structure (MR_Subgoal, MR_MemoNonRecord) with a call table entry, the slot // will point to that structure; in other forms of tabling, it will point // to the call's MR_TableNode. // // The flags field encodes boolean properties of the procedure. For now, // the only property is whether the procedure has a pair of I/O state // arguments. // // If the procedure lives on the nondet stack, or if it cannot create any // temporary nondet stack frames, the maybe_maxfr field will contain a negative // number. If it lives on the det stack, and can create temporary nondet stack // frames, it will contain the number of the stack slot that contains the // value of maxfr on entry, for use in executing the retry debugger command // from the middle of the procedure. #define MR_EVAL_METHOD_MEMO_STRICT MR_EVAL_METHOD_MEMO #define MR_EVAL_METHOD_MEMO_FAST_LOOSE MR_EVAL_METHOD_MEMO #define MR_EVAL_METHOD_MEMO_SPECIFIED MR_EVAL_METHOD_MEMO typedef enum { MR_EVAL_METHOD_NORMAL, MR_EVAL_METHOD_LOOP_CHECK, MR_EVAL_METHOD_MEMO, MR_EVAL_METHOD_MINIMAL_STACK_COPY, MR_EVAL_METHOD_MINIMAL_OWN_STACKS_CONSUMER, MR_EVAL_METHOD_MINIMAL_OWN_STACKS_GENERATOR, MR_EVAL_METHOD_TABLE_IO, MR_EVAL_METHOD_TABLE_IO_DECL, MR_EVAL_METHOD_TABLE_IO_UNITIZE, MR_EVAL_METHOD_TABLE_IO_UNITIZE_DECL } MR_EvalMethod; typedef MR_int_least8_t MR_EvalMethodInt; typedef enum { MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_NONE), MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_BASIC), MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_BASIC_USER), MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_SHALLOW), MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_DEEP), MR_DEFINE_MERCURY_ENUM_CONST(MR_TRACE_LEVEL_DECL_REP) } MR_TraceLevel; typedef MR_int_least8_t MR_TraceLevelInt; typedef struct MR_ExecTrace_Struct { const MR_LabelLayout *MR_exec_call_label; const MR_ModuleLayout *MR_exec_module_layout; const MR_LabelLayout **MR_exec_labels; MR_uint_least32_t MR_exec_num_labels; MR_TableInfo MR_exec_table_info; const MR_uint_least16_t *MR_exec_head_var_nums; const MR_uint_least32_t *MR_exec_used_var_names; MR_uint_least16_t MR_exec_num_head_vars; MR_uint_least16_t MR_exec_max_named_var_num; MR_uint_least16_t MR_exec_max_r_num; MR_uint_least16_t MR_exec_max_f_num; MR_int_least8_t MR_exec_maybe_from_full; MR_int_least8_t MR_exec_maybe_io_seq; MR_int_least8_t MR_exec_maybe_trail; MR_int_least8_t MR_exec_maybe_maxfr; MR_EvalMethodInt MR_exec_eval_method_CAST_ME; MR_int_least8_t MR_exec_maybe_call_table; MR_TraceLevelInt MR_exec_trace_level_CAST_ME; MR_uint_least8_t MR_exec_flags; MR_int_least8_t MR_exec_maybe_tail_rec; } MR_ExecTrace; #define MR_compute_max_mr_num(max_mr_num, layout) \ do { \ int max_r_num; \ \ max_r_num = (layout)->MR_sll_entry->MR_sle_max_r_num + \ MR_NUM_SPECIAL_REG; \ max_mr_num = MR_max(max_r_num, MR_FIRST_UNREAL_R_SLOT); \ } while (0) // The code in the compiler that creates the flag field is // encode_exec_trace_flags in stack_layout.m. #define MR_PROC_LAYOUT_FLAG_HAS_IO_STATE_PAIR 0x1 #define MR_PROC_LAYOUT_FLAG_HAS_HIGHER_ORDER_ARG 0x2 #define MR_trace_find_reused_frames(proc_layout, sp, reused_frames) \ do { \ const MR_ExecTrace *exec_trace; \ int tailrec_slot; \ \ exec_trace = proc_layout->MR_sle_exec_trace; \ if (exec_trace == NULL) { \ (reused_frames) = 0; \ } else { \ tailrec_slot = proc_layout->MR_sle_maybe_tailrec; \ if (tailrec_slot <= 0) { \ (reused_frames) = 0; \ } else { \ if (MR_DETISM_DET_STACK(proc_layout->MR_sle_detism)) { \ (reused_frames) = MR_based_stackvar((sp), tailrec_slot);\ } else { \ MR_fatal_error("tailrec reuses nondet stack frames"); \ } \ } \ } \ } while (0) // Proc layout structures contain one, two or three substructures. // // - The first substructure is the MR_StackTraversal structure, which contains // information that enables the stack to be traversed, e.g. for accurate gc. // It is always present if proc layouts are present at all. // // - The second group is the MR_ProcId union, which identifies the // procedure in terms that are meaningful to both humans and machines. // It will be generated only if the module is compiled with stack tracing, // execution tracing or profiling. The MR_ProcId union has two alternatives, // one for user-defined procedures and one for procedures of the compiler // generated Unify, Index and Compare predicates. // // - The third group is everything else. Currently, this consists of // information that is of interest to the debugger, to the deep profiler, // or both. // // The information that is of interest to the debugger only is stored in // the MR_ExecTrace structure, which will be generated only if the module // is compiled with execution tracing. The information that is of interest to // the deep profiler is stored in the MR_ProcStatic structure, which will be // generated only if the module is compiled in a deep profiling grade. The // other fields in the group are of interest to both the debugger and the // deep profiler, and will be generated if either execution tracing or deep // profiling is enabled. // // If the body_bytes field is NULL, it means that no representation of the // procedure body is available. If non-NULL, it contains a pointer to an // array of bytecodes that represents the body of the procedure. The // bytecode array should be interpreted by the read_proc_rep predicate in // mdbcomp/program_representation.m (it starts with an encoded form of the // array's length). Its contents are generated by compiler/prog_rep.m. // // The module_common_layout field points to the part of the module layout // structure of the module containing the procedure that is common to the // debugger and the deep profiler. Amongst other things, it gives access to // the string table that the body_bytes fields refers to. // // The runtime system considers all proc layout structures to be of type // MR_ProcLayout, but must use the macros defined below to check for the // existence of each substructure before accessing the fields of that // substructure. The macros are MR_PROC_LAYOUT_HAS_PROC_ID to check for the // MR_ProcId substructure, MR_PROC_LAYOUT_HAS_EXEC_TRACE to check for the // MR_ExecTrace substructure, and MR_PROC_LAYOUT_HAS_PROC_STATIC to check for // the MR_ProcStatic substructure. // // The reason why some substructures may be missing is to save space. // If the options with which a module is compiled do not require execution // tracing, then the MR_ExecTrace substructure will not present, and if the // options do not require procedure identification, then the MR_ProcId // substructure will not be present either. The body_bytes and module_layout // fields cannot be non-NULL unless at least one of exec trace and proc static // substructures is present, but they are otherwise independent of those // substructures. // // The compiler itself generates proc layout structures using the following // three types. // // - When generating only stack traversal information, the compiler will // generate proc layout structures of type MR_ProcLayout_Traversal. // // - When generating stack traversal and procedure id information, plus // possibly others, the compiler will generate proc layout structures of // types MR_ProcLayoutUser and MR_ProcLayoutUCI. struct MR_ProcLayout_Struct { MR_StackTraversal MR_sle_traversal; MR_ProcId MR_sle_proc_id; MR_STATIC_CODE_CONST MR_ExecTrace *MR_sle_exec_trace; MR_ProcStatic *MR_sle_proc_static; const MR_uint_least8_t *MR_sle_body_bytes; const MR_ModuleLayout *MR_sle_module_layout; }; typedef struct MR_ProcLayoutUser_Struct { MR_StackTraversal MR_user_traversal; MR_UserProcId MR_user_id; MR_STATIC_CODE_CONST MR_ExecTrace *MR_sle_exec_trace; MR_ProcStatic *MR_sle_proc_static; const MR_uint_least8_t *MR_sle_body_bytes; const MR_ModuleLayout *MR_sle_module_layout; } MR_ProcLayoutUser; typedef struct MR_ProcLayoutUCI_Struct { MR_StackTraversal MR_uci_traversal; MR_UCIProcId MR_uci_id; MR_STATIC_CODE_CONST MR_ExecTrace *MR_sle_exec_trace; MR_ProcStatic *MR_sle_proc_static; const MR_uint_least8_t *MR_sle_body_bytes; const MR_ModuleLayout *MR_sle_module_layout; } MR_ProcLayoutUCI; typedef struct MR_ProcLayout_Traversal_Struct { MR_StackTraversal MR_trav_traversal; MR_Word MR_trav_no_proc_id; // will be -1 } MR_ProcLayout_Traversal; #define MR_PROC_LAYOUT_HAS_PROC_ID(entry) \ (MR_PROC_ID_EXISTS(entry->MR_sle_proc_id)) #define MR_PROC_LAYOUT_HAS_EXEC_TRACE(entry) \ (MR_PROC_LAYOUT_HAS_PROC_ID(entry) && \ entry->MR_sle_exec_trace != NULL) #define MR_PROC_LAYOUT_HAS_PROC_STATIC(entry) \ (MR_PROC_LAYOUT_HAS_PROC_ID(entry) && \ entry->MR_sle_proc_static != NULL) #define MR_PROC_LAYOUT_HAS_THIRD_GROUP(entry) \ (MR_PROC_LAYOUT_HAS_PROC_ID(entry) && \ ( entry->MR_sle_exec_trace != NULL \ || entry->MR_sle_proc_static != NULL)) #define MR_sle_code_addr MR_sle_traversal.MR_trav_code_addr #define MR_sle_succip_locn MR_sle_traversal.MR_trav_succip_locn #define MR_sle_stack_slots MR_sle_traversal.MR_trav_stack_slots #define MR_sle_detism MR_sle_traversal.MR_trav_detism #define MR_sle_user MR_sle_proc_id.MR_proc_user #define MR_sle_uci MR_sle_proc_id.MR_proc_uci #define MR_sle_call_label MR_sle_exec_trace->MR_exec_call_label #define MR_sle_module_layout MR_sle_exec_trace->MR_exec_module_layout #define MR_sle_labels MR_sle_exec_trace->MR_exec_labels #define MR_sle_num_labels MR_sle_exec_trace->MR_exec_num_labels #define MR_sle_tabling_pointer MR_sle_exec_trace->MR_exec_tabling_pointer #define MR_sle_table_info MR_sle_exec_trace->MR_exec_table_info #define MR_sle_head_var_nums MR_sle_exec_trace->MR_exec_head_var_nums #define MR_sle_num_head_vars MR_sle_exec_trace->MR_exec_num_head_vars #define MR_sle_used_var_names MR_sle_exec_trace->MR_exec_used_var_names #define MR_sle_max_named_var_num MR_sle_exec_trace->MR_exec_max_named_var_num #define MR_sle_max_r_num MR_sle_exec_trace->MR_exec_max_r_num #define MR_sle_max_f_num MR_sle_exec_trace->MR_exec_max_f_num #define MR_sle_maybe_from_full MR_sle_exec_trace->MR_exec_maybe_from_full #define MR_sle_maybe_io_seq MR_sle_exec_trace->MR_exec_maybe_io_seq #define MR_sle_maybe_trail MR_sle_exec_trace->MR_exec_maybe_trail #define MR_sle_maybe_maxfr MR_sle_exec_trace->MR_exec_maybe_maxfr #define MR_sle_maybe_call_table MR_sle_exec_trace->MR_exec_maybe_call_table #define MR_sle_maybe_decl_debug MR_sle_exec_trace->MR_exec_maybe_decl_debug #define MR_sle_maybe_tailrec MR_sle_exec_trace->MR_exec_maybe_tail_rec #define MR_sle_eval_method(proc_layout_ptr) \ ((MR_EvalMethod) (proc_layout_ptr)-> \ MR_sle_exec_trace->MR_exec_eval_method_CAST_ME) #define MR_sle_trace_level(proc_layout_ptr) \ ((MR_TraceLevel) (proc_layout_ptr)-> \ MR_sle_exec_trace->MR_exec_trace_level_CAST_ME) #define MR_proc_has_io_state_pair(proc_layout_ptr) \ ((proc_layout_ptr)->MR_sle_exec_trace->MR_exec_flags \ & MR_PROC_LAYOUT_FLAG_HAS_IO_STATE_PAIR) #define MR_proc_has_higher_order_arg(proc_layout_ptr) \ ((proc_layout_ptr)->MR_sle_exec_trace->MR_exec_flags \ & MR_PROC_LAYOUT_FLAG_HAS_HIGHER_ORDER_ARG) // Adjust the arity of functions for printing. #define MR_sle_user_adjusted_arity(entry) \ ((entry)->MR_sle_user.MR_user_arity - \ (((entry)->MR_sle_user.MR_user_pred_or_func == MR_FUNCTION) ? 1 : 0)) #define MR_MAX_VARNAME_SIZE 160 // Return the name (if any) of the variable with the given HLDS variable number // in the procedure indicated by the first argument. // // The name will actually be found by MR_name_in_string_table, so the // comments there about name size and should_copy apply here as well. extern MR_ConstString MR_hlds_var_name(const MR_ProcLayout *entry, int hlds_var_num, int *should_copy); // Return the name (if any) of the variable with the given name code // in the given string table. // // Sometimes, the returned name will point to static, const storage, // whose contents are valid until the end of the program's execution, // while at other times, it will point to a buffer whose contents // will be valid only until the next call to MR_name_in_string_table. // // Callers that want to know which is the case should pass a non-NULL // value for should_copy. The returned name will point to the buffer // if and only if *should_copy is true. The size of the buffer is // MR_MAX_VARNAME_SIZE bytes. extern MR_ConstString MR_name_in_string_table(const char *string_table, MR_Integer string_table_size, MR_uint_least32_t name_code, int *should_copy); // Given a string, see whether its end consists a sequence of digits. // If yes, return the offset of the first digit in this sequence relative // to the start of the string. Otherwise, return a negative number. extern int MR_find_start_of_num_suffix(const char *str); // Define a layout structure for a procedure, containing information // for stack traversal and procedure identification. // // The slot count and the succip location parameters do not have to be // supplied for procedures that live on the nondet stack, since for such // procedures the size of the frame can be deduced from the prevfr field // and the location of the succip is fixed. // // An unknown slot count should be signalled by MR_PROC_NO_SLOT_COUNT. // An unknown succip location should be signalled by MR_LONG_LVAL_TYPE_UNKNOWN. // // For the procedure identification, we always use the same module name // for the defining and declaring modules, since procedures whose code // is hand-written as C modules cannot be inlined in other Mercury modules. // // Due to the possibility that code addresses are not static, any use of // the MR_MAKE_PROC_ID_PROC_LAYOUT macro has to be accompanied by a call to the // MR_INIT_PROC_LAYOUT_ADDR macro in the initialization code of the C module // that defines the entry. (The cast in the body of MR_INIT_PROC_LAYOUT_ADDR // is needed because compiler-generated layout structures may use any of the // variant types listed above.) #define MR_PROC_NO_SLOT_COUNT -1 #ifdef MR_STATIC_CODE_ADDRESSES #define MR_MAKE_PROC_LAYOUT_ADDR(entry) MR_ENTRY(entry) #define MR_INIT_PROC_LAYOUT_ADDR(entry) do { } while (0) #else #define MR_MAKE_PROC_LAYOUT_ADDR(entry) ((MR_Code *) NULL) #define MR_INIT_PROC_LAYOUT_ADDR(entry) \ do { \ ((MR_ProcLayout *) & \ MR_PASTE2(mercury_data__proc_layout__, entry)) \ ->MR_sle_code_addr = MR_ENTRY(entry); \ } while (0) #endif #define MR_MAKE_USER_PROC_STATIC_PROC_LAYOUT(sc, detism, slots, succip_locn, \ pf, module, name, arity, mode, proc_static) \ MR_declare_entry(MR_proc_entry_user_name(module, name, \ arity, mode)); \ sc const MR_ProcLayoutUser \ MR_proc_layout_user_name(module, name, arity, mode) = { \ { \ MR_MAKE_PROC_LAYOUT_ADDR( \ MR_proc_entry_user_name(module, name, \ arity, mode)), \ succip_locn, \ slots, \ detism \ }, \ { \ pf, \ MR_STRINGIFY(module), \ MR_STRINGIFY(module), \ MR_STRINGIFY(name), \ arity, \ mode \ }, \ NULL, \ (MR_ProcStatic *) proc_static \ } #define MR_MAKE_UCI_PROC_STATIC_PROC_LAYOUT(sc, detism, slots, succip_locn, \ module, name, type, arity, mode, proc_static) \ MR_declare_entry(MR_proc_entry_uci_name(module, name, \ type, arity, mode)); \ sc const MR_ProcLayoutUCI \ MR_proc_layout_uci_name(module, name, type, arity, mode) = { \ { \ MR_MAKE_PROC_LAYOUT_ADDR( \ MR_proc_entry_uci_name(module, name, \ type, arity, mode)), \ succip_locn, \ slots, \ detism \ }, \ { \ MR_STRINGIFY(type), \ MR_STRINGIFY(module), \ MR_STRINGIFY(module), \ MR_STRINGIFY(name), \ arity, \ mode \ }, \ NULL, \ (MR_ProcStatic *) proc_static \ } #define MR_NO_EXTERN_DECL #define MR_STATIC_USER_PROC_STATIC_PROC_LAYOUT(detism, slots, succip_locn, \ pf, module, name, arity, mode) \ MR_MAKE_USER_PROC_STATIC_PROC_LAYOUT(static, detism, slots, \ succip_locn, pf, module, name, arity, mode, \ &MR_proc_static_user_name(module, name, arity, mode)) #define MR_EXTERN_USER_PROC_STATIC_PROC_LAYOUT(detism, slots, succip_locn, \ pf, module, name, arity, mode) \ MR_MAKE_USER_PROC_STATIC_PROC_LAYOUT(MR_NO_EXTERN_DECL, detism, slots, \ succip_locn, pf, module, name, arity, mode, \ &MR_proc_static_user_name(module, name, arity, mode)) #define MR_STATIC_UCI_PROC_STATIC_PROC_LAYOUT(detism, slots, succip_locn, \ module, name, type, arity, mode) \ MR_MAKE_UCI_PROC_STATIC_PROC_LAYOUT(static, detism, slots, \ succip_locn, module, name, type, arity, mode, \ &MR_proc_static_uci_name(module, name, type, arity, mode)) #define MR_EXTERN_UCI_PROC_STATIC_PROC_LAYOUT(detism, slots, succip_locn, \ module, name, type, arity, mode) \ MR_MAKE_UCI_PROC_STATIC_PROC_LAYOUT(MR_NO_EXTERN_DECL, detism, slots, \ succip_locn, module, name, type, arity, mode, \ &MR_proc_static_uci_name(module, name, type, arity, mode)) #define MR_STATIC_USER_PROC_ID_PROC_LAYOUT(detism, slots, succip_locn, \ pf, module, name, arity, mode) \ MR_MAKE_USER_PROC_STATIC_PROC_LAYOUT(static, detism, slots, \ succip_locn, pf, module, name, arity, mode, NULL) #define MR_EXTERN_USER_PROC_ID_PROC_LAYOUT(detism, slots, succip_locn, \ pf, module, name, arity, mode) \ MR_MAKE_USER_PROC_STATIC_PROC_LAYOUT(MR_NO_EXTERN_DECL, detism, slots, \ succip_locn, pf, module, name, arity, mode, NULL) #define MR_DECLARE_UCI_PROC_STATIC_LAYOUTS(mod, n, a) \ const MR_ProcLayoutUCI \ MR_proc_layout_uci_name(mod, __Unify__, n, a, 0); \ const MR_ProcLayoutUCI \ MR_proc_layout_uci_name(mod, __Compare__, n, a, 0); \ const MR_ProcLayoutUCI \ MR_proc_layout_uci_name(mod, __CompareRep__, n, a, 0); // In procedures compiled with execution tracing, three items are stored // in stack slots with fixed numbers. They are: // // the event number of the last event before the call event, // the call number, and // the call depth. // // Note that the first slot does not store the number of the call event // itself, but rather the number of the call event minus one. The reason // for this is that (a) incrementing the number stored in this slot would // increase executable size, and (b) if the procedure is shallow traced, // MR_trace may not be called for the call event, so we cannot shift the // burden of initializing fields to the MR_trace of the call event either. // // The following macros will access the fixed slots. They can be used whenever // MR_PROC_LAYOUT_HAS_EXEC_TRACE(entry) is true; which set you should use // depends on the determinism of the procedure. // // These macros have to be kept in sync with compiler/trace.m. #define MR_event_num_framevar(base_curfr) MR_based_framevar(base_curfr, 1) #define MR_call_num_framevar(base_curfr) MR_based_framevar(base_curfr, 2) #define MR_call_depth_framevar(base_curfr) MR_based_framevar(base_curfr, 3) #define MR_event_num_stackvar(base_sp) MR_based_stackvar(base_sp, 1) #define MR_call_num_stackvar(base_sp) MR_based_stackvar(base_sp, 2) #define MR_call_depth_stackvar(base_sp) MR_based_stackvar(base_sp, 3) // In model_non procedures compiled with --trace-redo, one or two other items // are stored in fixed stack slots. These are // // the address of the layout structure for the redo event // the saved copy of the from-full flag (only if trace level is shallow) // // The following macros will access these slots. They should be used only from // within the code that calls MR_trace for the REDO event. // // This macros have to be kept in sync with compiler/trace.m. #define MR_redo_layout_framevar(base_curfr) MR_based_framevar(base_curfr, 4) #define MR_redo_fromfull_framevar(base_curfr) MR_based_framevar(base_curfr, 5) //////////////////////////////////////////////////////////////////////////// // Definitions for MR_ModuleLayout. // // The layout structure for a module contains the following fields. // // The MR_ml_name field contains the name of the module. // // The MR_ml_string_table field contains the module's string table, which // contains strings referred to by other layout structures in the module // (initially only the tables containing variables names, referred to from // label layout structures). The MR_ml_string_table_size field gives the size // of the table in bytes. // // The MR_ml_procs field points to an array containing pointers to the proc // layout structures of all the procedures in the module; the MR_ml_proc_count // field gives the number of entries in the array. // // The MR_ml_module_file_layout field points to an array of N file layout // pointers if the module has labels corresponding to contexts that refer // to the names of N files. For each file, the table gives its name, the // number of labels in that file in this module, and for each such label, // it gives its line number and a pointer to its label layout struct. // The corresponding elements of the label_lineno and label_layout arrays // refer to the same label. (The reason why they are not stored together // is space efficiency; adding a 16 bit field to a label layout structure would // require padding.) The labels are sorted on line number. // // The MR_ml_trace_level field gives the trace level that the module was // compiled with. If the MR_TraceLevel enum is modified, then the // corresponding function in compiler/trace_params.m must also be updated. // // The MR_ml_suppressed_events events field encodes the set of event types // (ports) that were suppressed when generating code for this module. The bit // given by the expression (1 << MR_PORT_<PORTTYPE>) will be set in this // integer iff trace port MR_PORT_<PORTTYPE> is suppressed. // // The MR_ml_label_exec_count field points to an array of integers, with each // integer holding the number of times execution has reached a given label. // Each label's layout structure records the index of that label in this array. // The most direct way to go the other way, to find out which label owns a // particular slot in this array, is to search the label arrays in the file // layout structures, and test their MR_sll_label_num_in_module fields. // (If we needed faster access, we could add another array with elements // corresponding to MR_ml_label_exec_count's pointing to the labels' layout // structures.) // // The MR_ml_num_label_exec_counts field contains the number of elements // in the MR_ml_label_exec_count array. typedef struct MR_ModuleFileLayout_Struct { MR_ConstString MR_mfl_filename; MR_Integer MR_mfl_label_count; // The following fields point to arrays of size MR_mfl_label_count. const MR_int_least16_t *MR_mfl_label_lineno; const MR_LabelLayout **MR_mfl_label_layout; } MR_ModuleFileLayout; // The version of the data structures in this file -- useful for bootstrapping. // If you write runtime code that checks this version number and can at least // handle the previous version of the data structure, it makes it easier to // bootstrap changes to these data structures. // // This number should be kept in sync with layout_version_number in // compiler/layout_out.m. #define MR_LAYOUT_VERSION MR_LAYOUT_VERSION__OISU #define MR_LAYOUT_VERSION__USER_DEFINED 1 #define MR_LAYOUT_VERSION__EVENTSETNAME 2 #define MR_LAYOUT_VERSION__SYNTH_ATTR 3 #define MR_LAYOUT_VERSION__COMMON 4 #define MR_LAYOUT_VERSION__OISU 5 struct MR_ModuleLayout_Struct { // The fields that are of interest to both deep profiling and debugging. MR_uint_least8_t MR_ml_version_number; MR_ConstString MR_ml_name; MR_Integer MR_ml_string_table_size; const char *MR_ml_string_table; // The fields that are of interest only to deep profiling. MR_Integer MR_ml_num_oisu_types; const MR_uint_least8_t *MR_ml_oisu_bytes; MR_Integer MR_ml_num_table_types; const MR_uint_least8_t *MR_ml_type_table_bytes; // The fields that are of interest only to debugging. MR_Integer MR_ml_proc_count; const MR_ProcLayout **MR_ml_procs; MR_Integer MR_ml_filename_count; const MR_ModuleFileLayout **MR_ml_module_file_layout; MR_TraceLevel MR_ml_trace_level; MR_int_least32_t MR_ml_suppressed_events; MR_int_least32_t MR_ml_num_label_exec_counts; MR_Unsigned *MR_ml_label_exec_count; const char *MR_ml_user_event_set_name; const char *MR_ml_user_event_set_desc; MR_int_least16_t MR_ml_user_event_max_num_attr; MR_int_least16_t MR_ml_num_user_event_specs; MR_UserEventSpec *MR_ml_user_event_specs; }; //////////////////////////////////////////////////////////////////////////// // Definitions for MR_ClosureId. // // Each closure contains an MR_ClosureId structure. The proc_id field // identifies the procedure called by the closure. The other fields identify // the context where the closure was created. // // The compiler generates closure id structures as either MR_UserClosureId // or MR_UCIClosureId structures in order to avoid initializing the // MR_ProcId union through an inappropriate member. struct MR_ClosureId_Struct { MR_ProcId MR_closure_proc_id; MR_ConstString MR_closure_module_name; MR_ConstString MR_closure_file_name; MR_Integer MR_closure_line_number; MR_ConstString MR_closure_goal_path; }; struct MR_UserClosureId_Struct { MR_UserProcId MR_user_closure_proc_id; MR_ConstString MR_user_closure_module_name; MR_ConstString MR_user_closure_file_name; MR_Integer MR_user_closure_line_number; MR_ConstString MR_user_closure_goal_path; }; struct MR_UCIClosureId_Struct { MR_UCIProcId MR_uci_closure_proc_id; MR_ConstString MR_uci_closure_module_name; MR_ConstString MR_uci_closure_file_name; MR_Integer MR_uci_closure_line_number; MR_ConstString MR_uci_closure_goal_path; }; #endif // not MERCURY_STACK_LAYOUT_H
PaulBone/mercury
runtime/mercury_stack_layout.h
C
gpl-2.0
76,588
<?php // flush output buffer die(json_encode(array( 'variables' => $variables, 'content' => render($page['content']) . render($page['content_bottom']), ))); ?>
mandelbro/Overlay-CMS
sites/all/themes/ursaminor/page--json.tpl.php
PHP
gpl-2.0
167
<?php $logo = get_option('custom_logo', EBOR_THEME_DIRECTORY . 'style/img/logo-dark.png'); $logo_light = get_option('custom_logo_light', EBOR_THEME_DIRECTORY . 'style/img/logo-light.png'); ?> <div class="nav-container"> <a id="top"></a> <nav class="nav-centered"> <?php get_template_part('inc/content-header','utility'); ?> <div class="text-center"> <a href="<?php echo esc_url(home_url('/')); ?>"> <img class="logo logo-light" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo_light); ?>" /> <img class="logo logo-dark" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo); ?>" /> </a> </div> <div class="nav-bar text-center"> <div class="module widget-handle mobile-toggle right visible-sm visible-xs"> <i class="ti-menu"></i> </div> <div class="module-group text-left"> <div class="module left"> <?php if ( has_nav_menu( 'primary' ) ){ wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 3, 'container' => false, 'container_class' => false, 'menu_class' => 'menu', 'fallback_cb' => 'wp_bootstrap_navwalker::fallback', 'walker' => new ebor_framework_medium_rare_bootstrap_navwalker() ) ); } else { echo '<ul class="menu"><li><a href="'. admin_url('nav-menus.php') .'">Set up a navigation menu now</a></li></ul>'; } ?> </div> <?php if( 'yes' == get_option('foundry_header_social', 'no') ){ get_template_part('inc/content-header', 'social'); } if( 'yes' == get_option('foundry_header_button', 'no') ){ get_template_part('inc/content-header', 'button'); } if( 'yes' == get_option('foundry_header_search', 'yes') ){ get_template_part('inc/content-header', 'search'); } if( class_exists('Woocommerce') && 'yes' == get_option('foundry_header_cart', 'yes') ){ get_template_part('inc/content-header', 'cart'); } if( function_exists('icl_get_languages') && 'yes' == get_option('foundry_header_wpml', 'yes') ){ get_template_part('inc/content-header', 'wpml'); } ?> </div> </div> </nav> </div>
seyekuyinu/highlifer
wp-content/themes/highlifer/inc/content-nav-centered.php
PHP
gpl-2.0
3,130
'======================================================================== 'Kartris - www.kartris.com 'Copyright 2021 CACTUSOFT 'GNU GENERAL PUBLIC LICENSE v2 'This program is free software distributed under the GPL without any 'warranty. 'www.gnu.org/licenses/gpl-2.0.html 'KARTRIS COMMERCIAL LICENSE 'If a valid license.config issued by Cactusoft is present, the KCL 'overrides the GPL v2. 'www.kartris.com/t-Kartris-Commercial-License.aspx '======================================================================== Imports System.Collections.Generic Imports System.Threading Imports System.Globalization Imports CkartrisBLL Imports KartSettingsManager Partial Class Back_BasketView Inherits System.Web.UI.UserControl Protected Shared BSKT_CustomerDiscount As Double Private Shared arrPromotionsDiscount As New ArrayList Protected objCurrency As New CurrenciesBLL Protected objItem As New BasketItem Protected blnAdjusted As Boolean Protected SESS_CurrencyID As Integer Protected APP_PricesIncTax, APP_ShowTaxDisplay, APP_USMultiStateTax As Boolean Private arrPromotions As New List(Of Kartris.Promotion) Private _objShippingDetails As Interfaces.objShippingDetails Private _ViewType As BasketBLL.VIEW_TYPE = BasketBLL.VIEW_TYPE.MAIN_BASKET Private _ViewOnly As Boolean Private _UserID As Integer 'we send in the customer ID Private blnShowPromotion As Boolean = True Public Shared ReadOnly Property Basket() As kartris.Basket Get If HttpContext.Current.Session("Basket") Is Nothing Then HttpContext.Current.Session("Basket") = New Kartris.Basket Return HttpContext.Current.Session("Basket") End Get End Property Public Shared Property BasketItems() As List(Of Kartris.BasketItem) Get If HttpContext.Current.Session("BasketItems") Is Nothing Then HttpContext.Current.Session("BasketItems") = New List(Of Kartris.BasketItem) Return HttpContext.Current.Session("BasketItems") End Get Set(ByVal value As List(Of Kartris.BasketItem)) HttpContext.Current.Session("BasketItems") = value End Set End Property Public ReadOnly Property GetBasket() As kartris.Basket Get Return Basket End Get End Property Public ReadOnly Property GetBasketItems() As List(Of Kartris.BasketItem) Get Return BasketItems End Get End Property Public ReadOnly Property GetPromotionsDiscount() As ArrayList Get Return arrPromotionsDiscount End Get End Property Public Property ViewType() As BasketBLL.VIEW_TYPE Get Return _ViewType End Get Set(ByVal value As BasketBLL.VIEW_TYPE) _ViewType = value End Set End Property Public Property ViewOnly() As Boolean Get Return _ViewOnly End Get Set(ByVal value As Boolean) _ViewOnly = value End Set End Property Public WriteOnly Property UserID() As Integer Set(ByVal value As Integer) _UserID = value End Set End Property Public Property ShippingDetails() As Interfaces.objShippingDetails Get _objShippingDetails = Session("_ShippingDetails") If _objShippingDetails IsNot Nothing Then _objShippingDetails.ShippableItemsTotalWeight = Basket.ShippingTotalWeight _objShippingDetails.ShippableItemsTotalPrice = Basket.ShippingTotalExTax End If Return _objShippingDetails End Get Set(ByVal value As Interfaces.objShippingDetails) _objShippingDetails = value _objShippingDetails.ShippableItemsTotalWeight = Basket.ShippingTotalWeight _objShippingDetails.ShippableItemsTotalPrice = Basket.ShippingTotalExTax Session("_ShippingDetails") = _objShippingDetails End Set End Property Public Property ShippingDestinationID() As Integer Get If Session("_ShippingDestinationID") Is Nothing Then Return 0 Else Return Session("_ShippingDestinationID") End If End Get Set(ByVal value As Integer) Session("_ShippingDestinationID") = value Session("numShippingCountryID") = value End Set End Property Public ReadOnly Property ShippingBoundary() As Double Get If GetKartConfig("frontend.checkout.shipping.calcbyweight") = "y" Then Return Basket.ShippingTotalWeight Else If KartSettingsManager.GetKartConfig("general.tax.pricesinctax") = "y" Then Return Basket.ShippingTotalExTax Else Return Basket.ShippingTotalIncTax End If End If End Get End Property Public ReadOnly Property SelectedShippingID() As Integer Get Return UC_ShippingMethodsDropdown.SelectedShippingID End Get End Property Public ReadOnly Property SelectedShippingAmount() As Double Get Return UC_ShippingMethodsDropdown.SelectedShippingAmount End Get End Property Public ReadOnly Property SelectedShippingMethod() As String Get Return Basket.ShippingName End Get End Property Private Property CouponCode() As String Get Return Session("CouponCode") & "" End Get Set(ByVal value As String) Session("CouponCode") = value End Set End Property Public Event ItemQuantityChanged() Sub LoadBasket() SESS_CurrencyID = Session("CUR_ID") Dim blnIsInCheckout As Boolean = True Basket.DB_C_CustomerID = _UserID Call Basket.LoadBasketItems() BasketItems = Basket.BasketItems If BasketItems.Count = 0 Then litBasketEmpty.Text = GetGlobalResourceObject("Basket", "ContentText_BasketEmpty") Else litBasketEmpty.Text = "" phdBasket.Visible = True End If Call Basket.Validate(False) rptBasket.DataSource = BasketItems rptBasket.DataBind() Call Basket.CalculateTotals() Call BasketBLL.CalculatePromotions(Basket, arrPromotions, arrPromotionsDiscount, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) Dim strCouponError As String = "" Call BasketBLL.CalculateCoupon(Basket, CouponCode & "", strCouponError, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) BSKT_CustomerDiscount = BasketBLL.GetCustomerDiscount(_UserID) Call BasketBLL.CalculateCustomerDiscount(Basket, BSKT_CustomerDiscount) Call BasketBLL.CalculateOrderHandlingCharge(Basket, Session("numShippingCountryID")) phdShipping.Visible = True UC_ShippingMethodsDropdown.Visible = True If blnIsInCheckout Then SetShipping(UC_ShippingMethodsDropdown.SelectedShippingID, UC_ShippingMethodsDropdown.SelectedShippingAmount, ShippingDestinationID) End If If Basket.OrderHandlingPrice.IncTax = 0 Then phdOrderHandling.Visible = False Else phdOrderHandling.Visible = True Try phdOutOfStockElectronic.Visible = Basket.AdjustedForElectronic phdOutOfStock.Visible = Basket.AdjustedQuantities Catch ex As Exception End Try Session("Basket") = Basket End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load SESS_CurrencyID = Session("CUR_ID") If ConfigurationManager.AppSettings("TaxRegime").ToLower = "us" Or ConfigurationManager.AppSettings("TaxRegime").ToLower = "simple" Then APP_PricesIncTax = False APP_ShowTaxDisplay = False APP_USMultiStateTax = True Else APP_PricesIncTax = LCase(GetKartConfig("general.tax.pricesinctax")) = "y" 'For checkout, we show tax if showtax is set to 'y' or 'c'. 'For other pages, only if it is set to 'y'. APP_ShowTaxDisplay = LCase(GetKartConfig("frontend.display.showtax")) = "y" APP_USMultiStateTax = False End If litError.Text = "" If Not (IsPostBack) Then Call LoadBasket() Else If Basket.OrderHandlingPrice.IncTax = 0 Then phdOrderHandling.Visible = False Else phdOrderHandling.Visible = True End If updPnlMainBasket.Update() End Sub Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender If ViewType = BasketBLL.VIEW_TYPE.MAIN_BASKET Then phdMainBasket.Visible = True phdControls.Visible = True phdBasketButtons.Visible = True ElseIf ViewType = BasketBLL.VIEW_TYPE.CHECKOUT_BASKET Then phdControls.Visible = False If Not _ViewOnly Then phdShippingSelection.Visible = True End If If ViewType = BasketBLL.VIEW_TYPE.CHECKOUT_BASKET And ViewOnly Then rptBasket.DataSource = BasketItems rptBasket.DataBind() End If phdMainBasket.Visible = True phdControls.Visible = True phdBasketButtons.Visible = True blnShowPromotion = True phdPromotions.Visible = True rptPromotions.DataSource = arrPromotions rptPromotions.DataBind() phdPromotions.Visible = IIf(arrPromotions.Count > 0 And blnShowPromotion, True, False) rptPromotionDiscount.DataSource = arrPromotionsDiscount rptPromotionDiscount.DataBind() phdPromotionDiscountHeader.Visible = IIf(arrPromotionsDiscount.Count > 0, True, False) If BasketItems Is Nothing OrElse BasketItems.Count = 0 Then phdBasket.Visible = False End If If UC_ShippingMethodsDropdown.SelectedShippingID > 0 Then phdShippingTax.Visible = True phdShippingTaxHide.Visible = False Else phdShippingTax.Visible = False phdShippingTaxHide.Visible = True End If Session("Basket") = Basket End Sub Sub QuantityChanged(ByVal Sender As Object, ByVal Args As EventArgs) Dim objQuantity As TextBox = Sender.Parent.FindControl("txtQuantity") Dim objBasketID As HiddenField = Sender.Parent.FindControl("hdfBasketID") If Not IsNumeric(objQuantity.Text) Then objQuantity.Text = "0" objQuantity.Focus() Else Try BasketBLL.UpdateQuantity(CInt(objBasketID.Value), CSng(objQuantity.Text)) Catch ex As Exception End Try End If Call LoadBasket() Try phdOutOfStockElectronic.Visible = Basket.AdjustedForElectronic phdOutOfStock.Visible = Basket.AdjustedQuantities Catch ex As Exception End Try updPnlMainBasket.Update() End Sub Sub RemoveItem_Click(ByVal Sender As Object, ByVal E As CommandEventArgs) Dim numItemID As Long Dim strArgument As String Dim numRemoveVersionID As Integer = 0 strArgument = E.CommandArgument Dim arrArguments() As String = strArgument.Split(";") numItemID = CLng(arrArguments(0)) numRemoveVersionID = CLng(arrArguments(1)) BasketBLL.DeleteBasketItems(CLng(numItemID)) Call LoadBasket() updPnlMainBasket.Update() End Sub Sub RemoveCoupon_Click(ByVal Sender As Object, ByVal E As CommandEventArgs) Dim strCouponError As String = "" Call Basket.CalculateTotals() Call BasketBLL.CalculatePromotions(Basket, arrPromotions, arrPromotionsDiscount, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) Session("CouponCode") = "" Call BasketBLL.CalculateCoupon(Basket, "", strCouponError, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) BSKT_CustomerDiscount = BasketBLL.GetCustomerDiscount(_UserID) Call BasketBLL.CalculateCustomerDiscount(Basket, BSKT_CustomerDiscount) Call BasketBLL.CalculateOrderHandlingCharge(Basket, Session("numShippingCountryID")) updPnlMainBasket.Update() End Sub Sub CustomText_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Dim numItemID As Long Dim numCustomCost As Double Dim strCustomType As String = "" numItemID = e.CommandArgument hidBasketID.Value = numItemID For Each objItem As BasketItem In BasketItems If objItem.ID = numItemID Then numCustomCost = objItem.CustomCost litCustomCost.Text = CurrenciesBLL.FormatCurrencyPrice(Session("CUR_ID"), objItem.CustomCost) lblCustomDesc.Text = objItem.CustomDesc hidCustomVersionID.Value = objItem.VersionID txtCustomText.Text = objItem.CustomText strCustomType = objItem.CustomType End If Next 'Hide cost line if zero If numCustomCost = 0 Then phdCustomizationPrice.Visible = False Else phdCustomizationPrice.Visible = True End If 'Text Customization (Required) 'Hide certain fields If strCustomType = "r" Then valCustomText.Visible = True phdCustomizationCancel.Visible = False Else valCustomText.Visible = False phdCustomizationCancel.Visible = True End If popCustomText.Show() updPnlCustomText.Update() End Sub Sub ProductName_Click(ByVal sender As Object, ByVal e As CommandEventArgs) Dim strItemInfo As String strItemInfo = e.CommandArgument If strItemInfo <> "" Then Try Dim arrInfo As String() = Split(strItemInfo, ";") If arrInfo(UBound(arrInfo)) <> "o" Then strItemInfo = "" End If Catch ex As Exception End Try End If Session("BasketItemInfo") = strItemInfo Dim strURL As String = e.CommandName Response.Redirect(strURL) End Sub Sub ApplyCoupon_Click(ByVal Sender As Object, ByVal E As CommandEventArgs) Dim strCouponError As String = "" Call Basket.CalculateTotals() Call BasketBLL.CalculatePromotions(Basket, arrPromotions, arrPromotionsDiscount, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) Call BasketBLL.CalculateCoupon(Basket, Trim(txtCouponCode.Text), strCouponError, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) If strCouponError <> "" Then With popMessage .SetTitle = GetGlobalResourceObject("Basket", "PageTitle_ShoppingBasket") .SetTextMessage = strCouponError .SetWidthHeight(300, 50) .ShowPopup() End With Else Session("CouponCode") = Trim(txtCouponCode.Text) End If BSKT_CustomerDiscount = BasketBLL.GetCustomerDiscount(_UserID) Call BasketBLL.CalculateCustomerDiscount(Basket, BSKT_CustomerDiscount) Call BasketBLL.CalculateOrderHandlingCharge(Basket, Session("numShippingCountryID")) updPnlMainBasket.Update() End Sub Sub EmptyBasket_Click(ByVal Sender As Object, ByVal E As CommandEventArgs) BasketBLL.DeleteBasket() Call LoadBasket() updPnlMainBasket.Update() End Sub Private Function GetProductIDs() As String Dim strProductIDs As String = "" If Not (BasketItems Is Nothing) Then For Each objItem As BasketItem In BasketItems strProductIDs = strProductIDs & objItem.ProductID & ";" Next End If Return strProductIDs End Function Private Function GetBasketItemByProductID(ByVal numProductID As Integer) As BasketItem For Each Item As BasketItem In BasketItems If Item.ProductID = numProductID Then Return Item Next Return Nothing End Function Public Function ShippingTotalIncTax() As Double Return Basket.ShippingTotalIncTax End Function Public Sub SetShipping(ByVal numShippingID As Integer, ByVal numShippingAmount As Double, ByVal numDestinationID As Integer) If ConfigurationManager.AppSettings("TaxRegime").ToLower = "us" Or ConfigurationManager.AppSettings("TaxRegime").ToLower = "simple" Then APP_PricesIncTax = False APP_ShowTaxDisplay = False APP_USMultiStateTax = True Else APP_PricesIncTax = LCase(GetKartConfig("general.tax.pricesinctax")) = "y" APP_ShowTaxDisplay = LCase(GetKartConfig("frontend.display.showtax")) = "y" APP_USMultiStateTax = False End If SESS_CurrencyID = Session("CUR_ID") Session("numShippingCountryID") = numDestinationID Basket.CalculateShipping(Val(HttpContext.Current.Session("LANG")), numShippingID, numShippingAmount, Session("numShippingCountryID"), ShippingDetails) BasketBLL.CalculateOrderHandlingCharge(Basket, Session("numShippingCountryID")) If Basket.OrderHandlingPrice.IncTax = 0 Then phdOrderHandling.Visible = False Else phdOrderHandling.Visible = True UpdatePromotionDiscount() Basket.Validate(False) Call Basket.CalculateTotals() Call BasketBLL.CalculatePromotions(Basket, arrPromotions, arrPromotionsDiscount, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) Dim strCouponError As String = "" Call BasketBLL.CalculateCoupon(Basket, Session("CouponCode") & "", strCouponError, (APP_PricesIncTax = False And APP_ShowTaxDisplay = False)) BSKT_CustomerDiscount = BasketBLL.GetCustomerDiscount(_UserID) Call BasketBLL.CalculateCustomerDiscount(Basket, BSKT_CustomerDiscount) BasketItems = Basket.BasketItems rptBasket.DataSource = BasketItems rptBasket.DataBind() Session("Basket") = Basket End Sub Private Sub UpdatePromotionDiscount() For Each objItem As PromotionBasketModifier In arrPromotionsDiscount objItem.ApplyTax = Basket.ApplyTax objItem.ExTax = objItem.ExTax objItem.IncTax = objItem.IncTax Next rptPromotionDiscount.DataSource = arrPromotionsDiscount rptPromotionDiscount.DataBind() End Sub Public Sub SetOrderHandlingCharge(ByVal numShippingCountryID As Integer) BasketBLL.CalculateOrderHandlingCharge(Basket, numShippingCountryID) End Sub Protected Sub rptBasket_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptBasket.ItemDataBound If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then objItem = e.Item.DataItem If LCase(objItem.ProductType) = "s" Then CType(e.Item.FindControl("phdProductType1"), PlaceHolder).Visible = True Else CType(e.Item.FindControl("phdProductType2"), PlaceHolder).Visible = True If objItem.HasCombinations Then CType(e.Item.FindControl("phdItemHasCombinations"), PlaceHolder).Visible = True Else CType(e.Item.FindControl("phdItemHasNoCombinations"), PlaceHolder).Visible = True End If End If Dim strURL As String = SiteMapHelper.CreateURL(SiteMapHelper.Page.CanonicalProduct, objItem.ProductID) If strURL.Contains("?") Then strURL = strURL & objItem.OptionLink Else strURL = strURL & Replace(objItem.OptionLink, "&", "?") End If CType(e.Item.FindControl("lnkBtnProductName"), LinkButton).CommandName = strURL If LCase(objItem.CustomType) <> "n" Then CType(e.Item.FindControl("lnkCustomize"), LinkButton).ToolTip = "(" & CurrenciesBLL.FormatCurrencyPrice(Session("CUR_ID"), objItem.CustomCost) & ")" & vbCrLf & objItem.CustomText CType(e.Item.FindControl("lnkCustomize"), LinkButton).Visible = True Else CType(e.Item.FindControl("lnkCustomize"), LinkButton).ToolTip = "" CType(e.Item.FindControl("lnkCustomize"), LinkButton).Visible = False End If If objItem.AdjustedQty Then CType(e.Item.FindControl("txtQuantity"), TextBox).CssClass = "quantity_changed" End If End If End Sub Protected Sub btnSaveCustomText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveCustomText.Click Dim numSessionID, numBasketID, numVersionID As Long Dim numQuantity As Double Dim strCustomText, strOptions As String If IsNumeric(hidBasketID.Value) Then numBasketID = CLng(hidBasketID.Value) Else numBasketID = 0 If numBasketID > 0 Then ''// comes from basket numVersionID = CLng(hidCustomVersionID.Value) strCustomText = Trim(txtCustomText.Text) strCustomText = CkartrisDisplayFunctions.StripHTML(strCustomText) BasketBLL.SaveCustomText(numBasketID, strCustomText) For Each objItem As BasketItem In BasketItems If numBasketID = objItem.ID Then objItem.CustomText = strCustomText End If Next rptBasket.DataSource = BasketItems rptBasket.DataBind() Call LoadBasket() updPnlMainBasket.Update() Else ''// comes from product page numSessionID = Session("SessionID") numVersionID = CLng(hidCustomVersionID.Value) numQuantity = CDbl(hidCustomQuantity.Value) strCustomText = Trim(txtCustomText.Text) strCustomText = CkartrisDisplayFunctions.StripHTML(strCustomText) strOptions = hidOptions.Value numBasketID = hidOptionBasketID.Value BasketBLL.AddNewBasketValue(BasketItems, BasketBLL.BASKET_PARENTS.BASKET, numSessionID, numVersionID, numQuantity, strCustomText, strOptions, numBasketID) ShowAddItemToBasket(numVersionID, numQuantity, True) End If End Sub Private Sub SaveCustomText(ByVal strCustomText As String, Optional ByVal numItemID As Integer = 0) If numItemID = 0 Then numItemID = btnSaveCustomText.CommandArgument End If BasketBLL.SaveCustomText(numItemID, strCustomText) For Each objItem As BasketItem In BasketItems If numItemID = objItem.ID Then objItem.CustomText = strCustomText End If Next rptBasket.DataSource = BasketItems rptBasket.DataBind() updPnlMainBasket.Update() End Sub Public Sub ShowCustomText(ByVal numVersionID As Long, ByVal numQuantity As Double, Optional ByVal strOptions As String = "", Optional ByVal numBasketValueID As Integer = 0) Dim strCustomType As String Dim tblCustomization As DataTable = BasketBLL.GetCustomization(numVersionID) Dim sessionID As Long If tblCustomization.Rows.Count > 0 Then strCustomType = LCase(tblCustomization.Rows(0).Item("V_CustomizationType")) If strCustomType <> "n" Then If strCustomType = "t" Or strCustomType = "r" Then 'Text Customization '(Optional or Required) hidBasketID.Value = "0" hidOptionBasketID.Value = numBasketValueID hidCustomType.Value = strCustomType hidCustomVersionID.Value = numVersionID hidCustomQuantity.Value = numQuantity hidOptions.Value = strOptions litCustomCost.Text = CurrenciesBLL.FormatCurrencyPrice(Session("CUR_ID"), CurrenciesBLL.ConvertCurrency(Session("CUR_ID"), tblCustomization.Rows(0).Item("V_CustomizationCost"))) lblCustomDesc.Text = tblCustomization.Rows(0).Item("V_CustomizationDesc") & "" Dim strCustomText As String = "" For Each objBasketItem As BasketItem In Basket.BasketItems If objBasketItem.ID = numBasketValueID Then strCustomText = objBasketItem.CustomText Exit For End If Next txtCustomText.Text = strCustomText 'Hide cost line if zero If tblCustomization.Rows(0).Item("V_CustomizationCost") = 0 Then phdCustomizationPrice.Visible = False Else phdCustomizationPrice.Visible = True End If 'Text Customization (Required) 'Hide certain fields If strCustomType = "r" Then valCustomText.Visible = True phdCustomizationCancel.Visible = False Else valCustomText.Visible = False phdCustomizationCancel.Visible = True End If End If popCustomText.Show() updPnlCustomText.Update() Else sessionID = Session("SessionID") BasketBLL.AddNewBasketValue(BasketItems, BasketBLL.BASKET_PARENTS.BASKET, sessionID, numVersionID, numQuantity, "", strOptions, numBasketValueID) Dim strUpdateBasket As String = GetGlobalResourceObject("Basket", "ContentText_ItemsUpdated") If strUpdateBasket = "" Then strUpdateBasket = "The item(s) were updated to your basket." If strOptions <> "" Then ShowAddItemToBasket(numVersionID, numQuantity, True) Else ShowAddItemToBasket(numVersionID, numQuantity) End If End If End If End Sub Private Sub ShowAddItemToBasket(ByVal VersionID As Integer, ByVal Quantity As Double, Optional ByVal blnDisplayPopup As Boolean = False) Dim objVersionsBLL As New VersionsBLL Dim tblVersion As DataTable tblVersion = objVersionsBLL._GetVersionByID(VersionID) If tblVersion.Rows.Count > 0 Then ''// add basket item quantity to new item qty and check for stock Dim numBasketQty As Double = 0 For Each itmBasket As BasketItem In BasketItems If VersionID = itmBasket.VersionID Then numBasketQty = itmBasket.Quantity Exit For End If Next If tblVersion.Rows(0).Item("V_QuantityWarnLevel") > 0 And (numBasketQty + Quantity) > tblVersion.Rows(0).Item("V_Quantity") Then 'Response.Redirect("~/Basket.aspx") End If End If 'This section below we now only 'need to run for options products Dim strBasketBehavior As String strBasketBehavior = LCase(KartSettingsManager.GetKartConfig("frontend.basket.behaviour")) End Sub Function SendOutputWithoutHTMLTags(ByVal strInput As String) As String Dim strNewString As String = "" For n As Integer = 1 To Len(strInput) If Mid(strInput, n, 1) = "<" Then While Mid(strInput, n, 1) <> ">" n = n + 1 End While n = n + 1 End If strNewString = strNewString & Mid(strInput, n, 1) Next Return strNewString End Function Protected Sub UC_ShippingMethodsDropdown_ShippingSelected(ByVal sender As Object, ByVal e As System.EventArgs) Handles UC_ShippingMethodsDropdown.ShippingSelected SetShipping(UC_ShippingMethodsDropdown.SelectedShippingID, UC_ShippingMethodsDropdown.SelectedShippingAmount, ShippingDestinationID) updPnlMainBasket.Update() End Sub Public Sub RefreshShippingMethods() UC_ShippingMethodsDropdown.DestinationID = ShippingDestinationID UC_ShippingMethodsDropdown.Boundary = ShippingBoundary UC_ShippingMethodsDropdown.ShippingDetails = ShippingDetails UC_ShippingMethodsDropdown.Refresh() SetShipping(UC_ShippingMethodsDropdown.SelectedShippingID, UC_ShippingMethodsDropdown.SelectedShippingAmount, ShippingDestinationID) updPnlMainBasket.Update() End Sub Protected Sub btnCancelCustomText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelCustomText.Click Dim numSessionID As Long Dim numBasketID, numVersionID As Long Dim numQuantity As Double Dim strOptions As String If IsNumeric(hidBasketID.Value) Then numBasketID = CLng(hidBasketID.Value) Else numBasketID = 0 If numBasketID = 0 Then numSessionID = Session("SessionID") numVersionID = CLng(hidCustomVersionID.Value) numQuantity = CDbl(hidCustomQuantity.Value) strOptions = hidOptions.Value BasketBLL.AddNewBasketValue(BasketItems, BasketBLL.BASKET_PARENTS.BASKET, numSessionID, numVersionID, numQuantity, "", strOptions) ShowAddItemToBasket(numVersionID, numQuantity) End If End Sub End Class
cactusoft/kartris
UserControls/Back/_BasketView.ascx.vb
Visual Basic
gpl-2.0
30,511
/** * * Apply your custom CSS here * */ body { } a { } .page-body.skin-white .sidebar-menu .main-menu li.has-sub>a:before { color: #666; } /*navbar*/ .navbar.horizontal-menu.navbar-minimal.navbar-fixed-top+.page-container>div>.sidebar-menu.fixed .sidebar-menu-inner{ top: 55px; } /*validate forms*/ form .form-group.validate-has-error .form-control + div { display: block; padding-top: 5px; font-size: 12px; color: #cc3f44; } form .form-group.validate-has-error .input-group + div { display: block; padding-top: 5px; font-size: 12px; color: #cc3f44; } form .form-group.validate-has-error .ui-select-container + div { display: block; padding-top: 5px; font-size: 12px; color: #cc3f44; } .ui-select-bootstrap button{ color: #333; background-color: #fff; border-color: #ccc; }
carlosthe19916/SistCoopEE_App
app/styles/custom.css
CSS
gpl-2.0
851
<?php /* Copyright (c) 2007 BeVolunteer This file is part of BW Rox. BW Rox is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. BW Rox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/> or write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ $words = new MOD_words(); ?> <div id="tour"> <h1><?php echo $words->get('tour_maps')?></h1> <h2><?php echo $words->getFormatted('tour_maps_title1')?></h2> <p><?php echo $words->getFormatted('tour_maps_text1')?></p> <div class="floatbox"> <img src="images/tour/map2.png" class="float_left" alt="maps" /> <h2><?php echo $words->getFormatted('tour_maps_title2')?></h2> <p><?php echo $words->getFormatted('tour_maps_text2')?></p> </div> <h2><?php echo $words->getFormatted('tour_maps_title3')?></h2> <p><?php echo $words->getFormatted('tour_maps_text3')?></p> <h2><a class="bigbutton" href="tour/openness" onclick="this.blur();" style="margin-bottom: 20px"><span><?php echo $words->getFormatted('tour_goNext')?> &raquo;</span></a> <?php echo $words->getFormatted('tour_openness')?></h2> </div>
BeWelcome/rox.prototypes
build/tour/templates/tourpage6.php
PHP
gpl-2.0
1,630
package app.toonido.mindorks.toonido; import android.app.Application; import com.parse.Parse; /** * Created by janisharali on 30/09/15. */ public class ToonidoApp extends Application { @Override public void onCreate() { super.onCreate(); // Enable Local Datastore. Parse.enableLocalDatastore(this); Parse.initialize(this, ToonidoConstants.PARSE_APPLICATION_ID, ToonidoConstants.PARSE_CLIENT_KEY); } }
mindorks/Toonido
Toonido/app/src/main/java/app/toonido/mindorks/toonido/ToonidoApp.java
Java
gpl-2.0
451
/*********************************************************************** * * avra - Assembler for the Atmel AVR microcontroller series * * Copyright (C) 1998-2004 Jon Anders Haugum, TObias Weber * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * * Authors of avra can be reached at: * email: [email protected], [email protected] * www: http://sourceforge.net/projects/avra */ /* * In append_type: added generic register names support * Alexey Pavluchenko, 16.Nov.2005 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "misc.h" #include "args.h" #include "avra.h" #include "device.h" /* Only Windows LIBC does support itoa, so we add this function for other systems here manually. Thank you Peter Hettkamp for your work. */ #ifndef WIN32 char * itoa(int num, char *str, const int number_format) { int num1 = num; int num_chars = 0; int pos; while (num1>0) { num_chars++; num1 /= number_format; } if (num_chars == 0) num_chars = 1; str[num_chars] = 0; for (pos = num_chars-1; pos>=0; pos--) { int cur_char = num % number_format; if (cur_char < 10) /* Insert number */ { str[pos] = cur_char + '0'; } else { str[pos] = cur_char-10 + 'A'; } num /= number_format; } return(str); } #endif int read_macro(struct prog_info *pi, char *name) { int loopok; int i; int start; struct macro *macro; struct macro_line *macro_line; struct macro_line **last_macro_line = NULL; struct macro_label *macro_label; if (pi->pass == PASS_1) { if (!name) { print_msg(pi, MSGTYPE_ERROR, "missing macro name"); return(True); } get_next_token(name, TERM_END); for (i = 0; !IS_END_OR_COMMENT(name[i]); i++) { if (!IS_LABEL(name[i])) { print_msg(pi, MSGTYPE_ERROR, "illegal characters used in macro name '%s'",name); return(False); } } macro = calloc(1, sizeof(struct macro)); if (!macro) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } if (pi->last_macro) pi->last_macro->next = macro; else pi->first_macro = macro; pi->last_macro = macro; macro->name = malloc(strlen(name) + 1); if (!macro->name) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(macro->name, name); macro->include_file = pi->fi->include_file; macro->first_line_number = pi->fi->line_number; last_macro_line = &macro->first_macro_line; } else /* pi->pass == PASS_2 */ { if (pi->list_line && pi->list_on) { fprintf(pi->list_file, " %s\n", pi->list_line); pi->list_line = NULL; } // reset macro label running numbers get_next_token(name, TERM_END); macro = get_macro(pi, name); if (!macro) { print_msg(pi, MSGTYPE_ERROR, "macro inconsistency in '%s'", name); return(True); } for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next) { macro_label->running_number = 0; } } loopok = True; while (loopok) { if (fgets_new(pi,pi->fi->buff, LINEBUFFER_LENGTH, pi->fi->fp)) { pi->fi->line_number++; i = 0; while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i])) i++; if (pi->fi->buff[i] == '.') { i++; if (!nocase_strncmp(&pi->fi->buff[i], "endm", 4)) loopok = False; if (!nocase_strncmp(&pi->fi->buff[i], "endmacro", 8)) loopok = False; } if (pi->pass == PASS_1) { if (loopok) { i = 0; /* find start of line */ while (IS_HOR_SPACE(pi->fi->buff[i]) && !IS_END_OR_COMMENT(pi->fi->buff[i])) { i++; } start = i; /* find end of line */ while (!IS_END_OR_COMMENT(pi->fi->buff[i]) && (IS_LABEL(pi->fi->buff[i]) || pi->fi->buff[i] == ':')) { i++; } if (pi->fi->buff[i-1] == ':' && (pi->fi->buff[i-2] == '%' && (IS_HOR_SPACE(pi->fi->buff[i]) || IS_END_OR_COMMENT(pi->fi->buff[i])))) { if (macro->first_label) { for (macro_label = macro->first_label; macro_label->next; macro_label=macro_label->next) { } macro_label->next = calloc(1,sizeof(struct macro_label)); macro_label = macro_label->next; } else { macro_label = calloc(1,sizeof(struct macro_label)); macro->first_label = macro_label; } macro_label->label = malloc(strlen(&pi->fi->buff[start])+1); pi->fi->buff[i-1] = '\0'; strcpy(macro_label->label, &pi->fi->buff[start]); pi->fi->buff[i-1] = ':'; macro_label->running_number = 0; } macro_line = calloc(1, sizeof(struct macro_line)); if (!macro_line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } *last_macro_line = macro_line; last_macro_line = &macro_line->next; macro_line->line = malloc(strlen(pi->fi->buff) + 1); if (!macro_line->line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(macro_line->line, &pi->fi->buff[start]); } } else if (pi->fi->buff && pi->list_file && pi->list_on) { if (pi->fi->buff[i] == ';') fprintf(pi->list_file, " %s\n", pi->fi->buff); else fprintf(pi->list_file, " %s\n", pi->fi->buff); } } else { if (feof(pi->fi->fp)) { print_msg(pi, MSGTYPE_ERROR, "Found no closing .ENDMACRO"); return(True); } else { perror(pi->fi->include_file->name); return(False); } } } return(True); } struct macro *get_macro(struct prog_info *pi, char *name) { struct macro *macro; for (macro = pi->first_macro; macro; macro = macro->next) if (!nocase_strcmp(macro->name, name)) return(macro); return(NULL); } void append_type(struct prog_info *pi, char *name, int c, char *value) { int p, l; struct def *def; p = strlen(name); name[p++] = '_'; if (c == 0) { name[p++] = 'v'; name[p] = '\0'; return; } l = strlen(value); if ((l==2 || l==3) && (tolower(value[0])=='r') && isdigit(value[1]) && (l==3 ? isdigit(value[2]) : 1) && (atoi(&value[1])<32)) { itoa((c*8),&name[p],10); return; } for (def = pi->first_def; def; def = def->next) if (!nocase_strcmp(def->name, value)) { itoa((c*8),&name[p],10); return; } name[p++] = 'i'; name[p] = '\0'; } /********************************************************* * This routine replaces the macro call with mnemonics. * *********************************************************/ int expand_macro(struct prog_info *pi, struct macro *macro, char *rest_line) { int ok = True, macro_arg_count = 0, off, a, b = 0, c, i = 0, j = 0; char *line = NULL; char *temp; char *macro_args[MAX_MACRO_ARGS]; char tmp[7]; char buff[LINEBUFFER_LENGTH]; char arg = False; char *nmn; //string buffer for 'n'ew 'm'acro 'n'ame struct macro_line *old_macro_line; struct macro_call *macro_call; struct macro_label *macro_label; if (rest_line) { //we reserve some extra space for extended macro parameters line = malloc(strlen(rest_line) + 20); if (!line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } /* exchange amca word 'src' with YH:YL and 'dst' with ZH:ZL */ for (c = 0, a = strlen(rest_line); c < a; c++) { switch (tolower(rest_line[c])) { case 's': if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 'r') && (rest_line[c+2] == 'c') && IS_SEPARATOR(rest_line[c+3])) { strcpy(&line[b],"YH:YL"); b += 5; c += 2; } else { line[b++] = rest_line[c]; } break; case 'd': if (IS_SEPARATOR(rest_line[c-1]) && (rest_line[c+1] == 's') && (rest_line[c+2] == 't') && IS_SEPARATOR(rest_line[c+3])) { strcpy(&line[b],"ZH:ZL"); b += 5; c += 2; } else { line[b++] = rest_line[c]; } break; // case ';': // break; default: line[b++] = rest_line[c]; } } strcpy(&line[b],"\n"); /* set CR/LF at the end of the line */ /* here we split up the macro arguments into "macro_args" * Extended macro code interpreter added by TW 2002 */ temp = line; /* test for advanced parameters */ if ( temp[0] == '[' ) // there must be "[" " then "]", else it is garbage { if (!strchr(temp, ']')) { print_msg(pi, MSGTYPE_ERROR, "found no closing ']'"); return(False); } // Okay now we are within the advanced code interpreter temp++; // = &temp[1]; // skip the first bracket nmn = malloc(LINEBUFFER_LENGTH); if (!nmn) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(nmn,macro->name); // create a new macro name buffer c = 1; // byte counter arg = True; // loop flag while (arg) { while (IS_HOR_SPACE(temp[0])) //skip leading spaces { temp++; // = &temp[1]; } off = 0; // pointer offset do { switch (temp[off]) //test current character code { case ':': temp[off] = '\0'; if (off > 0) { c++; macro_args[macro_arg_count++] = temp; } else { print_msg(pi, MSGTYPE_ERROR, "missing register before ':'",nmn); return(False); } break; case ']': arg = False; case ',': a = off; do temp[a--] = '\0'; while ( IS_HOR_SPACE(temp[a]) ); if (off > 0) { macro_args[macro_arg_count++] = temp; append_type(pi, nmn, c, temp); c = 1; } else { append_type(pi, nmn, 0, temp); c = 1; } break; default: off++; } } while (temp[off] != '\0'); if (arg) temp = &temp[off+1]; else break; } macro = get_macro(pi,nmn); if (macro == NULL) { print_msg(pi, MSGTYPE_ERROR, "Macro %s is not defined !",nmn); return(False); } free(nmn); } /* or else, we handle the macro as normal macro */ else { line = malloc(strlen(rest_line) + 1); if (!line) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } strcpy(line, rest_line); temp = line; while (temp) { macro_args[macro_arg_count++] = temp; temp = get_next_token(temp, TERM_COMMA); } } } if (pi->pass == PASS_1) { macro_call = calloc(1, sizeof(struct macro_call)); if (!macro_call) { print_msg(pi, MSGTYPE_OUT_OF_MEM, NULL); return(False); } if (pi->last_macro_call) pi->last_macro_call->next = macro_call; else pi->first_macro_call = macro_call; pi->last_macro_call = macro_call; macro_call->line_number = pi->fi->line_number; macro_call->include_file = pi->fi->include_file; macro_call->macro = macro; macro_call->prev_on_stack = pi->macro_call; if (macro_call->prev_on_stack) { macro_call->nest_level = macro_call->prev_on_stack->nest_level + 1; macro_call->prev_line_index = macro_call->prev_on_stack->line_index; } } else { for (macro_call = pi->first_macro_call; macro_call; macro_call = macro_call->next) { if ((macro_call->include_file->num == pi->fi->include_file->num) && (macro_call->line_number == pi->fi->line_number)) { if (pi->macro_call) { /* Find correct macro_call when using recursion and nesting */ if (macro_call->prev_on_stack == pi->macro_call) if ((macro_call->nest_level == (pi->macro_call->nest_level + 1)) && (macro_call->prev_line_index == pi->macro_call->line_index)) break; } else break; } } if (pi->list_line && pi->list_on) { fprintf(pi->list_file, "C:%06x + %s\n", pi->cseg_addr, pi->list_line); pi->list_line = NULL; } } macro_call->line_index = 0; pi->macro_call = macro_call; old_macro_line = pi->macro_line; //printf("\nconvert macro: '%s'\n",macro->name); for (pi->macro_line = macro->first_macro_line; pi->macro_line && ok; pi->macro_line = pi->macro_line->next) { macro_call->line_index++; if (GET_ARG(pi->args, ARG_LISTMAC)) pi->list_line = buff; else pi->list_line = NULL; /* here we change jumps/calls within macro that corresponds to macro labels. Only in case there is an entry in macro_label list */ strcpy(buff,"\0"); macro_label = get_macro_label(pi->macro_line->line,macro); if (macro_label) { /* test if the right macro label has been found */ temp = strstr(pi->macro_line->line,macro_label->label); c = strlen(macro_label->label); if (temp[c] == ':') /* it is a label definition */ { macro_label->running_number++; strncpy(buff, macro_label->label, c - 1); buff[c - 1] = 0; i = strlen(buff) + 2; /* we set the process indeafter label */ /* add running number to it */ strcpy(&buff[c-1],itoa(macro_label->running_number, tmp, 10)); strcat(buff, ":\0"); } else if (IS_HOR_SPACE(temp[c]) || IS_END_OR_COMMENT(temp[c])) /* it is a jump to a macro defined label */ { strcpy(buff,pi->macro_line->line); temp = strstr(buff, macro_label->label); i = temp - buff + strlen(macro_label->label); strncpy(temp, macro_label->label, c - 1); strcpy(&temp[c-1], itoa(macro_label->running_number, tmp, 10)); } } else { i = 0; } /* here we check every character of current line */ for (j = i; pi->macro_line->line[i] != '\0'; i++) { /* check for register place holders */ if (pi->macro_line->line[i] == '@') { i++; if (!isdigit(pi->macro_line->line[i])) print_msg(pi, MSGTYPE_ERROR, "@ must be followed by a number"); else if ((pi->macro_line->line[i] - '0') >= macro_arg_count) print_msg(pi, MSGTYPE_ERROR, "Missing macro argument (for @%c)", pi->macro_line->line[i]); else { /* and replace them with given registers */ strcat(&buff[j], macro_args[pi->macro_line->line[i] - '0']); j += strlen(macro_args[pi->macro_line->line[i] - '0']); } } else if (pi->macro_line->line[i] == ';') { strncat(buff, "\n", 1); break; } else { strncat(buff, &pi->macro_line->line[i], 1); } } ok = parse_line(pi, buff); if (ok) { if ((pi->pass == PASS_2) && pi->list_line && pi->list_on) fprintf(pi->list_file, " %s\n", pi->list_line); if (pi->error_count >= pi->max_errors) { print_msg(pi, MSGTYPE_MESSAGE, "Maximum error count reached. Exiting..."); ok = False; break; } } } pi->macro_line = old_macro_line; pi->macro_call = macro_call->prev_on_stack; if (rest_line) free(line); return(ok); } struct macro_label *get_macro_label(char *line, struct macro *macro) { char *temp; struct macro_label *macro_label; for (macro_label = macro->first_label; macro_label; macro_label = macro_label->next) { temp = strstr(line,macro_label->label); if (temp) { return macro_label; } } return NULL; } /* end of macro.c */
pearsonalan/avra
src/macro.c
C
gpl-2.0
15,499
{% extends "base.html" %} {% load staticfiles %} {% block head_title %}{% block listing_head_title %}{% endblock %}{% endblock %} {% block content %} <div id="account" class="ui centered two column grid stackable container" style="margin-top: 20px;"> <div class="four wide column"> <div class="ui large one item menu"> <a href="{% url 'accounts:listings' %}" class="ui item"> <i class="ui arrow left icon"></i> Back to Dashboard </a> </div> <div class="ui large vertical fluid menu"> <div class="header center aligned item"> <div class="ui center aligned small header"> Listing Steps </div> </div> <a href="{% url 'listings:edit_listing_description' listing_id=listing.id %}" class=" {% if request.resolver_match.url_name == "edit_listing_description" %}active{% endif %} item"> Description {% if listing.description_complete %} <i class="ui green checkmark icon"></i> {% else %} <i class="ui grey plus icon"></i> {% endif %} </a> <a href="{% url 'listings:edit_listing_location' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "edit_listing_location" %}active{% endif %} item"> Location {% if listing.location_complete %} <i class="ui green checkmark icon"></i> {% else %} <i class="ui grey plus icon"></i> {% endif %} </a> <a href="{% url 'listings:edit_listing_details' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "edit_listing_details" %}active{% endif %} item"> Details {% if listing.details_complete %} <i class="ui green checkmark icon"></i> {% else %} <i class="ui grey plus icon"></i> {% endif %} </a> <a href="{% url 'listings:edit_listing_photos' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "edit_listing_photos" %}active{% endif %} item"> Photos {% if listing.photos_complete %} <i class="ui green checkmark icon"></i> {% else %} <i class="ui grey plus icon"></i> {% endif %} </a> <a href="{% url 'listings:edit_listing_calendar' listing_id=listing.id %}" class="{% if request.resolver_match.url_name == "edit_listing_calendar" %}active{% endif %} item"> Calendar {% if listing.calendar_complete %} <i class="ui green checkmark icon"></i> {% else %} <i class="ui grey plus icon"></i> {% endif %} </a> </div> <div class="ui card"> <div class="content"> {% if listing.listing_complete %} <div class="ui center aligned header"> Ready to publish! </div> <div class="description"> You are ready to publish your listing. Don't worry you can come back and edit it later. </div> {% elif listing.published %} <div class="ui center aligned header"> Currently published </div> <div class="description"> This listing is currently published and publicly accessible. You can temporarily unpublish the listing. </div> {% else %} <div class="ui center aligned header"> Steps remaining: {{ listing.steps_remaining }} </div> <div class="description"> To publish your listing complete the steps above. You can always come back and finish it later. </div> {% endif %} </div> <div class="extra content"> {% if listing.published %} <a href="{% url "listings:unpublish_listing" listing_id=listing.id %}" class="ui orange button">Unpublish</a> {% elif listing.listing_complete %} <a href="{% url "listings:publish_listing" listing_id=listing.id %}" class="ui green button">Publish</a> {% else %} <div class="ui disabled button">Publish</div> {% endif %} <a href="{% url "listings:delete_listing" listing_id=listing.id %}" id="delete-listing" class="ui red delete button">Delete</a> </div> </div> </div> <div class="nine wide column"> {% block listing_content %} {% endblock %} </div> </div> <div id="confirm_delete" class="ui small modal"> <div class="header"> Delete listing </div> <div class="content"> <p>Are you sure you want to delete this listing? You will not be able to retrieve it if deleted.</p> </div> <div class="actions"> <div class="ui cancel button"> Cancel </div> <div class="ui negative approve right labeled icon button"> Yes <i class="remove icon"></i> </div> </div> </div> {% endblock %} {% block scripts %} {% block listing_scripts %} {% endblock %} <script type="text/javascript"> $('#delete-listing').click(function(){ event.preventDefault(); var deleteLink = $(this).attr("href"); var row = $(this).parents('.ui.row'); var divider = row.prev('.divider'); $('#confirm_delete').modal({ onApprove : function() { $.get(deleteLink); divider.hide("medium", function() { $(this).remove(); }); row.hide("medium", function() { $(this).remove(); }); } }) .modal('show'); }); </script> {% endblock %}
NilsJPWerner/Sublet-Uchicago
templates/listing/listing_base.html
HTML
gpl-2.0
5,380
/* * linux/init/main.c * * Copyright (C) 1991, 1992 Linus Torvalds * * GK 2/5/95 - Changed to support mounting root fs via NFS * Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96 * Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96 * Simplified starting of init: Michael A. Griffith <[email protected]> */ #define DEBUG #include <linux/types.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/kernel.h> #include <linux/syscalls.h> #include <linux/stackprotector.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/bootmem.h> #include <linux/acpi.h> #include <linux/tty.h> #include <linux/percpu.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/kernel_stat.h> #include <linux/start_kernel.h> #include <linux/security.h> #include <linux/smp.h> #include <linux/profile.h> #include <linux/rcupdate.h> #include <linux/moduleparam.h> #include <linux/kallsyms.h> #include <linux/writeback.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/cgroup.h> #include <linux/efi.h> #include <linux/tick.h> #include <linux/interrupt.h> #include <linux/taskstats_kern.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/rmap.h> #include <linux/mempolicy.h> #include <linux/key.h> #include <linux/buffer_head.h> #include <linux/page_cgroup.h> #include <linux/debug_locks.h> #include <linux/debugobjects.h> #include <linux/lockdep.h> #include <linux/kmemleak.h> #include <linux/pid_namespace.h> #include <linux/device.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/signal.h> #include <linux/idr.h> #include <linux/kgdb.h> #include <linux/ftrace.h> #include <linux/async.h> #include <linux/kmemcheck.h> #include <linux/sfi.h> #include <linux/shmem_fs.h> #include <linux/slab.h> #include <linux/perf_event.h> #include <linux/file.h> #include <linux/ptrace.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <linux/sched_clock.h> #include <linux/random.h> #include <asm/io.h> #include <asm/bugs.h> #include <asm/setup.h> #include <asm/sections.h> #include <asm/cacheflush.h> #ifdef CONFIG_X86_LOCAL_APIC #include <asm/smp.h> #endif #ifdef CONFIG_HTC_EARLY_RTB #include <linux/msm_rtb.h> #endif static int kernel_init(void *); extern void init_IRQ(void); extern void fork_init(unsigned long); extern void mca_init(void); extern void sbus_init(void); extern void radix_tree_init(void); #ifndef CONFIG_DEBUG_RODATA static inline void mark_rodata_ro(void) { } #endif #ifdef CONFIG_TC extern void tc_init(void); #endif bool early_boot_irqs_disabled __read_mostly; enum system_states system_state __read_mostly; EXPORT_SYMBOL(system_state); #define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT #define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT extern void time_init(void); void (*__initdata late_time_init)(void); extern void softirq_init(void); char __initdata boot_command_line[COMMAND_LINE_SIZE]; char *saved_command_line; char *hashed_command_line; static char *static_command_line; static char *execute_command; static char *ramdisk_execute_command; unsigned int reset_devices; EXPORT_SYMBOL(reset_devices); static int __init set_reset_devices(char *str) { reset_devices = 1; return 1; } __setup("reset_devices", set_reset_devices); static const char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, }; const char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, }; static const char *panic_later, *panic_param; extern const struct obs_kernel_param __setup_start[], __setup_end[]; static int __init obsolete_checksetup(char *line) { const struct obs_kernel_param *p; int had_early_param = 0; p = __setup_start; do { int n = strlen(p->str); if (parameqn(line, p->str, n)) { if (p->early) { if (line[n] == '\0' || line[n] == '=') had_early_param = 1; } else if (!p->setup_func) { pr_warn("Parameter %s is obsolete, ignored\n", p->str); return 1; } else if (p->setup_func(line + n)) return 1; } p++; } while (p < __setup_end); return had_early_param; } unsigned long loops_per_jiffy = (1<<12); EXPORT_SYMBOL(loops_per_jiffy); static int __init debug_kernel(char *str) { console_loglevel = 10; return 0; } static int __init quiet_kernel(char *str) { console_loglevel = 4; return 0; } early_param("debug", debug_kernel); early_param("quiet", quiet_kernel); static int __init loglevel(char *str) { int newlevel; if (get_option(&str, &newlevel)) { console_loglevel = newlevel; return 0; } return -EINVAL; } early_param("loglevel", loglevel); static int __init repair_env_string(char *param, char *val, const char *unused) { if (val) { if (val == param+strlen(param)+1) val[-1] = '='; else if (val == param+strlen(param)+2) { val[-2] = '='; memmove(val-1, val, strlen(val)+1); val--; } else BUG(); } return 0; } static int __init unknown_bootoption(char *param, char *val, const char *unused) { repair_env_string(param, val, unused); if (obsolete_checksetup(param)) return 0; if (strchr(param, '.') && (!val || strchr(param, '.') < val)) return 0; if (panic_later) return 0; if (val) { unsigned int i; for (i = 0; envp_init[i]; i++) { if (i == MAX_INIT_ENVS) { panic_later = "Too many boot env vars at `%s'"; panic_param = param; } if (!strncmp(param, envp_init[i], val - param)) break; } envp_init[i] = param; } else { unsigned int i; for (i = 0; argv_init[i]; i++) { if (i == MAX_INIT_ARGS) { panic_later = "Too many boot init vars at `%s'"; panic_param = param; } } argv_init[i] = param; } return 0; } static int __init init_setup(char *str) { unsigned int i; execute_command = str; for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("init=", init_setup); static int __init rdinit_setup(char *str) { unsigned int i; ramdisk_execute_command = str; for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("rdinit=", rdinit_setup); #ifndef CONFIG_SMP static const unsigned int setup_max_cpus = NR_CPUS; #ifdef CONFIG_X86_LOCAL_APIC static void __init smp_init(void) { APIC_init_uniprocessor(); } #else #define smp_init() do { } while (0) #endif static inline void setup_nr_cpu_ids(void) { } static inline void smp_prepare_cpus(unsigned int maxcpus) { } #endif static void __init setup_command_line(char *command_line) { saved_command_line = alloc_bootmem(strlen (boot_command_line)+1); static_command_line = alloc_bootmem(strlen (command_line)+1); strcpy (saved_command_line, boot_command_line); strcpy (static_command_line, command_line); } #define RAW_SN_LEN 4 static void __init hash_sn(void) { char *p; unsigned int td_sf = 0; size_t cmdline_len, sf_len; cmdline_len = strlen(saved_command_line); sf_len = strlen("td.sf="); hashed_command_line = alloc_bootmem(cmdline_len + 1); strncpy(hashed_command_line, saved_command_line, cmdline_len); hashed_command_line[cmdline_len] = '\0'; p = saved_command_line; for (p = saved_command_line; p < saved_command_line + cmdline_len - sf_len; p++) { if (!strncmp(p, "td.sf=", sf_len)) { p += sf_len; if (*p != '0') td_sf = 1; break; } } if (td_sf) { unsigned int i; size_t sn_len = 0; for (p = hashed_command_line; p < hashed_command_line + cmdline_len - strlen("androidboot.serialno="); p++) { if (!strncmp(p, "androidboot.serialno=", strlen("androidboot.serialno="))) { p += strlen("androidboot.serialno="); while (*p != ' ' && *p != '\0') { sn_len++; p++; } p -= sn_len; for (i = sn_len - 1; i >= RAW_SN_LEN; i--) *p++ = '*'; break; } } } } static __initdata DECLARE_COMPLETION(kthreadd_done); static noinline void __init_refok rest_init(void) { int pid; const struct sched_param param = { .sched_priority = 1 }; rcu_scheduler_starting(); kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); numa_default_policy(); pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES); rcu_read_lock(); kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns); rcu_read_unlock(); sched_setscheduler_nocheck(kthreadd_task, SCHED_FIFO, &param); complete(&kthreadd_done); init_idle_bootup_task(current); schedule_preempt_disabled(); cpu_startup_entry(CPUHP_ONLINE); } static int __init do_early_param(char *param, char *val, const char *unused) { const struct obs_kernel_param *p; for (p = __setup_start; p < __setup_end; p++) { if ((p->early && parameq(param, p->str)) || (strcmp(param, "console") == 0 && strcmp(p->str, "earlycon") == 0) ) { if (p->setup_func(val) != 0) pr_warn("Malformed early option '%s'\n", param); } } return 0; } void __init parse_early_options(char *cmdline) { parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param); } void __init parse_early_param(void) { #if defined(CONFIG_EARLY_PRINTK) void deferred_early_console_init(void); #endif static __initdata int done = 0; static __initdata char tmp_cmdline[COMMAND_LINE_SIZE]; if (done) return; strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE); parse_early_options(tmp_cmdline); done = 1; #if defined(CONFIG_EARLY_PRINTK) deferred_early_console_init(); #endif } static void __init boot_cpu_init(void) { int cpu = smp_processor_id(); set_cpu_online(cpu, true); set_cpu_active(cpu, true); set_cpu_present(cpu, true); set_cpu_possible(cpu, true); } void __init __weak smp_setup_processor_id(void) { } # if THREAD_SIZE >= PAGE_SIZE void __init __weak thread_info_cache_init(void) { } #endif static void __init mm_init(void) { page_cgroup_init_flatmem(); mem_init(); kmem_cache_init(); percpu_init_late(); pgtable_cache_init(); vmalloc_init(); } asmlinkage void __init start_kernel(void) { char * command_line; extern const struct kernel_param __start___param[], __stop___param[]; lockdep_init(); smp_setup_processor_id(); debug_objects_early_init(); cgroup_init_early(); local_irq_disable(); early_boot_irqs_disabled = true; boot_cpu_init(); page_address_init(); pr_notice("%s", linux_banner); setup_arch(&command_line); boot_init_stack_canary(); mm_init_owner(&init_mm, &init_task); mm_init_cpumask(&init_mm); setup_command_line(command_line); hash_sn(); setup_nr_cpu_ids(); setup_per_cpu_areas(); smp_prepare_boot_cpu(); build_all_zonelists(NULL, NULL); page_alloc_init(); pr_notice("Kernel command line: %s\n", hashed_command_line); parse_early_param(); parse_args("Booting kernel", static_command_line, __start___param, __stop___param - __start___param, -1, -1, &unknown_bootoption); jump_label_init(); setup_log_buf(0); pidhash_init(); vfs_caches_init_early(); sort_main_extable(); trap_init(); mm_init(); sched_init(); preempt_disable(); if (WARN(!irqs_disabled(), "Interrupts were enabled *very* early, fixing it\n")) local_irq_disable(); idr_init_cache(); perf_event_init(); rcu_init(); tick_nohz_init(); radix_tree_init(); early_irq_init(); init_IRQ(); tick_init(); init_timers(); hrtimers_init(); softirq_init(); timekeeping_init(); time_init(); sched_clock_postinit(); profile_init(); call_function_init(); WARN(!irqs_disabled(), "Interrupts were enabled early\n"); early_boot_irqs_disabled = false; local_irq_enable(); kmem_cache_init_late(); console_init(); if (panic_later) panic(panic_later, panic_param); lockdep_info(); locking_selftest(); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok && page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) { pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n", page_to_pfn(virt_to_page((void *)initrd_start)), min_low_pfn); initrd_start = 0; } #endif page_cgroup_init(); debug_objects_mem_init(); kmemleak_init(); setup_per_cpu_pageset(); numa_policy_init(); if (late_time_init) late_time_init(); sched_clock_init(); calibrate_delay(); pidmap_init(); anon_vma_init(); #ifdef CONFIG_X86 if (efi_enabled(EFI_RUNTIME_SERVICES)) efi_enter_virtual_mode(); #endif #ifdef CONFIG_X86_ESPFIX64 init_espfix_bsp(); #endif thread_info_cache_init(); cred_init(); fork_init(totalram_pages); proc_caches_init(); buffer_init(); key_init(); security_init(); dbg_late_init(); vfs_caches_init(totalram_pages); signals_init(); page_writeback_init(); #ifdef CONFIG_PROC_FS proc_root_init(); #endif cgroup_init(); cpuset_init(); taskstats_init_early(); delayacct_init(); check_bugs(); acpi_early_init(); sfi_init_late(); if (efi_enabled(EFI_RUNTIME_SERVICES)) { efi_late_init(); efi_free_boot_services(); } ftrace_init(); rest_init(); } static void __init do_ctors(void) { #ifdef CONFIG_CONSTRUCTORS ctor_fn_t *fn = (ctor_fn_t *) __ctors_start; for (; fn < (ctor_fn_t *) __ctors_end; fn++) (*fn)(); #endif } bool initcall_debug; core_param(initcall_debug, initcall_debug, bool, 0644); static char msgbuf[64]; static int __init_or_module do_one_initcall_debug(initcall_t fn) { ktime_t calltime, delta, rettime; unsigned long long duration; int ret; pr_debug("calling %pF @ %i\n", fn, task_pid_nr(current)); calltime = ktime_get(); ret = fn(); rettime = ktime_get(); delta = ktime_sub(rettime, calltime); duration = (unsigned long long) ktime_to_ns(delta) >> 10; pr_debug("initcall %pF returned %d after %lld usecs\n", fn, ret, duration); return ret; } int __init_or_module do_one_initcall(initcall_t fn) { int count = preempt_count(); int ret; #ifdef CONFIG_HTC_EARLY_RTB uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0x00000000)); #endif if (initcall_debug) ret = do_one_initcall_debug(fn); else ret = fn(); #ifdef CONFIG_HTC_EARLY_RTB uncached_logk_pc(LOGK_INITCALL, (void *)fn, (void *)(0xffffffff)); #endif msgbuf[0] = 0; if (preempt_count() != count) { sprintf(msgbuf, "preemption imbalance "); preempt_count() = count; } if (irqs_disabled()) { strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf)); local_irq_enable(); } WARN(msgbuf[0], "initcall %pF returned with %s\n", fn, msgbuf); return ret; } extern initcall_t __initcall_start[]; extern initcall_t __initcall0_start[]; extern initcall_t __initcall1_start[]; extern initcall_t __initcall2_start[]; extern initcall_t __initcall3_start[]; extern initcall_t __initcall4_start[]; extern initcall_t __initcall5_start[]; extern initcall_t __initcall6_start[]; extern initcall_t __initcall7_start[]; extern initcall_t __initcall_end[]; static initcall_t *initcall_levels[] __initdata = { __initcall0_start, __initcall1_start, __initcall2_start, __initcall3_start, __initcall4_start, __initcall5_start, __initcall6_start, __initcall7_start, __initcall_end, }; static char *initcall_level_names[] __initdata = { "early", "core", "postcore", "arch", "subsys", "fs", "device", "late", }; static void __init do_initcall_level(int level) { extern const struct kernel_param __start___param[], __stop___param[]; initcall_t *fn; strcpy(static_command_line, saved_command_line); parse_args(initcall_level_names[level], static_command_line, __start___param, __stop___param - __start___param, level, level, &repair_env_string); for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++) do_one_initcall(*fn); } static void __init do_initcalls(void) { int level; for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++) do_initcall_level(level); } static void __init do_basic_setup(void) { cpuset_init_smp(); usermodehelper_init(); shmem_init(); driver_init(); init_irq_proc(); do_ctors(); usermodehelper_enable(); do_initcalls(); random_int_secret_init(); } static void __init do_pre_smp_initcalls(void) { initcall_t *fn; for (fn = __initcall_start; fn < __initcall0_start; fn++) do_one_initcall(*fn); } void __init load_default_modules(void) { load_default_elevator_module(); } static int run_init_process(const char *init_filename) { argv_init[0] = init_filename; return do_execve(init_filename, (const char __user *const __user *)argv_init, (const char __user *const __user *)envp_init); } static noinline void __init kernel_init_freeable(void); static int __ref kernel_init(void *unused) { kernel_init_freeable(); async_synchronize_full(); free_initmem(); mark_rodata_ro(); system_state = SYSTEM_RUNNING; numa_default_policy(); flush_delayed_fput(); if (ramdisk_execute_command) { if (!run_init_process(ramdisk_execute_command)) return 0; pr_err("Failed to execute %s\n", ramdisk_execute_command); } if (execute_command) { if (!run_init_process(execute_command)) return 0; pr_err("Failed to execute %s. Attempting defaults...\n", execute_command); } if (!run_init_process("/sbin/init") || !run_init_process("/etc/init") || !run_init_process("/bin/init") || !run_init_process("/bin/sh")) return 0; panic("No init found. Try passing init= option to kernel. " "See Linux Documentation/init.txt for guidance."); } static noinline void __init kernel_init_freeable(void) { wait_for_completion(&kthreadd_done); gfp_allowed_mask = __GFP_BITS_MASK; set_mems_allowed(node_states[N_MEMORY]); set_cpus_allowed_ptr(current, cpu_all_mask); cad_pid = task_pid(current); smp_prepare_cpus(setup_max_cpus); do_pre_smp_initcalls(); lockup_detector_init(); smp_init(); #ifdef CONFIG_HTC_EARLY_RTB htc_early_rtb_init(); #endif sched_init_smp(); do_basic_setup(); if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0) pr_err("Warning: unable to open an initial console.\n"); (void) sys_dup(0); (void) sys_dup(0); if (!ramdisk_execute_command) ramdisk_execute_command = "/init"; if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) { ramdisk_execute_command = NULL; prepare_namespace(); } load_default_modules(); }
flar2/ElementalX-m9
init/main.c
C
gpl-2.0
18,082
/*********************************************************************** * d:/Werk/src/csmash-0.3.8.new/conv/parts.h * $Id: parts.h,v 1.16 2003/07/28 17:03:10 nan Exp $ * * Copyright by ESESoft. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***********************************************************************/ #ifndef __wata_ESESoft_9465__parts_h__INCLUDED__ #define __wata_ESESoft_9465__parts_h__INCLUDED__ /***********************************************************************/ #include <algorithm> #include <vector> #include "float" #include "matrix" #include "affine" /* __BEGIN__BEGIN__ */ vector4F Affine2Quaternion(affine4F aff); affine4F Quaternion2Affine(vector4F v, vector4F p); class edge { public: short v0, v1; short p0, p1; }; class color4b { public: typedef unsigned char element_t; typedef unsigned char byte; enum { element_size = 4, }; byte r, g, b, a; inline color4b() {} inline color4b(byte i, byte a=255) : r(i), g(i), b(i), a(a) {} inline color4b(byte r, byte g, byte b, byte a=255) : r(r), g(g), b(b), a(a) {} byte* element_array() { return (byte*)this; } const byte* element_array() const { return (byte*)this; } void glBind() const { glColor4ubv((const GLubyte*)element_array()); } }; class color4f { public: typedef unsigned char element_t; enum { element_size = 4, }; float r, g, b, a; inline color4f() {} inline color4f(int i, int a=255) : r(i/255.0F), g(i/255.0F), b(i/255.0F), a(a/255.0F) {} inline color4f(int r, int g, int b, int a=255) : r(r/255.0F), g(g/255.0F), b(b/255.0F), a(a/255.0F) {} float* element_array() { return (float*)this; } const float* element_array() const { return (float*)this; } void glBind() const { glColor4fv(element_array()); } }; class colormap { public: typedef color4f color_t; enum { map_size = 256, }; bool load(const char *file); void fill(const color_t& c) { std::fill(&map[0], &map[map_size], c); } inline color_t& operator [](int i) { return map[i]; } inline const color_t& operator [](int i) const { return map[i]; } public: color_t map[map_size]; }; class polygon; class polyhedron { public: int numPoints, numPolygons, numEdges; vector3F *points; vector3F *texcoord; short (*polygons)[4]; unsigned char *cindex; vector3F (*normals)[4]; vector3F *planeNormal; edge *edges; char *filename; GLuint texturename; colormap cmap; polyhedron(const char *filename); ~polyhedron(); polyhedron& operator *=(const affine4F &m); //normal vectors are destroyed inline int polsize(int i) const { return (0 > polygons[i][3]) ? 3 : 4; } polygon getPolygon(int i) const; void getNormal(); protected: void initColormap(); }; /// polygon access object class polygon { friend class polyhedron; protected: inline polygon(const polyhedron& parent, int polynum) : p(parent), num(polynum) { size = (p.polygons[num][3] < 0) ? 3 : 4; } public: inline int round(int idx) const { return (idx+size)%size; } inline int pround(int idx) const { return idx%size; } inline short ri(int idx) const { return p.polygons[num][idx]; } inline short i(int idx) const { return p.polygons[num][round(idx)]; } inline const vector3F& rv(int idx) const { return p.points[ri(idx)]; } inline const vector3F& v(int idx) const { return p.points[i(idx)]; } inline const vector3F& rst(int idx) const { return p.texcoord[ri(idx)]; } inline const vector3F& st(int idx) const { return p.texcoord[i(idx)]; } inline const vector3F& rn(int idx) const { return p.normals[num][idx]; } inline const vector3F& n(int idx) const { return p.normals[num][round(idx)]; } inline const vector3F& n(void) const { return p.planeNormal[num]; } inline const unsigned char c() const { return p.cindex[num]; } inline short getv(short vidx) const { for (int k = 0; size > k; ++k) if (vidx == ri(k)) return k; return -1; } inline short gete(const edge&e, int* way) const { return gete(e.v0, e.v1, way); } inline short gete(short v0, short v1, int* way) const { for (int k = 0; size > k; ++k) { if (v0 == ri(k)) { if (v1 == ri(pround(k+1))) { *way = +1; return k; } else if (v1 == i(k-1)) { *way = -1; return k; } } } return -1; } inline GLenum glBeginSize() const { return (3 == size) ? GL_TRIANGLES : GL_QUADS; } public: const polyhedron& p; int num; int size; }; inline polygon polyhedron::getPolygon(int i) const { return polygon(*this, i); } class affineanim { public: int numFrames; affine4F *matrices; affineanim(int num); affineanim(const char *filename); ~affineanim(); inline const affine4F& operator[](int i) const { return matrices[i]; } inline affine4F& operator [](int i) { return matrices[i]; } }; class affinemotion { public: polyhedron ref; affineanim anim; affinemotion(const char *ref, const char *anim); void write(const char *basename); inline bool valid() const { return ref.numPoints > 0 && anim.numFrames > 0; } }; class quaternionanim { public: int numFrames; std::vector<vector4F> quaternions; vector3F origin; quaternionanim(int num); quaternionanim(const char *filename); ~quaternionanim(); inline const vector4F& operator[](int i) const { return quaternions[i]; } inline const vector4F operator[](float i) const { if ( i == (int)i ) { return quaternions[(int)i]; } else { vector4F q1 = quaternions[(int)i]; vector4F q2 = quaternions[(int)i+1]; if ( q1[1]*q2[1]+q1[2]*q2[2]+q1[3]*q2[3] < 0 ) q2 = -q2; return q1*(1-(i-(int)i)) + q2*(i-(int)i); } } inline vector4F& operator [](int i) { return quaternions[i]; } inline vector4F operator[](float i) { if ( i == (int)i ) { return quaternions[(int)i]; } else { vector4F q1 = quaternions[(int)i]; vector4F q2 = quaternions[(int)i+1]; if ( q1[1]*q2[1]+q1[2]*q2[2]+q1[3]*q2[3] < 0 ) q2 = -q2; return q1*(1-(i-(int)i)) + q2*(i-(int)i); } } }; class quaternionmotion { public: polyhedron ref; quaternionanim anim; quaternionmotion(const char *ref, const char *anim); //void write(const char *basename); inline bool valid() const { return ref.numPoints > 0 && anim.numFrames > 0; } }; class partsmotion { public: int numParts; static polyhedron **polyparts; affineanim *origin; quaternionanim **qanim; partsmotion(const char *basename); virtual ~partsmotion(); virtual bool render(int frame, float xdiff, float ydiff, float zdiff); virtual bool render(double frame, float xdiff, float ydiff, float zdiff); virtual bool renderWire(int frame, float xdiff, float ydiff, float zdiff); virtual bool renderWire(double frame, float xdiff, float ydiff, float zdiff); virtual bool renderArmOnly(double frame, float xdiff, float ydiff, float zdiff); private: void drawleg( float xdiff, float ydiff, float zdiff, bool isWireFrame ); void legIK( vector3F hip, vector3F &knee, vector3F &heel, vector3F toe, float thighLength, float shinLength, float footSize, bool isWireFrame ); void drawbody( vector3F neck, vector3F waist, bool isWireFrame ); void renderparts( int partsNum, bool isWireFrame ); }; /* __END__END__ */ /***********************************************************************/ #endif /*********************************************************************** * END OF parts.h ***********************************************************************/
ironsteel/cannon-smash
parts.h
C
gpl-2.0
9,100
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252"> <TITLE></TITLE> <META NAME="GENERATOR" CONTENT="OpenOffice 4.0.0 (Win32)"> <META NAME="AUTHOR" CONTENT="Jouni Santara"> <META NAME="CREATED" CONTENT="20140315;10351377"> <META NAME="CHANGEDBY" CONTENT="Jouni Santara"> <META NAME="CHANGED" CONTENT="20140321;11410882"> <STYLE> <!-- BODY,DIV,TABLE,THEAD,TBODY,TFOOT,TR,TH,TD,P { font-family:"Arial"; font-size:x-small } --> </STYLE> </HEAD> <BODY TEXT="#000000"> <TABLE FRAME=VOID CELLSPACING=0 COLS=13 RULES=NONE BORDER=0> <COLGROUP><COL WIDTH=125><COL WIDTH=82><COL WIDTH=121><COL WIDTH=100><COL WIDTH=86><COL WIDTH=129><COL WIDTH=51><COL WIDTH=52><COL WIDTH=55><COL WIDTH=104><COL WIDTH=67><COL WIDTH=80><COL WIDTH=86></COLGROUP> <TBODY> <TR> <TD WIDTH=125 HEIGHT=24 ALIGN=LEFT><BR></TD> <TD WIDTH=82 ALIGN=CENTER><BR></TD> <TD WIDTH=121 ALIGN=CENTER><BR></TD> <TD WIDTH=100 ALIGN=LEFT><U><FONT SIZE=4>Charts and their options</FONT></U></TD> <TD WIDTH=86 ALIGN=CENTER><BR></TD> <TD WIDTH=129 ALIGN=CENTER><BR></TD> <TD WIDTH=51 ALIGN=CENTER><BR></TD> <TD WIDTH=52 ALIGN=CENTER><BR></TD> <TD WIDTH=55 ALIGN=CENTER><BR></TD> <TD WIDTH=104 ALIGN=LEFT><BR></TD> <TD WIDTH=67 ALIGN=LEFT><BR></TD> <TD WIDTH=80 ALIGN=LEFT><BR></TD> <TD WIDTH=86 ALIGN=LEFT><BR></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> </TR> <TR> <TD HEIGHT=24 ALIGN=LEFT><B><FONT SIZE=4><BR></FONT></B></TD> <TD ALIGN=LEFT>The following options (at least) are available from the different chart's types.</TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=CENTER><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> <TD ALIGN=LEFT><BR></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><BR></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000" ALIGN=LEFT><B><FONT COLOR="#808080">Chart Type</FONT></B></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=CENTER><FONT COLOR="#808080"><BR></FONT></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD> <TD STYLE="border-top: 1px solid #000000" ALIGN=LEFT><BR></TD> <TD STYLE="border-top: 1px solid #000000; border-right: 1px solid #000000" ALIGN=LEFT><BR></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><B><FONT COLOR="#808080">Option</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">linePlusBar</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">cumulativeLineData</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">stackedArea</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">discreteBar</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">horizontalMultiBar</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Pie</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Donut</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1 COLOR="#000000">Bullet</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>ScatterBubble</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>MultiBar</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>viewFinder</FONT></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><FONT SIZE=1>simpleLine</FONT></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">clipEdge</FONT></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-top: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">color</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">donut</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">donutRatio</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">groupSpacing</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">labelThreshold</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">labelType</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">reduceXTicks</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">rightAlignYAxis</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">rotateLabels</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showControls</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showDistX</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showDistY</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showLabels</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showLegend</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showValues</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showXAxis</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">showYAxis</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><BR></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">staggerLabels</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">tooltips</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">transitionDuration</FONT></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> </TR> <TR> <TD HEIGHT=17 ALIGN=LEFT><FONT SIZE=1 COLOR="#999999">useInteractiveGuideline</FONT></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B><BR></B></TD> <TD STYLE="border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" ALIGN=CENTER><B>X</B></TD> </TR> </TBODY> </TABLE> <!-- ************************************************************************** --> </BODY> </HTML>
wp-plugins/nvd3-visualisations
docs/chart_options.html
HTML
gpl-2.0
37,147
<?php global $post, $sc_post_class; $post_id = $post->ID; $post_obj = new sc_post($post_id); $post_comments = get_comments_number( $post_id ); ?> <!--item--> <div class="entry <?php echo esc_attr( $sc_post_class ); ?> post-item"> <?php $main_image = $post_obj->get_main_image('thumb-image'); if (!empty( $main_image ) ) { ?> <figure> <img src="<?php echo esc_url ( $main_image ); ?>" alt="<?php the_title(); ?>" /> <figcaption><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><i class="ico eldorado_eyelash"></i> <span><?php _e('View post', 'socialchef'); ?></span></a></figcaption> </figure> <?php } ?> <div class="container"> <h2><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><?php the_title(); ?></a></h2> <div class="actions"> <div> <div class="date"><i class="ico eldorado_calendar_1"></i><?php the_time('F j, Y'); ?></div> <div class="comments"><i class="ico eldorado_comment_baloon"></i><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>#comments"><?php echo $post_comments; ?></a></div> </div> </div> <div class="excerpt"> <?php the_excerpt(); ?> </div> </div> </div> <!--item-->
foodiedaily/tts
wp-content/themes/SocialChef/includes/parts/post-item.php
PHP
gpl-2.0
1,175
/* Festalon - NSF Player * Copyright (C) 2004 Xodnizel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <string.h> #include <stdlib.h> #include "../types.h" #include "x6502.h" #include "cart.h" #include "memory.h" /* 16 are (sort of) reserved for UNIF/iNES and 16 to map other stuff. */ static INLINE void setpageptr(NESCART *ca, int s, uint32 A, uint8 *p, int ram) { uint32 AB=A>>11; int x; if(p) for(x=(s>>1)-1;x>=0;x--) { ca->PRGIsRAM[AB+x]=ram; ca->Page[AB+x]=p-A; } else for(x=(s>>1)-1;x>=0;x--) { ca->PRGIsRAM[AB+x]=0; ca->Page[AB+x]=0; } } static uint8 nothing[8192]; void FESTAC_Kill(NESCART *ca) { free(ca); } NESCART *FESTAC_Init(void) { int x; NESCART *ca; if(!(ca=malloc(sizeof(NESCART)))) return(0); memset(ca,0,sizeof(NESCART)); for(x=0;x<32;x++) { ca->Page[x]=nothing-x*2048; ca->PRGptr[x]=0; ca->PRGsize[x]=0; } return(ca); } void FESTAC_SetupPRG(NESCART *ca, int chip, uint8 *p, uint32 size, int ram) { ca->PRGptr[chip]=p; ca->PRGsize[chip]=size; ca->PRGmask2[chip]=(size>>11)-1; ca->PRGmask4[chip]=(size>>12)-1; ca->PRGmask8[chip]=(size>>13)-1; ca->PRGmask16[chip]=(size>>14)-1; ca->PRGmask32[chip]=(size>>15)-1; ca->PRGram[chip]=ram?1:0; } DECLFR(CartBR) { NESCART *ca=private; return ca->Page[A>>11][A]; } DECLFW(CartBW) { NESCART *ca=private; if(ca->PRGIsRAM[A>>11] && ca->Page[A>>11]) ca->Page[A>>11][A]=V; } DECLFR(CartBROB) { NESCART *ca=private; if(!ca->Page[A>>11]) return(DB); return ca->Page[A>>11][A]; } void FASTAPASS(3) setprg2r(NESCART *ca, int r, unsigned int A, unsigned int V) { V&=ca->PRGmask2[r]; setpageptr(ca,2,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<11]):0,ca->PRGram[r]); } void FASTAPASS(2) setprg2(NESCART *ca, uint32 A, uint32 V) { setprg2r(ca,0,A,V); } void FASTAPASS(3) setprg4r(NESCART *ca, int r, unsigned int A, unsigned int V) { V&=ca->PRGmask4[r]; setpageptr(ca,4,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<12]):0,ca->PRGram[r]); } void FASTAPASS(2) setprg4(NESCART *ca, uint32 A, uint32 V) { setprg4r(ca,0,A,V); } void FASTAPASS(3) setprg8r(NESCART *ca, int r, unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=8192) { V&=ca->PRGmask8[r]; setpageptr(ca,8,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<13]):0,ca->PRGram[r]); } else { uint32 VA=V<<2; int x; for(x=0;x<4;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg8(NESCART *ca, uint32 A, uint32 V) { setprg8r(ca,0,A,V); } void FASTAPASS(3) setprg16r(NESCART *ca, int r, unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=16384) { V&=ca->PRGmask16[r]; setpageptr(ca,16,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<14]):0,ca->PRGram[r]); } else { uint32 VA=V<<3; int x; for(x=0;x<8;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg16(NESCART *ca, uint32 A, uint32 V) { setprg16r(ca,0,A,V); } void FASTAPASS(3) setprg32r(NESCART *ca, int r,unsigned int A, unsigned int V) { if(ca->PRGsize[r]>=32768) { V&=ca->PRGmask32[r]; setpageptr(ca,32,A,ca->PRGptr[r]?(&ca->PRGptr[r][V<<15]):0,ca->PRGram[r]); } else { uint32 VA=V<<4; int x; for(x=0;x<16;x++) setpageptr(ca,2,A+(x<<11),ca->PRGptr[r]?(&ca->PRGptr[r][((VA+x)&ca->PRGmask2[r])<<11]):0,ca->PRGram[r]); } } void FASTAPASS(2) setprg32(NESCART *ca, uint32 A, uint32 V) { setprg32r(ca,0,A,V); }
ahefner/festalon
src/nes/cart.c
C
gpl-2.0
4,179
<div class='result'> add task success<br /> {{task}}<br /> <a href='show'>check</a> </div>
sakishum/celery_djange_example
celerytest_010/src/demo/templates/success.html
HTML
gpl-2.0
91
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2020 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ include ('../inc/includes.php'); Session::checkRight("reports", READ); Html::header(Report::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "tools", "report"); Report::title(); // Titre echo "<form name='form' method='post' action='report.year.list.php'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4'>".__("Equipment's report by year")."</th></tr>"; // 3. Selection d'affichage pour generer la liste echo "<tr class='tab_bg_2'>"; echo "<td width='20%' class='b center'>".__('Item type')."</td>"; echo "<td width='30%'>"; $values = [0 => __('All')]; foreach ($CFG_GLPI["contract_types"] as $itemtype) { if ($item = getItemForItemtype($itemtype)) { $values[$itemtype] = $item->getTypeName(); } } Dropdown::showFromArray('item_type', $values, ['value' => 0, 'multiple' => true]); echo "</td>"; echo "<td width='20%' class='center'><p class='b'>"._n('Date', 'Dates', 1)."</p></td>"; echo "<td width='30%'>"; $y = date("Y"); $values = [ 0 => __('All')]; for ($i=($y-10); $i<($y+10); $i++) { $values[$i] = $i; } Dropdown::showFromArray('year', $values, ['value' => $y, 'multiple' => true]); echo "</td></tr>"; echo "<tr class='tab_bg_2'><td colspan='4' class='center'>"; echo "<input type='submit' value=\"".__s('Display report')."\" class='submit'></td></tr>"; echo "</table>"; Html::closeForm(); Html::footer();
edgardmessias/glpi
front/report.year.php
PHP
gpl-2.0
2,639
<div id="roomTitle">Welcome to Agavi :: home of the convention nazis :: 911GT2 coming soon :: http://www.agavi.org :: http://svn.agavi.org/branches/0.11/ if you want to use SVN (don't use trunk, earth will explode) :: Have a question? Just ask it, and wait patiently, because patience is the key to happiness :: We're looking for documentation contributors and developers :: http://trac.agavi.org/milestone/0.11 :: irc logs http://users.tkk.fi/~tjorri/agavi/logs</div> <div id="watermark" class="transparent50"></div> <div id="messages"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="name"><a href="info">RossC0</a></td> <td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td> <td class="time">00:16</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">kaos|work</a></td> <td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td> <td class="time">00:28</td> </tr> <tr> <td class="message">or something which gets called in a regular timeframe</td> <td class="time">00:29</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">impl</a></td> <td class="message">timers</td> <td class="time">00:29</td> </tr> <tr class="action"> <td class="message">got it</td> <td class="time">00:29</td> </tr> <tr class="self"> <td class="name"><a href="info">Wombert</a></td> <td class="message">is that so?</td> <td class="time">00:32</td> </tr> <tr class="highlight"> <td class="name"><a href="info">v-dogg</a></td> <td class="message">Wombert Zombert :)</td> <td class="time">00:33</td> </tr> <tr> <td class="name"><a href="info">RossC0</a></td> <td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td> <td class="time">00:16</td> </tr> <tr class="event"> <td class="name"><a href="info">kaos|work</a></td> <td class="message">has joined the channel</td> <td class="time">00:23</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">kaos|work</a></td> <td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td> <td class="time">00:28</td> </tr> <tr> <td class="message">or something which gets called in a regular timeframe</td> <td class="time">00:29</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">impl</a></td> <td class="message">timers</td> <td class="time">00:29</td> </tr> <tr> <td class="message">got it</td> <td class="time">00:29</td> </tr> <tr class="self"> <td class="name"><a href="info">Wombert</a></td> <td class="message">is that so?</td> <td class="time">00:32</td> </tr> <tr class="highlight"> <td class="name"><a href="info">v-dogg</a></td> <td class="message">Wombert Zombert :)</td> <td class="time">00:33</td> </tr> <tr> <td class="name"><a href="info">RossC0</a></td> <td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td> <td class="time">00:16</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">kaos|work</a></td> <td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td> <td class="time">00:28</td> </tr> <tr> <td class="message">or something which gets called in a regular timeframe</td> <td class="time">00:29</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">impl</a></td> <td class="message">timers</td> <td class="time">00:29</td> </tr> <tr> <td class="message">got it</td> <td class="time">00:29</td> </tr> <tr class="self"> <td class="name"><a href="info">Wombert</a></td> <td class="message">is that so?</td> <td class="time">00:32</td> </tr> <tr class="highlight"> <td class="name"><a href="info">v-dogg</a></td> <td class="message">Wombert Zombert :)</td> <td class="time">00:33</td> </tr> <tr> <td class="name"><a href="info">RossC0</a></td> <td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td> <td class="time">00:16</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">kaos|work</a></td> <td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td> <td class="time">00:28</td> </tr> <tr> <td class="message">or something which gets called in a regular timeframe</td> <td class="time">00:29</td> </tr> <tr> <td class="name" rowspan="2"><a href="info">impl</a></td> <td class="message">timers</td> <td class="time">00:29</td> </tr> <tr> <td class="message">got it</td> <td class="time">00:29</td> </tr> <tr class="self"> <td class="name"><a href="info">Wombert</a></td> <td class="message">is that so?</td> <td class="time">00:32</td> </tr> <tr class="highlight"> <td class="name"><a href="info">v-dogg</a></td> <td class="message">Wombert Zombert :)</td> <td class="time">00:33</td> </tr> </table> </div>
dzuelke/Chuckwalla
app/modules/Web/templates/IndexSuccess.php
PHP
gpl-2.0
7,471
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androidtweak.inputmethod.myanmar; import android.content.Context; import com.androidtweak.inputmethod.keyboard.ProximityInfo; public class SynchronouslyLoadedUserBinaryDictionary extends UserBinaryDictionary { public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale) { this(context, locale, false); } public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale, final boolean alsoUseMoreRestrictiveLocales) { super(context, locale, alsoUseMoreRestrictiveLocales); } @Override public synchronized void getWords(final WordComposer codes, final CharSequence prevWordForBigrams, final WordCallback callback, final ProximityInfo proximityInfo) { syncReloadDictionaryIfRequired(); getWordsInner(codes, prevWordForBigrams, callback, proximityInfo); } @Override public synchronized boolean isValidWord(CharSequence word) { syncReloadDictionaryIfRequired(); return isValidWordInner(word); } }
soeminnminn/MyanmarIME
src/com/androidtweak/inputmethod/myanmar/SynchronouslyLoadedUserBinaryDictionary.java
Java
gpl-2.0
1,712
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, * USA * * The full GNU General Public License is included in this distribution * in the file called COPYING. * * Contact Information: * Intel Linux Wireless <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <linux/etherdevice.h> #include <linux/ip.h> #include <linux/fs.h> #include <net/cfg80211.h> #include <net/ipv6.h> #include <net/tcp.h> #include <net/addrconf.h> #include "iwl-modparams.h" #include "fw-api.h" #include "mvm.h" void iwl_mvm_set_rekey_data(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_gtk_rekey_data *data) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (iwlwifi_mod_params.sw_crypto) return; mutex_lock(&mvm->mutex); memcpy(mvmvif->rekey_data.kek, data->kek, NL80211_KEK_LEN); memcpy(mvmvif->rekey_data.kck, data->kck, NL80211_KCK_LEN); mvmvif->rekey_data.replay_ctr = cpu_to_le64(be64_to_cpup((__be64 *)&data->replay_ctr)); mvmvif->rekey_data.valid = true; mutex_unlock(&mvm->mutex); } #if IS_ENABLED(CONFIG_IPV6) void iwl_mvm_ipv6_addr_change(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct inet6_dev *idev) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct inet6_ifaddr *ifa; int idx = 0; read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { mvmvif->target_ipv6_addrs[idx] = ifa->addr; idx++; if (idx >= IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_MAX) break; } read_unlock_bh(&idev->lock); mvmvif->num_target_ipv6_addrs = idx; } #endif void iwl_mvm_set_default_unicast_key(struct ieee80211_hw *hw, struct ieee80211_vif *vif, int idx) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); mvmvif->tx_key_idx = idx; } static void iwl_mvm_convert_p1k(u16 *p1k, __le16 *out) { int i; for (i = 0; i < IWL_P1K_SIZE; i++) out[i] = cpu_to_le16(p1k[i]); } struct wowlan_key_data { struct iwl_wowlan_rsc_tsc_params_cmd *rsc_tsc; struct iwl_wowlan_tkip_params_cmd *tkip; bool error, use_rsc_tsc, use_tkip; int wep_key_idx; }; static void iwl_mvm_wowlan_program_keys(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key, void *_data) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct wowlan_key_data *data = _data; struct aes_sc *aes_sc, *aes_tx_sc = NULL; struct tkip_sc *tkip_sc, *tkip_tx_sc = NULL; struct iwl_p1k_cache *rx_p1ks; u8 *rx_mic_key; struct ieee80211_key_seq seq; u32 cur_rx_iv32 = 0; u16 p1k[IWL_P1K_SIZE]; int ret, i; mutex_lock(&mvm->mutex); switch (key->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: { /* hack it for now */ struct { struct iwl_mvm_wep_key_cmd wep_key_cmd; struct iwl_mvm_wep_key wep_key; } __packed wkc = { .wep_key_cmd.mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), .wep_key_cmd.num_keys = 1, /* firmware sets STA_KEY_FLG_WEP_13BYTES */ .wep_key_cmd.decryption_type = STA_KEY_FLG_WEP, .wep_key.key_index = key->keyidx, .wep_key.key_size = key->keylen, }; /* * This will fail -- the key functions don't set support * pairwise WEP keys. However, that's better than silently * failing WoWLAN. Or maybe not? */ if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) break; memcpy(&wkc.wep_key.key[3], key->key, key->keylen); if (key->keyidx == mvmvif->tx_key_idx) { /* TX key must be at offset 0 */ wkc.wep_key.key_offset = 0; } else { /* others start at 1 */ data->wep_key_idx++; wkc.wep_key.key_offset = data->wep_key_idx; } ret = iwl_mvm_send_cmd_pdu(mvm, WEP_KEY, CMD_SYNC, sizeof(wkc), &wkc); data->error = ret != 0; mvm->ptk_ivlen = key->iv_len; mvm->ptk_icvlen = key->icv_len; mvm->gtk_ivlen = key->iv_len; mvm->gtk_icvlen = key->icv_len; /* don't upload key again */ goto out_unlock; } default: data->error = true; goto out_unlock; case WLAN_CIPHER_SUITE_AES_CMAC: /* * Ignore CMAC keys -- the WoWLAN firmware doesn't support them * but we also shouldn't abort suspend due to that. It does have * support for the IGTK key renewal, but doesn't really use the * IGTK for anything. This means we could spuriously wake up or * be deauthenticated, but that was considered acceptable. */ goto out_unlock; case WLAN_CIPHER_SUITE_TKIP: if (sta) { tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.unicast_rsc; tkip_tx_sc = &data->rsc_tsc->all_tsc_rsc.tkip.tsc; rx_p1ks = data->tkip->rx_uni; ieee80211_get_key_tx_seq(key, &seq); tkip_tx_sc->iv16 = cpu_to_le16(seq.tkip.iv16); tkip_tx_sc->iv32 = cpu_to_le32(seq.tkip.iv32); ieee80211_get_tkip_p1k_iv(key, seq.tkip.iv32, p1k); iwl_mvm_convert_p1k(p1k, data->tkip->tx.p1k); memcpy(data->tkip->mic_keys.tx, &key->key[NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY], IWL_MIC_KEY_SIZE); rx_mic_key = data->tkip->mic_keys.rx_unicast; } else { tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.multicast_rsc; rx_p1ks = data->tkip->rx_multi; rx_mic_key = data->tkip->mic_keys.rx_mcast; } /* * For non-QoS this relies on the fact that both the uCode and * mac80211 use TID 0 (as they need to to avoid replay attacks) * for checking the IV in the frames. */ for (i = 0; i < IWL_NUM_RSC; i++) { ieee80211_get_key_rx_seq(key, i, &seq); tkip_sc[i].iv16 = cpu_to_le16(seq.tkip.iv16); tkip_sc[i].iv32 = cpu_to_le32(seq.tkip.iv32); /* wrapping isn't allowed, AP must rekey */ if (seq.tkip.iv32 > cur_rx_iv32) cur_rx_iv32 = seq.tkip.iv32; } ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid, cur_rx_iv32, p1k); iwl_mvm_convert_p1k(p1k, rx_p1ks[0].p1k); ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid, cur_rx_iv32 + 1, p1k); iwl_mvm_convert_p1k(p1k, rx_p1ks[1].p1k); memcpy(rx_mic_key, &key->key[NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY], IWL_MIC_KEY_SIZE); data->use_tkip = true; data->use_rsc_tsc = true; break; case WLAN_CIPHER_SUITE_CCMP: if (sta) { u8 *pn = seq.ccmp.pn; aes_sc = data->rsc_tsc->all_tsc_rsc.aes.unicast_rsc; aes_tx_sc = &data->rsc_tsc->all_tsc_rsc.aes.tsc; ieee80211_get_key_tx_seq(key, &seq); aes_tx_sc->pn = cpu_to_le64((u64)pn[5] | ((u64)pn[4] << 8) | ((u64)pn[3] << 16) | ((u64)pn[2] << 24) | ((u64)pn[1] << 32) | ((u64)pn[0] << 40)); } else { aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc; } /* * For non-QoS this relies on the fact that both the uCode and * mac80211 use TID 0 for checking the IV in the frames. */ for (i = 0; i < IWL_NUM_RSC; i++) { u8 *pn = seq.ccmp.pn; ieee80211_get_key_rx_seq(key, i, &seq); aes_sc->pn = cpu_to_le64((u64)pn[5] | ((u64)pn[4] << 8) | ((u64)pn[3] << 16) | ((u64)pn[2] << 24) | ((u64)pn[1] << 32) | ((u64)pn[0] << 40)); } data->use_rsc_tsc = true; break; } /* * The D3 firmware hardcodes the key offset 0 as the key it uses * to transmit packets to the AP, i.e. the PTK. */ if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) { key->hw_key_idx = 0; mvm->ptk_ivlen = key->iv_len; mvm->ptk_icvlen = key->icv_len; } else { /* * firmware only supports TSC/RSC for a single key, * so if there are multiple keep overwriting them * with new ones -- this relies on mac80211 doing * list_add_tail(). */ key->hw_key_idx = 1; mvm->gtk_ivlen = key->iv_len; mvm->gtk_icvlen = key->icv_len; } ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, true); data->error = ret != 0; out_unlock: mutex_unlock(&mvm->mutex); } static int iwl_mvm_send_patterns(struct iwl_mvm *mvm, struct cfg80211_wowlan *wowlan) { struct iwl_wowlan_patterns_cmd *pattern_cmd; struct iwl_host_cmd cmd = { .id = WOWLAN_PATTERNS, .dataflags[0] = IWL_HCMD_DFL_NOCOPY, .flags = CMD_SYNC, }; int i, err; if (!wowlan->n_patterns) return 0; cmd.len[0] = sizeof(*pattern_cmd) + wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern); pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL); if (!pattern_cmd) return -ENOMEM; pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns); for (i = 0; i < wowlan->n_patterns; i++) { int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8); memcpy(&pattern_cmd->patterns[i].mask, wowlan->patterns[i].mask, mask_len); memcpy(&pattern_cmd->patterns[i].pattern, wowlan->patterns[i].pattern, wowlan->patterns[i].pattern_len); pattern_cmd->patterns[i].mask_size = mask_len; pattern_cmd->patterns[i].pattern_size = wowlan->patterns[i].pattern_len; } cmd.data[0] = pattern_cmd; err = iwl_mvm_send_cmd(mvm, &cmd); kfree(pattern_cmd); return err; } static int iwl_mvm_send_proto_offload(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { union { struct iwl_proto_offload_cmd_v1 v1; struct iwl_proto_offload_cmd_v2 v2; struct iwl_proto_offload_cmd_v3_small v3s; struct iwl_proto_offload_cmd_v3_large v3l; } cmd = {}; struct iwl_host_cmd hcmd = { .id = PROT_OFFLOAD_CONFIG_CMD, .flags = CMD_SYNC, .data[0] = &cmd, .dataflags[0] = IWL_HCMD_DFL_DUP, }; struct iwl_proto_offload_cmd_common *common; u32 enabled = 0, size; u32 capa_flags = mvm->fw->ucode_capa.flags; #if IS_ENABLED(CONFIG_IPV6) struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); int i; if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL || capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_LARGE) { struct iwl_ns_config *nsc; struct iwl_targ_addr *addrs; int n_nsc, n_addrs; int c; if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) { nsc = cmd.v3s.ns_config; n_nsc = IWL_PROTO_OFFLOAD_NUM_NS_CONFIG_V3S; addrs = cmd.v3s.targ_addrs; n_addrs = IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V3S; } else { nsc = cmd.v3l.ns_config; n_nsc = IWL_PROTO_OFFLOAD_NUM_NS_CONFIG_V3L; addrs = cmd.v3l.targ_addrs; n_addrs = IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V3L; } if (mvmvif->num_target_ipv6_addrs) enabled |= IWL_D3_PROTO_OFFLOAD_NS; /* * For each address we have (and that will fit) fill a target * address struct and combine for NS offload structs with the * solicited node addresses. */ for (i = 0, c = 0; i < mvmvif->num_target_ipv6_addrs && i < n_addrs && c < n_nsc; i++) { struct in6_addr solicited_addr; int j; addrconf_addr_solict_mult(&mvmvif->target_ipv6_addrs[i], &solicited_addr); for (j = 0; j < c; j++) if (ipv6_addr_cmp(&nsc[j].dest_ipv6_addr, &solicited_addr) == 0) break; if (j == c) c++; addrs[i].addr = mvmvif->target_ipv6_addrs[i]; addrs[i].config_num = cpu_to_le32(j); nsc[j].dest_ipv6_addr = solicited_addr; memcpy(nsc[j].target_mac_addr, vif->addr, ETH_ALEN); } if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) cmd.v3s.num_valid_ipv6_addrs = cpu_to_le32(i); else cmd.v3l.num_valid_ipv6_addrs = cpu_to_le32(i); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_D3_6_IPV6_ADDRS) { if (mvmvif->num_target_ipv6_addrs) { enabled |= IWL_D3_PROTO_OFFLOAD_NS; memcpy(cmd.v2.ndp_mac_addr, vif->addr, ETH_ALEN); } BUILD_BUG_ON(sizeof(cmd.v2.target_ipv6_addr[0]) != sizeof(mvmvif->target_ipv6_addrs[0])); for (i = 0; i < min(mvmvif->num_target_ipv6_addrs, IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V2); i++) memcpy(cmd.v2.target_ipv6_addr[i], &mvmvif->target_ipv6_addrs[i], sizeof(cmd.v2.target_ipv6_addr[i])); } else { if (mvmvif->num_target_ipv6_addrs) { enabled |= IWL_D3_PROTO_OFFLOAD_NS; memcpy(cmd.v1.ndp_mac_addr, vif->addr, ETH_ALEN); } BUILD_BUG_ON(sizeof(cmd.v1.target_ipv6_addr[0]) != sizeof(mvmvif->target_ipv6_addrs[0])); for (i = 0; i < min(mvmvif->num_target_ipv6_addrs, IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_V1); i++) memcpy(cmd.v1.target_ipv6_addr[i], &mvmvif->target_ipv6_addrs[i], sizeof(cmd.v1.target_ipv6_addr[i])); } #endif if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_SMALL) { common = &cmd.v3s.common; size = sizeof(cmd.v3s); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_NEW_NSOFFL_LARGE) { common = &cmd.v3l.common; size = sizeof(cmd.v3l); } else if (capa_flags & IWL_UCODE_TLV_FLAGS_D3_6_IPV6_ADDRS) { common = &cmd.v2.common; size = sizeof(cmd.v2); } else { common = &cmd.v1.common; size = sizeof(cmd.v1); } if (vif->bss_conf.arp_addr_cnt) { enabled |= IWL_D3_PROTO_OFFLOAD_ARP; common->host_ipv4_addr = vif->bss_conf.arp_addr_list[0]; memcpy(common->arp_mac_addr, vif->addr, ETH_ALEN); } if (!enabled) return 0; common->enabled = cpu_to_le32(enabled); hcmd.len[0] = size; return iwl_mvm_send_cmd(mvm, &hcmd); } enum iwl_mvm_tcp_packet_type { MVM_TCP_TX_SYN, MVM_TCP_RX_SYNACK, MVM_TCP_TX_DATA, MVM_TCP_RX_ACK, MVM_TCP_RX_WAKE, MVM_TCP_TX_FIN, }; static __le16 pseudo_hdr_check(int len, __be32 saddr, __be32 daddr) { __sum16 check = tcp_v4_check(len, saddr, daddr, 0); return cpu_to_le16(be16_to_cpu((__force __be16)check)); } static void iwl_mvm_build_tcp_packet(struct ieee80211_vif *vif, struct cfg80211_wowlan_tcp *tcp, void *_pkt, u8 *mask, __le16 *pseudo_hdr_csum, enum iwl_mvm_tcp_packet_type ptype) { struct { struct ethhdr eth; struct iphdr ip; struct tcphdr tcp; u8 data[]; } __packed *pkt = _pkt; u16 ip_tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr); int i; pkt->eth.h_proto = cpu_to_be16(ETH_P_IP), pkt->ip.version = 4; pkt->ip.ihl = 5; pkt->ip.protocol = IPPROTO_TCP; switch (ptype) { case MVM_TCP_TX_SYN: case MVM_TCP_TX_DATA: case MVM_TCP_TX_FIN: memcpy(pkt->eth.h_dest, tcp->dst_mac, ETH_ALEN); memcpy(pkt->eth.h_source, vif->addr, ETH_ALEN); pkt->ip.ttl = 128; pkt->ip.saddr = tcp->src; pkt->ip.daddr = tcp->dst; pkt->tcp.source = cpu_to_be16(tcp->src_port); pkt->tcp.dest = cpu_to_be16(tcp->dst_port); /* overwritten for TX SYN later */ pkt->tcp.doff = sizeof(struct tcphdr) / 4; pkt->tcp.window = cpu_to_be16(65000); break; case MVM_TCP_RX_SYNACK: case MVM_TCP_RX_ACK: case MVM_TCP_RX_WAKE: memcpy(pkt->eth.h_dest, vif->addr, ETH_ALEN); memcpy(pkt->eth.h_source, tcp->dst_mac, ETH_ALEN); pkt->ip.saddr = tcp->dst; pkt->ip.daddr = tcp->src; pkt->tcp.source = cpu_to_be16(tcp->dst_port); pkt->tcp.dest = cpu_to_be16(tcp->src_port); break; default: WARN_ON(1); return; } switch (ptype) { case MVM_TCP_TX_SYN: /* firmware assumes 8 option bytes - 8 NOPs for now */ memset(pkt->data, 0x01, 8); ip_tot_len += 8; pkt->tcp.doff = (sizeof(struct tcphdr) + 8) / 4; pkt->tcp.syn = 1; break; case MVM_TCP_TX_DATA: ip_tot_len += tcp->payload_len; memcpy(pkt->data, tcp->payload, tcp->payload_len); pkt->tcp.psh = 1; pkt->tcp.ack = 1; break; case MVM_TCP_TX_FIN: pkt->tcp.fin = 1; pkt->tcp.ack = 1; break; case MVM_TCP_RX_SYNACK: pkt->tcp.syn = 1; pkt->tcp.ack = 1; break; case MVM_TCP_RX_ACK: pkt->tcp.ack = 1; break; case MVM_TCP_RX_WAKE: ip_tot_len += tcp->wake_len; pkt->tcp.psh = 1; pkt->tcp.ack = 1; memcpy(pkt->data, tcp->wake_data, tcp->wake_len); break; } switch (ptype) { case MVM_TCP_TX_SYN: case MVM_TCP_TX_DATA: case MVM_TCP_TX_FIN: pkt->ip.tot_len = cpu_to_be16(ip_tot_len); pkt->ip.check = ip_fast_csum(&pkt->ip, pkt->ip.ihl); break; case MVM_TCP_RX_WAKE: for (i = 0; i < DIV_ROUND_UP(tcp->wake_len, 8); i++) { u8 tmp = tcp->wake_mask[i]; mask[i + 6] |= tmp << 6; if (i + 1 < DIV_ROUND_UP(tcp->wake_len, 8)) mask[i + 7] = tmp >> 2; } /* fall through for ethernet/IP/TCP headers mask */ case MVM_TCP_RX_SYNACK: case MVM_TCP_RX_ACK: mask[0] = 0xff; /* match ethernet */ /* * match ethernet, ip.version, ip.ihl * the ip.ihl half byte is really masked out by firmware */ mask[1] = 0x7f; mask[2] = 0x80; /* match ip.protocol */ mask[3] = 0xfc; /* match ip.saddr, ip.daddr */ mask[4] = 0x3f; /* match ip.daddr, tcp.source, tcp.dest */ mask[5] = 0x80; /* match tcp flags */ /* leave rest (0 or set for MVM_TCP_RX_WAKE) */ break; }; *pseudo_hdr_csum = pseudo_hdr_check(ip_tot_len - sizeof(struct iphdr), pkt->ip.saddr, pkt->ip.daddr); } static int iwl_mvm_send_remote_wake_cfg(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct cfg80211_wowlan_tcp *tcp) { struct iwl_wowlan_remote_wake_config *cfg; struct iwl_host_cmd cmd = { .id = REMOTE_WAKE_CONFIG_CMD, .len = { sizeof(*cfg), }, .dataflags = { IWL_HCMD_DFL_NOCOPY, }, .flags = CMD_SYNC, }; int ret; if (!tcp) return 0; cfg = kzalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return -ENOMEM; cmd.data[0] = cfg; cfg->max_syn_retries = 10; cfg->max_data_retries = 10; cfg->tcp_syn_ack_timeout = 1; /* seconds */ cfg->tcp_ack_timeout = 1; /* seconds */ /* SYN (TX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->syn_tx.data, NULL, &cfg->syn_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_SYN); cfg->syn_tx.info.tcp_payload_length = 0; /* SYN/ACK (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->synack_rx.data, cfg->synack_rx.rx_mask, &cfg->synack_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_SYNACK); cfg->synack_rx.info.tcp_payload_length = 0; /* KEEPALIVE/ACK (TX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->keepalive_tx.data, NULL, &cfg->keepalive_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_DATA); cfg->keepalive_tx.info.tcp_payload_length = cpu_to_le16(tcp->payload_len); cfg->sequence_number_offset = tcp->payload_seq.offset; /* length must be 0..4, the field is little endian */ cfg->sequence_number_length = tcp->payload_seq.len; cfg->initial_sequence_number = cpu_to_le32(tcp->payload_seq.start); cfg->keepalive_interval = cpu_to_le16(tcp->data_interval); if (tcp->payload_tok.len) { cfg->token_offset = tcp->payload_tok.offset; cfg->token_length = tcp->payload_tok.len; cfg->num_tokens = cpu_to_le16(tcp->tokens_size % tcp->payload_tok.len); memcpy(cfg->tokens, tcp->payload_tok.token_stream, tcp->tokens_size); } else { /* set tokens to max value to almost never run out */ cfg->num_tokens = cpu_to_le16(65535); } /* ACK (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->keepalive_ack_rx.data, cfg->keepalive_ack_rx.rx_mask, &cfg->keepalive_ack_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_ACK); cfg->keepalive_ack_rx.info.tcp_payload_length = 0; /* WAKEUP (RX) */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->wake_rx.data, cfg->wake_rx.rx_mask, &cfg->wake_rx.info.tcp_pseudo_header_checksum, MVM_TCP_RX_WAKE); cfg->wake_rx.info.tcp_payload_length = cpu_to_le16(tcp->wake_len); /* FIN */ iwl_mvm_build_tcp_packet( vif, tcp, cfg->fin_tx.data, NULL, &cfg->fin_tx.info.tcp_pseudo_header_checksum, MVM_TCP_TX_FIN); cfg->fin_tx.info.tcp_payload_length = 0; ret = iwl_mvm_send_cmd(mvm, &cmd); kfree(cfg); return ret; } struct iwl_d3_iter_data { struct iwl_mvm *mvm; struct ieee80211_vif *vif; bool error; }; static void iwl_mvm_d3_iface_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_d3_iter_data *data = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (vif->type != NL80211_IFTYPE_STATION || vif->p2p) return; if (mvmvif->ap_sta_id == IWL_MVM_STATION_COUNT) return; if (data->vif) { IWL_ERR(data->mvm, "More than one managed interface active!\n"); data->error = true; return; } data->vif = vif; } static int iwl_mvm_d3_reprogram(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct ieee80211_sta *ap_sta) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct ieee80211_chanctx_conf *ctx; u8 chains_static, chains_dynamic; struct cfg80211_chan_def chandef; int ret, i; struct iwl_binding_cmd binding_cmd = {}; struct iwl_time_quota_cmd quota_cmd = {}; u32 status; /* add back the PHY */ if (WARN_ON(!mvmvif->phy_ctxt)) return -EINVAL; rcu_read_lock(); ctx = rcu_dereference(vif->chanctx_conf); if (WARN_ON(!ctx)) { rcu_read_unlock(); return -EINVAL; } chandef = ctx->def; chains_static = ctx->rx_chains_static; chains_dynamic = ctx->rx_chains_dynamic; rcu_read_unlock(); ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef, chains_static, chains_dynamic); if (ret) return ret; /* add back the MAC */ mvmvif->uploaded = false; if (WARN_ON(!vif->bss_conf.assoc)) return -EINVAL; /* hack */ vif->bss_conf.assoc = false; ret = iwl_mvm_mac_ctxt_add(mvm, vif); vif->bss_conf.assoc = true; if (ret) return ret; /* add back binding - XXX refactor? */ binding_cmd.id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD); binding_cmd.phy = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)); for (i = 1; i < MAX_MACS_IN_BINDING; i++) binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID); status = 0; ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD, sizeof(binding_cmd), &binding_cmd, &status); if (ret) { IWL_ERR(mvm, "Failed to add binding: %d\n", ret); return ret; } if (status) { IWL_ERR(mvm, "Binding command failed: %u\n", status); return -EIO; } ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false); if (ret) return ret; rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta); ret = iwl_mvm_mac_ctxt_changed(mvm, vif); if (ret) return ret; /* and some quota */ quota_cmd.quotas[0].id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id, mvmvif->phy_ctxt->color)); quota_cmd.quotas[0].quota = cpu_to_le32(100); quota_cmd.quotas[0].max_duration = cpu_to_le32(1000); for (i = 1; i < MAX_BINDINGS; i++) quota_cmd.quotas[i].id_and_color = cpu_to_le32(FW_CTXT_INVALID); ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, CMD_SYNC, sizeof(quota_cmd), &quota_cmd); if (ret) IWL_ERR(mvm, "Failed to send quota: %d\n", ret); return 0; } static int iwl_mvm_get_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_nonqos_seq_query_cmd query_cmd = { .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET), .mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), }; struct iwl_host_cmd cmd = { .id = NON_QOS_TX_COUNTER_CMD, .flags = CMD_SYNC | CMD_WANT_SKB, }; int err; u32 size; if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) { cmd.data[0] = &query_cmd; cmd.len[0] = sizeof(query_cmd); } err = iwl_mvm_send_cmd(mvm, &cmd); if (err) return err; size = le32_to_cpu(cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; size -= sizeof(cmd.resp_pkt->hdr); if (size < sizeof(__le16)) { err = -EINVAL; } else { err = le16_to_cpup((__le16 *)cmd.resp_pkt->data); /* new API returns next, not last-used seqno */ if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) err = (u16) (err - 0x10); } iwl_free_resp(&cmd); return err; } void iwl_mvm_set_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_nonqos_seq_query_cmd query_cmd = { .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET), .mac_id_n_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)), .value = cpu_to_le16(mvmvif->seqno), }; /* return if called during restart, not resume from D3 */ if (!mvmvif->seqno_valid) return; mvmvif->seqno_valid = false; if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API)) return; if (iwl_mvm_send_cmd_pdu(mvm, NON_QOS_TX_COUNTER_CMD, CMD_SYNC, sizeof(query_cmd), &query_cmd)) IWL_ERR(mvm, "failed to set non-QoS seqno\n"); } static int __iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan, bool test) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); struct iwl_d3_iter_data suspend_iter_data = { .mvm = mvm, }; struct ieee80211_vif *vif; struct iwl_mvm_vif *mvmvif; struct ieee80211_sta *ap_sta; struct iwl_mvm_sta *mvm_ap_sta; struct iwl_wowlan_config_cmd wowlan_config_cmd = {}; struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {}; struct iwl_wowlan_tkip_params_cmd tkip_cmd = {}; struct iwl_d3_manager_config d3_cfg_cmd_data = { /* * Program the minimum sleep time to 10 seconds, as many * platforms have issues processing a wakeup signal while * still being in the process of suspending. */ .min_sleep_time = cpu_to_le32(10 * 1000 * 1000), }; struct iwl_host_cmd d3_cfg_cmd = { .id = D3_CONFIG_CMD, .flags = CMD_SYNC | CMD_WANT_SKB, .data[0] = &d3_cfg_cmd_data, .len[0] = sizeof(d3_cfg_cmd_data), }; struct wowlan_key_data key_data = { .use_rsc_tsc = false, .tkip = &tkip_cmd, .use_tkip = false, }; int ret, i; int len __maybe_unused; u8 old_aux_sta_id, old_ap_sta_id = IWL_MVM_STATION_COUNT; if (!wowlan) { /* * mac80211 shouldn't get here, but for D3 test * it doesn't warrant a warning */ WARN_ON(!test); return -EINVAL; } key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL); if (!key_data.rsc_tsc) return -ENOMEM; mutex_lock(&mvm->mutex); old_aux_sta_id = mvm->aux_sta.sta_id; /* see if there's only a single BSS vif and it's associated */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_iface_iterator, &suspend_iter_data); if (suspend_iter_data.error || !suspend_iter_data.vif) { ret = 1; goto out_noreset; } vif = suspend_iter_data.vif; mvmvif = iwl_mvm_vif_from_mac80211(vif); ap_sta = rcu_dereference_protected( mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], lockdep_is_held(&mvm->mutex)); if (IS_ERR_OR_NULL(ap_sta)) { ret = -EINVAL; goto out_noreset; } mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv; /* TODO: wowlan_config_cmd.wowlan_ba_teardown_tids */ wowlan_config_cmd.is_11n_connection = ap_sta->ht_cap.ht_supported; /* Query the last used seqno and set it */ ret = iwl_mvm_get_last_nonqos_seq(mvm, vif); if (ret < 0) goto out_noreset; wowlan_config_cmd.non_qos_seq = cpu_to_le16(ret); /* * For QoS counters, we store the one to use next, so subtract 0x10 * since the uCode will add 0x10 *before* using the value while we * increment after using the value (i.e. store the next value to use). */ for (i = 0; i < IWL_MAX_TID_COUNT; i++) { u16 seq = mvm_ap_sta->tid_data[i].seq_number; seq -= 0x10; wowlan_config_cmd.qos_seq[i] = cpu_to_le16(seq); } if (wowlan->disconnect) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS | IWL_WOWLAN_WAKEUP_LINK_CHANGE); if (wowlan->magic_pkt) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET); if (wowlan->gtk_rekey_failure) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL); if (wowlan->eap_identity_req) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ); if (wowlan->four_way_handshake) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE); if (wowlan->n_patterns) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH); if (wowlan->rfkill_release) wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT); if (wowlan->tcp) { /* * Set the "link change" (really "link lost") flag as well * since that implies losing the TCP connection. */ wowlan_config_cmd.wakeup_filter |= cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS | IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE | IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET | IWL_WOWLAN_WAKEUP_LINK_CHANGE); } iwl_mvm_cancel_scan(mvm); iwl_trans_stop_device(mvm->trans); /* * The D3 firmware still hardcodes the AP station ID for the * BSS we're associated with as 0. Store the real STA ID here * and assign 0. When we leave this function, we'll restore * the original value for the resume code. */ old_ap_sta_id = mvm_ap_sta->sta_id; mvm_ap_sta->sta_id = 0; mvmvif->ap_sta_id = 0; /* * Set the HW restart bit -- this is mostly true as we're * going to load new firmware and reprogram that, though * the reprogramming is going to be manual to avoid adding * all the MACs that aren't support. * We don't have to clear up everything though because the * reprogramming is manual. When we resume, we'll actually * go through a proper restart sequence again to switch * back to the runtime firmware image. */ set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); /* We reprogram keys and shouldn't allocate new key indices */ memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table)); mvm->ptk_ivlen = 0; mvm->ptk_icvlen = 0; mvm->ptk_ivlen = 0; mvm->ptk_icvlen = 0; /* * The D3 firmware still hardcodes the AP station ID for the * BSS we're associated with as 0. As a result, we have to move * the auxiliary station to ID 1 so the ID 0 remains free for * the AP station for later. * We set the sta_id to 1 here, and reset it to its previous * value (that we stored above) later. */ mvm->aux_sta.sta_id = 1; ret = iwl_mvm_load_d3_fw(mvm); if (ret) goto out; ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta); if (ret) goto out; if (!iwlwifi_mod_params.sw_crypto) { /* * This needs to be unlocked due to lock ordering * constraints. Since we're in the suspend path * that isn't really a problem though. */ mutex_unlock(&mvm->mutex); ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_wowlan_program_keys, &key_data); mutex_lock(&mvm->mutex); if (key_data.error) { ret = -EIO; goto out; } if (key_data.use_rsc_tsc) { struct iwl_host_cmd rsc_tsc_cmd = { .id = WOWLAN_TSC_RSC_PARAM, .flags = CMD_SYNC, .data[0] = key_data.rsc_tsc, .dataflags[0] = IWL_HCMD_DFL_NOCOPY, .len[0] = sizeof(*key_data.rsc_tsc), }; ret = iwl_mvm_send_cmd(mvm, &rsc_tsc_cmd); if (ret) goto out; } if (key_data.use_tkip) { ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_TKIP_PARAM, CMD_SYNC, sizeof(tkip_cmd), &tkip_cmd); if (ret) goto out; } if (mvmvif->rekey_data.valid) { memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd)); memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck, NL80211_KCK_LEN); kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN); memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek, NL80211_KEK_LEN); kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN); kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr; ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_KEK_KCK_MATERIAL, CMD_SYNC, sizeof(kek_kck_cmd), &kek_kck_cmd); if (ret) goto out; } } ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, CMD_SYNC, sizeof(wowlan_config_cmd), &wowlan_config_cmd); if (ret) goto out; ret = iwl_mvm_send_patterns(mvm, wowlan); if (ret) goto out; ret = iwl_mvm_send_proto_offload(mvm, vif); if (ret) goto out; ret = iwl_mvm_send_remote_wake_cfg(mvm, vif, wowlan->tcp); if (ret) goto out; ret = iwl_mvm_power_update_device_mode(mvm); if (ret) goto out; ret = iwl_mvm_power_update_mode(mvm, vif); if (ret) goto out; #ifdef CONFIG_IWLWIFI_DEBUGFS if (mvm->d3_wake_sysassert) d3_cfg_cmd_data.wakeup_flags |= cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR); #endif /* must be last -- this switches firmware state */ ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd); if (ret) goto out; #ifdef CONFIG_IWLWIFI_DEBUGFS len = le32_to_cpu(d3_cfg_cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; if (len >= sizeof(u32) * 2) { mvm->d3_test_pme_ptr = le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data); } #endif iwl_free_resp(&d3_cfg_cmd); clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); iwl_trans_d3_suspend(mvm->trans, test); out: mvm->aux_sta.sta_id = old_aux_sta_id; mvm_ap_sta->sta_id = old_ap_sta_id; mvmvif->ap_sta_id = old_ap_sta_id; if (ret < 0) ieee80211_restart_hw(mvm->hw); out_noreset: kfree(key_data.rsc_tsc); mutex_unlock(&mvm->mutex); return ret; } int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan) { return __iwl_mvm_suspend(hw, wowlan, false); } /* converted data from the different status responses */ struct iwl_wowlan_status_data { u16 pattern_number; u16 qos_seq_ctr[8]; u32 wakeup_reasons; u32 wake_packet_length; u32 wake_packet_bufsize; const u8 *wake_packet; }; static void iwl_mvm_report_wakeup_reasons(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_wowlan_status_data *status) { struct sk_buff *pkt = NULL; struct cfg80211_wowlan_wakeup wakeup = { .pattern_idx = -1, }; struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup; u32 reasons = status->wakeup_reasons; if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) { wakeup_report = NULL; goto report; } if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET) wakeup.magic_pkt = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN) wakeup.pattern_idx = status->pattern_number; if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON | IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH)) wakeup.disconnect = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE) wakeup.gtk_rekey_failure = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED) wakeup.rfkill_release = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST) wakeup.eap_identity_req = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE) wakeup.four_way_handshake = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS) wakeup.tcp_connlost = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE) wakeup.tcp_nomoretokens = true; if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET) wakeup.tcp_match = true; if (status->wake_packet_bufsize) { int pktsize = status->wake_packet_bufsize; int pktlen = status->wake_packet_length; const u8 *pktdata = status->wake_packet; struct ieee80211_hdr *hdr = (void *)pktdata; int truncated = pktlen - pktsize; /* this would be a firmware bug */ if (WARN_ON_ONCE(truncated < 0)) truncated = 0; if (ieee80211_is_data(hdr->frame_control)) { int hdrlen = ieee80211_hdrlen(hdr->frame_control); int ivlen = 0, icvlen = 4; /* also FCS */ pkt = alloc_skb(pktsize, GFP_KERNEL); if (!pkt) goto report; memcpy(skb_put(pkt, hdrlen), pktdata, hdrlen); pktdata += hdrlen; pktsize -= hdrlen; if (ieee80211_has_protected(hdr->frame_control)) { /* * This is unlocked and using gtk_i(c)vlen, * but since everything is under RTNL still * that's not really a problem - changing * it would be difficult. */ if (is_multicast_ether_addr(hdr->addr1)) { ivlen = mvm->gtk_ivlen; icvlen += mvm->gtk_icvlen; } else { ivlen = mvm->ptk_ivlen; icvlen += mvm->ptk_icvlen; } } /* if truncated, FCS/ICV is (partially) gone */ if (truncated >= icvlen) { icvlen = 0; truncated -= icvlen; } else { icvlen -= truncated; truncated = 0; } pktsize -= ivlen + icvlen; pktdata += ivlen; memcpy(skb_put(pkt, pktsize), pktdata, pktsize); if (ieee80211_data_to_8023(pkt, vif->addr, vif->type)) goto report; wakeup.packet = pkt->data; wakeup.packet_present_len = pkt->len; wakeup.packet_len = pkt->len - truncated; wakeup.packet_80211 = false; } else { int fcslen = 4; if (truncated >= 4) { truncated -= 4; fcslen = 0; } else { fcslen -= truncated; truncated = 0; } pktsize -= fcslen; wakeup.packet = status->wake_packet; wakeup.packet_present_len = pktsize; wakeup.packet_len = pktlen - truncated; wakeup.packet_80211 = true; } } report: ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL); kfree_skb(pkt); } static void iwl_mvm_aes_sc_to_seq(struct aes_sc *sc, struct ieee80211_key_seq *seq) { u64 pn; pn = le64_to_cpu(sc->pn); seq->ccmp.pn[0] = pn >> 40; seq->ccmp.pn[1] = pn >> 32; seq->ccmp.pn[2] = pn >> 24; seq->ccmp.pn[3] = pn >> 16; seq->ccmp.pn[4] = pn >> 8; seq->ccmp.pn[5] = pn; } static void iwl_mvm_tkip_sc_to_seq(struct tkip_sc *sc, struct ieee80211_key_seq *seq) { seq->tkip.iv32 = le32_to_cpu(sc->iv32); seq->tkip.iv16 = le16_to_cpu(sc->iv16); } static void iwl_mvm_set_aes_rx_seq(struct aes_sc *scs, struct ieee80211_key_conf *key) { int tid; BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS); for (tid = 0; tid < IWL_NUM_RSC; tid++) { struct ieee80211_key_seq seq = {}; iwl_mvm_aes_sc_to_seq(&scs[tid], &seq); ieee80211_set_key_rx_seq(key, tid, &seq); } } static void iwl_mvm_set_tkip_rx_seq(struct tkip_sc *scs, struct ieee80211_key_conf *key) { int tid; BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS); for (tid = 0; tid < IWL_NUM_RSC; tid++) { struct ieee80211_key_seq seq = {}; iwl_mvm_tkip_sc_to_seq(&scs[tid], &seq); ieee80211_set_key_rx_seq(key, tid, &seq); } } static void iwl_mvm_set_key_rx_seq(struct ieee80211_key_conf *key, struct iwl_wowlan_status_v6 *status) { union iwl_all_tsc_rsc *rsc = &status->gtk.rsc.all_tsc_rsc; switch (key->cipher) { case WLAN_CIPHER_SUITE_CCMP: iwl_mvm_set_aes_rx_seq(rsc->aes.multicast_rsc, key); break; case WLAN_CIPHER_SUITE_TKIP: iwl_mvm_set_tkip_rx_seq(rsc->tkip.multicast_rsc, key); break; default: WARN_ON(1); } } struct iwl_mvm_d3_gtk_iter_data { struct iwl_wowlan_status_v6 *status; void *last_gtk; u32 cipher; bool find_phase, unhandled_cipher; int num_keys; }; static void iwl_mvm_d3_update_gtks(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key, void *_data) { struct iwl_mvm_d3_gtk_iter_data *data = _data; if (data->unhandled_cipher) return; switch (key->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: /* ignore WEP completely, nothing to do */ return; case WLAN_CIPHER_SUITE_CCMP: case WLAN_CIPHER_SUITE_TKIP: /* we support these */ break; default: /* everything else (even CMAC for MFP) - disconnect from AP */ data->unhandled_cipher = true; return; } data->num_keys++; /* * pairwise key - update sequence counters only; * note that this assumes no TDLS sessions are active */ if (sta) { struct ieee80211_key_seq seq = {}; union iwl_all_tsc_rsc *sc = &data->status->gtk.rsc.all_tsc_rsc; if (data->find_phase) return; switch (key->cipher) { case WLAN_CIPHER_SUITE_CCMP: iwl_mvm_aes_sc_to_seq(&sc->aes.tsc, &seq); iwl_mvm_set_aes_rx_seq(sc->aes.unicast_rsc, key); break; case WLAN_CIPHER_SUITE_TKIP: iwl_mvm_tkip_sc_to_seq(&sc->tkip.tsc, &seq); iwl_mvm_set_tkip_rx_seq(sc->tkip.unicast_rsc, key); break; } ieee80211_set_key_tx_seq(key, &seq); /* that's it for this key */ return; } if (data->find_phase) { data->last_gtk = key; data->cipher = key->cipher; return; } if (data->status->num_of_gtk_rekeys) ieee80211_remove_key(key); else if (data->last_gtk == key) iwl_mvm_set_key_rx_seq(key, data->status); } static bool iwl_mvm_setup_connection_keep(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_wowlan_status_v6 *status) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm_d3_gtk_iter_data gtkdata = { .status = status, }; u32 disconnection_reasons = IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON | IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH; if (!status || !vif->bss_conf.bssid) return false; if (le32_to_cpu(status->wakeup_reasons) & disconnection_reasons) return false; /* find last GTK that we used initially, if any */ gtkdata.find_phase = true; ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_d3_update_gtks, &gtkdata); /* not trying to keep connections with MFP/unhandled ciphers */ if (gtkdata.unhandled_cipher) return false; if (!gtkdata.num_keys) goto out; if (!gtkdata.last_gtk) return false; /* * invalidate all other GTKs that might still exist and update * the one that we used */ gtkdata.find_phase = false; ieee80211_iter_keys(mvm->hw, vif, iwl_mvm_d3_update_gtks, &gtkdata); if (status->num_of_gtk_rekeys) { struct ieee80211_key_conf *key; struct { struct ieee80211_key_conf conf; u8 key[32]; } conf = { .conf.cipher = gtkdata.cipher, .conf.keyidx = status->gtk.key_index, }; switch (gtkdata.cipher) { case WLAN_CIPHER_SUITE_CCMP: conf.conf.keylen = WLAN_KEY_LEN_CCMP; memcpy(conf.conf.key, status->gtk.decrypt_key, WLAN_KEY_LEN_CCMP); break; case WLAN_CIPHER_SUITE_TKIP: conf.conf.keylen = WLAN_KEY_LEN_TKIP; memcpy(conf.conf.key, status->gtk.decrypt_key, 16); /* leave TX MIC key zeroed, we don't use it anyway */ memcpy(conf.conf.key + NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY, status->gtk.tkip_mic_key, 8); break; } key = ieee80211_gtk_rekey_add(vif, &conf.conf); if (IS_ERR(key)) return false; iwl_mvm_set_key_rx_seq(key, status); } if (status->num_of_gtk_rekeys) { __be64 replay_ctr = cpu_to_be64(le64_to_cpu(status->replay_ctr)); ieee80211_gtk_rekey_notify(vif, vif->bss_conf.bssid, (void *)&replay_ctr, GFP_KERNEL); } out: mvmvif->seqno_valid = true; /* +0x10 because the set API expects next-to-use, not last-used */ mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10; return true; } /* releases the MVM mutex */ static bool iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { u32 base = mvm->error_event_table; struct error_table_start { /* cf. struct iwl_error_event_table */ u32 valid; u32 error_id; } err_info; struct iwl_host_cmd cmd = { .id = WOWLAN_GET_STATUSES, .flags = CMD_SYNC | CMD_WANT_SKB, }; struct iwl_wowlan_status_data status; struct iwl_wowlan_status_v6 *status_v6; int ret, len, status_size, i; bool keep; struct ieee80211_sta *ap_sta; struct iwl_mvm_sta *mvm_ap_sta; iwl_trans_read_mem_bytes(mvm->trans, base, &err_info, sizeof(err_info)); if (err_info.valid) { IWL_INFO(mvm, "error table is valid (%d)\n", err_info.valid); if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) { struct cfg80211_wowlan_wakeup wakeup = { .rfkill_release = true, }; ieee80211_report_wowlan_wakeup(vif, &wakeup, GFP_KERNEL); } goto out_unlock; } /* only for tracing for now */ ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, CMD_SYNC, 0, NULL); if (ret) IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret); ret = iwl_mvm_send_cmd(mvm, &cmd); if (ret) { IWL_ERR(mvm, "failed to query status (%d)\n", ret); goto out_unlock; } /* RF-kill already asserted again... */ if (!cmd.resp_pkt) goto out_unlock; if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) status_size = sizeof(struct iwl_wowlan_status_v6); else status_size = sizeof(struct iwl_wowlan_status_v4); len = le32_to_cpu(cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK; if (len - sizeof(struct iwl_cmd_header) < status_size) { IWL_ERR(mvm, "Invalid WoWLAN status response!\n"); goto out_free_resp; } if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_D3_CONTINUITY_API) { status_v6 = (void *)cmd.resp_pkt->data; status.pattern_number = le16_to_cpu(status_v6->pattern_number); for (i = 0; i < 8; i++) status.qos_seq_ctr[i] = le16_to_cpu(status_v6->qos_seq_ctr[i]); status.wakeup_reasons = le32_to_cpu(status_v6->wakeup_reasons); status.wake_packet_length = le32_to_cpu(status_v6->wake_packet_length); status.wake_packet_bufsize = le32_to_cpu(status_v6->wake_packet_bufsize); status.wake_packet = status_v6->wake_packet; } else { struct iwl_wowlan_status_v4 *status_v4; status_v6 = NULL; status_v4 = (void *)cmd.resp_pkt->data; status.pattern_number = le16_to_cpu(status_v4->pattern_number); for (i = 0; i < 8; i++) status.qos_seq_ctr[i] = le16_to_cpu(status_v4->qos_seq_ctr[i]); status.wakeup_reasons = le32_to_cpu(status_v4->wakeup_reasons); status.wake_packet_length = le32_to_cpu(status_v4->wake_packet_length); status.wake_packet_bufsize = le32_to_cpu(status_v4->wake_packet_bufsize); status.wake_packet = status_v4->wake_packet; } if (len - sizeof(struct iwl_cmd_header) != status_size + ALIGN(status.wake_packet_bufsize, 4)) { IWL_ERR(mvm, "Invalid WoWLAN status response!\n"); goto out_free_resp; } /* still at hard-coded place 0 for D3 image */ ap_sta = rcu_dereference_protected( mvm->fw_id_to_mac_id[0], lockdep_is_held(&mvm->mutex)); if (IS_ERR_OR_NULL(ap_sta)) goto out_free_resp; mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv; for (i = 0; i < IWL_MAX_TID_COUNT; i++) { u16 seq = status.qos_seq_ctr[i]; /* firmware stores last-used value, we store next value */ seq += 0x10; mvm_ap_sta->tid_data[i].seq_number = seq; } /* now we have all the data we need, unlock to avoid mac80211 issues */ mutex_unlock(&mvm->mutex); iwl_mvm_report_wakeup_reasons(mvm, vif, &status); keep = iwl_mvm_setup_connection_keep(mvm, vif, status_v6); iwl_free_resp(&cmd); return keep; out_free_resp: iwl_free_resp(&cmd); out_unlock: mutex_unlock(&mvm->mutex); return false; } static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm) { #ifdef CONFIG_IWLWIFI_DEBUGFS const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN]; u32 len = img->sec[IWL_UCODE_SECTION_DATA].len; u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset; if (!mvm->store_d3_resume_sram) return; if (!mvm->d3_resume_sram) { mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL); if (!mvm->d3_resume_sram) return; } iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len); #endif } static void iwl_mvm_d3_disconnect_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { /* skip the one we keep connection on */ if (data == vif) return; if (vif->type == NL80211_IFTYPE_STATION) ieee80211_resume_disconnect(vif); } static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test) { struct iwl_d3_iter_data resume_iter_data = { .mvm = mvm, }; struct ieee80211_vif *vif = NULL; int ret; enum iwl_d3_status d3_status; bool keep = false; mutex_lock(&mvm->mutex); /* get the BSS vif pointer again */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_iface_iterator, &resume_iter_data); if (WARN_ON(resume_iter_data.error || !resume_iter_data.vif)) goto out_unlock; vif = resume_iter_data.vif; ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test); if (ret) goto out_unlock; if (d3_status != IWL_D3_STATUS_ALIVE) { IWL_INFO(mvm, "Device was reset during suspend\n"); goto out_unlock; } /* query SRAM first in case we want event logging */ iwl_mvm_read_d3_sram(mvm); keep = iwl_mvm_query_wakeup_reasons(mvm, vif); #ifdef CONFIG_IWLWIFI_DEBUGFS if (keep) mvm->keep_vif = vif; #endif /* has unlocked the mutex, so skip that */ goto out; out_unlock: mutex_unlock(&mvm->mutex); out: if (!test) ieee80211_iterate_active_interfaces_rtnl(mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_disconnect_iter, keep ? vif : NULL); /* return 1 to reconfigure the device */ set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status); return 1; } int iwl_mvm_resume(struct ieee80211_hw *hw) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); return __iwl_mvm_resume(mvm, false); } void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled) { struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw); device_set_wakeup_enable(mvm->trans->dev, enabled); } #ifdef CONFIG_IWLWIFI_DEBUGFS static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file) { struct iwl_mvm *mvm = inode->i_private; int err; if (mvm->d3_test_active) return -EBUSY; file->private_data = inode->i_private; ieee80211_stop_queues(mvm->hw); synchronize_net(); /* start pseudo D3 */ rtnl_lock(); err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true); rtnl_unlock(); if (err > 0) err = -EINVAL; if (err) { ieee80211_wake_queues(mvm->hw); return err; } mvm->d3_test_active = true; mvm->keep_vif = NULL; return 0; } static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct iwl_mvm *mvm = file->private_data; u32 pme_asserted; while (true) { /* read pme_ptr if available */ if (mvm->d3_test_pme_ptr) { pme_asserted = iwl_trans_read_mem32(mvm->trans, mvm->d3_test_pme_ptr); if (pme_asserted) break; } if (msleep_interruptible(100)) break; } return 0; } static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac, struct ieee80211_vif *vif) { /* skip the one we keep connection on */ if (_data == vif) return; if (vif->type == NL80211_IFTYPE_STATION) ieee80211_connection_loss(vif); } static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file) { struct iwl_mvm *mvm = inode->i_private; int remaining_time = 10; mvm->d3_test_active = false; __iwl_mvm_resume(mvm, true); iwl_abort_notification_waits(&mvm->notif_wait); ieee80211_restart_hw(mvm->hw); /* wait for restart and disconnect all interfaces */ while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) && remaining_time > 0) { remaining_time--; msleep(1000); } if (remaining_time == 0) IWL_ERR(mvm, "Timed out waiting for HW restart to finish!\n"); ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_d3_test_disconn_work_iter, mvm->keep_vif); ieee80211_wake_queues(mvm->hw); return 0; } const struct file_operations iwl_dbgfs_d3_test_ops = { .llseek = no_llseek, .open = iwl_mvm_d3_test_open, .read = iwl_mvm_d3_test_read, .release = iwl_mvm_d3_test_release, }; #endif
freedesktop-unofficial-mirror/tegra__linux
drivers/net/wireless/iwlwifi/mvm/d3.c
C
gpl-2.0
53,080
<div class="row"> <div class="col-sm-12"> <div class="row"> <div class="text-center"> <h1 class="tada animated font-xl "> <span style="position: relative;"> <i class="fa fa-play fa-rotate-90 fa-border fa-4x"></i> <span> <?php if($updated): ?> <b style="position:absolute; right: -30px; top:-10" class="badge bg-color-green font-md"><i class="fa fa-check txt-color-black"></i> </b> <?php else: ?> <b style="position:absolute; right: -30px; top:-10" class="badge bg-color-red font-md"><i class="fa fa-refresh error"></i></b> <?php endif; ?> </span> </span> </h1> <?php if($updated): ?> <h2 class="font-xl"><strong>Great! Your FABtotum Personal Fabricator is up to date</strong></h2> <?php else: ?> <h2 class="font-xl title"><strong> New important software updates are now available</strong></h2> <button id="update" class="btn btn-lg bg-color-red txt-color-white">Update now!</button> <p class="lead semi-bold"> <small class="off-message hidden">Please don't turn off the printer until the operation is completed</small> </p> <button data-toggle="modal" data-backdrop="static" data-target="#modal" class="btn btn-xs bg-color-blue txt-color-white " style="">&nbsp;See what's new!</button> <?php endif; ?> </div> </div> <?php if(!$updated): ?> <div class="row"> <div class="col-sm-12"> <div class="text-center margin-top-10"> <div class="well mini"> <p class="text-left"> <span class="download-info">Downloading update files</span> <span class="pull-right"> <span class="percent"></span> </span> </p> <div class="progress"> <div class="progress progress-striped"> <div class="progress-bar download-progress bg-color-blue" role="progressbar" style="width: 0%"></div> </div> </div> </div> <button id="cancel" class="btn btn-lg bg-color-red txt-color-white"> Cancel</button> </div> </div> </div> <?php endif; ?> </div> </div> <?php if(!$updated): ?> <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 class="modal-title" id="myModalLabel">FABUI v.<?php echo $remote_version; ?> Changelog</h4> </div> <div class="modal-body no-padding"> <?php echo fabui_changelog($remote_version) ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">OK</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <?php endif; ?>
FABtotum/FAB-UI
fabui/application/modules/updates/views/index/index.php
PHP
gpl-2.0
2,891
/*! * Font Awesome 3.2.0 * the iconic font designed for Bootstrap * ------------------------------------------------------------------------------ * The full suite of pictographic icons, examples, and documentation can be * found at http://fontawesome.io. Stay up to date on Twitter at * http://twitter.com/fontawesome. * * License * ------------------------------------------------------------------------------ * - The Font Awesome font is licensed under SIL OFL 1.1 - * http://scripts.sil.org/OFL * - Font Awesome CSS, LESS, and SASS files are licensed under MIT License - * http://opensource.org/licenses/mit-license.html * - Font Awesome documentation licensed under CC BY 3.0 - * http://creativecommons.org/licenses/by/3.0/ * - Attribution is no longer required in Font Awesome 3.0, but much appreciated: * "Font Awesome by Dave Gandy - http://fontawesome.io" * * Author - Dave Gandy * ------------------------------------------------------------------------------ * Email: [email protected] * Twitter: http://twitter.com/byscuits * Work: Lead Product Designer @ Kyruus - http://kyruus.com */ .icon-large{font-size:1.3333333333333333em;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;vertical-align:middle;} .nav [class^="icon-"],.nav [class*=" icon-"]{vertical-align:inherit;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;}.nav [class^="icon-"].icon-large,.nav [class*=" icon-"].icon-large{vertical-align:-25%;} .nav-pills [class^="icon-"].icon-large,.nav-tabs [class^="icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large{line-height:.75em;margin-top:-7px;padding-top:5px;margin-bottom:-5px;padding-bottom:4px;} .btn [class^="icon-"].pull-left,.btn [class*=" icon-"].pull-left,.btn [class^="icon-"].pull-right,.btn [class*=" icon-"].pull-right{vertical-align:inherit;} .btn [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large{margin-top:-0.5em;} a [class^="icon-"],a [class*=" icon-"]{cursor:pointer;} .icon-glass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf000;');} .icon-music{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf001;');} .icon-search{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf002;');} .icon-envelope-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf003;');} .icon-heart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf004;');} .icon-star{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf005;');} .icon-star-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf006;');} .icon-user{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf007;');} .icon-film{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf008;');} .icon-th-large{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf009;');} .icon-th{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf00a;');} .icon-th-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf00b;');} .icon-ok{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf00c;');} .icon-remove{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf00d;');} .icon-zoom-in{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf00e;');} .icon-zoom-out{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf010;');} .icon-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf011;');} .icon-power-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf011;');} .icon-signal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf012;');} .icon-cog{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf013;');} .icon-trash{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf014;');} .icon-home{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf015;');} .icon-file-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf016;');} .icon-time{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf017;');} .icon-road{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf018;');} .icon-download-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf019;');} .icon-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01a;');} .icon-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01b;');} .icon-inbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01c;');} .icon-play-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01d;');} .icon-repeat{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01e;');} .icon-rotate-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf01e;');} .icon-refresh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf021;');} .icon-list-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf022;');} .icon-lock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf023;');} .icon-flag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf024;');} .icon-headphones{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf025;');} .icon-volume-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf026;');} .icon-volume-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf027;');} .icon-volume-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf028;');} .icon-qrcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf029;');} .icon-barcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02a;');} .icon-tag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02b;');} .icon-tags{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02c;');} .icon-book{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02d;');} .icon-bookmark{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02e;');} .icon-print{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf02f;');} .icon-camera{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf030;');} .icon-font{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf031;');} .icon-bold{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf032;');} .icon-italic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf033;');} .icon-text-height{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf034;');} .icon-text-width{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf035;');} .icon-align-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf036;');} .icon-align-center{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf037;');} .icon-align-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf038;');} .icon-align-justify{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf039;');} .icon-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf03a;');} .icon-indent-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf03b;');} .icon-indent-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf03c;');} .icon-facetime-video{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf03d;');} .icon-picture{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf03e;');} .icon-pencil{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf040;');} .icon-map-marker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf041;');} .icon-adjust{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf042;');} .icon-tint{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf043;');} .icon-edit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf044;');} .icon-share{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf045;');} .icon-check{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf046;');} .icon-move{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf047;');} .icon-step-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf048;');} .icon-fast-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf049;');} .icon-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf04a;');} .icon-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf04b;');} .icon-pause{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf04c;');} .icon-stop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf04d;');} .icon-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf04e;');} .icon-fast-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf050;');} .icon-step-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf051;');} .icon-eject{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf052;');} .icon-chevron-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf053;');} .icon-chevron-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf054;');} .icon-plus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf055;');} .icon-minus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf056;');} .icon-remove-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf057;');} .icon-ok-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf058;');} .icon-question-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf059;');} .icon-info-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf05a;');} .icon-screenshot{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf05b;');} .icon-remove-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf05c;');} .icon-ok-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf05d;');} .icon-ban-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf05e;');} .icon-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf060;');} .icon-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf061;');} .icon-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf062;');} .icon-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf063;');} .icon-share-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf064;');} .icon-mail-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf064;');} .icon-resize-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf065;');} .icon-resize-small{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf066;');} .icon-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf067;');} .icon-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf068;');} .icon-asterisk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf069;');} .icon-exclamation-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf06a;');} .icon-gift{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf06b;');} .icon-leaf{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf06c;');} .icon-fire{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf06d;');} .icon-eye-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf06e;');} .icon-eye-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf070;');} .icon-warning-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf071;');} .icon-plane{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf072;');} .icon-calendar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf073;');} .icon-random{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf074;');} .icon-comment{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf075;');} .icon-magnet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf076;');} .icon-chevron-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf077;');} .icon-chevron-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf078;');} .icon-retweet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf079;');} .icon-shopping-cart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf07a;');} .icon-folder-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf07b;');} .icon-folder-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf07c;');} .icon-resize-vertical{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf07d;');} .icon-resize-horizontal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf07e;');} .icon-bar-chart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf080;');} .icon-twitter-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf081;');} .icon-facebook-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf082;');} .icon-camera-retro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf083;');} .icon-key{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf084;');} .icon-cogs{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf085;');} .icon-comments{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf086;');} .icon-thumbs-up-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf087;');} .icon-thumbs-down-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf088;');} .icon-star-half{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf089;');} .icon-heart-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf08a;');} .icon-signout{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf08b;');} .icon-linkedin-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf08c;');} .icon-pushpin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf08d;');} .icon-external-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf08e;');} .icon-signin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf090;');} .icon-trophy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf091;');} .icon-github-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf092;');} .icon-upload-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf093;');} .icon-lemon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf094;');} .icon-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf095;');} .icon-check-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf096;');} .icon-unchecked{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf096;');} .icon-bookmark-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf097;');} .icon-phone-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf098;');} .icon-twitter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf099;');} .icon-facebook{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf09a;');} .icon-github{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf09b;');} .icon-unlock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf09c;');} .icon-credit-card{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf09d;');} .icon-rss{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf09e;');} .icon-hdd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a0;');} .icon-bullhorn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a1;');} .icon-bell{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a2;');} .icon-certificate{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a3;');} .icon-hand-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a4;');} .icon-hand-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a5;');} .icon-hand-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a6;');} .icon-hand-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a7;');} .icon-circle-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a8;');} .icon-circle-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0a9;');} .icon-circle-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0aa;');} .icon-circle-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ab;');} .icon-globe{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ac;');} .icon-wrench{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ad;');} .icon-tasks{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ae;');} .icon-filter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0b0;');} .icon-briefcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0b1;');} .icon-fullscreen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0b2;');} .icon-group{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c0;');} .icon-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c1;');} .icon-cloud{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c2;');} .icon-beaker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c3;');} .icon-cut{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c4;');} .icon-copy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c5;');} .icon-paper-clip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c6;');} .icon-paperclip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c6;');} .icon-save{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c7;');} .icon-sign-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c8;');} .icon-reorder{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0c9;');} .icon-list-ul{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ca;');} .icon-list-ol{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0cb;');} .icon-strikethrough{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0cc;');} .icon-underline{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0cd;');} .icon-table{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ce;');} .icon-magic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d0;');} .icon-truck{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d1;');} .icon-pinterest{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d2;');} .icon-pinterest-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d3;');} .icon-google-plus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d4;');} .icon-google-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d5;');} .icon-money{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d6;');} .icon-caret-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d7;');} .icon-caret-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d8;');} .icon-caret-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0d9;');} .icon-caret-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0da;');} .icon-columns{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0db;');} .icon-sort{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0dc;');} .icon-sort-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0dd;');} .icon-sort-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0de;');} .icon-envelope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e0;');} .icon-linkedin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e1;');} .icon-undo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e2;');} .icon-rotate-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e2;');} .icon-legal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e3;');} .icon-dashboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e4;');} .icon-comment-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e5;');} .icon-comments-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e6;');} .icon-bolt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e7;');} .icon-sitemap{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e8;');} .icon-umbrella{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0e9;');} .icon-paste{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ea;');} .icon-lightbulb{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0eb;');} .icon-exchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ec;');} .icon-cloud-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ed;');} .icon-cloud-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0ee;');} .icon-user-md{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f0;');} .icon-stethoscope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f1;');} .icon-suitcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f2;');} .icon-bell-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f3;');} .icon-coffee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f4;');} .icon-food{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f5;');} .icon-file-text-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f6;');} .icon-building{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f7;');} .icon-hospital{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f8;');} .icon-ambulance{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0f9;');} .icon-medkit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0fa;');} .icon-fighter-jet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0fb;');} .icon-beer{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0fc;');} .icon-h-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0fd;');} .icon-plus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf0fe;');} .icon-double-angle-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf100;');} .icon-double-angle-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf101;');} .icon-double-angle-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf102;');} .icon-double-angle-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf103;');} .icon-angle-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf104;');} .icon-angle-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf105;');} .icon-angle-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf106;');} .icon-angle-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf107;');} .icon-desktop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf108;');} .icon-laptop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf109;');} .icon-tablet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf10a;');} .icon-mobile-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf10b;');} .icon-circle-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf10c;');} .icon-quote-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf10d;');} .icon-quote-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf10e;');} .icon-spinner{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf110;');} .icon-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf111;');} .icon-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf112;');} .icon-mail-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf112;');} .icon-github-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf113;');} .icon-folder-close-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf114;');} .icon-folder-open-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf115;');} .icon-expand-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf116;');} .icon-collapse-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf117;');} .icon-smile{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf118;');} .icon-frown{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf119;');} .icon-meh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf11a;');} .icon-gamepad{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf11b;');} .icon-keyboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf11c;');} .icon-flag-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf11d;');} .icon-flag-checkered{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf11e;');} .icon-terminal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf120;');} .icon-code{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf121;');} .icon-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf122;');} .icon-mail-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf122;');} .icon-star-half-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf123;');} .icon-star-half-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf123;');} .icon-location-arrow{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf124;');} .icon-crop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf125;');} .icon-code-fork{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf126;');} .icon-unlink{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf127;');} .icon-question{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf128;');} .icon-info{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf129;');} .icon-exclamation{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf12a;');} .icon-superscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf12b;');} .icon-subscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf12c;');} .icon-eraser{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf12d;');} .icon-puzzle-piece{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf12e;');} .icon-microphone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf130;');} .icon-microphone-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf131;');} .icon-shield{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf132;');} .icon-calendar-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf133;');} .icon-fire-extinguisher{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf134;');} .icon-rocket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf135;');} .icon-maxcdn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf136;');} .icon-chevron-sign-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf137;');} .icon-chevron-sign-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf138;');} .icon-chevron-sign-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf139;');} .icon-chevron-sign-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf13a;');} .icon-html5{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf13b;');} .icon-css3{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf13c;');} .icon-anchor{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf13d;');} .icon-unlock-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf13e;');} .icon-bullseye{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf140;');} .icon-ellipsis-horizontal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf141;');} .icon-ellipsis-vertical{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf142;');} .icon-rss-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf143;');} .icon-play-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf144;');} .icon-ticket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf145;');} .icon-minus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf146;');} .icon-check-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf147;');} .icon-level-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf148;');} .icon-level-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf149;');} .icon-check-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf14a;');} .icon-edit-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf14b;');} .icon-external-link-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf14c;');} .icon-share-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf14d;');} .icon-compass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf14e;');} .icon-collapse{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf150;');} .icon-collapse-top{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf151;');} .icon-expand{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf152;');} .icon-eur{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf153;');} .icon-euro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf153;');} .icon-gbp{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf154;');} .icon-usd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf155;');} .icon-dollar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf155;');} .icon-inr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf156;');} .icon-rupee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf156;');} .icon-jpy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf157;');} .icon-yen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf157;');} .icon-cny{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf158;');} .icon-renminbi{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf158;');} .icon-krw{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf159;');} .icon-won{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf159;');} .icon-btc{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15a;');} .icon-bitcoin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15a;');} .icon-file{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15b;');} .icon-file-text{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15c;');} .icon-sort-by-alphabet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15d;');} .icon-sort-by-alphabet-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf15e;');} .icon-sort-by-attributes{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf160;');} .icon-sort-by-attributes-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf161;');} .icon-sort-by-order{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf162;');} .icon-sort-by-order-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf163;');} .icon-thumbs-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf164;');} .icon-thumbs-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf165;');} .icon-youtube-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf166;');} .icon-youtube{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf167;');} .icon-xing{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf168;');} .icon-xing-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf169;');} .icon-youtube-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf16a;');} .icon-dropbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf16b;');} .icon-stackexchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf16c;');} .icon-instagram{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf16d;');} .icon-flickr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf16e;');} .icon-adn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf170;');} .icon-bitbucket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf171;');} .icon-bitbucket-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf172;');} .icon-tumblr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf173;');} .icon-tumblr-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf174;');} .icon-long-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf175;');} .icon-long-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf176;');} .icon-long-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf177;');} .icon-long-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf178;');} .icon-apple{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf179;');} .icon-windows{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf17a;');} .icon-android{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf17b;');} .icon-linux{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf17c;');} .icon-dribble{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf17d;');} .icon-skype{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf17e;');} .icon-foursquare{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf180;');} .icon-trello{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf181;');} .icon-female{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf182;');} .icon-male{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf183;');} .icon-gittip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf184;');} .icon-sun{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf185;');} .icon-moon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf186;');} .icon-archive{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf187;');} .icon-bug{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf188;');} .icon-vk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf189;');} .icon-weibo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf18a;');} .icon-renren{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '&#xf18b;');}
oniiru/html
sendy/css/font-awesome-ie7.min.css
CSS
gpl-2.0
38,749
include ../../Makerules OBJ=halftrace.o prepare_ref.o ray_lay.o ray_xyz.o refmod_all.o ref_time.o reftrace.o vrefmod.o %.o:%.f90 $(FC) -c $(FFLAGS) $< all: compile compile: $(OBJ) clean: @rm -f $(OBJ)
marcelobianchi/tomocode
SUBR/1D_TRACING/Makefile
Makefile
gpl-2.0
209
<h2 class="page-header"><a href="<?= $Page->Url ?>"><?= $Page->Title ?></a></h2> <?= $Page->Content ?>
sukovanej/Bundle
func/defaults/page_single.php
PHP
gpl-2.0
103
<div align="center"><a href="/onestop/metadata-manager">Metadata Manager Documentation Home</a></div> <hr> **Estimated Reading Time: 15 minutes** # Upstream Connecting via Kafka ## Table of Contents * [Integrating upstream application to the underlying Kafka system](#integrating-upstream-application-to-the-underlying-kafka-system) * [Features](#features) * [Apache NiFi](#apache-nifi) * [Nifi as a Producer](#nifi-as-a-producer) * [Nifi as bidirectional Data Flows](#nifi-as-bidirectional-data-flows) * [kafka producer](#kafka-producer) * [Kafka connects](#kafka-connects) ## Integrating upstream application to the underlying Kafka system Metadata can be published into the OneStop system in two different ways, using Registry application [REST API](onestop-metadata-loading) or directly integrating upstream applications to the underline OneStop kafka cluster. This guide will take a look at some approaches for integrating upstream applications and Kafka, and look at some examples regarding the tools Kafka supports. Before we dive in, it's worth mentioning the single common data format, Apache Avro, which OneStop application is using for ensuring all data sources and integration points comply to it. Apache Avro is an [open source data serialization format](http://avro.apache.org/docs/1.9.1/). It relies on schema that define fields and their type. Avro also supports schema evolution. See [Avro schema project](https://github.com/cedardevs/schemas/tree/master/schemas-core) for details. ## Features - [Using Apache NiFi](#apache-niFi) - [Using kafka producer](#kafka-producer) - [Using Kafka connects](#kafka-connects) ### Apache NiFi NiFi is a highly scalable and user friendly UI based system that provides support for data collection and processing. In this case, Nifi can act as a source and sink to bring data to and from Kafka, which helps in automating the flow of data between systems in a Reliable, efficient, and manageable way. NiFi is able to support multiple versions of the Kafka client in a single NiFi instance. The Apache NiFi 1.10.0 release contains the following Kafka processors: - ConsumeKafka & PublishKafka using the 0.9 client - ConsumeKafka_1_0 & PublishKafka_1_0 using the 1.0 client - ConsumeKafka_2_0 & PublishKafka_2_0 using the 2.0 client Kafka does not necessarily provide backward compatibility between versions, so use kafka processors that is compatible with the OneStop kafka broker version. See [Apache NiFi website](https://nifi.apache.org/) page for details. #### Nifi as a Producer A simple use case of NiFi is to act as a Kafka producer, which can bring data from sources directly to a NiFi instance, which can then deliver data to the appropriate Kafka topic. Each instance of PublishKafka could have concurrent tasks executing and each of this tasks publishes messages independently. Here is the NiFi template with two processors and controller services configuration: ![sample kafka publishing flow](sampleCode/nifiKafkaFlow.png) The above example uses GenerateFlowFile processor to create FlowFiles of random data and PublishKafkaRecord processor with the Confluent Schema Registry to publish records to kafka. Sample Nifi template [download the sample nifi template](sampleCode/nifi-kafkaPublishing-template.xml). #### Nifi as bidirectional Data Flows Additional and more complex use case is combining tools such as Kafka, and kafka stream processing platform with Nifi to create a self-adjusting data flow. Kafka Stream is a lightweight library for creating stream processing applications. In this case, NiFi brings data to Kafka which makes it available to a stream processing platform with the results being written back to a different Kafka topic for downstream consumers. ### kafka producer kafka producer uses a Kafka producer API to write a producer that can be used to published record directly to kafka broker. see [kafka producer Confluent docs](https://docs.confluent.io/current/clients/producer.html) page for details. Let's look at a simple Kafka producer implementation using java. To create a Kafka producer, you need to pass a list of bootstrap servers/Kafka brokers and also specify a client.id that uniquely identifies this Producer client. you will need to specify a Key_serializer and a value_serializer, which Kafka will use to encode the message id as a Kafka record key, and the message body as the Kafka record value. Import the Kafka packages and define a constant for the producer to connect to the Kafka broker. ```java import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; public class KafkaProducerTest { private final static String TOPIC = "test-topic"; private final static String BOOTSTRAP_SERVERS = "localhost:9092"; private final static String SCHEMA_REGISTRY_URL = "localhost:8081"; private final static String CLIENT_ID = "test-client"; private final static String COMPRESSION_TYPE = "zstd"; private static Producer<Long, String> createProducer() { props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, SCHEMA_REGISTRY_URL); props.put(ProducerConfig.CLIENT_ID_CONFIG, CLIENT_ID); props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, COMPRESSION_TYPE); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.name); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.name); return new KafkaProducer<>(props); } } ``` The constant BOOTSTRAP_SERVERS_CONFIG is set to `http://localhost:9092` as default which also can be a comma separated list that the Producer uses to establish an initial connection to the Kafka cluster. The CLIENT_ID_CONFIG value is an id to pass to the server when making requests so the server can track the source of requests. The KEY_SERIALIZER_CLASS_CONFIG value is a Kafka Serializer class for Kafka record keys that implements the Kafka Serializer interface. Notice that we set this to StringSerializer as the message ids type. The VALUE_SERIALIZER_CLASS_CONFIG value is a Kafka Serializer class for Kafka record values that implements the Kafka Serializer interface. Notice that we set this to AbstractKafkaAvroSerDeConfig as the message body in OneStop is in Avro format. Import an Avro schema packages and changing an incoming message to Avro format. ```java import org.cedar.schemas.avro.psi.Input; import org.cedar.schemas.avro.psi.Method; import org.cedar.schemas.avro.psi.OperationType; import org.cedar.schemas.avro.psi.RecordType; public class KafkaProducerTest { ... private static Input buildInputTopicMessage(Map info) { Input.Builder builder = Input.newBuilder(); builder.setType(RecordType.collection); builder.setMethod(Method.PUT); builder.setContent(String.valueOf(info)); builder.setContentType(CONTENT_TYPE); builder.setSource(SOURCE); builder.setOperation(OperationType.NO_OP); return builder.build(); } } ``` The builder is setting the require fields which is define here in the [Input avro schema definition](https://github.com/cedardevs/schemas/blob/master/schemas-core/src/main/resources/avro/psi/input.avsc). see [sample kafka producer java code](sampleCode/kafkaSampleTest.java) file for detail. ### Kafka connects Kafka connect, which includes source and sink, can also be used to published data from upstream source into kafka broker. see [kafka connect Confluent page](https://docs.confluent.io/current/connect/index.html) for more details. <hr> <div align="center"><a href="#">Top of Page</a></div>
cedardevs/onestop
docs/metadata-manager/v3/upstream-kafka-connect.md
Markdown
gpl-2.0
8,041
<? session_start(); session_destroy(); header("Location: ../index.html"); ?>
EverywhereHouseControl/ServerBackEnd
LoginPro/php/salir.php
PHP
gpl-2.0
82
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace XORCISMModel { using System; using System.Collections.Generic; public partial class LIBRARYREFERENCE { public int LibraryReferenceID { get; set; } } }
athiasjerome/XORCISM
SOURCES/XORCISMModel/LIBRARYREFERENCE.cs
C#
gpl-2.0
618
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/jquery.jscrollpane.custom.css" /> <link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/bookblock.css" /> <link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/custom.css" /> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/modernizr.custom.79639.js"></script> <div id="container" class="container"> <div class="menu-panel"> <h3>Table of Contents</h3> <ul id="menu-toc" class="menu-toc"> <?php print $menu_items; ?> </ul> </div> <div class="bb-custom-wrapper"> <div id="bb-bookblock" class="bb-bookblock"> <?php print $item_content; ?> </div> <nav> <span id="bb-nav-prev">&larr;</span> <span id="bb-nav-next">&rarr;</span> </nav> <span id="tblcontents" class="menu-button">Table of Contents</span> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.mousewheel.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.jscrollpane.min.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquerypp.custom.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.bookblock.js"></script> <script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/page.js"></script> <script> $(function() { Page.init(); }); </script>
aaronday/dxf
sites/all/modules/dxf_general/templates/foot_print_view.tpl.php
PHP
gpl-2.0
1,690
require 'rails_helper' def topics_controller_show_gen_perm_tests(expected, ctx) expected.each do |sym, status| params = "topic_id: #{sym}.id, slug: #{sym}.slug" if sym == :nonexist params = "topic_id: nonexist_topic_id" end ctx.instance_eval(" it 'returns #{status} for #{sym}' do begin xhr :get, :show, #{params} expect(response.status).to eq(#{status}) rescue Discourse::NotLoggedIn expect(302).to eq(#{status}) end end") end end describe TopicsController do context 'wordpress' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } let!(:p2) { Fabricate(:post, topic: topic, user:user )} it "returns the JSON in the format our wordpress plugin needs" do SiteSetting.external_system_avatars_enabled = false xhr :get, :wordpress, topic_id: topic.id, best: 3 expect(response).to be_success json = ::JSON.parse(response.body) expect(json).to be_present # The JSON has the data the wordpress plugin needs expect(json['id']).to eq(topic.id) expect(json['posts_count']).to eq(2) expect(json['filtered_posts_count']).to eq(2) # Posts expect(json['posts'].size).to eq(1) post = json['posts'][0] expect(post['id']).to eq(p2.id) expect(post['username']).to eq(user.username) expect(post['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}") expect(post['name']).to eq(user.name) expect(post['created_at']).to be_present expect(post['cooked']).to eq(p2.cooked) # Participants expect(json['participants'].size).to eq(1) participant = json['participants'][0] expect(participant['id']).to eq(user.id) expect(participant['username']).to eq(user.username) expect(participant['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}") end end context 'move_posts' do it 'needs you to be logged in' do expect { xhr :post, :move_posts, topic_id: 111, title: 'blah', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn) end describe 'moving to a new topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } it "raises an error without postIds" do expect { xhr :post, :move_posts, topic_id: topic.id, title: 'blah' }.to raise_error(ActionController::ParameterMissing) end it "raises an error when the user doesn't have permission to move the posts" do Guardian.any_instance.expects(:can_move_posts?).returns(false) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [1,2,3] expect(response).to be_forbidden end context 'success' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah', category_id: 123).returns(topic) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id], category_id: 123 end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end context 'failure' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah').returns(nil) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id] end it "returns JSON with a false success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(false) expect(result['url']).to be_blank end end end describe "moving replied posts" do let!(:user) { log_in(:moderator) } let!(:p1) { Fabricate(:post, user: user) } let!(:topic) { p1.topic } let!(:p2) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: p1.post_number ) } context 'success' do before do PostReply.create(post_id: p1.id, reply_id: p2.id) end it "moves the child posts too" do Topic.any_instance.expects(:move_posts).with(user, [p1.id, p2.id], title: 'blah').returns(topic) xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p1.id], reply_post_ids: [p1.id] end end end describe 'moving to an existing topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } let(:dest_topic) { Fabricate(:topic) } context 'success' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(topic) xhr :post, :move_posts, topic_id: topic.id, post_ids: [p2.id], destination_topic_id: dest_topic.id end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end context 'failure' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(nil) xhr :post, :move_posts, topic_id: topic.id, destination_topic_id: dest_topic.id, post_ids: [p2.id] end it "returns JSON with a false success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(false) expect(result['url']).to be_blank end end end end context "merge_topic" do it 'needs you to be logged in' do expect { xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345 }.to raise_error(Discourse::NotLoggedIn) end describe 'moving to a new topic' do let!(:user) { log_in(:moderator) } let(:p1) { Fabricate(:post, user: user) } let(:topic) { p1.topic } it "raises an error without destination_topic_id" do expect { xhr :post, :merge_topic, topic_id: topic.id }.to raise_error(ActionController::ParameterMissing) end it "raises an error when the user doesn't have permission to merge" do Guardian.any_instance.expects(:can_move_posts?).returns(false) xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345 expect(response).to be_forbidden end let(:dest_topic) { Fabricate(:topic) } context 'moves all the posts to the destination topic' do let(:p2) { Fabricate(:post, user: user) } before do Topic.any_instance.expects(:move_posts).with(user, [p1.id], destination_topic_id: dest_topic.id).returns(topic) xhr :post, :merge_topic, topic_id: topic.id, destination_topic_id: dest_topic.id end it "returns success" do expect(response).to be_success result = ::JSON.parse(response.body) expect(result['success']).to eq(true) expect(result['url']).to be_present end end end end context 'change_post_owners' do it 'needs you to be logged in' do expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn) end describe 'forbidden to moderators' do let!(:moderator) { log_in(:moderator) } it 'correctly denies' do xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] expect(response).to be_forbidden end end describe 'forbidden to trust_level_4s' do let!(:trust_level_4) { log_in(:trust_level_4) } it 'correctly denies' do xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] expect(response).to be_forbidden end end describe 'changing ownership' do let!(:editor) { log_in(:admin) } let(:topic) { Fabricate(:topic) } let(:user_a) { Fabricate(:user) } let(:p1) { Fabricate(:post, topic_id: topic.id) } let(:p2) { Fabricate(:post, topic_id: topic.id) } it "raises an error with a parameter missing" do expect { xhr :post, :change_post_owners, topic_id: 111, post_ids: [1,2,3] }.to raise_error(ActionController::ParameterMissing) expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a' }.to raise_error(ActionController::ParameterMissing) end it "calls PostOwnerChanger" do PostOwnerChanger.any_instance.expects(:change_owner!).returns(true) xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id] expect(response).to be_success end it "changes multiple posts" do # an integration test xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id, p2.id] p1.reload; p2.reload expect(p1.user).not_to eq(nil) expect(p1.user).to eq(p2.user) end it "works with deleted users" do deleted_user = Fabricate(:user) t2 = Fabricate(:topic, user: deleted_user) p3 = Fabricate(:post, topic_id: t2.id, user: deleted_user) deleted_user.save t2.save p3.save UserDestroyer.new(editor).destroy(deleted_user, { delete_posts: true, context: 'test', delete_as_spammer: true }) xhr :post, :change_post_owners, topic_id: t2.id, username: user_a.username_lower, post_ids: [p3.id] expect(response).to be_success t2.reload p3.reload expect(t2.deleted_at).to be_nil expect(p3.user).to eq(user_a) end end end context 'change_timestamps' do let(:params) { { topic_id: 1, timestamp: Time.zone.now } } it 'needs you to be logged in' do expect { xhr :put, :change_timestamps, params }.to raise_error(Discourse::NotLoggedIn) end [:moderator, :trust_level_4].each do |user| describe "forbidden to #{user}" do let!(user) { log_in(user) } it 'correctly denies' do xhr :put, :change_timestamps, params expect(response).to be_forbidden end end end describe 'changing timestamps' do let!(:admin) { log_in(:admin) } let(:old_timestamp) { Time.zone.now } let(:new_timestamp) { old_timestamp - 1.day } let!(:topic) { Fabricate(:topic, created_at: old_timestamp) } let!(:p1) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp) } let!(:p2) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp + 1.day) } it 'raises an error with a missing parameter' do expect { xhr :put, :change_timestamps, topic_id: 1 }.to raise_error(ActionController::ParameterMissing) end it 'should update the timestamps of selected posts' do xhr :put, :change_timestamps, topic_id: topic.id, timestamp: new_timestamp.to_f expect(topic.reload.created_at).to be_within_one_second_of(new_timestamp) expect(p1.reload.created_at).to be_within_one_second_of(new_timestamp) expect(p2.reload.created_at).to be_within_one_second_of(old_timestamp) end end end context 'clear_pin' do it 'needs you to be logged in' do expect { xhr :put, :clear_pin, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end context 'when logged in' do let(:topic) { Fabricate(:topic) } let!(:user) { log_in } it "fails when the user can't see the topic" do Guardian.any_instance.expects(:can_see?).with(topic).returns(false) xhr :put, :clear_pin, topic_id: topic.id expect(response).not_to be_success end describe 'when the user can see the topic' do it "calls clear_pin_for if the user can see the topic" do Topic.any_instance.expects(:clear_pin_for).with(user).once xhr :put, :clear_pin, topic_id: topic.id end it "succeeds" do xhr :put, :clear_pin, topic_id: topic.id expect(response).to be_success end end end end context 'status' do it 'needs you to be logged in' do expect { xhr :put, :status, topic_id: 1, status: 'visible', enabled: true }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @user = log_in(:moderator) @topic = Fabricate(:topic, user: @user) end it "raises an exception if you can't change it" do Guardian.any_instance.expects(:can_moderate?).with(@topic).returns(false) xhr :put, :status, topic_id: @topic.id, status: 'visible', enabled: 'true' expect(response).to be_forbidden end it 'requires the status parameter' do expect { xhr :put, :status, topic_id: @topic.id, enabled: true }.to raise_error(ActionController::ParameterMissing) end it 'requires the enabled parameter' do expect { xhr :put, :status, topic_id: @topic.id, status: 'visible' }.to raise_error(ActionController::ParameterMissing) end it 'raises an error with a status not in the whitelist' do expect { xhr :put, :status, topic_id: @topic.id, status: 'title', enabled: 'true' }.to raise_error(Discourse::InvalidParameters) end it 'calls update_status on the forum topic with false' do Topic.any_instance.expects(:update_status).with('closed', false, @user, until: nil) xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'false' end it 'calls update_status on the forum topic with true' do Topic.any_instance.expects(:update_status).with('closed', true, @user, until: nil) xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'true' end end end context 'delete_timings' do it 'needs you to be logged in' do expect { xhr :delete, :destroy_timings, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end context 'when logged in' do before do @user = log_in @topic = Fabricate(:topic, user: @user) @topic_user = TopicUser.get(@topic, @topic.user) end it 'deletes the forum topic user record' do PostTiming.expects(:destroy_for).with(@user.id, [@topic.id]) xhr :delete, :destroy_timings, topic_id: @topic.id end end end describe 'mute/unmute' do it 'needs you to be logged in' do expect { xhr :put, :mute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn) end it 'needs you to be logged in' do expect { xhr :put, :unmute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) end end end describe 'recover' do it "won't allow us to recover a topic when we're not logged in" do expect { xhr :put, :recover, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do let(:topic) { Fabricate(:topic, user: log_in, deleted_at: Time.now, deleted_by: log_in) } describe 'without access' do it "raises an exception when the user doesn't have permission to delete the topic" do Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(false) xhr :put, :recover, topic_id: topic.id expect(response).to be_forbidden end end context 'with permission' do before do Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(true) end it 'succeeds' do PostDestroyer.any_instance.expects(:recover) xhr :put, :recover, topic_id: topic.id expect(response).to be_success end end end end describe 'delete' do it "won't allow us to delete a topic when we're not logged in" do expect { xhr :delete, :destroy, id: 1 }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do let(:topic) { Fabricate(:topic, user: log_in) } describe 'without access' do it "raises an exception when the user doesn't have permission to delete the topic" do Guardian.any_instance.expects(:can_delete?).with(topic).returns(false) xhr :delete, :destroy, id: topic.id expect(response).to be_forbidden end end describe 'with permission' do before do Guardian.any_instance.expects(:can_delete?).with(topic).returns(true) end it 'succeeds' do PostDestroyer.any_instance.expects(:destroy) xhr :delete, :destroy, id: topic.id expect(response).to be_success end end end end describe 'id_for_slug' do let(:topic) { Fabricate(:post).topic } it "returns JSON for the slug" do xhr :get, :id_for_slug, slug: topic.slug expect(response).to be_success json = ::JSON.parse(response.body) expect(json).to be_present expect(json['topic_id']).to eq(topic.id) expect(json['url']).to eq(topic.url) expect(json['slug']).to eq(topic.slug) end it "returns invalid access if the user can't see the topic" do Guardian.any_instance.expects(:can_see?).with(topic).returns(false) xhr :get, :id_for_slug, slug: topic.slug expect(response).not_to be_success end end describe 'show full render' do render_views it 'correctly renders canoicals' do topic = Fabricate(:post).topic get :show, topic_id: topic.id, slug: topic.slug expect(response).to be_success expect(css_select("link[rel=canonical]").length).to eq(1) end end describe 'show' do let(:topic) { Fabricate(:post).topic } let!(:p1) { Fabricate(:post, user: topic.user) } let!(:p2) { Fabricate(:post, user: topic.user) } it 'shows a topic correctly' do xhr :get, :show, topic_id: topic.id, slug: topic.slug expect(response).to be_success end it 'return 404 for an invalid page' do xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2 expect(response.code).to eq("404") end it 'can find a topic given a slug in the id param' do xhr :get, :show, id: topic.slug expect(response).to redirect_to(topic.relative_url) end it 'keeps the post_number parameter around when redirecting' do xhr :get, :show, id: topic.slug, post_number: 42 expect(response).to redirect_to(topic.relative_url + "/42") end it 'keeps the page around when redirecting' do xhr :get, :show, id: topic.slug, post_number: 42, page: 123 expect(response).to redirect_to(topic.relative_url + "/42?page=123") end it 'does not accept page params as an array' do xhr :get, :show, id: topic.slug, post_number: 42, page: [2] expect(response).to redirect_to("#{topic.relative_url}/42?page=1") end it 'returns 404 when an invalid slug is given and no id' do xhr :get, :show, id: 'nope-nope' expect(response.status).to eq(404) end it 'returns a 404 when slug and topic id do not match a topic' do xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up' expect(response.status).to eq(404) end context 'a topic with nil slug exists' do before do @nil_slug_topic = Fabricate(:topic) Topic.connection.execute("update topics set slug=null where id = #{@nil_slug_topic.id}") # can't find a way to set slug column to null using the model end it 'returns a 404 when slug and topic id do not match a topic' do xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up' expect(response.status).to eq(404) end end context 'permission errors' do let(:allowed_user) { Fabricate(:user) } let(:allowed_group) { Fabricate(:group) } let(:secure_category) { c = Fabricate(:category) c.permissions = [[allowed_group, :full]] c.save allowed_user.groups = [allowed_group] allowed_user.save c } let(:normal_topic) { Fabricate(:topic) } let(:secure_topic) { Fabricate(:topic, category: secure_category) } let(:private_topic) { Fabricate(:private_message_topic, user: allowed_user) } let(:deleted_topic) { Fabricate(:deleted_topic) } let(:deleted_secure_topic) { Fabricate(:topic, category: secure_category, deleted_at: 1.day.ago) } let(:deleted_private_topic) { Fabricate(:private_message_topic, user: allowed_user, deleted_at: 1.day.ago) } let(:nonexist_topic_id) { Topic.last.id + 10000 } context 'anonymous' do expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 302, :deleted_topic => 410, :deleted_secure_topic => 403, :deleted_private_topic => 302, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'anonymous with login required' do before do SiteSetting.login_required = true end expected = { :normal_topic => 302, :secure_topic => 302, :private_topic => 302, :deleted_topic => 302, :deleted_secure_topic => 302, :deleted_private_topic => 302, :nonexist => 302 } topics_controller_show_gen_perm_tests(expected, self) end context 'normal user' do before do log_in(:user) end expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 403, :deleted_topic => 410, :deleted_secure_topic => 403, :deleted_private_topic => 403, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'allowed user' do before do log_in_user(allowed_user) end expected = { :normal_topic => 200, :secure_topic => 200, :private_topic => 200, :deleted_topic => 410, :deleted_secure_topic => 410, :deleted_private_topic => 410, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'moderator' do before do log_in(:moderator) end expected = { :normal_topic => 200, :secure_topic => 403, :private_topic => 403, :deleted_topic => 200, :deleted_secure_topic => 403, :deleted_private_topic => 403, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end context 'admin' do before do log_in(:admin) end expected = { :normal_topic => 200, :secure_topic => 200, :private_topic => 200, :deleted_topic => 200, :deleted_secure_topic => 200, :deleted_private_topic => 200, :nonexist => 404 } topics_controller_show_gen_perm_tests(expected, self) end end it 'records a view' do expect { xhr :get, :show, topic_id: topic.id, slug: topic.slug }.to change(TopicViewItem, :count).by(1) end it 'records incoming links' do user = Fabricate(:user) get :show, topic_id: topic.id, slug: topic.slug, u: user.username expect(IncomingLink.count).to eq(1) end it 'records redirects' do @request.env['HTTP_REFERER'] = 'http://twitter.com' get :show, { id: topic.id } @request.env['HTTP_REFERER'] = nil get :show, topic_id: topic.id, slug: topic.slug link = IncomingLink.first expect(link.referer).to eq('http://twitter.com') end it 'tracks a visit for all html requests' do current_user = log_in(:coding_horror) TopicUser.expects(:track_visit!).with(topic.id, current_user.id) get :show, topic_id: topic.id, slug: topic.slug end context 'consider for a promotion' do let!(:user) { log_in(:coding_horror) } let(:promotion) do result = double Promotion.stubs(:new).with(user).returns(result) result end it "reviews the user for a promotion if they're new" do user.update_column(:trust_level, TrustLevel[0]) Promotion.any_instance.expects(:review) get :show, topic_id: topic.id, slug: topic.slug end end context 'filters' do it 'grabs first page when no filter is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19) xhr :get, :show, topic_id: topic.id, slug: topic.slug end it 'grabs first page when first page is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19) xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 1 end it 'grabs correct range when a page number is provided' do TopicView.any_instance.expects(:filter_posts_in_range).with(20, 39) xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2 end it 'delegates a post_number param to TopicView#filter_posts_near' do TopicView.any_instance.expects(:filter_posts_near).with(p2.post_number) xhr :get, :show, topic_id: topic.id, slug: topic.slug, post_number: p2.post_number end end context "when 'login required' site setting has been enabled" do before { SiteSetting.login_required = true } context 'and the user is logged in' do before { log_in(:coding_horror) } it 'shows the topic' do get :show, topic_id: topic.id, slug: topic.slug expect(response).to be_successful end end context 'and the user is not logged in' do let(:api_key) { topic.user.generate_api_key(topic.user) } it 'redirects to the login page' do get :show, topic_id: topic.id, slug: topic.slug expect(response).to redirect_to login_path end it 'shows the topic if valid api key is provided' do get :show, topic_id: topic.id, slug: topic.slug, api_key: api_key.key expect(response).to be_successful topic.reload # free test, only costs a reload expect(topic.views).to eq(1) end it 'returns 403 for an invalid key' do get :show, topic_id: topic.id, slug: topic.slug, api_key: "bad" expect(response.code.to_i).to be(403) end end end end describe '#feed' do let(:topic) { Fabricate(:post).topic } it 'renders rss of the topic' do get :feed, topic_id: topic.id, slug: 'foo', format: :rss expect(response).to be_success expect(response.content_type).to eq('application/rss+xml') end end describe 'update' do it "won't allow us to update a topic when we're not logged in" do expect { xhr :put, :update, topic_id: 1, slug: 'xyz' }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) Fabricate(:post, topic: @topic) end describe 'without permission' do it "raises an exception when the user doesn't have permission to update the topic" do Guardian.any_instance.expects(:can_edit?).with(@topic).returns(false) xhr :put, :update, topic_id: @topic.id, slug: @topic.title expect(response).to be_forbidden end end describe 'with permission' do before do Guardian.any_instance.expects(:can_edit?).with(@topic).returns(true) end it 'succeeds' do xhr :put, :update, topic_id: @topic.id, slug: @topic.title expect(response).to be_success expect(::JSON.parse(response.body)['basic_topic']).to be_present end it 'allows a change of title' do xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic' @topic.reload expect(@topic.title).to eq('This is a new title for the topic') end it 'triggers a change of category' do Topic.any_instance.expects(:change_category_to_id).with(123).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 123 end it 'allows to change category to "uncategorized"' do Topic.any_instance.expects(:change_category_to_id).with(0).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: "" end it "returns errors with invalid titles" do xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'asdf' expect(response).not_to be_success end it "returns errors when the rate limit is exceeded" do EditRateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60)) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic' expect(response).not_to be_success end it "returns errors with invalid categories" do Topic.any_instance.expects(:change_category_to_id).returns(false) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: -1 expect(response).not_to be_success end it "doesn't call the PostRevisor when there is no changes" do PostRevisor.any_instance.expects(:revise!).never xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: @topic.category_id expect(response).to be_success end context 'when topic is private' do before do @topic.archetype = Archetype.private_message @topic.category = nil @topic.save! end context 'when there are no changes' do it 'does not call the PostRevisor' do PostRevisor.any_instance.expects(:revise!).never xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: nil expect(response).to be_success end end end context "allow_uncategorized_topics is false" do before do SiteSetting.stubs(:allow_uncategorized_topics).returns(false) end it "can add a category to an uncategorized topic" do Topic.any_instance.expects(:change_category_to_id).with(456).returns(true) xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 456 expect(response).to be_success end end end end end describe 'invite' do describe "group invites" do it "works correctly" do group = Fabricate(:group) topic = Fabricate(:topic) _admin = log_in(:admin) xhr :post, :invite, topic_id: topic.id, email: '[email protected]', group_ids: "#{group.id}" expect(response).to be_success invite = Invite.find_by(email: '[email protected]') groups = invite.groups.to_a expect(groups.count).to eq(1) expect(groups[0].id).to eq(group.id) end end it "won't allow us to invite toa topic when we're not logged in" do expect { xhr :post, :invite, topic_id: 1, email: '[email protected]' }.to raise_error(Discourse::NotLoggedIn) end describe 'when logged in as group manager' do let(:group_manager) { log_in } let(:group) { Fabricate(:group).tap { |g| g.add_owner(group_manager) } } let(:private_category) { Fabricate(:private_category, group: group) } let(:group_private_topic) { Fabricate(:topic, category: private_category, user: group_manager) } let(:recipient) { '[email protected]' } it "should attach group to the invite" do xhr :post, :invite, topic_id: group_private_topic.id, user: recipient expect(response).to be_success expect(Invite.find_by(email: recipient).groups).to eq([group]) end end describe 'when logged in' do before do @topic = Fabricate(:topic, user: log_in) end it 'requires an email parameter' do expect { xhr :post, :invite, topic_id: @topic.id }.to raise_error(ActionController::ParameterMissing) end describe 'without permission' do it "raises an exception when the user doesn't have permission to invite to the topic" do xhr :post, :invite, topic_id: @topic.id, user: '[email protected]' expect(response).to be_forbidden end end describe 'with admin permission' do let!(:admin) do log_in :admin end it 'should work as expected' do xhr :post, :invite, topic_id: @topic.id, user: '[email protected]' expect(response).to be_success expect(::JSON.parse(response.body)).to eq({'success' => 'OK'}) expect(Invite.where(invited_by_id: admin.id).count).to eq(1) end it 'should fail on shoddy email' do xhr :post, :invite, topic_id: @topic.id, user: 'i_am_not_an_email' expect(response).not_to be_success expect(::JSON.parse(response.body)).to eq({'failed' => 'FAILED'}) end end end end describe 'autoclose' do it 'needs you to be logged in' do expect { xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false }.to raise_error(Discourse::NotLoggedIn) end it 'needs you to be an admin or mod' do log_in xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false expect(response).to be_forbidden end describe 'when logged in' do before do @admin = log_in(:admin) @topic = Fabricate(:topic, user: @admin) end it "can set a topic's auto close time and 'based on last post' property" do Topic.any_instance.expects(:set_auto_close).with("24", {by_user: @admin, timezone_offset: -240}) xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: '24', auto_close_based_on_last_post: true, timezone_offset: -240 json = ::JSON.parse(response.body) expect(json).to have_key('auto_close_at') expect(json).to have_key('auto_close_hours') end it "can remove a topic's auto close time" do Topic.any_instance.expects(:set_auto_close).with(nil, anything) xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: nil, auto_close_based_on_last_post: false, timezone_offset: -240 end it "will close a topic when the time expires" do topic = Fabricate(:topic) Timecop.freeze(20.hours.ago) do create_post(topic: topic, raw: "This is the body of my cool post in the topic, but it's a bit old now") end topic.save Jobs.expects(:enqueue_at).at_least_once xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 24, auto_close_based_on_last_post: true topic.reload expect(topic.closed).to eq(false) expect(topic.posts.last.raw).to match(/cool post/) Timecop.freeze(5.hours.from_now) do Jobs::CloseTopic.new.execute({topic_id: topic.id, user_id: @admin.id}) end topic.reload expect(topic.closed).to eq(true) expect(topic.posts.last.raw).to match(/automatically closed/) end it "will immediately close if the last post is old enough" do topic = Fabricate(:topic) Timecop.freeze(20.hours.ago) do create_post(topic: topic) end topic.save Topic.reset_highest(topic.id) topic.reload xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 10, auto_close_based_on_last_post: true topic.reload expect(topic.closed).to eq(true) expect(topic.posts.last.raw).to match(/after the last reply/) expect(topic.posts.last.raw).to match(/10 hours/) end end end describe 'make_banner' do it 'needs you to be a staff member' do log_in xhr :put, :make_banner, topic_id: 99 expect(response).to be_forbidden end describe 'when logged in' do it "changes the topic archetype to 'banner'" do topic = Fabricate(:topic, user: log_in(:admin)) Topic.any_instance.expects(:make_banner!) xhr :put, :make_banner, topic_id: topic.id expect(response).to be_success end end end describe 'remove_banner' do it 'needs you to be a staff member' do log_in xhr :put, :remove_banner, topic_id: 99 expect(response).to be_forbidden end describe 'when logged in' do it "resets the topic archetype" do topic = Fabricate(:topic, user: log_in(:admin)) Topic.any_instance.expects(:remove_banner!) xhr :put, :remove_banner, topic_id: topic.id expect(response).to be_success end end end describe "bulk" do it 'needs you to be logged in' do expect { xhr :put, :bulk }.to raise_error(Discourse::NotLoggedIn) end describe "when logged in" do let!(:user) { log_in } let(:operation) { {type: 'change_category', category_id: '1'} } let(:topic_ids) { [1,2,3] } it "requires a list of topic_ids or filter" do expect { xhr :put, :bulk, operation: operation }.to raise_error(ActionController::ParameterMissing) end it "requires an operation param" do expect { xhr :put, :bulk, topic_ids: topic_ids}.to raise_error(ActionController::ParameterMissing) end it "requires a type field for the operation param" do expect { xhr :put, :bulk, topic_ids: topic_ids, operation: {}}.to raise_error(ActionController::ParameterMissing) end it "delegates work to `TopicsBulkAction`" do topics_bulk_action = mock TopicsBulkAction.expects(:new).with(user, topic_ids, operation, group: nil).returns(topics_bulk_action) topics_bulk_action.expects(:perform!) xhr :put, :bulk, topic_ids: topic_ids, operation: operation end end end describe 'remove_bookmarks' do it "should remove bookmarks properly from non first post" do bookmark = PostActionType.types[:bookmark] user = log_in post = create_post post2 = create_post(topic_id: post.topic_id) PostAction.act(user, post2, bookmark) xhr :put, :bookmark, topic_id: post.topic_id expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(2) xhr :put, :remove_bookmarks, topic_id: post.topic_id expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(0) end end describe 'reset_new' do it 'needs you to be logged in' do expect { xhr :put, :reset_new }.to raise_error(Discourse::NotLoggedIn) end let(:user) { log_in(:user) } it "updates the `new_since` date" do old_date = 2.years.ago user.user_stat.update_column(:new_since, old_date) xhr :put, :reset_new user.reload expect(user.user_stat.new_since.to_date).not_to eq(old_date.to_date) end end describe "feature_stats" do it "works" do xhr :get, :feature_stats, category_id: 1 expect(response).to be_success json = JSON.parse(response.body) expect(json["pinned_in_category_count"]).to eq(0) expect(json["pinned_globally_count"]).to eq(0) expect(json["banner_count"]).to eq(0) end it "allows unlisted banner topic" do Fabricate(:topic, category_id: 1, archetype: Archetype.banner, visible: false) xhr :get, :feature_stats, category_id: 1 json = JSON.parse(response.body) expect(json["banner_count"]).to eq(1) end end describe "x-robots-tag" do it "is included for unlisted topics" do topic = Fabricate(:topic, visible: false) get :show, topic_id: topic.id, slug: topic.slug expect(response.headers['X-Robots-Tag']).to eq('noindex') end it "is not included for normal topics" do topic = Fabricate(:topic, visible: true) get :show, topic_id: topic.id, slug: topic.slug expect(response.headers['X-Robots-Tag']).to eq(nil) end end end
scossar/discourse-dev
spec/controllers/topics_controller_spec.rb
Ruby
gpl-2.0
40,999
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from subscriber.models import Consumer, ConsumerType, Recharge, TotalRecharge, ACL from product.models import Product from voice_records.models import VoiceRecord, VoiceReg from sms.models import SMSPayment # from local_lib.v3 import is_number, is_float from local_lib.v3 import is_number, is_float, is_bangladeshi_number, is_japanese_number, send_sms from transaction.models import Transaction, ProductsInTransaction, BuyerSellerAccount, dueTransaction from shop_inventory.models import Inventory, BuySellProfitInventoryIndividual, BuySellProfitInventory from transcriber_management.models import Transcriber, TranscriberInTranscription, FailedTranscription import datetime from django.db.models import Q from django.contrib.auth.models import User from django.contrib.sessions.backends.db import SessionStore from django.db.models import Count @csrf_exempt def login_page(request): return render(request, 'pages/login.html') @csrf_exempt def login_auth(request): postdata = request.POST print(postdata) if 'username' and 'password' in postdata: print(postdata['username']) login_username = postdata['username'] print(postdata['password']) if ACL.objects.filter(loginID=postdata['username'][-9:]).exists(): login_username = login_username[-9:] else: login_username = login_username user = authenticate(username=login_username, password=postdata['password']) if user is not None: if user.is_active: login(request, user) request.session['user'] = login_username if user.is_superuser: res = redirect('/admin') else: res = redirect('/') else: res = render(request, 'pages/login.html', {'wrong': True, 'text': 'The password is valid, but the account has been disabled!'}) else: res = render(request, 'pages/login.html', {'wrong': True, 'text': 'The username and password you have entered is not correct. Please retry'}) else: res = render(request, 'pages/login.html', {'wrong': False}) res['Access-Control-Allow-Origin'] = "*" res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept" res['Access-Control-Allow-Methods'] = "PUT, GET, POST, DELETE, OPTIONS" return res def logout_now(request): logout(request) return render(request, 'pages/login.html') @login_required(login_url='/login/') def home(request): transcriber_name = request.session['user'] print request.session['user'] if ACL.objects.filter(loginID=transcriber_name).exists(): login_user = ACL.objects.get(loginID=transcriber_name) print(login_user.loginUser.name) transcriber_name = login_user.loginUser.name if login_user.loginUser.type.type_name == 'Distributor': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'SR': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'Seller': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') elif login_user.loginUser.type.type_name == 'Buyer': if login_user.loginUser.number_of_child == 'CHANGED !!!': return render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name}) else: return redirect('/change_password/') else: number_of_reg_calls = VoiceReg.objects.filter().count() number_of_transaction_calls = VoiceRecord.objects.filter().count() total = number_of_reg_calls + number_of_transaction_calls if total > 0: reg_call_percentage = (number_of_reg_calls / float(total)) * 100 transaction_call_percentage = (number_of_transaction_calls / float(total)) * 100 else: transaction_call_percentage = 0 reg_call_percentage = 0 today_month = datetime.date.today().month today_year = datetime.date.today().year count = 1 data_2 = '' data_3 = '' data_4 = '' data_5 = '' data_6 = '' max = 0 max_table_2 = 0 total_sell = VoiceRecord.objects.filter(purpose='sell').count() total_buy = VoiceRecord.objects.filter(purpose='buy').count() total_money_transaction = SMSPayment.objects.filter().count() total_for_chart2 = number_of_reg_calls + number_of_transaction_calls if total_for_chart2 > 0: sell_percentage = (total_sell / float(total_for_chart2)) * 100 buy_percentage = (total_buy / float(total_for_chart2)) * 100 money_transaction_percentage = (total_money_transaction / float(total_for_chart2)) * 100 else: sell_percentage = 0 buy_percentage = 0 money_transaction_percentage = 0 while count < 32: total_call_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() total_reg_that_day = VoiceReg.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() if max < total_call_that_day: max = total_call_that_day + 2 if max < total_reg_that_day: max = total_reg_that_day + 2 data_2 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_call_that_day) data_3 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_reg_that_day) total_buy_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count, purpose='buy').count() total_sell_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count, purpose='sell').count() total_payment_that_day = SMSPayment.objects.filter(DateAdded__month=today_month, DateAdded__year=today_year, DateAdded__day=count).count() if max_table_2 < total_buy_that_day: max_table_2 = total_buy_that_day + 2 if max_table_2 < total_sell_that_day: max_table_2 = total_sell_that_day + 2 if max_table_2 < total_payment_that_day: max_table_2 = total_payment_that_day + 2 data_4 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_buy_that_day) data_5 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_sell_that_day) data_6 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_payment_that_day) count += 1 data_2 = data_2[:-1] data_3 = data_3[:-1] data_4 = data_4[:-1] data_5 = data_5[:-1] data_6 = data_6[:-1] number_of_transactions = Transaction.objects.filter().count() number_of_transactions_with_due = Transaction.objects.filter(total_due__gt=0).count() number_of_transactions_without_due = Transaction.objects.filter(total_due__lte=0).count() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) print(all_consumer_for_base.count) return render(request, 'pages/index.html', {'shop_list_base': all_shop_for_base, 'number_of_reg_calls': number_of_reg_calls, 'transcriber_name': transcriber_name, 'number_of_transaction_calls': number_of_transaction_calls, 'all_consumer_for_base' :all_consumer_for_base, 'reg_call_percentage': reg_call_percentage, 'transaction_call_percentage': transaction_call_percentage, 'data_2': data_2, 'data_3': data_3, 'data_4': data_4, 'data_5': data_5, 'data_6': data_6, 'max': max, 'number_of_transactions': number_of_transactions, 'number_of_transactions_with_due': number_of_transactions_with_due, 'number_of_transactions_without_due': number_of_transactions_without_due, 'max_table_2': max_table_2, 'total_sell': total_sell, 'total_buy': total_buy, 'total_money_transaction': total_money_transaction, 'sell_percentage': sell_percentage, 'buy_percentage': buy_percentage, 'money_transaction_percentage': money_transaction_percentage, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def translator_page(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/translator.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) # all report views are here @login_required(login_url='/login/') def report_monthly_shop(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id total_sell = 0 total_sell_due = 0 total_sell_paid = 0 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object): total_sell += month_sell.total_amount_of_transaction total_sell_due += month_sell.total_due total_sell_paid += month_sell.total_paid for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object): total_purchase += month_purchase.total_amount_of_transaction total_purchase_due += month_purchase.total_due total_purchase_paid += month_purchase.total_paid shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_monthly_shop.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'shop_id': shop_id, 'all_consumer_for_base' :all_consumer_for_base, 'total_sell': total_sell, 'transcriber_name': transcriber_name, 'total_sell_due': total_sell_due, 'total_sell_paid': total_sell_paid, 'bangla': bangla, 'total_purchase': total_purchase, 'total_purchase_due': total_purchase_due, 'total_purchase_paid': total_purchase_paid, 'all_user_for_base': all_user_for_base}) # report_monthly_shop_json @login_required(login_url='/login/') def report_monthly_shop_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': rank = 1 this_year = datetime.date.today().year # this_month = 1 this_day = 1 for this_month in range(1, 13, 1): count = 0 for this_day in range(1, 32, 1): for a_product in Product.objects.all(): product_price = 0 product_name = a_product.name total_sell = 0 total_due = 0 total_paid = 0 for this_day_sell_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=this_day): total_sell += this_day_sell_transaction.total_amount total_due += this_day_sell_transaction.total_due total_paid += this_day_sell_transaction.total_paid count += 1 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for this_day_purchase_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=this_day): total_purchase += this_day_purchase_transaction.total_amount total_purchase_due += this_day_purchase_transaction.total_due total_purchase_paid += this_day_purchase_transaction.total_paid count += 1 if count > 0: output += '["%s/%s/%s","%s","%s","%s","%s","%s","%s"] ,' % (this_day, this_month, this_year, total_sell, total_paid, total_due, total_purchase, total_purchase_paid, total_purchase_due) count = 0 # this_day += 1 # this_month = this_month + 1 if get_data['t'] == '2': for this_day_transaction in Transaction.objects.filter(Q(seller=shop_object) | Q(buyer=shop_object)): # start counting for this product id = this_day_transaction.pk date = this_day_transaction.DateAdded if this_day_transaction.seller == shop_object: with_trade = this_day_transaction.buyer trade_type = 'Sell' elif this_day_transaction.buyer == shop_object: with_trade = this_day_transaction.seller trade_type = 'Buy' number_of_items = ProductsInTransaction.objects.filter(TID=this_day_transaction).count() total_amount = this_day_transaction.total_amount total_paid = this_day_transaction.total_paid total_due = this_day_transaction.total_due output += '["%s","%s","%s","%s","%s","%s","%s","%s"] ,' % (id, date, with_trade, trade_type, number_of_items, total_amount, total_paid, total_due) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_sales_analysis(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() if 'ban' in get_data: bangla = True else: bangla = False transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_sales_analysis.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, 'bangla': bangla, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_sales_analysis_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit) rank += 1 if get_data['t'] == '2': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 previous_product_price = 0 change = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if count == 0: previous_product_price = product_in_this_transaction.price_per_unit product_price = product_in_this_transaction.price_per_unit change += abs(previous_product_price - product_price) count += 1 if count > 0: output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count, change/count) rank += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 8: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: if day == 1: output += '["%s","","","",""] ,' % 'Sunday' elif day == 2: output += '["%s","","","",""] ,' % 'Monday' elif day == 3: output += '["%s","","","",""] ,' % 'Tuesday' elif day == 4: output += '["%s","","","",""] ,' % 'Wednesday' elif day == 5: output += '["%s","","","",""] ,' % 'Thursday' elif day == 6: output += '["%s","","","",""] ,' % 'Friday' elif day == 7: output += '["%s","","","",""] ,' % 'Saturday' day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_payment(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'pages/report_payment.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'all_consumer_for_base' :all_consumer_for_base, 'buyer_account': buyer_account, 'transcriber_name': transcriber_name, 'seller_account': seller_account, 'shop_name': shop_name, 'bangla': bangla, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_due(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = SMSPayment.objects.filter(seller=shop_object) seller_account = SMSPayment.objects.filter(buyer=shop_object) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_due.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'buyer_account': buyer_account, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'seller_account': seller_account, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id if 'ban' in get_data: bangla = True else: bangla = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_profit.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'shop_id': shop_id, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': this_year = datetime.date.today().year this_month = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while this_month < 13: day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 if count > 0: if day_string: if this_month == 1: output += '["January","",""], ' elif this_month == 2: output += '["February","",""], ' elif this_month == 3: output += '["March","",""], ' elif this_month == 4: output += '["April","",""], ' elif this_month == 5: output += '["May","",""], ' elif this_month == 6: output += '["June","",""], ' elif this_month == 7: output += '["July","",""], ' elif this_month == 8: output += '["August","",""], ' elif this_month == 9: output += '["September","",""], ' elif this_month == 10: output += '["October","",""], ' elif this_month == 11: output += '["November","",""], ' elif this_month == 12: output += '["December","",""], ' day_string = False output += '["","%s","%s"] ,' % (product_name, product_profit) # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) this_month += 1 if get_data['t'] == '2': this_year = datetime.date.today().year this_month = 1 while this_month < 13: day = 1 while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 if count > 0: if day_string: output += '["%s/%s/%s","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s"] ,' % (product_name, product_profit) day += 1 this_month += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object, DateAdded__year=this_year): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") @login_required(login_url='/login/') def report_product(request): get_data = request.GET shop_name = get_data['shop'] if 'ban' in get_data: bangla = True else: bangla = False shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object)) selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_product.html', {'shop_list_base': all_shop_for_base, 'shop_inventory': shop_inventory, 'shop_name': shop_name, 'shop_id': shop_id, 'bangla': bangla, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'selected_products_buy': selected_products_buy, 'selected_products': selected_products, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_product_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') output = '{"data": [ ' if get_data['t'] == '1': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: # if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: # if a_product.bulk_to_retail_unit == 0: # count = count + product_in_this_transaction.quantity # product_price = product_price + product_in_this_transaction.price_per_unit # else: # count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit # product_price = product_price + product_in_this_transaction.price_per_unit # else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit * product_in_this_transaction.quantity if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '2': this_year = datetime.date.today().year this_month = datetime.date.today().month day = 1 while day < 32: day_string = True for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (product_name, count, a_product.bulk_wholesale_unit, float(product_price / count)) day += 1 if get_data['t'] == '3': this_year = datetime.date.today().year this_month = datetime.date.today().month for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) if get_data['t'] == '4': this_year = datetime.date.today().year this_month = datetime.date.today().month for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s","%s"] ,' % (product_name, count, a_product.retail_unit, float(product_price / count)) output = output[:-1] output += ']}' selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) return HttpResponse(output, content_type="text/plain") # paste the template name of the report_analytical instead of report_product here @login_required(login_url='/login/') def report_analytical(request): all_product = Product.objects.all() final_output = '' get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) shop_id = shop_object.id for product in all_product: print(product.name) if ProductsInTransaction.objects.filter(product=product).exists(): product_output = "[%s, " % product.name sold_amount = 0 for product_details in ProductsInTransaction.objects.filter(product=product): sold_amount = sold_amount + product_details.quantity product_output += str(sold_amount) final_output += product_output final_output += "] ," print(final_output) final_output = final_output[:-1] print(final_output) add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/reports_analytical.html', {'all_product': all_product, 'add_notification': add_notification, 'shop_list_base': all_shop_for_base, 'product_sell': final_output, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'shop_id': shop_id, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_analytical_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) if get_data['t'] == '1': all_product = Product.objects.all() final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \ '{ "id": "", "label": "Units", "pattern": "", "type": "number" } ], "rows": [ ' for product in all_product: print(product.name) if ProductsInTransaction.objects.filter(product=product).exists(): product_name = product.name sold_amount = 0 for transaction_id in Transaction.objects.filter(seller=shop_object): for product_details in ProductsInTransaction.objects.filter(product=product, TID=transaction_id): sold_amount = sold_amount + product_details.quantity final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product_name, sold_amount) final_output = final_output[:-1] print(final_output) if get_data['t'] == '2': all_product = BuySellProfitInventory.objects.filter(shop=shop_object) final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \ '{ "id": "", "label": "Profit", "pattern": "", "type": "number" } ], "rows": [ ' for product in all_product: final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product.product, product.profit) final_output = final_output[:-1] print(final_output) final_output += ']}' print(final_output) return HttpResponse(final_output, content_type="text/plain") # till this views created based on the list from mail @login_required(login_url='/login/') def report_recharge(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_recharge.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_callduration(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_callduration_graph.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) # not necessary @login_required(login_url='/login/') def report_transaction(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transaction.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_calltranscription(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transcription.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_usercall(request): shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_user_call_recharge.html', {'shop_list_base': all_shop_for_base, 'transcriber_name': transcriber_name, 'all_consumer_for_base' :all_consumer_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def transcription_page(request): print(request.POST) number_of_pending_calls = VoiceRecord.objects.filter(transcribed=False).count() number_of_pending_reg_calls = VoiceReg.objects.filter(completed=False).count() type_of_subscriber = ConsumerType.objects.all() number_of_fail_calls = VoiceRecord.objects.filter(with_error=True).count() number_of_completed_calls = VoiceRecord.objects.filter(with_error=False, transcribed=True).count() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] return render(request, 'pages/transcription.html', dict(pending_calls=number_of_pending_calls, types=type_of_subscriber, pending_calls_reg=number_of_pending_reg_calls, number_of_fail_calls=str(number_of_fail_calls), number_of_completed_calls=number_of_completed_calls, transcriber_name=transcriber_name, shop_list_base=all_shop_for_base,all_consumer_for_base=all_consumer_for_base, all_user_for_base=all_user_for_base)) # report views ends here @login_required(login_url='/login/') def add_subscriber_page(request): all_subscriber = Consumer.objects.all() type_of_subscriber = ConsumerType.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Consumer.objects.filter(id=delID).exists(): item_for_delete = Consumer.objects.get(id=delID) notification = 'Daily statement for the user : ' + item_for_delete.name + ' is sent successfully.' # item_for_delete.delete() sales_statement = '' purchase_statement = '' today_date = datetime.date.today() today_day = today_date.day today_month = today_date.month today_year = today_date.year # for selling sell_transactions = Transaction.objects.filter(seller=item_for_delete, DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year) total_sales = 0 total_due = 0 total_paid = 0 for sell_transaction in sell_transactions: total_sales += sell_transaction.total_amount total_paid += sell_transaction.total_paid total_due += sell_transaction.total_due if total_sales > 0: sales_statement = ' bikroy korechen mot: ' + str(total_sales) + ' takar. nogod peyechen : ' + \ str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.' buy_transactions = Transaction.objects.filter(buyer=item_for_delete, DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year) total_purchase = 0 total_due = 0 total_paid = 0 for buy_transaction in buy_transactions: total_purchase += buy_transaction.total_amount total_paid += buy_transaction.total_paid total_due += buy_transaction.total_due if total_purchase > 0: purchase_statement = ' kinechen mot: ' + str(total_purchase) + ' takar. Nogod diyechen : ' + \ str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.' final_text = 'Aj apni' + sales_statement + purchase_statement + ' Dhonnobad' if total_purchase > 0 or total_sales > 0: print(final_text) send_sms(final_text, item_for_delete.phone) else: notification = 'Item not found' return render(request, 'pages/add_subscriber.html', {'subscribers': all_subscriber, 'types': type_of_subscriber, 'add_notification': add_notification, 'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'notification':notification, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def add_product_page(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Product.objects.filter(id=delID).exists(): item_for_delete = Product.objects.get(id=delID) notification = 'The product : ' + item_for_delete.name + ' is deleted successfully.' item_for_delete.delete() else: notification = 'Item not found' return render(request, 'pages/add_product.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name,'notification': notification, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_transcriber_performance.html', {'all_product': all_product, 'add_notification': add_notification, 'transcriber_name': transcriber_name, 'all_consumer_for_base' :all_consumer_for_base, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance_json(request): final_output = '{"data": [ ' for transcriber in Transcriber.objects.all(): number_of_transcriptions = TranscriberInTranscription.objects.filter(name=transcriber).count() total_time_taken = 0 total_product_trancribed = 0 for transcriber_in_transaction in TranscriberInTranscription.objects.filter(name=transcriber): total_time_taken += float(transcriber_in_transaction.time_taken) total_product_trancribed += transcriber_in_transaction.number_of_products if number_of_transcriptions > 0: avg_time = total_time_taken / number_of_transcriptions avg_product = total_product_trancribed / number_of_transcriptions final_output += '["%s","%s","%s","%s","%s"] ,' % (transcriber.id, transcriber.name, number_of_transcriptions, avg_time, avg_product) final_output = final_output[:-1] final_output += ']}' return HttpResponse(final_output, content_type="text/plain") @login_required(login_url='/login/') def user_balance_recharge(request): post_data = request.POST notification = '' for all_consumers in Consumer.objects.all(): if Recharge.objects.filter(user=all_consumers).exists(): print('Already_Added') else: new_added = Recharge(user=all_consumers) new_added.save() if TotalRecharge.objects.filter(user=all_consumers).exists(): print('Already_Added') else: new_added = TotalRecharge(user=all_consumers) new_added.save() add_notification = False if 'user' in post_data and 'recharge_amount' in post_data: user_name = post_data['user'] user_object = Consumer.objects.get(name=user_name) if is_number(post_data['recharge_amount']) or is_float(post_data['recharge_amount']): new_recharge_added = Recharge(user=user_object, amount=float(post_data['recharge_amount'])) new_recharge_added.save() new_recharge_update = TotalRecharge.objects.get(user=user_object) new_recharge_update.amount += float(post_data['recharge_amount']) new_recharge_update.save() add_notification = True notification = 'Amount %s has been added to the number %s' %(post_data['recharge_amount'], user_object.phone) else: notification = 'Something went wrong. Please try again.' recharge_all = TotalRecharge.objects.all() today_date = datetime.date.today() today_day = today_date.day today_month = today_date.month today_year = today_date.year recharge_today = Recharge.objects.filter(DateAdded__day=today_day, DateAdded__month=today_month, DateAdded__year=today_year, amount__gt=0) all_product = Product.objects.all() shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'pages/report_user_call_recharge.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base' :all_consumer_for_base, 'shop_list_base': all_shop_for_base, 'recharge_all': recharge_all, 'transcriber_name': transcriber_name, 'recharge_today': recharge_today, 'all_user_for_base': all_user_for_base, 'notification': notification}) # views for printing @login_required(login_url='/login/') def report_monthly_shop_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) total_sell = 0 total_sell_due = 0 total_sell_paid = 0 total_purchase = 0 total_purchase_due = 0 total_purchase_paid = 0 for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object): total_sell += month_sell.total_amount_of_transaction total_sell_due += month_sell.total_due total_sell_paid += month_sell.total_paid for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object): total_purchase += month_purchase.total_amount_of_transaction total_purchase_due += month_purchase.total_due total_purchase_paid += month_purchase.total_paid shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'print/report_monthly_shop.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base' :all_consumer_for_base, 'total_sell': total_sell, 'transcriber_name': transcriber_name, 'total_sell_due': total_sell_due, 'total_sell_paid': total_sell_paid, 'bangla': bangla, 'total_purchase': total_purchase, 'total_purchase_due': total_purchase_due, 'total_purchase_paid': total_purchase_paid, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_due_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__gt=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__gt=0) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_due.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'buyer_account': buyer_account, 'all_consumer_for_base' :all_consumer_for_base, 'bangla': bangla, 'seller_account': seller_account, 'transcriber_name': transcriber_name, 'shop_name': shop_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_payment_print(request): get_data = request.GET if 'ban' in get_data: bangla = True else: bangla = False shop_name = get_data['shop'] shop_object = Consumer.objects.get(name=shop_name) sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0) buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0) shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0) seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_payment.html', {'shop_list_base': all_shop_for_base, 'sell_transaction_with_due': sell_transaction_with_due, 'buy_transaction_with_due': buy_transaction_with_due, 'all_consumer_for_base' :all_consumer_for_base, 'buyer_account': buyer_account, 'transcriber_name': transcriber_name, 'seller_account': seller_account, 'shop_name': shop_name, 'bangla': bangla, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_product_print(request): get_data = request.GET shop_name = get_data['shop'] if 'ban' in get_data: bangla = True else: bangla = False shop_object = Consumer.objects.get(name=shop_name) shop_inventory = Inventory.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object)) selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object)) all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_product.html', {'shop_list_base': all_shop_for_base, 'shop_inventory': shop_inventory, 'shop_name': shop_name, 'bangla': bangla, 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'selected_products_buy': selected_products_buy, 'selected_products': selected_products, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_sales_analysis_print(request): get_data = request.GET shop_name = get_data['shop'] shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) transcriber_name = request.session['user'] return render(request, 'print/report_sales_analysis.html', {'shop_list_base': all_shop_for_base, 'all_consumer_for_base' :all_consumer_for_base, 'shop_name': shop_name, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_profit_print(request): get_data = request.GET shop_name = get_data['shop'] shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_profit.html', {'shop_list_base': all_shop_for_base, 'shop_name': shop_name, 'all_consumer_for_base':all_consumer_for_base, 'transcriber_name': transcriber_name, 'all_user_for_base': all_user_for_base}) @login_required(login_url='/login/') def report_transcriber_performance_print(request): all_product = Product.objects.all() add_notification = False shop_consumer = ConsumerType.objects.get(type_name='Seller') all_shop_for_base = Consumer.objects.filter(type=shop_consumer) all_user_for_base = Consumer.objects.all() transcriber_name = request.session['user'] shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) return render(request, 'print/report_transcriber_performance.html', {'all_product': all_product, 'add_notification': add_notification, 'all_consumer_for_base':all_consumer_for_base, 'transcriber_name': transcriber_name, 'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base}) # SR section @login_required(login_url='/login/') def sr_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/SR/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransaction': allTransaction}) @login_required(login_url='/login/') def sr_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) return render(request, 'pages/SR/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'allBalance': allBalance}) @login_required(login_url='/login/') def sr_report_sales_analysis(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name post_data = request.POST print(post_data) shop_object = sr_object shop_name = shop_object.name shop_id = shop_object.id if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/SR/report_sales_analysis.html', {'shop_name': shop_name, # 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, # 'bangla': bangla, 'transcriber_name': transcriber_name, 'month': month, 'year': year}) @login_required(login_url='/login/') def sr_report_sales_analysis_json(request): get_data = request.GET shop_name = get_data['shop'] shop_object = Consumer.objects.get(id=shop_name) shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object) shop_consumer = ConsumerType.objects.get(type_name='Seller') this_year = get_data['year'] print(this_year) this_month = get_data['month'] output = '{"data": [ ' if get_data['t'] == '1': rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit) rank += 1 if get_data['t'] == '2': rank = 1 for a_product in Product.objects.all(): count = 0 # product_price = 0 previous_product_price = 0 change = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if count == 0: previous_product_price = product_in_this_transaction.price_per_unit product_price = product_in_this_transaction.price_per_unit change += abs(previous_product_price - product_price) count += 1 if count > 0: output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count, change/count) rank += 1 if get_data['t'] == '3': print(this_month) day = 1 # # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 32: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month, DateAdded__day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) if get_data['t'] == '4': day = 1 # output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year) while day < 8: day_string = True rank = 1 for a_product in Product.objects.all(): count = 0 product_price = 0 product_name = a_product.name for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day): # start counting for this product for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction): if product_in_this_transaction.product == a_product: if product_in_this_transaction.unit == a_product.bulk_wholesale_unit: if a_product.bulk_to_retail_unit == 0: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit else: count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit else: count = count + product_in_this_transaction.quantity product_price = product_price + product_in_this_transaction.price_per_unit if count > 0: if day_string: if day == 1: output += '["%s","","","",""] ,' % 'Sunday' elif day == 2: output += '["%s","","","",""] ,' % 'Monday' elif day == 3: output += '["%s","","","",""] ,' % 'Tuesday' elif day == 4: output += '["%s","","","",""] ,' % 'Wednesday' elif day == 5: output += '["%s","","","",""] ,' % 'Thursday' elif day == 6: output += '["%s","","","",""] ,' % 'Friday' elif day == 7: output += '["%s","","","",""] ,' % 'Saturday' day_string = False output += '["","%s","%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit, float(product_price / count)) rank += 1 day += 1 if get_data['t'] == '5': this_year = datetime.date.today().year day_string = True for a_product in Product.objects.all(): count = 0 product_profit = 0 product_name = a_product.name for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object): # start counting for this product if this_day_transaction.product == a_product: product_profit += this_day_transaction.profit count += 1 output += '["%s","%s"] ,' % (product_name, product_profit) output = output[:-1] output += ']}' return HttpResponse(output, content_type="text/plain") # Distributor Section @login_required(login_url='/login/') def add_sr_page(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name all_subscriber = ACL.objects.filter(distUser=dr_object) # type_of_subscriber = ConsumerType.objects.all() add_notification = False # shop_consumer = ConsumerType.objects.get(type_name='Seller') # all_shop_for_base = Consumer.objects.filter(type=shop_consumer) # all_user_for_base = Consumer.objects.all() # transcriber_name = request.session['user'] # shop_consumer2 = ConsumerType.objects.get(type_name='Buyer') # all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2) notification = '' if 'delete' in request.GET: get_data = request.GET add_notification = True delID = get_data['delete'] if Consumer.objects.filter(id=delID).exists(): item_for_delete = Consumer.objects.get(id=delID) notification = 'The Consumer : ' + item_for_delete.name + ' is deleted successfully.' item_for_delete.delete() else: notification = 'Item not found' return render(request, 'pages/Distributor/add_SR.html', {'subscribers': all_subscriber,'add_notification': add_notification, # 'shop_list_base': all_shop_for_base, # 'all_consumer_for_base' :all_consumer_for_base, 'transcriber_name': transcriber_name, 'notification': notification}) @login_required(login_url='/login/') def dr_monthly_report(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id all_subscriber = ACL.objects.filter(distUser=dr_object) post_data = request.POST print(post_data) if 'sr' in post_data: sr_object = Consumer.objects.get(id=post_data['sr']) allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name, 'hasReport': True, 'subscribers': all_subscriber, 'transcriber_id': transcriber_id, 'allTransaction': allTransaction}) else: # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name, 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'hasReport': False}) @login_required(login_url='/login/') def dr_due_report(request): sr_name = request.session['user'] dr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id all_subscriber = ACL.objects.filter(distUser=dr_object) post_data = request.POST if 'sr' in post_data: sr_object = Consumer.objects.get(id=post_data['sr']) allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'transcriber_id': transcriber_id, 'hasReport': True, 'subscribers': all_subscriber, 'allBalance': allBalance}) else: # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name, 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'hasReport': False}) @login_required(login_url='/login/') def dr_report_sales_analysis(request): dr_name = request.session['user'] dr_object = ACL.objects.get(loginID=dr_name).loginUser transcriber_name = dr_object.name transcriber_id = dr_object.id post_data = request.POST print(post_data) # shop_object = sr_object # all_subscriber = ACL.objects.filter(distUser=dr_object) hasReport = False if 'sr' in post_data: shop_id = post_data['sr'] shop_name = Consumer.objects.get(id=shop_id).name hasReport = True if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': shop_name, 'transcriber_id': transcriber_id, 'shop_id': shop_id, 'subscribers': all_subscriber, 'transcriber_name': transcriber_name, 'month': month, 'hasReport': hasReport, 'year': year}) else: return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': 'Not Selected', 'transcriber_id': transcriber_id, 'subscribers': all_subscriber, 'transcriber_name': transcriber_name, 'hasReport': hasReport}) # Shop Module @login_required(login_url='/login/') def shop_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object) return render(request, 'pages/Shop/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransactionIn': allTransactionIn, 'allTransaction': allTransaction}) @login_required(login_url='/login/') def shop_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) sell_transaction = Transaction.objects.filter(seller=sr_object) dueTransactions = dueTransaction.objects.filter(seller=sr_object) allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object) sell_transactionIn = Transaction.objects.filter(buyer=sr_object) dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object) return render(request, 'pages/Shop/report_due.html', {'transcriber_name': transcriber_name, 'sell_transaction': sell_transaction, 'dueTransactions': dueTransactions, 'allBalance': allBalance, 'sell_transactionIn': sell_transactionIn, 'dueTransactionsIn': dueTransactionsIn, 'allBalanceIn': allBalanceIn}) @login_required(login_url='/login/') def shop_report_sales_analysis(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name post_data = request.POST print(post_data) shop_object = sr_object shop_name = shop_object.name shop_id = shop_object.id if 'month' in post_data and 'year' in post_data: month = post_data['month'] year = post_data['year'] else: month = datetime.date.today().month year = datetime.date.today().year return render(request, 'pages/Shop/report_sales_analysis.html', {'shop_name': shop_name, # 'all_consumer_for_base' :all_consumer_for_base, 'shop_id': shop_id, # 'bangla': bangla, 'transcriber_name': transcriber_name, 'month': month, 'year': year}) # Consumer Module @login_required(login_url='/login/') def user_monthly_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name # allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object) allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object) return render(request, 'pages/Consumer/report_monthly.html', {'transcriber_name': transcriber_name, 'allTransactionIn': allTransactionIn}) @login_required(login_url='/login/') def user_due_report(request): sr_name = request.session['user'] sr_object = ACL.objects.get(loginID=sr_name).loginUser transcriber_name = sr_object.name # allBalance = BuyerSellerAccount.objects.filter(seller=sr_object) # sell_transaction = Transaction.objects.filter(seller=sr_object) # dueTransactions = dueTransaction.objects.filter(seller=sr_object) allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object) sell_transactionIn = Transaction.objects.filter(buyer=sr_object) dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object) return render(request, 'pages/Consumer/report_due.html', {'transcriber_name': transcriber_name, # 'sell_transaction': sell_transaction, # 'dueTransactions': dueTransactions, # 'allBalance': allBalance, 'sell_transactionIn': sell_transactionIn, 'dueTransactionsIn': dueTransactionsIn, 'allBalanceIn': allBalanceIn}) @login_required(login_url='/login/') def change_password(request): # user = request.session['user'] post_data = request.POST user_name = request.session['user'] user_object = ACL.objects.get(loginID=user_name).loginUser transcriber_name = user_object.name user = user_object.phone[-9:] wrong = False text = '' if 'csrfmiddlewaretoken' in post_data: if post_data['password'] == post_data['re-password']: if User.objects.filter(username=user).exists(): u = User.objects.get(username=user) u.set_password(post_data['password']) u.save() user_ID = user_object.id this_user = Consumer.objects.get(id=user_ID) this_user.number_of_child = 'CHANGED !!!' this_user.save() wrong = True text = 'Password is successfully changed' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = True text = 'Something Wrong' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = True text = 'Passwords do NOT match. Please try again' if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) else: wrong = False if user_object.type.type_name == 'Distributor': display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'SR': display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Seller': display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong, 'text': text}) elif user_object.type.type_name == 'Buyer': display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name, 'wrong': wrong}) return display
ShovanSarker/sense_v4_withLocal
template_manager/views.py
Python
gpl-2.0
113,348
<?php /** * Display single product reviews (comments) * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ global $woocommerce, $product; if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! comments_open() ) return; ?> <div id="reviews"> <div id="comments"> <h2><?php if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ( $count = $product->get_rating_count() ) ) printf( _n('%s review for %s', '%s reviews for %s', $count, 'woocommerce'), $count, get_the_title() ); else _e( 'Reviews', 'woocommerce' ); ?></h2> <?php if ( have_comments() ) : ?> <ol class="commentlist"> <?php wp_list_comments( apply_filters( 'woocommerce_product_review_list_args', array( 'callback' => 'woocommerce_comments' ) ) ); ?> </ol> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : echo '<nav class="woocommerce-pagination">'; paginate_comments_links( apply_filters( 'woocommerce_comment_pagination_args', array( 'prev_text' => '&larr;', 'next_text' => '&rarr;', 'type' => 'list', ) ) ); echo '</nav>'; endif; ?> <?php else : ?> <p class="woocommerce-noreviews"><?php _e( 'There are no reviews yet.', 'woocommerce' ); ?></p> <?php endif; ?> </div> <?php if ( get_option( 'woocommerce_review_rating_verification_required' ) === 'no' || wc_customer_bought_product( '', get_current_user_id(), $product->id ) ) : ?> <div id="review_form_wrapper"> <div id="review_form"> <?php $commenter = wp_get_current_commenter(); $comment_form = array( 'title_reply' => have_comments() ? __( 'Add a review', 'woocommerce' ) : __( 'Be the first to review', 'woocommerce' ) . ' &ldquo;' . get_the_title() . '&rdquo;', 'title_reply_to' => __( 'Leave a Reply to %s', 'woocommerce' ), 'comment_notes_before' => '', 'comment_notes_after' => '', 'fields' => array( 'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', 'woocommerce' ) . ' <span class="required">*</span></label> ' . '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>', 'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email', 'woocommerce' ) . ' <span class="required">*</span></label> ' . '<input id="email" name="email" type="text" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30" aria-required="true" /></p>', ), 'label_submit' => __( 'Submit', 'woocommerce' ), 'logged_in_as' => '', 'comment_field' => '' ); if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' ) { $comment_form['comment_field'] = '<p class="comment-form-rating"><label for="rating">' . __( 'Your Rating', 'woocommerce' ) .'</label><select name="rating" id="rating"> <option value="">' . __( 'Rate&hellip;', 'woocommerce' ) . '</option> <option value="5">' . __( 'Perfect', 'woocommerce' ) . '</option> <option value="4">' . __( 'Good', 'woocommerce' ) . '</option> <option value="3">' . __( 'Average', 'woocommerce' ) . '</option> <option value="2">' . __( 'Not that bad', 'woocommerce' ) . '</option> <option value="1">' . __( 'Very Poor', 'woocommerce' ) . '</option> </select></p>'; } $comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', 'woocommerce' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . wp_nonce_field( 'woocommerce-comment_rating', '_wpnonce', true, false ) . '</p>'; comment_form( apply_filters( 'woocommerce_product_review_comment_form_args', $comment_form ) ); ?> </div> </div> <?php else : ?> <p class="woocommerce-verification-required"><?php _e( 'Only logged in customers who have purchased this product may leave a review.', 'woocommerce' ); ?></p> <?php endif; ?> <div class="clear"></div> </div>
mickburgs/sjaaktramper
wp-content/plugins/woocommerce/templates/single-product-reviews.php
PHP
gpl-2.0
4,254
package com.atux.bean.consulta; import com.atux.comun.FilterBaseLocal; /** * Created by MATRIX-JAVA on 27/11/2014. */ public class UnidadFlt extends FilterBaseLocal { public static final String PICK = "PICK"; public UnidadFlt(String unidad) { this.unidad = unidad; } public UnidadFlt() { } private String unidad; private String coUnidad; public String getUnidad() { return unidad; } public void setUnidad(String unidad) { this.unidad = unidad; } public String getCoUnidad() { return coUnidad; } public void setCoUnidad(String coUnidad) { this.coUnidad = coUnidad; } }
AlanGuerraQuispe/SisAtuxVenta
atux-domain/src/main/java/com/atux/bean/consulta/UnidadFlt.java
Java
gpl-2.0
719
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Project WiSH</title> <style fprolloverstyle>A:hover {color: red; font-weight: bold} </style> </head> <body style="background-attachment: fixed"> <p align="center"> <A href="http://sourceforge.net"> <IMG src="http://sourceforge.net/sflogo.php?group_id=68802&amp;type=5" border="0" alt="SourceForge Logo"></A> <h1 align="center"><b>Linux X10 universal device driver</b></h1> <h2 align="center"><b>(aka Project WiSH)</b></h2> <ul> <li> <p align="left"><a href="http://wish.sourceforge.net/index1.html">x10dev (Version 1.X</a>) for <b>Kernel 2.4.X:</b>&nbsp; Linux driver for Kernel 2.4 supporting the CM11A, CM17A, SmartHome PowerLink Serial, and SmartHome PowerLink USB transceivers.</p></li> <li> <p align="left"><a href="http://wish.sourceforge.net/index2.html">x10dev-2 (Version 2.X</a>) for <b>Kernel 2.6.7+ and Kernel 2.4</b>:&nbsp; for Kernel 2.6.7 and higher supporting the CM11A, SmartHome PowerLink Serial, and SmartHome PowerLink USB.&nbsp; For Kernel 2.4 supporting the CM11A and SmartHome PowerLink Serial.</p></li> <li> <p align="left"><a href="http://wish.sourceforge.net/x10web.html">x10web (Java GUI) Version 1.X</a>:&nbsp; Java client GUI and socket server for both wish Version 1.X and Version 2.X</p> </li> </ul> <hr> <p> This module is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as publised by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. </p><p> This module is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. </p><p> You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA </p><p> Should you need to contact the author, you can do so by email to <[email protected]>. </p> </body> </html>
jralls/Wish2
html/index.html
HTML
gpl-2.0
2,224
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright © 2000-2004 Marco Pesenti Gritti * Copyright © 2009 Collabora Ltd. * Copyright © 2011 Igalia S.L. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "config.h" #include "window-commands.h" #include "ephy-bookmarks-editor.h" #include "ephy-bookmarks-ui.h" #include "ephy-debug.h" #include "ephy-dialog.h" #include "ephy-embed-container.h" #include "ephy-embed-prefs.h" #include "ephy-embed-shell.h" #include "ephy-embed-single.h" #include "ephy-embed-utils.h" #include "ephy-embed.h" #include "ephy-file-chooser.h" #include "ephy-file-helpers.h" #include "ephy-find-toolbar.h" #include "ephy-gui.h" #include "ephy-history-window.h" #include "ephy-link.h" #include "ephy-location-entry.h" #include "ephy-notebook.h" #include "ephy-prefs.h" #include "ephy-private.h" #include "ephy-settings.h" #include "ephy-shell.h" #include "ephy-state.h" #include "ephy-string.h" #include "ephy-web-app-utils.h" #include "ephy-zoom.h" #include "pdm-dialog.h" #include <gio/gio.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <libnotify/notify.h> #include <libsoup/soup.h> #include <string.h> #ifdef HAVE_WEBKIT2 #include <webkit2/webkit2.h> #else #include <webkit/webkit.h> #endif void window_cmd_file_print (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (EPHY_IS_EMBED (embed)); view = ephy_embed_get_web_view (embed); ephy_web_view_print (view); } void window_cmd_file_send_to (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; char *command, *subject, *body; const char *location, *title; GdkScreen *screen; GError *error = NULL; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); location = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); title = ephy_web_view_get_title (ephy_embed_get_web_view (embed)); subject = g_uri_escape_string (title, NULL, TRUE); body = g_uri_escape_string (location, NULL, TRUE); command = g_strconcat ("mailto:", "?Subject=", subject, "&Body=", body, NULL); g_free (subject); g_free (body); if (window) { screen = gtk_widget_get_screen (GTK_WIDGET (window)); } else { screen = gdk_screen_get_default (); } if (!gtk_show_uri (screen, command, gtk_get_current_event_time(), &error)) { g_warning ("Unable to send link by email: %s\n", error->message); g_error_free (error); } g_free (command); } static gboolean event_with_shift (void) { GdkEvent *event; GdkEventType type = 0; guint state = 0; event = gtk_get_current_event (); if (event) { type = event->type; if (type == GDK_BUTTON_RELEASE) { state = event->button.state; } else if (type == GDK_KEY_PRESS || type == GDK_KEY_RELEASE) { state = event->key.state; } gdk_event_free (event); } return (state & GDK_SHIFT_MASK) != 0; } void window_cmd_go_location (GtkAction *action, EphyWindow *window) { ephy_window_activate_location (window); } void window_cmd_view_stop (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); webkit_web_view_stop_loading (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); } void window_cmd_view_reload (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; WebKitWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); gtk_widget_grab_focus (GTK_WIDGET (embed)); view = EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed); if (event_with_shift ()) webkit_web_view_reload_bypass_cache (view); else webkit_web_view_reload (view); } void window_cmd_file_bookmark_page (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); ephy_bookmarks_ui_add_bookmark (GTK_WINDOW (window), ephy_web_view_get_address (ephy_embed_get_web_view (embed)), ephy_web_view_get_title (ephy_embed_get_web_view (embed))); } static void open_response_cb (GtkDialog *dialog, int response, EphyWindow *window) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { ephy_window_load_url (window, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } static void save_response_cb (GtkDialog *dialog, int response, EphyEmbed *embed) { if (response == GTK_RESPONSE_ACCEPT) { char *uri, *converted; uri = gtk_file_chooser_get_uri (GTK_FILE_CHOOSER (dialog)); if (uri != NULL) { converted = g_filename_to_utf8 (uri, -1, NULL, NULL, NULL); if (converted != NULL) { EphyWebView *web_view = ephy_embed_get_web_view (embed); ephy_web_view_save (web_view, converted); } g_free (converted); g_free (uri); } } gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_open (GtkAction *action, EphyWindow *window) { EphyFileChooser *dialog; dialog = ephy_file_chooser_new (_("Open"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_OPEN, EPHY_PREFS_STATE_OPEN_DIR, EPHY_FILE_FILTER_ALL_SUPPORTED); g_signal_connect (dialog, "response", G_CALLBACK (open_response_cb), window); gtk_widget_show (GTK_WIDGET (dialog)); } static char * get_suggested_filename (EphyWebView *view) { char *suggested_filename; const char *mimetype; #ifdef HAVE_WEBKIT2 WebKitURIResponse *response; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; #endif WebKitWebResource *web_resource; #ifdef HAVE_WEBKIT2 web_resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); response = webkit_web_resource_get_response (web_resource); mimetype = webkit_uri_response_get_mime_type (response); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); web_resource = webkit_web_data_source_get_main_resource (data_source); mimetype = webkit_web_resource_get_mime_type (web_resource); #endif if ((g_ascii_strncasecmp (mimetype, "text/html", 9)) == 0) { /* Web Title will be used as suggested filename*/ suggested_filename = g_strconcat (ephy_web_view_get_title (view), ".html", NULL); } else { SoupURI *soup_uri = soup_uri_new (webkit_web_resource_get_uri (web_resource)); suggested_filename = g_path_get_basename (soup_uri->path); soup_uri_free (soup_uri); } return suggested_filename; } void window_cmd_file_save_as (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; EphyFileChooser *dialog; char *suggested_filename; EphyWebView *view; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); dialog = ephy_file_chooser_new (_("Save"), GTK_WIDGET (window), GTK_FILE_CHOOSER_ACTION_SAVE, EPHY_PREFS_STATE_SAVE_DIR, EPHY_FILE_FILTER_NONE); gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE); view = ephy_embed_get_web_view (embed); suggested_filename = get_suggested_filename (view); gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), suggested_filename); g_free (suggested_filename); g_signal_connect (dialog, "response", G_CALLBACK (save_response_cb), embed); gtk_widget_show (GTK_WIDGET (dialog)); } typedef struct { EphyWebView *view; GtkWidget *image; GtkWidget *entry; GtkWidget *spinner; GtkWidget *box; char *icon_href; } EphyApplicationDialogData; static void ephy_application_dialog_data_free (EphyApplicationDialogData *data) { g_free (data->icon_href); g_slice_free (EphyApplicationDialogData, data); } static void take_page_snapshot_and_set_image (EphyApplicationDialogData *data) { GdkPixbuf *snapshot; int x, y, w, h; x = y = 0; w = h = 128; /* GNOME hi-res icon size. */ snapshot = ephy_web_view_get_snapshot (data->view, x, y, w, h); gtk_image_set_from_pixbuf (GTK_IMAGE (data->image), snapshot); g_object_unref (snapshot); } #ifdef HAVE_WEBKIT2 static void download_finished_cb (WebKitDownload *download, EphyApplicationDialogData *data) { char *filename; filename = g_filename_from_uri (webkit_download_get_destination (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); } static void download_failed_cb (WebKitDownload *download, GError *error, EphyApplicationDialogData *data) { g_signal_handlers_disconnect_by_func (download, download_finished_cb, data); /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); } #else static void download_status_changed_cb (WebKitDownload *download, GParamSpec *spec, EphyApplicationDialogData *data) { WebKitDownloadStatus status = webkit_download_get_status (download); char *filename; switch (status) { case WEBKIT_DOWNLOAD_STATUS_FINISHED: filename = g_filename_from_uri (webkit_download_get_destination_uri (download), NULL, NULL); gtk_image_set_from_file (GTK_IMAGE (data->image), filename); g_free (filename); break; case WEBKIT_DOWNLOAD_STATUS_ERROR: case WEBKIT_DOWNLOAD_STATUS_CANCELLED: /* Something happened, default to a page snapshot. */ take_page_snapshot_and_set_image (data); break; default: break; } } #endif static void download_icon_and_set_image (EphyApplicationDialogData *data) { #ifndef HAVE_WEBKIT2 WebKitNetworkRequest *request; #endif WebKitDownload *download; char *destination, *destination_uri, *tmp_filename; #ifdef HAVE_WEBKIT2 download = webkit_web_context_download_uri (webkit_web_context_get_default (), data->icon_href); #else request = webkit_network_request_new (data->icon_href); download = webkit_download_new (request); g_object_unref (request); #endif tmp_filename = ephy_file_tmp_filename ("ephy-download-XXXXXX", NULL); destination = g_build_filename (ephy_file_tmp_dir (), tmp_filename, NULL); destination_uri = g_filename_to_uri (destination, NULL, NULL); #ifdef HAVE_WEBKIT2 webkit_download_set_destination (download, destination_uri); #else webkit_download_set_destination_uri (download, destination_uri); #endif g_free (destination); g_free (destination_uri); g_free (tmp_filename); #ifdef HAVE_WEBKIT2 g_signal_connect (download, "finished", G_CALLBACK (download_finished_cb), data); g_signal_connect (download, "failed", G_CALLBACK (download_failed_cb), data); #else g_signal_connect (download, "notify::status", G_CALLBACK (download_status_changed_cb), data); webkit_download_start (download); #endif } static void fill_default_application_image (EphyApplicationDialogData *data) { #ifdef HAVE_WEBKIT2 /* TODO: DOM Bindindgs */ #else WebKitDOMDocument *document; WebKitDOMNodeList *links; gulong length, i; document = webkit_web_view_get_dom_document (WEBKIT_WEB_VIEW (data->view)); links = webkit_dom_document_get_elements_by_tag_name (document, "link"); length = webkit_dom_node_list_get_length (links); for (i = 0; i < length; i++) { char *rel; WebKitDOMNode *node = webkit_dom_node_list_item (links, i); rel = webkit_dom_html_link_element_get_rel (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); /* TODO: support more than one possible icon. */ if (g_strcmp0 (rel, "apple-touch-icon") == 0 || g_strcmp0 (rel, "apple-touch-icon-precomposed") == 0) { data->icon_href = webkit_dom_html_link_element_get_href (WEBKIT_DOM_HTML_LINK_ELEMENT (node)); download_icon_and_set_image (data); g_free (rel); return; } } #endif /* If we make it here, no "apple-touch-icon" link was * found. Take a snapshot of the page. */ take_page_snapshot_and_set_image (data); } static void fill_default_application_title (EphyApplicationDialogData *data) { const char *title = ephy_web_view_get_title (data->view); gtk_entry_set_text (GTK_ENTRY (data->entry), title); } static void notify_launch_cb (NotifyNotification *notification, char *action, gpointer user_data) { char * desktop_file = user_data; /* A gross hack to be able to launch epiphany from within * Epiphany. Might be a good idea to figure out a better * solution... */ g_unsetenv (EPHY_UUID_ENVVAR); ephy_file_launch_desktop_file (desktop_file, NULL, 0, NULL); g_free (desktop_file); } static gboolean confirm_web_application_overwrite (GtkWindow *parent, const char *title) { GtkResponseType response; GtkWidget *dialog; dialog = gtk_message_dialog_new (parent, 0, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, _("A web application named '%s' already exists. Do you want to replace it?"), title); gtk_dialog_add_buttons (GTK_DIALOG (dialog), _("Cancel"), GTK_RESPONSE_CANCEL, _("Replace"), GTK_RESPONSE_OK, NULL); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("An application with the same name already exists. Replacing it will " "overwrite it.")); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); return response == GTK_RESPONSE_OK; } static void dialog_save_as_application_response_cb (GtkDialog *dialog, gint response, EphyApplicationDialogData *data) { const char *app_name; char *desktop_file; char *message; NotifyNotification *notification; if (response == GTK_RESPONSE_OK) { app_name = gtk_entry_get_text (GTK_ENTRY (data->entry)); if (ephy_web_application_exists (app_name)) { if (confirm_web_application_overwrite (GTK_WINDOW (dialog), app_name)) ephy_web_application_delete (app_name); else return; } /* Create Web Application, including a new profile and .desktop file. */ desktop_file = ephy_web_application_create (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (data->view)), app_name, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); if (desktop_file) message = g_strdup_printf (_("The application '%s' is ready to be used"), app_name); else message = g_strdup_printf (_("The application '%s' could not be created"), app_name); notification = notify_notification_new (message, NULL, NULL); g_free (message); if (desktop_file) { notify_notification_add_action (notification, "launch", _("Launch"), (NotifyActionCallback)notify_launch_cb, g_path_get_basename (desktop_file), NULL); notify_notification_set_icon_from_pixbuf (notification, gtk_image_get_pixbuf (GTK_IMAGE (data->image))); g_free (desktop_file); } notify_notification_set_timeout (notification, NOTIFY_EXPIRES_DEFAULT); notify_notification_set_urgency (notification, NOTIFY_URGENCY_LOW); notify_notification_set_hint (notification, "transient", g_variant_new_boolean (TRUE)); notify_notification_show (notification, NULL); } ephy_application_dialog_data_free (data); gtk_widget_destroy (GTK_WIDGET (dialog)); } void window_cmd_file_save_as_application (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkWidget *dialog, *box, *image, *entry, *content_area; EphyWebView *view; EphyApplicationDialogData *data; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); view = EPHY_WEB_VIEW (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); /* Show dialog with icon, title. */ dialog = gtk_dialog_new_with_buttons (_("Create Web Application"), GTK_WINDOW (window), 0, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, _("C_reate"), GTK_RESPONSE_OK, NULL); content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog)); gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); gtk_box_set_spacing (GTK_BOX (content_area), 14); /* 14 + 2 * 5 = 24 */ box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5); gtk_container_add (GTK_CONTAINER (content_area), box); image = gtk_image_new (); gtk_widget_set_size_request (image, 128, 128); gtk_container_add (GTK_CONTAINER (box), image); entry = gtk_entry_new (); gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE); gtk_box_pack_end (GTK_BOX (box), entry, FALSE, FALSE, 0); data = g_slice_new0 (EphyApplicationDialogData); data->view = view; data->image = image; data->entry = entry; fill_default_application_image (data); fill_default_application_title (data); gtk_widget_show_all (dialog); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK); g_signal_connect (dialog, "response", G_CALLBACK (dialog_save_as_application_response_cb), data); gtk_widget_show_all (dialog); } void window_cmd_file_work_offline (GtkAction *action, EphyWindow *window) { /* TODO: WebKitGTK+ does not currently support offline status. */ #if 0 EphyEmbedSingle *single; gboolean offline; single = EPHY_EMBED_SINGLE (ephy_embed_shell_get_embed_single (embed_shell)); offline = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); ephy_embed_single_set_network_status (single, !offline); #endif } void window_cmd_file_close_window (GtkAction *action, EphyWindow *window) { GtkWidget *notebook; EphyEmbed *embed; notebook = ephy_window_get_notebook (window); if (g_settings_get_boolean (EPHY_SETTINGS_LOCKDOWN, EPHY_PREFS_LOCKDOWN_QUIT) && gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook)) == 1) { return; } embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); g_signal_emit_by_name (notebook, "tab-close-request", embed); } void window_cmd_edit_undo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Undo"); #else webkit_web_view_undo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_redo (GtkAction *action, EphyWindow *window) { GtkWidget *widget; GtkWidget *embed; GtkWidget *location_entry; widget = gtk_window_get_focus (GTK_WINDOW (window)); location_entry = gtk_widget_get_ancestor (widget, EPHY_TYPE_LOCATION_ENTRY); if (location_entry) { ephy_location_entry_undo_reset (EPHY_LOCATION_ENTRY (location_entry)); } else { embed = gtk_widget_get_ancestor (widget, EPHY_TYPE_EMBED); if (embed) { #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed)), "Redo"); #else webkit_web_view_redo (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (EPHY_EMBED (embed))); #endif } } } void window_cmd_edit_cut (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_cut_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_CUT); #else webkit_web_view_cut_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_copy (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_copy_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_COPY); #else webkit_web_view_copy_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_paste (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_paste_clipboard (GTK_EDITABLE (widget)); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), WEBKIT_EDITING_COMMAND_PASTE); #else webkit_web_view_paste_clipboard (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_delete (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_delete_text (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); /* FIXME: TODO */ #if 0 ephy_command_manager_do_command (EPHY_COMMAND_MANAGER (embed), "cmd_delete"); #endif } } void window_cmd_edit_select_all (GtkAction *action, EphyWindow *window) { GtkWidget *widget = gtk_window_get_focus (GTK_WINDOW (window)); if (GTK_IS_EDITABLE (widget)) { gtk_editable_select_region (GTK_EDITABLE (widget), 0, -1); } else { EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); #ifdef HAVE_WEBKIT2 webkit_web_view_execute_editing_command (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed), "SelectAll"); #else webkit_web_view_select_all (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (embed)); #endif } } void window_cmd_edit_find (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_open (toolbar, FALSE, FALSE); } void window_cmd_edit_find_next (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_next (toolbar); } void window_cmd_edit_find_prev (GtkAction *action, EphyWindow *window) { EphyFindToolbar *toolbar; toolbar = EPHY_FIND_TOOLBAR (ephy_window_get_find_toolbar (window)); ephy_find_toolbar_find_previous (toolbar); } void window_cmd_view_fullscreen (GtkAction *action, EphyWindow *window) { if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action))) gtk_window_fullscreen (GTK_WINDOW (window)); else gtk_window_unfullscreen (GTK_WINDOW (window)); } void window_cmd_view_zoom_in (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_IN); } void window_cmd_view_zoom_out (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, ZOOM_OUT); } void window_cmd_view_zoom_normal (GtkAction *action, EphyWindow *window) { ephy_window_set_zoom (window, 1.0); } static void view_source_embedded (const char *uri, EphyEmbed *embed) { EphyEmbed *new_embed; new_embed = ephy_shell_new_tab (ephy_shell_get_default (), EPHY_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (embed))), embed, NULL, EPHY_NEW_TAB_JUMP | EPHY_NEW_TAB_IN_EXISTING_WINDOW | EPHY_NEW_TAB_APPEND_AFTER); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else webkit_web_view_set_view_source_mode (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), TRUE); webkit_web_view_load_uri (EPHY_GET_WEBKIT_WEB_VIEW_FROM_EMBED (new_embed), uri); #endif } static void save_temp_source_close_cb (GOutputStream *ostream, GAsyncResult *result, gpointer data) { char *uri; GFile *file; GError *error = NULL; g_output_stream_close_finish (ostream, result, &error); if (error) { g_warning ("Unable to close file: %s", error->message); g_error_free (error); return; } uri = (char*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-uri"); file = g_file_new_for_uri (uri); if (!ephy_file_launch_handler ("text/plain", file, gtk_get_current_event_time ())) { /* Fallback to view the source inside the browser */ const char *uri; EphyEmbed *embed; uri = (const char*) g_object_get_data (G_OBJECT (ostream), "ephy-original-source-uri"); embed = (EphyEmbed*)g_object_get_data (G_OBJECT (ostream), "ephy-save-temp-source-embed"); view_source_embedded (uri, embed); } g_object_unref (ostream); g_object_unref (file); } static void save_temp_source_write_cb (GOutputStream *ostream, GAsyncResult *result, GString *data) { GError *error = NULL; gssize written; written = g_output_stream_write_finish (ostream, result, &error); if (error) { g_string_free (data, TRUE); g_warning ("Unable to write to file: %s", error->message); g_error_free (error); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } if (written == data->len) { g_string_free (data, TRUE); g_output_stream_close_async (ostream, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_close_cb, NULL); return; } data->len -= written; data->str += written; g_output_stream_write_async (ostream, data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); } #ifdef HAVE_WEBKIT2 static void get_main_resource_data_cb (WebKitWebResource *resource, GAsyncResult *result, GOutputStream *ostream) { guchar *data; gsize data_length; GString *data_str; GError *error = NULL; data = webkit_web_resource_get_data_finish (resource, result, &data_length, &error); if (error) { g_warning ("Unable to get main resource data: %s", error->message); g_error_free (error); return; } /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ data_str = g_string_new_len ((gchar *)data, data_length); g_free (data); g_output_stream_write_async (ostream, data_str->str, data_str->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data_str); } #endif static void save_temp_source_replace_cb (GFile *file, GAsyncResult *result, EphyEmbed *embed) { EphyWebView *view; #ifdef HAVE_WEBKIT2 WebKitWebResource *resource; #else WebKitWebFrame *frame; WebKitWebDataSource *data_source; GString *const_data; GString *data; #endif GFileOutputStream *ostream; GError *error = NULL; ostream = g_file_replace_finish (file, result, &error); if (error) { g_warning ("Unable to replace file: %s", error->message); g_error_free (error); return; } g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-uri", g_file_get_uri (file), g_free); view = ephy_embed_get_web_view (embed); g_object_set_data_full (G_OBJECT (ostream), "ephy-original-source-uri", g_strdup (webkit_web_view_get_uri (WEBKIT_WEB_VIEW (view))), g_free), g_object_set_data_full (G_OBJECT (ostream), "ephy-save-temp-source-embed", g_object_ref (embed), g_object_unref); #ifdef HAVE_WEBKIT2 resource = webkit_web_view_get_main_resource (WEBKIT_WEB_VIEW (view)); webkit_web_resource_get_data (resource, NULL, (GAsyncReadyCallback)get_main_resource_data_cb, ostream); #else frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (view)); data_source = webkit_web_frame_get_data_source (frame); const_data = webkit_web_data_source_get_data (data_source); /* We create a new GString here because we need to make sure * we keep writing in case of partial writes */ if (const_data) data = g_string_new_len (const_data->str, const_data->len); else data = g_string_new_len ("", 0); g_output_stream_write_async (G_OUTPUT_STREAM (ostream), data->str, data->len, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_write_cb, data); #endif } static void save_temp_source (EphyEmbed *embed, guint32 user_time) { GFile *file; char *tmp, *base; const char *static_temp_dir; static_temp_dir = ephy_file_tmp_dir (); if (static_temp_dir == NULL) { return; } base = g_build_filename (static_temp_dir, "viewsourceXXXXXX", NULL); tmp = ephy_file_tmp_filename (base, "html"); g_free (base); if (tmp == NULL) { return; } file = g_file_new_for_path (tmp); g_file_replace_async (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION|G_FILE_CREATE_PRIVATE, G_PRIORITY_DEFAULT, NULL, (GAsyncReadyCallback)save_temp_source_replace_cb, embed); g_object_unref (file); g_free (tmp); } void window_cmd_view_page_source (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; const char *address; guint32 user_time; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_return_if_fail (embed != NULL); address = ephy_web_view_get_address (ephy_embed_get_web_view (embed)); #ifdef HAVE_WEBKIT2 /* TODO: View Source */ #else if (g_settings_get_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_INTERNAL_VIEW_SOURCE)) { view_source_embedded (address, embed); return; } #endif user_time = gtk_get_current_event_time (); if (g_str_has_prefix (address, "file://")) { GFile *file; file = g_file_new_for_uri (address); ephy_file_launch_handler ("text/plain", file, user_time); g_object_unref (file); } else { save_temp_source (embed, user_time); } } #define ABOUT_GROUP "About" void window_cmd_help_about (GtkAction *action, GtkWidget *window) { const char *licence_part[] = { N_("Web is free software; you can redistribute it and/or modify " "it under the terms of the GNU General Public License as published by " "the Free Software Foundation; either version 2 of the License, or " "(at your option) any later version."), N_("The GNOME Web Browser is distributed in the hope that it will be useful, " "but WITHOUT ANY WARRANTY; without even the implied warranty of " "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " "GNU General Public License for more details."), N_("You should have received a copy of the GNU General Public License " "along with the GNOME Web Browser; if not, write to the Free Software Foundation, Inc., " "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA") }; char *licence = NULL, *comments = NULL; GKeyFile *key_file; GError *error = NULL; char **list, **authors, **contributors, **past_authors, **artists, **documenters; gsize n_authors, n_contributors, n_past_authors, n_artists, n_documenters, i, j; key_file = g_key_file_new (); if (!g_key_file_load_from_file (key_file, DATADIR G_DIR_SEPARATOR_S "about.ini", 0, &error)) { g_warning ("Couldn't load about data: %s\n", error->message); g_error_free (error); return; } list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Authors", &n_authors, NULL); contributors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Contributors", &n_contributors, NULL); past_authors = g_key_file_get_string_list (key_file, ABOUT_GROUP, "PastAuthors", &n_past_authors, NULL); #define APPEND(_to,_from) \ _to[i++] = g_strdup (_from); #define APPEND_STRV_AND_FREE(_to,_from) \ if (_from)\ {\ for (j = 0; _from[j] != NULL; ++j)\ {\ _to[i++] = _from[j];\ }\ g_free (_from);\ } authors = g_new (char *, (list ? n_authors : 0) + (contributors ? n_contributors : 0) + (past_authors ? n_past_authors : 0) + 7 + 1); i = 0; APPEND_STRV_AND_FREE (authors, list); APPEND (authors, ""); APPEND (authors, _("Contact us at:")); APPEND (authors, "<[email protected]>"); APPEND (authors, ""); APPEND (authors, _("Contributors:")); APPEND_STRV_AND_FREE (authors, contributors); APPEND (authors, ""); APPEND (authors, _("Past developers:")); APPEND_STRV_AND_FREE (authors, past_authors); authors[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Artists", &n_artists, NULL); artists = g_new (char *, (list ? n_artists : 0) + 4 + 1); i = 0; APPEND_STRV_AND_FREE (artists, list); APPEND (artists, ""); APPEND (artists, _("Contact us at:")); APPEND (artists, "<[email protected]>"); APPEND (artists, "<[email protected]>"); artists[i++] = NULL; list = g_key_file_get_string_list (key_file, ABOUT_GROUP, "Documenters", &n_documenters, NULL); documenters = g_new (char *, (list ? n_documenters : 0) + 3 + 1); i = 0; APPEND_STRV_AND_FREE (documenters, list); APPEND (documenters, ""); APPEND (documenters, _("Contact us at:")); APPEND (documenters, "<[email protected]>"); documenters[i++] = NULL; #undef APPEND #undef APPEND_STRV_AND_FREE g_key_file_free (key_file); #ifdef HAVE_WEBKIT2 comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_get_major_version (), webkit_get_minor_version (), webkit_get_micro_version ()); #else comments = g_strdup_printf (_("Lets you view web pages and find information on the internet.\n" "Powered by WebKit %d.%d.%d"), webkit_major_version (), webkit_minor_version (), webkit_micro_version ()); #endif licence = g_strjoin ("\n\n", _(licence_part[0]), _(licence_part[1]), _(licence_part[2]), NULL); gtk_show_about_dialog (window ? GTK_WINDOW (window) : NULL, "program-name", _("Web"), "version", VERSION, "copyright", "Copyright © 2002–2004 Marco Pesenti Gritti\n" "Copyright © 2003–2012 The Web Developers", "artists", artists, "authors", authors, "comments", comments, "documenters", documenters, /* Translators: This is a special message that shouldn't be translated * literally. It is used in the about box to give credits to * the translators. * Thus, you should translate it to your name and email address. * You should also include other translators who have contributed to * this translation; in that case, please write each of them on a separate * line seperated by newlines (\n). */ "translator-credits", _("translator-credits"), "logo-icon-name", "web-browser", "website", "http://www.gnome.org/projects/epiphany", "website-label", _("Web Website"), "license", licence, "wrap-license", TRUE, NULL); g_free (comments); g_free (licence); g_strfreev (artists); g_strfreev (authors); g_strfreev (documenters); } void window_cmd_tabs_next (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_next_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_previous (GtkAction *action, EphyWindow *window) { GtkWidget *nb; nb = ephy_window_get_notebook (window); g_return_if_fail (nb != NULL); ephy_notebook_prev_page (EPHY_NOTEBOOK (nb)); } void window_cmd_tabs_move_left (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); if (page < 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page - 1); } void window_cmd_tabs_move_right (GtkAction *action, EphyWindow *window) { GtkWidget *child; GtkNotebook *notebook; int page, n_pages; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); page = gtk_notebook_get_current_page (notebook); n_pages = gtk_notebook_get_n_pages (notebook) - 1; if (page > n_pages - 1) return; child = gtk_notebook_get_nth_page (notebook, page); gtk_notebook_reorder_child (notebook, child, page + 1); } void window_cmd_tabs_detach (GtkAction *action, EphyWindow *window) { EphyEmbed *embed; GtkNotebook *notebook; EphyWindow *new_window; notebook = GTK_NOTEBOOK (ephy_window_get_notebook (window)); if (gtk_notebook_get_n_pages (notebook) <= 1) return; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); g_object_ref_sink (embed); gtk_notebook_remove_page (notebook, gtk_notebook_page_num (notebook, GTK_WIDGET (embed))); new_window = ephy_window_new (); ephy_embed_container_add_child (EPHY_EMBED_CONTAINER (new_window), embed, 0, FALSE); g_object_unref (embed); gtk_window_present (GTK_WINDOW (new_window)); } void window_cmd_load_location (GtkAction *action, EphyWindow *window) { const char *location; location = ephy_window_get_location (window); if (location) { EphyBookmarks *bookmarks; char *address; bookmarks = ephy_shell_get_bookmarks (ephy_shell_get_default ()); address = ephy_bookmarks_resolve_address (bookmarks, location, NULL); g_return_if_fail (address != NULL); ephy_link_open (EPHY_LINK (window), address, ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)), ephy_link_flags_from_current_event ()); } } void window_cmd_browse_with_caret (GtkAction *action, EphyWindow *window) { gboolean active; EphyEmbed *embed; embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (window)); active = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); /* FIXME: perhaps a bit of a kludge; we check if there's an * active embed because we don't want to show the dialog on * startup when we sync the GtkAction with our GConf * preference */ if (active && embed) { GtkWidget *dialog; int response; dialog = gtk_message_dialog_new (GTK_WINDOW (window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_CANCEL, _("Enable caret browsing mode?")); gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), _("Pressing F7 turns caret browsing on or off. This feature " "places a moveable cursor in web pages, allowing you to move " "around with your keyboard. Do you want to enable caret browsing on?")); gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Enable"), GTK_RESPONSE_ACCEPT); gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); response = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (response == GTK_RESPONSE_CANCEL) { gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE); return; } } g_settings_set_boolean (EPHY_SETTINGS_MAIN, EPHY_PREFS_ENABLE_CARET_BROWSING, active); }
jdapena/epiphany
src/window-commands.c
C
gpl-2.0
40,646
<?php /** * Kumbia Enterprise Framework * * LICENSE * * This source file is subject to the New BSD License that is bundled * with this package in the file docs/LICENSE.txt. * * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Kumbia * @package Generator * @subpackage GeneratorReport * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com) * @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com) * @license New BSD License * @version $Id: Doc.php 82 2009-09-13 21:06:31Z gutierrezandresfelipe $ */ /** * DocGenerator * * Generador de Reportes en Word * * @category Kumbia * @package Generator * @subpackage GeneratorReport * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com) * @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com) * @license New BSD License */ function doc($result, $sumArray, $title, $weightArray, $headerArray){ $config = CoreConfig::readAppConfig(); $active_app = Router::getApplication(); $file = md5(uniqid()); $content = " <html> <head> <title>REPORTE DE ".i18n::strtoupper($title)."</title> </head> <body bgcolor='white'> <div style='font-size:20px;font-family:Verdana;color:#000000'>".i18n::strtoupper($config->application->name)."</div>\n <div style='font-size:18px;font-family:Verdana;color:#000000'>REPORTE DE ".i18n::strtoupper($title)."</div>\n <div style='font-size:18px;font-family:Verdana;color:#000000'>".date("Y-m-d H:i")."</div>\n <br/> <table cellspacing='0' border=1 style='border:1px solid #969696'> "; $content.= "<tr bgcolor='#F2F2F2'>\n"; $numberHeaders = count($headerArray); for($i=0;$i<$numberHeaders;++$i){ $content.= "<th style='font-family:Verdana;font-size:12px'>".$headerArray[$i]."</th>\n"; } $content.= "</tr>\n"; $l = 5; foreach($result as $row){ $content.= "<tr bgcolor='white'>\n"; $numberColumns = count($row); for($i=0;$i<$numberColumns;++$i){ if(is_numeric($row[$i])){ $content.= "<td style='font-family:Verdana;font-size:12px' align='center'>{$row[$i]}</td>"; } else { $content.= "<td style='font-family:Verdana;font-size:12px'>{$row[$i]}&nbsp;</td>"; } } $content.= "</tr>\n"; ++$l; } file_put_contents("public/temp/$file.doc", $content); if(isset($raw_output)){ echo "<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>"; } else { Generator::formsPrint("<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>"); } }
softdesignermonteria/proyecto
Library/Kumbia/Generator/GeneratorReport/Format/Doc.php
PHP
gpl-2.0
2,823
#ifndef __INC_USERVIA_H #define __INC_USERVIA_H #include "via.h" extern VIA uservia; extern ALLEGRO_USTR *prt_clip_str; extern FILE *prt_fp; void uservia_reset(void); void uservia_write(uint16_t addr, uint8_t val); uint8_t uservia_read(uint16_t addr); void uservia_savestate(FILE *f); void uservia_loadstate(FILE *f); extern uint8_t lpt_dac; void uservia_set_ca1(int level); void uservia_set_ca2(int level); void uservia_set_cb1(int level); void uservia_set_cb2(int level); #endif
stardot/b-em
src/uservia.h
C
gpl-2.0
500
// Locale support (codecvt) -*- C++ -*- // Copyright (C) 2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. #include <codecvt> #include <cstring> // std::memcpy, std::memcmp #include <bits/stl_algobase.h> // std::max #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace { // Largest code point that fits in a single UTF-16 code unit. const char32_t max_single_utf16_unit = 0xFFFF; const char32_t max_code_point = 0x10FFFF; template<typename Elem> struct range { Elem* next; Elem* end; Elem operator*() const { return *next; } range& operator++() { ++next; return *this; } size_t size() const { return end - next; } }; // Multibyte sequences can have "header" consisting of Byte Order Mark const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF }; const unsigned char utf16_bom[4] = { 0xFE, 0xFF }; const unsigned char utf16le_bom[4] = { 0xFF, 0xFE }; template<size_t N> inline bool write_bom(range<char>& to, const unsigned char (&bom)[N]) { if (to.size() < N) return false; memcpy(to.next, bom, N); to.next += N; return true; } // If generate_header is set in mode write out UTF-8 BOM. bool write_utf8_bom(range<char>& to, codecvt_mode mode) { if (mode & generate_header) return write_bom(to, utf8_bom); return true; } // If generate_header is set in mode write out the UTF-16 BOM indicated // by whether little_endian is set in mode. bool write_utf16_bom(range<char16_t>& to, codecvt_mode mode) { if (mode & generate_header) { if (!to.size()) return false; auto* bom = (mode & little_endian) ? utf16le_bom : utf16_bom; std::memcpy(to.next, bom, 2); ++to.next; } return true; } template<size_t N> inline bool read_bom(range<const char>& from, const unsigned char (&bom)[N]) { if (from.size() >= N && !memcmp(from.next, bom, N)) { from.next += N; return true; } return false; } // If consume_header is set in mode update from.next to after any BOM. void read_utf8_bom(range<const char>& from, codecvt_mode mode) { if (mode & consume_header) read_bom(from, utf8_bom); } // If consume_header is set in mode update from.next to after any BOM. // Return little_endian iff the UTF-16LE BOM was present. codecvt_mode read_utf16_bom(range<const char16_t>& from, codecvt_mode mode) { if (mode & consume_header && from.size()) { if (*from.next == 0xFEFF) ++from.next; else if (*from.next == 0xFFFE) { ++from.next; return little_endian; } } return {}; } // Read a codepoint from a UTF-8 multibyte sequence. // Updates from.next if the codepoint is not greater than maxcode. // Returns -1 if there is an invalid or incomplete multibyte character. char32_t read_utf8_code_point(range<const char>& from, unsigned long maxcode) { size_t avail = from.size(); if (avail == 0) return -1; unsigned char c1 = from.next[0]; // https://en.wikipedia.org/wiki/UTF-8#Sample_code if (c1 < 0x80) { ++from.next; return c1; } else if (c1 < 0xC2) // continuation or overlong 2-byte sequence return -1; else if (c1 < 0xE0) // 2-byte sequence { if (avail < 2) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 6) + c2 - 0x3080; if (c <= maxcode) from.next += 2; return c; } else if (c1 < 0xF0) // 3-byte sequence { if (avail < 3) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; if (c1 == 0xE0 && c2 < 0xA0) // overlong return -1; unsigned char c3 = from.next[2]; if ((c3 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 12) + (c2 << 6) + c3 - 0xE2080; if (c <= maxcode) from.next += 3; return c; } else if (c1 < 0xF5) // 4-byte sequence { if (avail < 4) return -1; unsigned char c2 = from.next[1]; if ((c2 & 0xC0) != 0x80) return -1; if (c1 == 0xF0 && c2 < 0x90) // overlong return -1; if (c1 == 0xF4 && c2 >= 0x90) // > U+10FFFF return -1; unsigned char c3 = from.next[2]; if ((c3 & 0xC0) != 0x80) return -1; unsigned char c4 = from.next[3]; if ((c4 & 0xC0) != 0x80) return -1; char32_t c = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4 - 0x3C82080; if (c <= maxcode) from.next += 4; return c; } else // > U+10FFFF return -1; } bool write_utf8_code_point(range<char>& to, char32_t code_point) { if (code_point < 0x80) { if (to.size() < 1) return false; *to.next++ = code_point; } else if (code_point <= 0x7FF) { if (to.size() < 2) return false; *to.next++ = (code_point >> 6) + 0xC0; *to.next++ = (code_point & 0x3F) + 0x80; } else if (code_point <= 0xFFFF) { if (to.size() < 3) return false; *to.next++ = (code_point >> 12) + 0xE0; *to.next++ = ((code_point >> 6) & 0x3F) + 0x80; *to.next++ = (code_point & 0x3F) + 0x80; } else if (code_point <= 0x10FFFF) { if (to.size() < 4) return false; *to.next++ = (code_point >> 18) + 0xF0; *to.next++ = ((code_point >> 12) & 0x3F) + 0x80; *to.next++ = ((code_point >> 6) & 0x3F) + 0x80; *to.next++ = (code_point & 0x3F) + 0x80; } else return false; return true; } inline char16_t adjust_byte_order(char16_t c, codecvt_mode mode) { #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ return (mode & little_endian) ? __builtin_bswap16(c) : c; #else return (mode & little_endian) ? c : __builtin_bswap16(c); #endif } // Read a codepoint from a UTF-16 multibyte sequence. // The sequence's endianness is indicated by (mode & little_endian). // Updates from.next if the codepoint is not greater than maxcode. // Returns -1 if there is an incomplete multibyte character. char32_t read_utf16_code_point(range<const char16_t>& from, unsigned long maxcode, codecvt_mode mode) { int inc = 1; char32_t c = adjust_byte_order(from.next[0], mode); if (c >= 0xD800 && c <= 0xDBFF) { if (from.size() < 2) return -1; const char16_t c2 = adjust_byte_order(from.next[1], mode); if (c2 >= 0xDC00 && c2 <= 0xDFFF) { c = (c << 10) + c2 - 0x35FDC00; inc = 2; } } if (c <= maxcode) from.next += inc; return c; } template<typename C> bool write_utf16_code_point(range<C>& to, char32_t codepoint, codecvt_mode mode) { static_assert(sizeof(C) >= 2, "a code unit must be at least 16-bit"); if (codepoint < max_single_utf16_unit) { if (to.size() > 0) { *to.next = codepoint; ++to.next; return true; } } else if (to.size() > 1) { // Algorithm from http://www.unicode.org/faq/utf_bom.html#utf16-4 const char32_t LEAD_OFFSET = 0xD800 - (0x10000 >> 10); char16_t lead = LEAD_OFFSET + (codepoint >> 10); char16_t trail = 0xDC00 + (codepoint & 0x3FF); to.next[0] = adjust_byte_order(lead, mode); to.next[1] = adjust_byte_order(trail, mode); to.next += 2; return true; } return false; } // utf8 -> ucs4 codecvt_base::result ucs4_in(range<const char>& from, range<char32_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { read_utf8_bom(from, mode); while (from.size() && to.size()) { const char32_t codepoint = read_utf8_code_point(from, maxcode); if (codepoint == char32_t(-1)) break; if (codepoint > maxcode) return codecvt_base::error; *to.next++ = codepoint; } return from.size() ? codecvt_base::partial : codecvt_base::ok; } // ucs4 -> utf8 codecvt_base::result ucs4_out(range<const char32_t>& from, range<char>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf8_bom(to, mode)) return codecvt_base::partial; while (from.size()) { const char32_t c = from.next[0]; if (c > maxcode) return codecvt_base::error; if (!write_utf8_code_point(to, c)) return codecvt_base::partial; ++from.next; } return codecvt_base::ok; } // utf16 -> ucs4 codecvt_base::result ucs4_in(range<const char16_t>& from, range<char32_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); while (from.size() && to.size()) { const char32_t codepoint = read_utf16_code_point(from, maxcode, mode); if (codepoint == char32_t(-1)) break; if (codepoint > maxcode) return codecvt_base::error; *to.next++ = codepoint; } return from.size() ? codecvt_base::partial : codecvt_base::ok; } // ucs4 -> utf16 codecvt_base::result ucs4_out(range<const char32_t>& from, range<char16_t>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf16_bom(to, mode)) return codecvt_base::partial; while (from.size()) { const char32_t c = from.next[0]; if (c > maxcode) return codecvt_base::error; if (!write_utf16_code_point(to, c, mode)) return codecvt_base::partial; ++from.next; } return codecvt_base::ok; } // utf8 -> utf16 template<typename C> codecvt_base::result utf16_in(range<const char>& from, range<C>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { read_utf8_bom(from, mode); while (from.size() && to.size()) { const char* first = from.next; if ((unsigned char)*first >= 0xF0 && to.size() < 2) return codecvt_base::partial; const char32_t codepoint = read_utf8_code_point(from, maxcode); if (codepoint == char32_t(-1)) return codecvt_base::partial; if (codepoint > maxcode) return codecvt_base::error; if (!write_utf16_code_point(to, codepoint, mode)) { from.next = first; return codecvt_base::partial; } } return codecvt_base::ok; } // utf16 -> utf8 template<typename C> codecvt_base::result utf16_out(range<const C>& from, range<char>& to, unsigned long maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf8_bom(to, mode)) return codecvt_base::partial; while (from.size()) { char32_t c = from.next[0]; int inc = 1; if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair { if (from.size() < 2) return codecvt_base::ok; // stop converting at this point const char32_t c2 = from.next[1]; if (c2 >= 0xDC00 && c2 <= 0xDFFF) { inc = 2; c = (c << 10) + c2 - 0x35FDC00; } else return codecvt_base::error; } if (c > maxcode) return codecvt_base::error; if (!write_utf8_code_point(to, c)) return codecvt_base::partial; from.next += inc; } return codecvt_base::ok; } // return pos such that [begin,pos) is valid UTF-16 string no longer than max const char* utf16_span(const char* begin, const char* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); size_t count = 0; while (count+1 < max) { char32_t c = read_utf8_code_point(from, maxcode); if (c == char32_t(-1)) break; else if (c > max_single_utf16_unit) ++count; ++count; } if (count+1 == max) // take one more character if it fits in a single unit read_utf8_code_point(from, std::max(max_single_utf16_unit, maxcode)); return from.next; } // utf8 -> ucs2 codecvt_base::result ucs2_in(range<const char>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { return utf16_in(from, to, std::max(max_single_utf16_unit, maxcode), mode); } // ucs2 -> utf8 codecvt_base::result ucs2_out(range<const char16_t>& from, range<char>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { return utf16_out(from, to, std::max(max_single_utf16_unit, maxcode), mode); } // ucs2 -> utf16 codecvt_base::result ucs2_out(range<const char16_t>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { if (!write_utf16_bom(to, mode)) return codecvt_base::partial; while (from.size() && to.size()) { char16_t c = from.next[0]; if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair return codecvt_base::error; if (c > maxcode) return codecvt_base::error; *to.next++ = adjust_byte_order(c, mode); ++from.next; } return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial; } // utf16 -> ucs2 codecvt_base::result ucs2_in(range<const char16_t>& from, range<char16_t>& to, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); maxcode = std::max(max_single_utf16_unit, maxcode); while (from.size() && to.size()) { const char32_t c = read_utf16_code_point(from, maxcode, mode); if (c == char32_t(-1)) break; if (c >= maxcode) return codecvt_base::error; *to.next++ = c; } return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial; } const char16_t* ucs2_span(const char16_t* begin, const char16_t* end, size_t max, char32_t maxcode, codecvt_mode mode) { range<const char16_t> from{ begin, end }; if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); maxcode = std::max(max_single_utf16_unit, maxcode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf16_code_point(from, maxcode, mode); return from.next; } const char* ucs2_span(const char* begin, const char* end, size_t max, char32_t maxcode, codecvt_mode mode) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); maxcode = std::max(max_single_utf16_unit, maxcode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf8_code_point(from, maxcode); return from.next; } // return pos such that [begin,pos) is valid UCS-4 string no longer than max const char* ucs4_span(const char* begin, const char* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char> from{ begin, end }; read_utf8_bom(from, mode); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf8_code_point(from, maxcode); return from.next; } // return pos such that [begin,pos) is valid UCS-4 string no longer than max const char16_t* ucs4_span(const char16_t* begin, const char16_t* end, size_t max, char32_t maxcode = max_code_point, codecvt_mode mode = {}) { range<const char16_t> from{ begin, end }; if (read_utf16_bom(from, mode) == little_endian) mode = codecvt_mode(mode & little_endian); char32_t c = 0; while (max-- && c <= maxcode) c = read_utf16_code_point(from, maxcode, mode); return from.next; } } // Define members of codecvt<char16_t, char, mbstate_t> specialization. // Converts from UTF-8 to UTF-16. locale::id codecvt<char16_t, char, mbstate_t>::id; codecvt<char16_t, char, mbstate_t>::~codecvt() { } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; // we don't use mbstate_t for the unicode facets } codecvt_base::result codecvt<char16_t, char, mbstate_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ codecvt_mode mode = {}; #else codecvt_mode mode = little_endian; #endif auto res = utf16_in(from, to, max_code_point, mode); __from_next = from.next; __to_next = to.next; return res; } int codecvt<char16_t, char, mbstate_t>::do_encoding() const throw() { return 0; } bool codecvt<char16_t, char, mbstate_t>::do_always_noconv() const throw() { return false; } int codecvt<char16_t, char, mbstate_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max); return __end - __from; } int codecvt<char16_t, char, mbstate_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } // Define members of codecvt<char32_t, char, mbstate_t> specialization. // Converts from UTF-8 to UTF-32 (aka UCS-4). locale::id codecvt<char32_t, char, mbstate_t>::id; codecvt<char32_t, char, mbstate_t>::~codecvt() { } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs4_out(from, to); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result codecvt<char32_t, char, mbstate_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to); __from_next = from.next; __to_next = to.next; return res; } int codecvt<char32_t, char, mbstate_t>::do_encoding() const throw() { return 0; } bool codecvt<char32_t, char, mbstate_t>::do_always_noconv() const throw() { return false; } int codecvt<char32_t, char, mbstate_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs4_span(__from, __end, __max); return __end - __from; } int codecvt<char32_t, char, mbstate_t>::do_max_length() const throw() { return 4; } // Define members of codecvt_utf8<char16_t> base class implementation. // Converts from UTF-8 to UCS-2. __codecvt_utf8_base<char16_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_base<char16_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_base<char16_t>::do_max_length() const throw() { return 3; } // Define members of codecvt_utf8<char32_t> base class implementation. // Converts from UTF-8 to UTF-32 (aka UCS-4). __codecvt_utf8_base<char32_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_base<char32_t>::do_max_length() const throw() { return 4; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf8<wchar_t> base class implementation. // Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t). __codecvt_utf8_base<wchar_t>::~__codecvt_utf8_base() { } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<char> to{ __to, __to_end }; #if __SIZEOF_WCHAR_T__ == 2 range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<const char32_t> from{ reinterpret_cast<const char32_t*>(__from), reinterpret_cast<const char32_t*>(__from_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = reinterpret_cast<const wchar_t*>(from.next); __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; #if __SIZEOF_WCHAR_T__ == 2 range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<char32_t> to{ reinterpret_cast<char32_t*>(__to), reinterpret_cast<char32_t*>(__to_end) }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = from.next; __to_next = reinterpret_cast<wchar_t*>(to.next); return res; } int __codecvt_utf8_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { #if __SIZEOF_WCHAR_T__ == 2 __end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 __end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode); #else __end = __from; #endif return __end - __from; } int __codecvt_utf8_base<wchar_t>::do_max_length() const throw() { return 4; } #endif // Define members of codecvt_utf16<char16_t> base class implementation. // Converts from UTF-16 to UCS-2. __codecvt_utf16_base<char16_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = reinterpret_cast<char*>(to.next); return res; } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; range<char16_t> to{ __to, __to_end }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); __from_next = reinterpret_cast<const char*>(from.next); __to_next = to.next; return res; } int __codecvt_utf16_base<char16_t>::do_encoding() const throw() { return 1; } bool __codecvt_utf16_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<char16_t>::do_max_length() const throw() { return 3; } // Define members of codecvt_utf16<char32_t> base class implementation. // Converts from UTF-16 to UTF-32 (aka UCS-4). __codecvt_utf16_base<char32_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = reinterpret_cast<char*>(to.next); return res; } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; range<char32_t> to{ __to, __to_end }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); __from_next = reinterpret_cast<const char*>(from.next); __to_next = to.next; return res; } int __codecvt_utf16_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf16_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<char32_t>::do_max_length() const throw() { return 3; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf16<wchar_t> base class implementation. // Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t). __codecvt_utf16_base<wchar_t>::~__codecvt_utf16_base() { } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<char> to{ __to, __to_end }; #if __SIZEOF_WCHAR_T__ == 2 range<const char16_t> from{ reinterpret_cast<const char16_t*>(__from), reinterpret_cast<const char16_t*>(__from_end) }; auto res = ucs2_out(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<const char32_t> from{ reinterpret_cast<const char32_t*>(__from), reinterpret_cast<const char32_t*>(__from_end) }; auto res = ucs4_out(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = reinterpret_cast<const wchar_t*>(from.next); __to_next = to.next; return res; } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf16_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; #if __SIZEOF_WCHAR_T__ == 2 range<char16_t> to{ reinterpret_cast<char16_t*>(__to), reinterpret_cast<char16_t*>(__to_end) }; auto res = ucs2_in(from, to, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 range<char32_t> to{ reinterpret_cast<char32_t*>(__to), reinterpret_cast<char32_t*>(__to_end) }; auto res = ucs4_in(from, to, _M_maxcode, _M_mode); #else return codecvt_base::error; #endif __from_next = from.next; __to_next = reinterpret_cast<wchar_t*>(to.next); return res; } int __codecvt_utf16_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf16_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf16_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { auto next = reinterpret_cast<const char16_t*>(__from); #if __SIZEOF_WCHAR_T__ == 2 next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); #elif __SIZEOF_WCHAR_T__ == 4 next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max, _M_maxcode, _M_mode); #endif return reinterpret_cast<const char*>(next) - __from; } int __codecvt_utf16_base<wchar_t>::do_max_length() const throw() { return 4; } #endif // Define members of codecvt_utf8_utf16<char16_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<char16_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char16_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<char16_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char16_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<char16_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<char16_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<char16_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<char16_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } // Define members of codecvt_utf8_utf16<char32_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<char32_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const char32_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<char32_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<char32_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<char32_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<char32_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<char32_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<char32_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } #ifdef _GLIBCXX_USE_WCHAR_T // Define members of codecvt_utf8_utf16<wchar_t> base class implementation. // Converts from UTF-8 to UTF-16. __codecvt_utf8_utf16_base<wchar_t>::~__codecvt_utf8_utf16_base() { } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_out(state_type&, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { range<const wchar_t> from{ __from, __from_end }; range<char> to{ __to, __to_end }; auto res = utf16_out(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_unshift(state_type&, extern_type* __to, extern_type*, extern_type*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result __codecvt_utf8_utf16_base<wchar_t>:: do_in(state_type&, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { range<const char> from{ __from, __from_end }; range<wchar_t> to{ __to, __to_end }; auto res = utf16_in(from, to, _M_maxcode, _M_mode); __from_next = from.next; __to_next = to.next; return res; } int __codecvt_utf8_utf16_base<wchar_t>::do_encoding() const throw() { return 0; } bool __codecvt_utf8_utf16_base<wchar_t>::do_always_noconv() const throw() { return false; } int __codecvt_utf8_utf16_base<wchar_t>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { __end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode); return __end - __from; } int __codecvt_utf8_utf16_base<wchar_t>::do_max_length() const throw() { // Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit, // whereas 4 byte sequences require two 16-bit code units. return 3; } #endif inline template class __codecvt_abstract_base<char16_t, char, mbstate_t>; inline template class __codecvt_abstract_base<char32_t, char, mbstate_t>; template class codecvt_byname<char16_t, char, mbstate_t>; template class codecvt_byname<char32_t, char, mbstate_t>; _GLIBCXX_END_NAMESPACE_VERSION } #endif // _GLIBCXX_USE_C99_STDINT_TR1
villevoutilainen/gcc
libstdc++-v3/src/c++11/codecvt.cc
C++
gpl-2.0
39,721
/** * Provides a DataSchema implementation which can be used to work with * delimited text data. * * @module dataschema * @submodule dataschema-text */ /** Provides a DataSchema implementation which can be used to work with delimited text data. See the `apply` method for usage. @class DataSchema.Text @extends DataSchema.Base @static **/ var Lang = Y.Lang, isString = Lang.isString, isUndef = Lang.isUndefined, SchemaText = { //////////////////////////////////////////////////////////////////////// // // DataSchema.Text static methods // //////////////////////////////////////////////////////////////////////// /** Applies a schema to a string of delimited data, returning a normalized object with results in the `results` property. The `meta` property of the response object is present for consistency, but is assigned an empty object. If the input data is absent or not a string, an `error` property will be added. Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct `apply` how to split up the string into an array of data arrays for processing. Use _schema.resultFields_ to specify the keys in the generated result objects in `response.results`. The key:value pairs will be assigned in the order of the _schema.resultFields_ array, assuming the values in the data records are defined in the same order. _schema.resultFields_ field identifiers are objects with the following properties: * `key` : <strong>(required)</strong> The property name you want the data value assigned to in the result object (String) * `parser`: A function or the name of a function on `Y.Parsers` used to convert the input value into a normalized type. Parser functions are passed the value as input and are expected to return a value. If no value parsing is needed, you can use just the desired property name string as the field identifier instead of an object (see example below). @example // Process simple csv var schema = { resultDelimiter: "\n", fieldDelimiter: ",", resultFields: [ 'fruit', 'color' ] }, data = "Banana,yellow\nOrange,orange\nEggplant,purple"; var response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "Banana", color: "yellow" } // Use parsers schema.resultFields = [ { key: 'fruit', parser: function (val) { return val.toUpperCase(); } }, 'color' // mix and match objects and strings ]; response = Y.DataSchema.Text.apply(schema, data); // response.results[0] is { fruit: "BANANA", color: "yellow" } @method apply @param {Object} schema Schema to apply. Supported configuration properties are: @param {String} schema.resultDelimiter Character or character sequence that marks the end of one record and the start of another. @param {String} [schema.fieldDelimiter] Character or character sequence that marks the end of a field and the start of another within the same record. @param {Array} [schema.resultFields] Field identifiers to assign values in the response records. See above for details. @param {String} data Text data. @return {Object} An Object with properties `results` and `meta` @static **/ apply: function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; if (isString(data) && schema && isString(schema.resultDelimiter)) { // Parse results data data_out = SchemaText._parseResults.call(this, schema, data_in, data_out); } else { Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text"); data_out.error = new Error("Text schema parse failure"); } return data_out; }, /** * Schema-parsed list of results from full data * * @method _parseResults * @param schema {Array} Schema to parse against. * @param text_in {String} Text to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _parseResults: function(schema, text_in, data_out) { var resultDelim = schema.resultDelimiter, fieldDelim = isString(schema.fieldDelimiter) && schema.fieldDelimiter, fields = schema.resultFields || [], results = [], parse = Y.DataSchema.Base.parse, results_in, fields_in, result, item, field, key, value, i, j; // Delete final delimiter at end of string if there if (text_in.slice(-resultDelim.length) === resultDelim) { text_in = text_in.slice(0, -resultDelim.length); } // Split into results results_in = text_in.split(schema.resultDelimiter); if (fieldDelim) { for (i = results_in.length - 1; i >= 0; --i) { result = {}; item = results_in[i]; fields_in = item.split(schema.fieldDelimiter); for (j = fields.length - 1; j >= 0; --j) { field = fields[j]; key = (!isUndef(field.key)) ? field.key : field; // FIXME: unless the key is an array index, this test // for fields_in[key] is useless. value = (!isUndef(fields_in[key])) ? fields_in[key] : fields_in[j]; result[key] = parse.call(this, value, field); } results[i] = result; } } else { results = results_in; } data_out.results = results; return data_out; } }; Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);
schancel/gameserver
public/js/yui3-3.12.0/src/dataschema/js/dataschema-text.js
JavaScript
gpl-2.0
6,718
# -*- coding: utf-8 -*- # # Watermarks documentation build configuration file, created by # sphinx-quickstart on Tue Apr 8 16:49:39 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os src_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'src') sys.path.insert(0, src_dir) import watermarks # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Watermarks' copyright = u'2014, Vladimir Chovanec' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = watermarks.__version__ # The full version, including alpha/beta/rc tags. release = watermarks.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Watermarksdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Watermarks.tex', u'Watermarks Documentation', u'Vladimir Chovanec', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'watermarks', u'Watermarks Documentation', [u'Vladimir Chovanec'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Watermarks', u'Watermarks Documentation', u'Vladimir Chovanec', 'Watermarks', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
vladozc/watermarks
doc/source/conf.py
Python
gpl-2.0
8,359
<?php /* * Page that is shown to the user when the plugin was not correctly installed. * This is just a fallback in case something went wrong somewhere. * Maybe it just needs to be removed alltogether. */ function gwolle_gb_installSplash() { ?> <div class="wrap"> <div id="icon-gwolle-gb"><br /></div> <h1>Gwolle-GB &#8212; <?php _e('Installation','gwolle-gb'); ?> </h1> <div> <?php if ( !isset($_REQUEST['install_gwolle_gb']) || $_REQUEST['install_gwolle_gb'] != 'install_gwolle_gb') { _e('Welcome!<br>It seems that either you\'re using this plugin for the first time or you\'ve deleted all settings.<br>However, to use this plugin we have to setup the database tables. Good for you, we\'ve made this as easy as possible.<br>All you\'ve got to do is click on that button below, and that\'s it.','gwolle-gb'); ?> <br /><br /> <div> <form action="<?php echo $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page']; ?>" method="POST"> <input type="hidden" id="install_gwolle_gb" name="install_gwolle_gb" value="install_gwolle_gb" /> <input type="submit" class="button button-primary" value="<?php esc_attr_e('Sure, let\'s do this!', 'gwolle-gb'); ?>"> </form> </div> <?php } elseif ( isset($_REQUEST['install_gwolle_gb']) && $_REQUEST['install_gwolle_gb'] == 'install_gwolle_gb' && !get_option('gwolle_gb_version') ) { // perform installation gwolle_gb_install(); echo sprintf( __('Allright, we\'re done. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] ); } else { echo sprintf( __('It looks like there has been an error. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] ); } ?> </div> </div> <?php }
artran03/AriChezVous
wp-content/plugins/gwolle-gb/admin/installSplash.php
PHP
gpl-2.0
1,824
/* This file was generated by SableCC (http://www.sablecc.org/). */ package se.sics.kola.node; public abstract class PResource extends Node { // Empty body }
kompics/kola
src/main/java/se/sics/kola/node/PResource.java
Java
gpl-2.0
164
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #define _CRT_SECURE_NO_WARNINGS #pragma once #include "targetver.h" #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <direct.h> #include <string.h> // TODO: reference additional headers your program requires here
fatalhalt/TXRExtractor
stdafx.h
C
gpl-2.0
414
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 2.2 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2009 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License along with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2009 * $Id$ * */ require_once 'CRM/Core/Selector/Base.php'; require_once 'CRM/Core/Selector/API.php'; require_once 'CRM/Utils/Pager.php'; require_once 'CRM/Utils/Sort.php'; require_once 'CRM/Contact/BAO/Query.php'; /** * This class is used to retrieve and display a range of * contacts that match the given criteria (specifically for * results of advanced search options. * */ class CRM_Grant_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API { /** * This defines two actions- View and Edit. * * @var array * @static */ static $_links = null; /** * we use desc to remind us what that column is, name is used in the tpl * * @var array * @static */ static $_columnHeaders; /** * Properties of contact we're interested in displaying * @var array * @static */ static $_properties = array( 'contact_id', 'contact_type', 'sort_name', 'grant_id', 'grant_status_id', 'grant_type_id', 'grant_amount_total', 'grant_amount_requested', 'grant_amount_granted', 'grant_application_received_date', 'grant_report_received', 'grant_money_transfer_date', ); /** * are we restricting ourselves to a single contact * * @access protected * @var boolean */ protected $_single = false; /** * are we restricting ourselves to a single contact * * @access protected * @var boolean */ protected $_limit = null; /** * what context are we being invoked from * * @access protected * @var string */ protected $_context = null; /** * queryParams is the array returned by exportValues called on * the HTML_QuickForm_Controller for that page. * * @var array * @access protected */ public $_queryParams; /** * represent the type of selector * * @var int * @access protected */ protected $_action; /** * The additional clause that we restrict the search with * * @var string */ protected $_grantClause = null; /** * The query object * * @var string */ protected $_query; /** * Class constructor * * @param array $queryParams array of parameters for query * @param int $action - action of search basic or advanced. * @param string $grantClause if the caller wants to further restrict the search * @param boolean $single are we dealing only with one contact? * @param int $limit how many participations do we want returned * * @return CRM_Contact_Selector * @access public */ function __construct(&$queryParams, $action = CRM_Core_Action::NONE, $grantClause = null, $single = false, $limit = null, $context = 'search' ) { // submitted form values $this->_queryParams =& $queryParams; $this->_single = $single; $this->_limit = $limit; $this->_context = $context; $this->_grantClause = $grantClause; // type of selector $this->_action = $action; $this->_query =& new CRM_Contact_BAO_Query( $this->_queryParams, null, null, false, false, CRM_Contact_BAO_Query::MODE_GRANT ); }//end of constructor /** * This method returns the links that are given for each search row. * currently the links added for each row are * * - View * - Edit * * @return array * @access public * */ static function &links() { $cid = CRM_Utils_Request::retrieve('cid', 'Integer', $this); if (!(self::$_links)) { self::$_links = array( CRM_Core_Action::VIEW => array( 'name' => ts('View'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant', 'title' => ts('View Grant'), ), CRM_Core_Action::UPDATE => array( 'name' => ts('Edit'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%', 'title' => ts('Edit Grant'), ), ); if ( $cid ) { $deleteExtra = ts('Are you sure you want to delete this grant?'); $delLink = array( CRM_Core_Action::DELETE => array( 'name' => ts('Delete'), 'url' => 'civicrm/contact/view/grant', 'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant', 'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&amp;confirmed=1\'; else return false;"', 'title' => ts('Delete Grant') ) ); self::$_links = self::$_links + $delLink ; } } return self::$_links; } //end of function /** * getter for array of the parameters required for creating pager. * * @param * @access public */ function getPagerParams($action, &$params) { $params['status'] = ts('Grant') . ' %%StatusMessage%%'; $params['csvString'] = null; if ( $this->_limit ) { $params['rowCount'] = $this->_limit; } else { $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT; } $params['buttonTop'] = 'PagerTopButton'; $params['buttonBottom'] = 'PagerBottomButton'; } //end of function /** * Returns total number of rows for the query. * * @param * @return int Total number of rows * @access public */ function getTotalCount($action) { return $this->_query->searchQuery( 0, 0, null, true, false, false, false, false, $this->_grantClause ); } /** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = null) { $result = $this->_query->searchQuery( $offset, $rowCount, $sort, false, false, false, false, false, $this->_grantClause ); // process the result of the query $rows = array( ); // check is the user has view/edit permission $permission = CRM_Core_Permission::VIEW; if ( CRM_Core_Permission::check( 'edit grants' ) ) { $permission = CRM_Core_Permission::EDIT; } require_once 'CRM/Grant/PseudoConstant.php'; $grantStatus = array( ); $grantStatus = CRM_Grant_PseudoConstant::grantStatus( ); $grantType = array( ); $grantType = CRM_Grant_PseudoConstant::grantType( ); $mask = CRM_Core_Action::mask( $permission ); while ($result->fetch()) { $row = array(); // the columns we are interested in foreach (self::$_properties as $property) { if ( isset( $result->$property ) ) { $row[$property] = $result->$property; } } //fix status display $row['grant_status'] = $grantStatus[$row['grant_status_id']]; $row['grant_type'] = $grantType[$row['grant_type_id']]; if ($this->_context == 'search') { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->grant_id; } $row['action'] = CRM_Core_Action::formLink( self::links(), $mask, array( 'id' => $result->grant_id, 'cid' => $result->contact_id, 'cxt' => $this->_context ) ); require_once( 'CRM/Contact/BAO/Contact/Utils.php' ); $row['contact_type' ] = CRM_Contact_BAO_Contact_Utils::getImage( $result->contact_type ); $rows[] = $row; } return $rows; } /** * @return array $qill which contains an array of strings * @access public */ // the current internationalisation is bad, but should more or less work // for most of "European" languages public function getQILL( ) { return $this->_query->qill( ); } /** * returns the column headers as an array of tuples: * (name, sortName (key to the sort array)) * * @param string $action the action being performed * @param enum $output what should the result set include (web/email/csv) * * @return array the column headers that need to be displayed * @access public */ public function &getColumnHeaders( $action = null, $output = null ) { if ( ! isset( self::$_columnHeaders ) ) { self::$_columnHeaders = array( array('name' => ts('Status'), 'sort' => 'grant_status_id', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Type'), 'sort' => 'grant_type_id', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Amount Requested'), 'sort' => 'grant_amount_total', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Amount Granted'), 'sort' => 'grant_amount_granted', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Application Received'), 'sort' => 'grant_application_received_date', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Report Received'), 'sort' => 'grant_report_received', 'direction' => CRM_Utils_Sort::DONTCARE, ), array( 'name' => ts('Money Transferred'), 'sort' => 'money_transfer_date', 'direction' => CRM_Utils_Sort::DONTCARE, ), array('desc' => ts('Actions') ), ); if ( ! $this->_single ) { $pre = array( array('desc' => ts('Contact Type') ), array( 'name' => ts('Name'), 'sort' => 'sort_name', 'direction' => CRM_Utils_Sort::ASCENDING, ) ); self::$_columnHeaders = array_merge( $pre, self::$_columnHeaders ); } } return self::$_columnHeaders; } function &getQuery( ) { return $this->_query; } /** * name of export file. * * @param string $output type of output * @return string name of the file */ function getExportFileName( $output = 'csv') { return ts('CiviCRM Grant Search'); } }//end of class
btribulski/girlsknowhow
sites/all/modules/civicrm/CRM/Grant/Selector/Search.php
PHP
gpl-2.0
16,778
/* * Copyright (C) 2013 Andreas Steffen * HSR Hochschule fuer Technik Rapperswil * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include "tcg_swid_attr_tag_inv.h" #include <pa_tnc/pa_tnc_msg.h> #include <bio/bio_writer.h> #include <bio/bio_reader.h> #include <utils/debug.h> typedef struct private_tcg_swid_attr_tag_inv_t private_tcg_swid_attr_tag_inv_t; /** * SWID Tag Inventory * see section 4.10 of TCG TNC SWID Message and Attributes for IF-M * * 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Tag ID Count | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Request ID Copy | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | EID Epoch | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Last EID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unique Sequence ID Length |Unique Sequence ID (var length)| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Tag (Variable) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define SWID_TAG_INV_SIZE 16 #define SWID_TAG_INV_RESERVED 0x00 /** * Private data of an tcg_swid_attr_tag_inv_t object. */ struct private_tcg_swid_attr_tag_inv_t { /** * Public members of tcg_swid_attr_tag_inv_t */ tcg_swid_attr_tag_inv_t public; /** * Vendor-specific attribute type */ pen_type_t type; /** * Attribute value */ chunk_t value; /** * Noskip flag */ bool noskip_flag; /** * Request ID */ u_int32_t request_id; /** * Event ID Epoch */ u_int32_t eid_epoch; /** * Last Event ID */ u_int32_t last_eid; /** * SWID Tag Inventory */ swid_inventory_t *inventory; /** * Reference count */ refcount_t ref; }; METHOD(pa_tnc_attr_t, get_type, pen_type_t, private_tcg_swid_attr_tag_inv_t *this) { return this->type; } METHOD(pa_tnc_attr_t, get_value, chunk_t, private_tcg_swid_attr_tag_inv_t *this) { return this->value; } METHOD(pa_tnc_attr_t, get_noskip_flag, bool, private_tcg_swid_attr_tag_inv_t *this) { return this->noskip_flag; } METHOD(pa_tnc_attr_t, set_noskip_flag,void, private_tcg_swid_attr_tag_inv_t *this, bool noskip) { this->noskip_flag = noskip; } METHOD(pa_tnc_attr_t, build, void, private_tcg_swid_attr_tag_inv_t *this) { bio_writer_t *writer; swid_tag_t *tag; enumerator_t *enumerator; if (this->value.ptr) { return; } writer = bio_writer_create(SWID_TAG_INV_SIZE); writer->write_uint8 (writer, SWID_TAG_INV_RESERVED); writer->write_uint24(writer, this->inventory->get_count(this->inventory)); writer->write_uint32(writer, this->request_id); writer->write_uint32(writer, this->eid_epoch); writer->write_uint32(writer, this->last_eid); enumerator = this->inventory->create_enumerator(this->inventory); while (enumerator->enumerate(enumerator, &tag)) { writer->write_data16(writer, tag->get_unique_seq_id(tag)); writer->write_data32(writer, tag->get_encoding(tag)); } enumerator->destroy(enumerator); this->value = writer->extract_buf(writer); writer->destroy(writer); } METHOD(pa_tnc_attr_t, process, status_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *offset) { bio_reader_t *reader; u_int32_t tag_count; u_int8_t reserved; chunk_t tag_encoding, unique_seq_id; swid_tag_t *tag; if (this->value.len < SWID_TAG_INV_SIZE) { DBG1(DBG_TNC, "insufficient data for SWID Tag Inventory"); *offset = 0; return FAILED; } reader = bio_reader_create(this->value); reader->read_uint8 (reader, &reserved); reader->read_uint24(reader, &tag_count); reader->read_uint32(reader, &this->request_id); reader->read_uint32(reader, &this->eid_epoch); reader->read_uint32(reader, &this->last_eid); *offset = SWID_TAG_INV_SIZE; while (tag_count--) { if (!reader->read_data16(reader, &unique_seq_id)) { DBG1(DBG_TNC, "insufficient data for Unique Sequence ID"); return FAILED; } *offset += 2 + unique_seq_id.len; if (!reader->read_data32(reader, &tag_encoding)) { DBG1(DBG_TNC, "insufficient data for Tag"); return FAILED; } *offset += 4 + tag_encoding.len; tag = swid_tag_create(tag_encoding, unique_seq_id); this->inventory->add(this->inventory, tag); } reader->destroy(reader); return SUCCESS; } METHOD(pa_tnc_attr_t, get_ref, pa_tnc_attr_t*, private_tcg_swid_attr_tag_inv_t *this) { ref_get(&this->ref); return &this->public.pa_tnc_attribute; } METHOD(pa_tnc_attr_t, destroy, void, private_tcg_swid_attr_tag_inv_t *this) { if (ref_put(&this->ref)) { this->inventory->destroy(this->inventory); free(this->value.ptr); free(this); } } METHOD(tcg_swid_attr_tag_inv_t, get_request_id, u_int32_t, private_tcg_swid_attr_tag_inv_t *this) { return this->request_id; } METHOD(tcg_swid_attr_tag_inv_t, get_last_eid, u_int32_t, private_tcg_swid_attr_tag_inv_t *this, u_int32_t *eid_epoch) { if (eid_epoch) { *eid_epoch = this->eid_epoch; } return this->last_eid; } METHOD(tcg_swid_attr_tag_inv_t, get_inventory, swid_inventory_t*, private_tcg_swid_attr_tag_inv_t *this) { return this->inventory; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create(u_int32_t request_id, u_int32_t eid_epoch, u_int32_t eid, swid_inventory_t *inventory) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .request_id = request_id, .eid_epoch = eid_epoch, .last_eid = eid, .inventory = inventory, .ref = 1, ); return &this->public.pa_tnc_attribute; } /** * Described in header. */ pa_tnc_attr_t *tcg_swid_attr_tag_inv_create_from_data(chunk_t data) { private_tcg_swid_attr_tag_inv_t *this; INIT(this, .public = { .pa_tnc_attribute = { .get_type = _get_type, .get_value = _get_value, .get_noskip_flag = _get_noskip_flag, .set_noskip_flag = _set_noskip_flag, .build = _build, .process = _process, .get_ref = _get_ref, .destroy = _destroy, }, .get_request_id = _get_request_id, .get_last_eid = _get_last_eid, .get_inventory = _get_inventory, }, .type = { PEN_TCG, TCG_SWID_TAG_INVENTORY }, .value = chunk_clone(data), .inventory = swid_inventory_create(TRUE), .ref = 1, ); return &this->public.pa_tnc_attribute; }
maire/strongswan
src/libpts/tcg/swid/tcg_swid_attr_tag_inv.c
C
gpl-2.0
7,725
<?php /** * @file * Drupal site-specific configuration file. * * IMPORTANT NOTE: * This file may have been set to read-only by the Drupal installation program. * If you make changes to this file, be sure to protect it again after making * your modifications. Failure to remove write permissions to this file is a * security risk. * * The configuration file to be loaded is based upon the rules below. However * if the multisite aliasing file named sites/sites.php is present, it will be * loaded, and the aliases in the array $sites will override the default * directory rules below. See sites/example.sites.php for more information about * aliases. * * The configuration directory will be discovered by stripping the website's * hostname from left to right and pathname from right to left. The first * configuration file found will be used and any others will be ignored. If no * other configuration file is found then the default configuration file at * 'sites/default' will be used. * * For example, for a fictitious site installed at * http://www.drupal.org:8080/mysite/test/, the 'settings.php' file is searched * for in the following directories: * * - sites/8080.www.drupal.org.mysite.test * - sites/www.drupal.org.mysite.test * - sites/drupal.org.mysite.test * - sites/org.mysite.test * * - sites/8080.www.drupal.org.mysite * - sites/www.drupal.org.mysite * - sites/drupal.org.mysite * - sites/org.mysite * * - sites/8080.www.drupal.org * - sites/www.drupal.org * - sites/drupal.org * - sites/org * * - sites/default * * Note that if you are installing on a non-standard port number, prefix the * hostname with that number. For example, * http://www.drupal.org:8080/mysite/test/ could be loaded from * sites/8080.www.drupal.org.mysite.test/. * * @see example.sites.php * @see conf_path() */ /** * Database settings: * * The $databases array specifies the database connection or * connections that Drupal may use. Drupal is able to connect * to multiple databases, including multiple types of databases, * during the same request. * * Each database connection is specified as an array of settings, * similar to the following: * @code * array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'port' => 3306, * 'prefix' => 'myprefix_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * The "driver" property indicates what Drupal database driver the * connection should use. This is usually the same as the name of the * database type, such as mysql or sqlite, but not always. The other * properties will vary depending on the driver. For SQLite, you must * specify a database file name in a directory that is writable by the * webserver. For most other drivers, you must specify a * username, password, host, and database name. * * Some database engines support transactions. In order to enable * transaction support for a given database, set the 'transactions' key * to TRUE. To disable it, set it to FALSE. Note that the default value * varies by driver. For MySQL, the default is FALSE since MyISAM tables * do not support transactions. * * For each database, you may optionally specify multiple "target" databases. * A target database allows Drupal to try to send certain queries to a * different database if it can but fall back to the default connection if not. * That is useful for master/slave replication, as Drupal may try to connect * to a slave server when appropriate and if one is not available will simply * fall back to the single master server. * * The general format for the $databases array is as follows: * @code * $databases['default']['default'] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['extra']['default'] = $info_array; * @endcode * * In the above example, $info_array is an array of settings described above. * The first line sets a "default" database that has one master database * (the second level default). The second and third lines create an array * of potential slave databases. Drupal will select one at random for a given * request as needed. The fourth line creates a new database with a name of * "extra". * * For a single database configuration, the following is sufficient: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => 'main_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * You can optionally set prefixes for some or all database table names * by using the 'prefix' setting. If a prefix is specified, the table * name will be prepended with its value. Be sure to use valid database * characters only, usually alphanumeric and underscore. If no prefixes * are desired, leave it as an empty string ''. * * To have all database names prefixed, set 'prefix' as a string: * @code * 'prefix' => 'main_', * @endcode * To provide prefixes for specific tables, set 'prefix' as an array. * The array's keys are the table names and the values are the prefixes. * The 'default' element is mandatory and holds the prefix for any tables * not specified elsewhere in the array. Example: * @code * 'prefix' => array( * 'default' => 'main_', * 'users' => 'shared_', * 'sessions' => 'shared_', * 'role' => 'shared_', * 'authmap' => 'shared_', * ), * @endcode * You can also use a reference to a schema/database as a prefix. This may be * useful if your Drupal installation exists in a schema that is not the default * or you want to access several databases from the same code base at the same * time. * Example: * @code * 'prefix' => array( * 'default' => 'main.', * 'users' => 'shared.', * 'sessions' => 'shared.', * 'role' => 'shared.', * 'authmap' => 'shared.', * ); * @endcode * NOTE: MySQL and SQLite's definition of a schema is a database. * * Advanced users can add or override initial commands to execute when * connecting to the database server, as well as PDO connection settings. For * example, to enable MySQL SELECT queries to exceed the max_join_size system * variable, and to reduce the database connection timeout to 5 seconds: * * @code * $databases['default']['default'] = array( * 'init_commands' => array( * 'big_selects' => 'SET SQL_BIG_SELECTS=1', * ), * 'pdo' => array( * PDO::ATTR_TIMEOUT => 5, * ), * ); * @endcode * * WARNING: These defaults are designed for database portability. Changing them * may cause unexpected behavior, including potential data loss. * * @see DatabaseConnection_mysql::__construct * @see DatabaseConnection_pgsql::__construct * @see DatabaseConnection_sqlite::__construct * * Database configuration format: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'pgsql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'sqlite', * 'database' => '/path/to/databasefilename', * ); * @endcode */ $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'm4c_wiki', 'username' => 'root', 'password' => '', 'host' => 'localhost', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), ), ); /** * Access control for update.php script. * * If you are updating your Drupal installation using the update.php script but * are not logged in using either an account with the "Administer software * updates" permission or the site maintenance account (the account that was * created during installation), you will need to modify the access check * statement below. Change the FALSE to a TRUE to disable the access check. * After finishing the upgrade, be sure to open this file again and change the * TRUE back to a FALSE! */ $update_free_access = FALSE; /** * Salt for one-time login links and cancel links, form tokens, etc. * * This variable will be set to a random value by the installer. All one-time * login links will be invalidated if the value is changed. Note that if your * site is deployed on a cluster of web servers, you must ensure that this * variable has the same value on each server. If this variable is empty, a hash * of the serialized database credentials will be used as a fallback salt. * * For enhanced security, you may set this variable to a value using the * contents of a file outside your docroot that is never saved together * with any backups of your Drupal files and database. * * Example: * $drupal_hash_salt = file_get_contents('/home/example/salt.txt'); * */ $drupal_hash_salt = 'SVoT4MlhRtpQNiBHSKMQJQAuaidUYAtUQ6X80sP8q7U'; /** * Base URL (optional). * * If Drupal is generating incorrect URLs on your site, which could * be in HTML headers (links to CSS and JS files) or visible links on pages * (such as in menus), uncomment the Base URL statement below (remove the * leading hash sign) and fill in the absolute URL to your Drupal installation. * * You might also want to force users to use a given domain. * See the .htaccess file for more information. * * Examples: * $base_url = 'http://www.example.com'; * $base_url = 'http://www.example.com:8888'; * $base_url = 'http://www.example.com/drupal'; * $base_url = 'https://www.example.com:8888/drupal'; * * It is not allowed to have a trailing slash; Drupal will add it * for you. */ # $base_url = 'http://www.example.com'; // NO trailing slash! /** * PHP settings: * * To see what PHP settings are possible, including whether they can be set at * runtime (by using ini_set()), read the PHP documentation: * http://www.php.net/manual/en/ini.list.php * See drupal_environment_initialize() in includes/bootstrap.inc for required * runtime settings and the .htaccess file for non-runtime settings. Settings * defined there should not be duplicated here so as to avoid conflict issues. */ /** * Some distributions of Linux (most notably Debian) ship their PHP * installations with garbage collection (gc) disabled. Since Drupal depends on * PHP's garbage collection for clearing sessions, ensure that garbage * collection occurs by using the most common settings. */ ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); /** * Set session lifetime (in seconds), i.e. the time from the user's last visit * to the active session may be deleted by the session garbage collector. When * a session is deleted, authenticated users are logged out, and the contents * of the user's $_SESSION variable is discarded. */ ini_set('session.gc_maxlifetime', 200000); /** * Set session cookie lifetime (in seconds), i.e. the time from the session is * created to the cookie expires, i.e. when the browser is expected to discard * the cookie. The value 0 means "until the browser is closed". */ ini_set('session.cookie_lifetime', 2000000); /** * If you encounter a situation where users post a large amount of text, and * the result is stripped out upon viewing but can still be edited, Drupal's * output filter may not have sufficient memory to process it. If you * experience this issue, you may wish to uncomment the following two lines * and increase the limits of these variables. For more information, see * http://php.net/manual/en/pcre.configuration.php. */ # ini_set('pcre.backtrack_limit', 200000); # ini_set('pcre.recursion_limit', 200000); /** * Drupal automatically generates a unique session cookie name for each site * based on its full domain name. If you have multiple domains pointing at the * same Drupal site, you can either redirect them all to a single domain (see * comment in .htaccess), or uncomment the line below and specify their shared * base domain. Doing so assures that users remain logged in as they cross * between your various domains. Make sure to always start the $cookie_domain * with a leading dot, as per RFC 2109. */ # $cookie_domain = '.example.com'; /** * Variable overrides: * * To override specific entries in the 'variable' table for this site, * set them here. You usually don't need to use this feature. This is * useful in a configuration file for a vhost or directory, rather than * the default settings.php. Any configuration setting from the 'variable' * table can be given a new value. Note that any values you provide in * these variable overrides will not be modifiable from the Drupal * administration interface. * * The following overrides are examples: * - site_name: Defines the site's name. * - theme_default: Defines the default theme for this site. * - anonymous: Defines the human-readable name of anonymous users. * Remove the leading hash signs to enable. */ # $conf['site_name'] = 'My Drupal site'; # $conf['theme_default'] = 'garland'; # $conf['anonymous'] = 'Visitor'; /** * A custom theme can be set for the offline page. This applies when the site * is explicitly set to maintenance mode through the administration page or when * the database is inactive due to an error. It can be set through the * 'maintenance_theme' key. The template file should also be copied into the * theme. It is located inside 'modules/system/maintenance-page.tpl.php'. * Note: This setting does not apply to installation and update pages. */ # $conf['maintenance_theme'] = 'bartik'; /** * Reverse Proxy Configuration: * * Reverse proxy servers are often used to enhance the performance * of heavily visited sites and may also provide other site caching, * security, or encryption benefits. In an environment where Drupal * is behind a reverse proxy, the real IP address of the client should * be determined such that the correct client IP address is available * to Drupal's logging, statistics, and access management systems. In * the most simple scenario, the proxy server will add an * X-Forwarded-For header to the request that contains the client IP * address. However, HTTP headers are vulnerable to spoofing, where a * malicious client could bypass restrictions by setting the * X-Forwarded-For header directly. Therefore, Drupal's proxy * configuration requires the IP addresses of all remote proxies to be * specified in $conf['reverse_proxy_addresses'] to work correctly. * * Enable this setting to get Drupal to determine the client IP from * the X-Forwarded-For header (or $conf['reverse_proxy_header'] if set). * If you are unsure about this setting, do not have a reverse proxy, * or Drupal operates in a shared hosting environment, this setting * should remain commented out. * * In order for this setting to be used you must specify every possible * reverse proxy IP address in $conf['reverse_proxy_addresses']. * If a complete list of reverse proxies is not available in your * environment (for example, if you use a CDN) you may set the * $_SERVER['REMOTE_ADDR'] variable directly in settings.php. * Be aware, however, that it is likely that this would allow IP * address spoofing unless more advanced precautions are taken. */ # $conf['reverse_proxy'] = TRUE; /** * Specify every reverse proxy IP address in your environment. * This setting is required if $conf['reverse_proxy'] is TRUE. */ # $conf['reverse_proxy_addresses'] = array('a.b.c.d', ...); /** * Set this value if your proxy server sends the client IP in a header * other than X-Forwarded-For. */ # $conf['reverse_proxy_header'] = 'HTTP_X_CLUSTER_CLIENT_IP'; /** * Page caching: * * By default, Drupal sends a "Vary: Cookie" HTTP header for anonymous page * views. This tells a HTTP proxy that it may return a page from its local * cache without contacting the web server, if the user sends the same Cookie * header as the user who originally requested the cached page. Without "Vary: * Cookie", authenticated users would also be served the anonymous page from * the cache. If the site has mostly anonymous users except a few known * editors/administrators, the Vary header can be omitted. This allows for * better caching in HTTP proxies (including reverse proxies), i.e. even if * clients send different cookies, they still get content served from the cache. * However, authenticated users should access the site directly (i.e. not use an * HTTP proxy, and bypass the reverse proxy if one is used) in order to avoid * getting cached pages from the proxy. */ # $conf['omit_vary_cookie'] = TRUE; /** * CSS/JS aggregated file gzip compression: * * By default, when CSS or JS aggregation and clean URLs are enabled Drupal will * store a gzip compressed (.gz) copy of the aggregated files. If this file is * available then rewrite rules in the default .htaccess file will serve these * files to browsers that accept gzip encoded content. This allows pages to load * faster for these users and has minimal impact on server load. If you are * using a webserver other than Apache httpd, or a caching reverse proxy that is * configured to cache and compress these files itself you may want to uncomment * one or both of the below lines, which will prevent gzip files being stored. */ # $conf['css_gzip_compression'] = FALSE; # $conf['js_gzip_compression'] = FALSE; /** * String overrides: * * To override specific strings on your site with or without enabling the Locale * module, add an entry to this list. This functionality allows you to change * a small number of your site's default English language interface strings. * * Remove the leading hash signs to enable. */ # $conf['locale_custom_strings_en'][''] = array( # 'forum' => 'Discussion board', # '@count min' => '@count minutes', # ); /** * * IP blocking: * * To bypass database queries for denied IP addresses, use this setting. * Drupal queries the {blocked_ips} table by default on every page request * for both authenticated and anonymous users. This allows the system to * block IP addresses from within the administrative interface and before any * modules are loaded. However on high traffic websites you may want to avoid * this query, allowing you to bypass database access altogether for anonymous * users under certain caching configurations. * * If using this setting, you will need to add back any IP addresses which * you may have blocked via the administrative interface. Each element of this * array represents a blocked IP address. Uncommenting the array and leaving it * empty will have the effect of disabling IP blocking on your site. * * Remove the leading hash signs to enable. */ # $conf['blocked_ips'] = array( # 'a.b.c.d', # ); /** * Fast 404 pages: * * Drupal can generate fully themed 404 pages. However, some of these responses * are for images or other resource files that are not displayed to the user. * This can waste bandwidth, and also generate server load. * * The options below return a simple, fast 404 page for URLs matching a * specific pattern: * - 404_fast_paths_exclude: A regular expression to match paths to exclude, * such as images generated by image styles, or dynamically-resized images. * If you need to add more paths, you can add '|path' to the expression. * - 404_fast_paths: A regular expression to match paths that should return a * simple 404 page, rather than the fully themed 404 page. If you don't have * any aliases ending in htm or html you can add '|s?html?' to the expression. * - 404_fast_html: The html to return for simple 404 pages. * * Add leading hash signs if you would like to disable this functionality. */ $conf['404_fast_paths_exclude'] = '/\/(?:styles)\//'; $conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'; $conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>'; /** * By default the page request process will return a fast 404 page for missing * files if they match the regular expression set in '404_fast_paths' and not * '404_fast_paths_exclude' above. 404 errors will simultaneously be logged in * the Drupal system log. * * You can choose to return a fast 404 page earlier for missing pages (as soon * as settings.php is loaded) by uncommenting the line below. This speeds up * server response time when loading 404 error pages and prevents the 404 error * from being logged in the Drupal system log. In order to prevent valid pages * such as image styles and other generated content that may match the * '404_fast_html' regular expression from returning 404 errors, it is necessary * to add them to the '404_fast_paths_exclude' regular expression above. Make * sure that you understand the effects of this feature before uncommenting the * line below. */ # drupal_fast_404(); /** * External access proxy settings: * * If your site must access the Internet via a web proxy then you can enter * the proxy settings here. Currently only basic authentication is supported * by using the username and password variables. The proxy_user_agent variable * can be set to NULL for proxies that require no User-Agent header or to a * non-empty string for proxies that limit requests to a specific agent. The * proxy_exceptions variable is an array of host names to be accessed directly, * not via proxy. */ # $conf['proxy_server'] = ''; # $conf['proxy_port'] = 8080; # $conf['proxy_username'] = ''; # $conf['proxy_password'] = ''; # $conf['proxy_user_agent'] = ''; # $conf['proxy_exceptions'] = array('127.0.0.1', 'localhost'); /** * Authorized file system operations: * * The Update manager module included with Drupal provides a mechanism for * site administrators to securely install missing updates for the site * directly through the web user interface. On securely-configured servers, * the Update manager will require the administrator to provide SSH or FTP * credentials before allowing the installation to proceed; this allows the * site to update the new files as the user who owns all the Drupal files, * instead of as the user the webserver is running as. On servers where the * webserver user is itself the owner of the Drupal files, the administrator * will not be prompted for SSH or FTP credentials (note that these server * setups are common on shared hosting, but are inherently insecure). * * Some sites might wish to disable the above functionality, and only update * the code directly via SSH or FTP themselves. This setting completely * disables all functionality related to these authorized file operations. * * @see http://drupal.org/node/244924 * * Remove the leading hash signs to disable. */ # $conf['allow_authorize_operations'] = FALSE;
jbricha/druwiki
sites/default/settings.php
PHP
gpl-2.0
23,497
using System; namespace Server.Items { public class LanternHand : BaseLight, IFlipable { public override int LabelNumber { get { return 1011221; } } // lantern public override int LitItemID { get { return ItemID == 0xA471 ? 0xA472 : 0xA476; } } public override int UnlitItemID { get { return ItemID == 0xA472 ? 0xA471 : 0xA475; } } public int NorthID { get { return Burning ? 0xA472 : 0xA471; } } public int WestID { get { return Burning ? 0xA476 : 0xA475; } } [Constructable] public LanternHand() : base(0xA471) { Weight = 1; } public void OnFlip(Mobile from) { if (ItemID == NorthID) ItemID = WestID; else if (ItemID == WestID) ItemID = NorthID; } public LanternHand(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
kevin-10/ServUO
Scripts/Items/Decorative/ArtisanFestivalRewards/LanternHand.cs
C#
gpl-2.0
1,255
class Extended_GetIn_EventHandlers { class StaticMGWeapon { class ace_ifa3staticweapon { getIn = "_this call ace_ifa3staticweapon_fnc_getIn"; }; }; class StaticMortar { class ace_ifa3staticweapon { getIn = "_this call ace_ifa3staticweapon_fnc_getIn"; }; }; };
bux/IFA3_ACE_COMPAT
addons/staticweapon/Extended_GetIn_EventHandlers.hpp
C++
gpl-2.0
283
/* HTVMS_WAISProt.c ** ** Adaptation for Lynx by F.Macrides ([email protected]) ** ** 31-May-1994 FM Initial version. ** **----------------------------------------------------------------------*/ /* ** Routines originally from WProt.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE: No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 Harry Morris, [email protected] 3.30.90 Harry Morris - removed chunk code from WAISSearchAPDU, - added makeWAISQueryType1Query() and readWAISType1Query() which replace makeWAISQueryTerms() and makeWAISQueryDocs(). 4.11.90 HWM - generalized conditional includes (see c-dialect.h) - renamed makeWAISType1Query() to makeWAISTextQuery() renamed readWAISType1Query() to readWAISTextQuery() 5.29.90 TS - fixed bug in makeWAISQueryDocs added CSTFreeWAISFoo functions */ #define _C_WAIS_protocol_ /* This file implements the Z39.50 extensions required for WAIS */ #include <HTUtils.h> #include <HTVMS_WaisUI.h> #include <HTVMS_WaisProt.h> #include <LYLeaks.h> /* very rough estimates of the size of an object */ #define DefWAISInitResponseSize (size_t)200 #define DefWAISSearchSize (size_t)3000 #define DefWAISSearchResponseSize (size_t)6000 #define DefWAISPresentSize (size_t)1000 #define DefWAISPresentResponseSize (size_t)6000 #define DefWAISDocHeaderSize (size_t)500 #define DefWAISShortHeaderSize (size_t)200 #define DefWAISLongHeaderSize (size_t)800 #define DefWAISDocTextSize (size_t)6000 #define DefWAISDocHeadlineSize (size_t)500 #define DefWAISDocCodeSize (size_t)500 #define RESERVE_SPACE_FOR_WAIS_HEADER(len) \ if (*len > 0) \ *len -= header_len; /*----------------------------------------------------------------------*/ static unsigned long userInfoTagSize PARAMS((data_tag tag, unsigned long length)); static unsigned long userInfoTagSize(tag,length) data_tag tag; unsigned long length; /* return the number of bytes required to write the user info tag and length */ { unsigned long size; /* calculate bytes required to represent tag. max tag is 16K */ size = writtenCompressedIntSize(tag); size += writtenCompressedIntSize(length); return(size); } /*----------------------------------------------------------------------*/ static char* writeUserInfoHeader PARAMS((data_tag tag,long infoSize, long estHeaderSize,char* buffer, long* len)); static char* writeUserInfoHeader(tag,infoSize,estHeaderSize,buffer,len) data_tag tag; long infoSize; long estHeaderSize; char* buffer; long* len; /* write the tag and size, making sure the info fits. return the true end of the info (after adjustment) note that the argument infoSize includes estHeaderSize. Note that the argument len is the number of bytes remaining in the buffer. Since we write the tag and size at the begining of the buffer (in space that we reserved) we don't want to pass len the calls which do that writing. */ { long dummyLen = 100; /* plenty of space for a tag and size */ char* buf = buffer; long realSize = infoSize - estHeaderSize; long realHeaderSize = userInfoTagSize(tag,realSize); if (buffer == NULL || *len == 0) return(NULL); /* write the tag */ buf = writeTag(tag,buf,&dummyLen); /* see if the if the header size was correct. if not, we have to shift the info to fit the real header size */ if (estHeaderSize != realHeaderSize) { /* make sure there is enough space */ CHECK_FOR_SPACE_LEFT(realHeaderSize - estHeaderSize,len); memmove(buffer + realHeaderSize,buffer + estHeaderSize,(size_t)(realSize)); } /* write the size */ writeCompressedInteger(realSize,buf,&dummyLen); /* return the true end of buffer */ return(buffer + realHeaderSize + realSize); } /*----------------------------------------------------------------------*/ static char* readUserInfoHeader PARAMS((data_tag* tag,unsigned long* num, char* buffer)); static char* readUserInfoHeader(tag,num,buffer) data_tag* tag; unsigned long* num; char* buffer; /* read the tag and size */ { char* buf = buffer; buf = readTag(tag,buf); buf = readCompressedInteger(num,buf); return(buf); } /*----------------------------------------------------------------------*/ WAISInitResponse* makeWAISInitResponse(chunkCode, chunkIDLen, chunkMarker, highlightMarker, deHighlightMarker, newLineChars) long chunkCode; long chunkIDLen; char* chunkMarker; char* highlightMarker; char* deHighlightMarker; char* newLineChars; /* create a WAIS init response object */ { WAISInitResponse* init = (WAISInitResponse*)s_malloc((size_t)sizeof(WAISInitResponse)); init->ChunkCode = chunkCode; /* note: none are copied! */ init->ChunkIDLength = chunkIDLen; init->ChunkMarker = chunkMarker; init->HighlightMarker = highlightMarker; init->DeHighlightMarker = deHighlightMarker; init->NewlineCharacters = newLineChars; return(init); } /*----------------------------------------------------------------------*/ void freeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init->ChunkMarker); s_free(init->HighlightMarker); s_free(init->DeHighlightMarker); s_free(init->NewlineCharacters); s_free(init); } /*----------------------------------------------------------------------*/ char* writeInitResponseInfo(init,buffer,len) InitResponseAPDU* init; char* buffer; long* len; /* write an init response object */ { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISInitResponseSize); char* buf = buffer + header_len; WAISInitResponse* info = (WAISInitResponse*)init->UserInformationField; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeNum(info->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(info->ChunkIDLength,DT_ChunkIDLength,buf,len); buf = writeString(info->ChunkMarker,DT_ChunkMarker,buf,len); buf = writeString(info->HighlightMarker,DT_HighlightMarker,buf,len); buf = writeString(info->DeHighlightMarker,DT_DeHighlightMarker,buf,len); buf = writeString(info->NewlineCharacters,DT_NewlineCharacters,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readInitResponseInfo(info,buffer) void** info; char* buffer; /* read an init response object */ { char* buf = buffer; unsigned long size; unsigned long headerSize; long chunkCode,chunkIDLen; data_tag tag1; char* chunkMarker = NULL; char* highlightMarker = NULL; char* deHighlightMarker = NULL; char* newLineChars = NULL; chunkCode = chunkIDLen = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_ChunkCode: buf = readNum(&chunkCode,buf); break; case DT_ChunkIDLength: buf = readNum(&chunkIDLen,buf); break; case DT_ChunkMarker: buf = readString(&chunkMarker,buf); break; case DT_HighlightMarker: buf = readString(&highlightMarker,buf); break; case DT_DeHighlightMarker: buf = readString(&deHighlightMarker,buf); break; case DT_NewlineCharacters: buf = readString(&newLineChars,buf); break; default: s_free(highlightMarker); s_free(deHighlightMarker); s_free(newLineChars); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISInitResponse(chunkCode,chunkIDLen,chunkMarker, highlightMarker,deHighlightMarker, newLineChars); return(buf); } /*----------------------------------------------------------------------*/ WAISSearch* makeWAISSearch(seedWords, docs, textList, dateFactor, beginDateRange, endDateRange, maxDocsRetrieved) char* seedWords; DocObj** docs; char** textList; long dateFactor; char* beginDateRange; char* endDateRange; long maxDocsRetrieved; /* create a type 3 query object */ { WAISSearch* query = (WAISSearch*)s_malloc((size_t)sizeof(WAISSearch)); query->SeedWords = seedWords; /* not copied! */ query->Docs = docs; /* not copied! */ query->TextList = textList; /* not copied! */ query->DateFactor = dateFactor; query->BeginDateRange = beginDateRange; query->EndDateRange = endDateRange; query->MaxDocumentsRetrieved = maxDocsRetrieved; return(query); } /*----------------------------------------------------------------------*/ void freeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { void* ptr = NULL; long i; s_free(query->SeedWords); if (query->Docs != NULL) for (i = 0,ptr = (void *)query->Docs[i]; ptr != NULL; ptr = (void *)query->Docs[++i]) freeDocObj((DocObj*)ptr); s_free(query->Docs); if (query->TextList != NULL) /* XXX revisit when textlist is fully defined */ for (i = 0,ptr = (void *)query->TextList[i]; ptr != NULL; ptr = (void *)query->TextList[++i]) s_free(ptr); s_free(query->TextList); s_free(query->BeginDateRange); s_free(query->EndDateRange); s_free(query); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingWholeDocument(docID,type) any* docID; char* type; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->DocumentID = docID; /* not copied! */ doc->Type = type; /* not copied! */ doc->ChunkCode = CT_document; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingLines(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using line chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_line; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingBytes(docID,type,start,end) any* docID; char* type; long start; long end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_byte; doc->DocumentID = docID; /* not copied */ doc->Type = type; /* not copied! */ doc->ChunkStart.Pos = start; doc->ChunkEnd.Pos = end; return(doc); } /*----------------------------------------------------------------------*/ DocObj* makeDocObjUsingParagraphs(docID,type,start,end) any* docID; char* type; any* start; any* end; /* construct a document object using byte chunks - only for use by servers */ { DocObj* doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); doc->ChunkCode = CT_paragraph; doc->DocumentID = docID; /* not copied */ doc->Type = type; doc->ChunkStart.ID = start; doc->ChunkEnd.ID = end; return(doc); } /*----------------------------------------------------------------------*/ void freeDocObj(doc) DocObj* doc; /* free a docObj */ { freeAny(doc->DocumentID); s_free(doc->Type); if (doc->ChunkCode == CT_paragraph) { freeAny(doc->ChunkStart.ID); freeAny(doc->ChunkEnd.ID); } s_free(doc); } /*----------------------------------------------------------------------*/ static char* writeDocObj PARAMS((DocObj* doc,char* buffer,long* len)); static char* writeDocObj(doc,buffer,len) DocObj* doc; char* buffer; long* len; /* write as little as we can about the doc obj */ { char* buf = buffer; /* we alwasy have to write the id, but its tag depends on if its a chunk */ if (doc->ChunkCode == CT_document) buf = writeAny(doc->DocumentID,DT_DocumentID,buf,len); else buf = writeAny(doc->DocumentID,DT_DocumentIDChunk,buf,len); if (doc->Type != NULL) buf = writeString(doc->Type,DT_TYPE,buf,len); switch (doc->ChunkCode) { case CT_document: /* do nothing - there is no chunk data */ break; case CT_byte: case CT_line: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeNum(doc->ChunkStart.Pos,DT_ChunkStartID,buf,len); buf = writeNum(doc->ChunkEnd.Pos,DT_ChunkEndID,buf,len); break; case CT_paragraph: buf = writeNum(doc->ChunkCode,DT_ChunkCode,buf,len); buf = writeAny(doc->ChunkStart.ID,DT_ChunkStartID,buf,len); buf = writeAny(doc->ChunkEnd.ID,DT_ChunkEndID,buf,len); break; default: panic("Implementation error: unknown chuck type %ld", doc->ChunkCode); break; } return(buf); } /*----------------------------------------------------------------------*/ static char* readDocObj PARAMS((DocObj** doc,char* buffer)); static char* readDocObj(doc,buffer) DocObj** doc; char* buffer; /* read whatever we have about the new document */ { char* buf = buffer; data_tag tag; *doc = (DocObj*)s_malloc((size_t)sizeof(DocObj)); tag = peekTag(buf); buf = readAny(&((*doc)->DocumentID),buf); if (tag == DT_DocumentID) { (*doc)->ChunkCode = CT_document; tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != what comes next */ buf = readString(&((*doc)->Type),buf); /* ChunkStart and ChunkEnd are undefined */ } else if (tag == DT_DocumentIDChunk) { boolean readParagraphs = false; /* for cleanup */ tag = peekTag(buf); if (tag == DT_TYPE) /* XXX depends on DT_TYPE != CT_FOO */ buf = readString(&((*doc)->Type),buf); buf = readNum(&((*doc)->ChunkCode),buf); switch ((*doc)->ChunkCode) { case CT_byte: case CT_line: buf = readNum(&((*doc)->ChunkStart.Pos),buf); buf = readNum(&((*doc)->ChunkEnd.Pos),buf); break; case CT_paragraph: readParagraphs = true; buf = readAny(&((*doc)->ChunkStart.ID),buf); buf = readAny(&((*doc)->ChunkEnd.ID),buf); break; default: freeAny((*doc)->DocumentID); if (readParagraphs) { freeAny((*doc)->ChunkStart.ID); freeAny((*doc)->ChunkEnd.ID); } s_free(doc); REPORT_READ_ERROR(buf); break; } } else { freeAny((*doc)->DocumentID); s_free(*doc); REPORT_READ_ERROR(buf); } return(buf); } /*----------------------------------------------------------------------*/ char* writeSearchInfo(query,buffer,len) SearchAPDU* query; char* buffer; long* len; /* write out a WAIS query (type 1 or 3) */ { if (strcmp(query->QueryType,QT_TextRetrievalQuery) == 0) { return(writeAny((any*)query->Query,DT_Query,buffer,len)); } else { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchSize); char* buf = buffer + header_len; WAISSearch* info = (WAISSearch*)query->Query; unsigned long size; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWords,DT_SeedWords,buf,len); if (info->Docs != NULL) { for (i = 0; info->Docs[i] != NULL; i++) { buf = writeDocObj(info->Docs[i],buf,len); } } /* XXX text list */ buf = writeNum(info->DateFactor,DT_DateFactor,buf,len); buf = writeString(info->BeginDateRange,DT_BeginDateRange,buf,len); buf = writeString(info->EndDateRange,DT_EndDateRange,buf,len); buf = writeNum(info->MaxDocumentsRetrieved,DT_MaxDocumentsRetrieved,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } } /*----------------------------------------------------------------------*/ char* readSearchInfo(info,buffer) void** info; char* buffer; /* read a WAIS query (type 1 or 3) */ { data_tag type = peekTag(buffer); if (type == DT_Query) /* this is a type 1 query */ { char* buf = buffer; any* query = NULL; buf = readAny(&query,buf); *info = (void *)query; return(buf); } else /* a type 3 query */ { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; char* seedWords = NULL; char* beginDateRange = NULL; char* endDateRange = NULL; long dateFactor,maxDocsRetrieved; char** textList = NULL; DocObj** docIDs = NULL; DocObj* doc = NULL; long docs = 0; long i; void* ptr = NULL; dateFactor = maxDocsRetrieved = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWords: buf = readString(&seedWords,buf); break; case DT_DocumentID: case DT_DocumentIDChunk: if (docIDs == NULL) /* create a new doc list */ { docIDs = (DocObj**)s_malloc((size_t)sizeof(DocObj*) * 2); } else /* grow the doc list */ { docIDs = (DocObj**)s_realloc((char*)docIDs,(size_t)(sizeof(DocObj*) * (docs + 2))); } buf = readDocObj(&doc,buf); if (buf == NULL) { s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ } RETURN_ON_NULL(buf); docIDs[docs++] = doc; /* put it in the list */ docIDs[docs] = NULL; break; case DT_TextList: /* XXX */ break; case DT_DateFactor: buf = readNum(&dateFactor,buf); break; case DT_BeginDateRange: buf = readString(&beginDateRange,buf); break; case DT_EndDateRange: buf = readString(&endDateRange,buf); break; case DT_MaxDocumentsRetrieved: buf = readNum(&maxDocsRetrieved,buf); break; default: s_free(seedWords); s_free(beginDateRange); s_free(endDateRange); if (docIDs != NULL) for (i = 0,ptr = (void *)docIDs[i]; ptr != NULL; ptr = (void *)docIDs[++i]) freeDocObj((DocObj*)ptr); s_free(docIDs); /* XXX should also free textlist when it is fully defined */ REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearch(seedWords,docIDs,textList, dateFactor,beginDateRange,endDateRange, maxDocsRetrieved); return(buf); } } /*----------------------------------------------------------------------*/ WAISDocumentHeader* makeWAISDocumentHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; /* construct a standard document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentHeader* header = (WAISDocumentHeader*)s_malloc((size_t)sizeof(WAISDocumentHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeader(header) WAISDocumentHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here ! */ s_free(header->Types); s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeader(header,buffer,len) WAISDocumentHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeaderGroup , DefWAISDocHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeader(header,buffer) WAISDocumentHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; char** types = NULL; char *source = NULL; char *date = NULL; char *headline = NULL; char *originCity = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); buf = readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentShortHeader* makeWAISDocumentShortHeader(docID, versionNumber, score, bestMatch, docLen, lines) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; /* construct a short document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentShortHeader* header = (WAISDocumentShortHeader*)s_malloc((size_t)sizeof(WAISDocumentShortHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { freeAny(header->DocumentID); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentShortHeader(header,buffer,len) WAISDocumentShortHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentShortHeaderGroup , DefWAISShortHeaderSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentShortHeaderGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentShortHeader(header,buffer) WAISDocumentShortHeader** header; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID = NULL; long versionNumber,score,bestMatch,docLength,lines; versionNumber = score = bestMatch = docLength = lines = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; default: freeAny(docID); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentShortHeader(docID,versionNumber,score,bestMatch, docLength,lines); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentLongHeader* makeWAISDocumentLongHeader(docID, versionNumber, score, bestMatch, docLen, lines, types, source, date, headline, originCity, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; long score; long bestMatch; long docLen; long lines; char** types; char* source; char* date; char* headline; char* originCity; char* stockCodes; char* companyCodes; char* industryCodes; /* construct a long document header, note that no fields are copied! if the application needs to save these fields, it should copy them, or set the field in this object to NULL before freeing it. */ { WAISDocumentLongHeader* header = (WAISDocumentLongHeader*)s_malloc((size_t)sizeof(WAISDocumentLongHeader)); header->DocumentID = docID; header->VersionNumber = versionNumber; header->Score = score; header->BestMatch = bestMatch; header->DocumentLength = docLen; header->Lines = lines; header->Types = types; header->Source = source; header->Date = date; header->Headline = headline; header->OriginCity = originCity; header->StockCodes = stockCodes; header->CompanyCodes = companyCodes; header->IndustryCodes = industryCodes; return(header); } /*----------------------------------------------------------------------*/ void freeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { freeAny(header->DocumentID); doList((void**)header->Types,fs_free); /* can't use the macro here! */ s_free(header->Source); s_free(header->Date); s_free(header->Headline); s_free(header->OriginCity); s_free(header->StockCodes); s_free(header->CompanyCodes); s_free(header->IndustryCodes); s_free(header); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentLongHeader(header,buffer,len) WAISDocumentLongHeader* header; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentLongHeaderGroup , DefWAISLongHeaderSize); char* buf = buffer + header_len; unsigned long size1; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(header->DocumentID,DT_DocumentID,buf,len); buf = writeNum(header->VersionNumber,DT_VersionNumber,buf,len); buf = writeNum(header->Score,DT_Score,buf,len); buf = writeNum(header->BestMatch,DT_BestMatch,buf,len); buf = writeNum(header->DocumentLength,DT_DocumentLength,buf,len); buf = writeNum(header->Lines,DT_Lines,buf,len); if (header->Types != NULL) { long size; char* ptr = NULL; long i; buf = writeTag(DT_TYPE_BLOCK,buf,len); for (i = 0,size = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) { long typeSize = strlen(ptr); size += writtenTagSize(DT_TYPE); size += writtenCompressedIntSize(typeSize); size += typeSize; } buf = writeCompressedInteger((unsigned long)size,buf,len); for (i = 0,ptr = header->Types[i]; ptr != NULL; ptr = header->Types[++i]) buf = writeString(ptr,DT_TYPE,buf,len); } buf = writeString(header->Source,DT_Source,buf,len); buf = writeString(header->Date,DT_Date,buf,len); buf = writeString(header->Headline,DT_Headline,buf,len); buf = writeString(header->OriginCity,DT_OriginCity,buf,len); buf = writeString(header->StockCodes,DT_StockCodes,buf,len); buf = writeString(header->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(header->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size1 = buf - buffer; buf = writeUserInfoHeader(DT_DocumentLongHeaderGroup,size1,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentLongHeader(header,buffer) WAISDocumentLongHeader** header; char* buffer; { char* buf = buffer; unsigned long size1; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber,score,bestMatch,docLength,lines; char **types; char *source,*date,*headline,*originCity,*stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = score = bestMatch = docLength = lines = UNUSED; types = NULL; source = date = headline = originCity = stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size1,buf); headerSize = buf - buffer; while (buf < (buffer + size1 + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Score: buf = readNum(&score,buf); break; case DT_BestMatch: buf = readNum(&bestMatch,buf); break; case DT_DocumentLength: buf = readNum(&docLength,buf); break; case DT_Lines: buf = readNum(&lines,buf); break; case DT_TYPE_BLOCK: { unsigned long size = -1; long numTypes = 0; buf = readTag(&tag,buf); readCompressedInteger(&size,buf); while (size > 0) { char* type = NULL; char* originalBuf = buf; buf = readString(&type,buf); types = (char**)s_realloc(types,(size_t)(sizeof(char*) * (numTypes + 2))); types[numTypes++] = type; types[numTypes] = NULL; size -= (buf - originalBuf); } } /* FALLTHRU */ case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *header = makeWAISDocumentLongHeader(docID,versionNumber,score,bestMatch, docLength,lines,types,source,date,headline, originCity,stockCodes,companyCodes, industryCodes); return(buf); } /*----------------------------------------------------------------------*/ WAISSearchResponse* makeWAISSearchResponse(seedWordsUsed, docHeaders, shortHeaders, longHeaders, text, headlines, codes, diagnostics) char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diagnostics; { WAISSearchResponse* response = (WAISSearchResponse*)s_malloc((size_t)sizeof(WAISSearchResponse)); response->SeedWordsUsed = seedWordsUsed; response->DocHeaders = docHeaders; response->ShortHeaders = shortHeaders; response->LongHeaders = longHeaders; response->Text = text; response->Headlines = headlines; response->Codes = codes; response->Diagnostics = diagnostics; return(response); } /*----------------------------------------------------------------------*/ void freeWAISSearchResponse(response) WAISSearchResponse* response; { void* ptr = NULL; long i; s_free(response->SeedWordsUsed); if (response->DocHeaders != NULL) for (i = 0,ptr = (void *)response->DocHeaders[i]; ptr != NULL; ptr = (void *)response->DocHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(response->DocHeaders); if (response->ShortHeaders != NULL) for (i = 0,ptr = (void *)response->ShortHeaders[i]; ptr != NULL; ptr = (void *)response->ShortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(response->ShortHeaders); if (response->LongHeaders != NULL) for (i = 0,ptr = (void *)response->LongHeaders[i]; ptr != NULL; ptr = (void *)response->LongHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(response->LongHeaders); if (response->Text != NULL) for (i = 0,ptr = (void *)response->Text[i]; ptr != NULL; ptr = (void *)response->Text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(response->Text); if (response->Headlines != NULL) for (i = 0,ptr = (void *)response->Headlines[i]; ptr != NULL; ptr = (void *)response->Headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(response->Headlines); if (response->Codes != NULL) for (i = 0,ptr = (void *)response->Codes[i]; ptr != NULL; ptr = (void *)response->Codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(response->Codes); if (response->Diagnostics != NULL) for (i = 0,ptr = (void *)response->Diagnostics[i]; ptr != NULL; ptr = (void *)response->Diagnostics[++i]) freeDiag((diagnosticRecord*)ptr); s_free(response->Diagnostics); s_free(response); } /*----------------------------------------------------------------------*/ char* writeSearchResponseInfo(query,buffer,len) SearchResponseAPDU* query; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_UserInformationLength, DefWAISSearchResponseSize); char* buf = buffer + header_len; WAISSearchResponse* info = (WAISSearchResponse*)query->DatabaseDiagnosticRecords; unsigned long size; void* header = NULL; long i; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeString(info->SeedWordsUsed,DT_SeedWordsUsed,buf,len); /* write out all the headers */ if (info->DocHeaders != NULL) { for (i = 0,header = (void *)info->DocHeaders[i]; header != NULL; header = (void *)info->DocHeaders[++i]) buf = writeWAISDocumentHeader((WAISDocumentHeader*)header,buf,len); } if (info->ShortHeaders != NULL) { for (i = 0,header = (void *)info->ShortHeaders[i]; header != NULL; header = (void *)info->ShortHeaders[++i]) buf = writeWAISDocumentShortHeader((WAISDocumentShortHeader*)header,buf,len); } if (info->LongHeaders != NULL) { for (i = 0,header = (void *)info->LongHeaders[i]; header != NULL; header = (void *)info->LongHeaders[++i]) buf = writeWAISDocumentLongHeader((WAISDocumentLongHeader*)header,buf,len); } if (info->Text != NULL) { for (i = 0,header = (void *)info->Text[i]; header != NULL; header = (void *)info->Text[++i]) buf = writeWAISDocumentText((WAISDocumentText*)header,buf,len); } if (info->Headlines != NULL) { for (i = 0,header = (void *)info->Headlines[i]; header != NULL; header = (void *)info->Headlines[++i]) buf = writeWAISDocumentHeadlines((WAISDocumentHeadlines*)header,buf,len); } if (info->Codes != NULL) { for (i = 0,header = (void *)info->Codes[i]; header != NULL;header = (void *)info->Codes[++i]) buf = writeWAISDocumentCodes((WAISDocumentCodes*)header,buf,len); } if (info->Diagnostics != NULL) { for (i = 0, header = (void *)info->Diagnostics[i]; header != NULL; header = (void *)info->Diagnostics[++i]) buf = writeDiag((diagnosticRecord*)header,buf,len); } /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_UserInformationLength,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ static void cleanUpWaisSearchResponse PARAMS((char* buf,char* seedWordsUsed, WAISDocumentHeader** docHeaders, WAISDocumentShortHeader** shortHeaders, WAISDocumentLongHeader** longHeaders, WAISDocumentText** text, WAISDocumentHeadlines** headlines, WAISDocumentCodes** codes, diagnosticRecord**diags)); static void cleanUpWaisSearchResponse (buf,seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags) char* buf; char* seedWordsUsed; WAISDocumentHeader** docHeaders; WAISDocumentShortHeader** shortHeaders; WAISDocumentLongHeader** longHeaders; WAISDocumentText** text; WAISDocumentHeadlines** headlines; WAISDocumentCodes** codes; diagnosticRecord** diags; /* if buf is NULL, we have just gotten a read error, and need to clean up any state we have built. If not, then everything is going fine, and we should just hang loose */ { void* ptr = NULL; long i; if (buf == NULL) { s_free(seedWordsUsed); if (docHeaders != NULL) for (i = 0,ptr = (void *)docHeaders[i]; ptr != NULL; ptr = (void *)docHeaders[++i]) freeWAISDocumentHeader((WAISDocumentHeader*)ptr); s_free(docHeaders); if (shortHeaders != NULL) for (i = 0,ptr = (void *)shortHeaders[i]; ptr != NULL; ptr = (void *)shortHeaders[++i]) freeWAISDocumentShortHeader((WAISDocumentShortHeader*)ptr); s_free(shortHeaders); if (longHeaders != NULL) for (i = 0,ptr = (void *)longHeaders[i]; ptr != NULL; ptr = (void *)longHeaders[++i]) freeWAISDocumentLongHeader((WAISDocumentLongHeader*)ptr); s_free(longHeaders); if (text != NULL) for (i = 0,ptr = (void *)text[i]; ptr != NULL; ptr = (void *)text[++i]) freeWAISDocumentText((WAISDocumentText*)ptr); s_free(text); if (headlines != NULL) for (i = 0,ptr = (void *)headlines[i]; ptr != NULL; ptr = (void *)headlines[++i]) freeWAISDocumentHeadlines((WAISDocumentHeadlines*)ptr); s_free(headlines); if (codes != NULL) for (i = 0,ptr = (void *)codes[i]; ptr != NULL; ptr = (void *)codes[++i]) freeWAISDocumentCodes((WAISDocumentCodes*)ptr); s_free(codes); if (diags != NULL) for (i = 0,ptr = (void *)diags[i]; ptr != NULL; ptr = (void *)diags[++i]) freeDiag((diagnosticRecord*)ptr); s_free(diags); } } /*----------------------------------------------------------------------*/ char* readSearchResponseInfo(info,buffer) void** info; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; void* header = NULL; WAISDocumentHeader** docHeaders = NULL; WAISDocumentShortHeader** shortHeaders = NULL; WAISDocumentLongHeader** longHeaders = NULL; WAISDocumentText** text = NULL; WAISDocumentHeadlines** headlines = NULL; WAISDocumentCodes** codes = NULL; long numDocHeaders,numLongHeaders,numShortHeaders,numText,numHeadlines; long numCodes; char* seedWordsUsed = NULL; diagnosticRecord** diags = NULL; diagnosticRecord* diag = NULL; long numDiags = 0; numDocHeaders = numLongHeaders = numShortHeaders = numText = numHeadlines = numCodes = 0; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_SeedWordsUsed: buf = readString(&seedWordsUsed,buf); break; case DT_DatabaseDiagnosticRecords: if (diags == NULL) /* create a new diag list */ { diags = (diagnosticRecord**)s_malloc((size_t)sizeof(diagnosticRecord*) * 2); } else /* grow the diag list */ { diags = (diagnosticRecord**)s_realloc((char*)diags,(size_t)(sizeof(diagnosticRecord*) * (numDiags + 2))); } buf = readDiag(&diag,buf); diags[numDiags++] = diag; /* put it in the list */ diags[numDiags] = NULL; break; case DT_DocumentHeaderGroup: if (docHeaders == NULL) /* create a new header list */ { docHeaders = (WAISDocumentHeader**)s_malloc((size_t)sizeof(WAISDocumentHeader*) * 2); } else /* grow the doc list */ { docHeaders = (WAISDocumentHeader**)s_realloc((char*)docHeaders,(size_t)(sizeof(WAISDocumentHeader*) * (numDocHeaders + 2))); } buf = readWAISDocumentHeader((WAISDocumentHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); docHeaders[numDocHeaders++] = (WAISDocumentHeader*)header; /* put it in the list */ docHeaders[numDocHeaders] = NULL; break; case DT_DocumentShortHeaderGroup: if (shortHeaders == NULL) /* create a new header list */ { shortHeaders = (WAISDocumentShortHeader**)s_malloc((size_t)sizeof(WAISDocumentShortHeader*) * 2); } else /* grow the doc list */ { shortHeaders = (WAISDocumentShortHeader**)s_realloc((char*)shortHeaders,(size_t)(sizeof(WAISDocumentShortHeader*) * (numShortHeaders + 2))); } buf = readWAISDocumentShortHeader((WAISDocumentShortHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); shortHeaders[numShortHeaders++] = (WAISDocumentShortHeader*)header; /* put it in the list */ shortHeaders[numShortHeaders] = NULL; break; case DT_DocumentLongHeaderGroup: if (longHeaders == NULL) /* create a new header list */ { longHeaders = (WAISDocumentLongHeader**)s_malloc((size_t)sizeof(WAISDocumentLongHeader*) * 2); } else /* grow the doc list */ { longHeaders = (WAISDocumentLongHeader**)s_realloc((char*)longHeaders,(size_t)(sizeof(WAISDocumentLongHeader*) * (numLongHeaders + 2))); } buf = readWAISDocumentLongHeader((WAISDocumentLongHeader**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); longHeaders[numLongHeaders++] = (WAISDocumentLongHeader*)header; /* put it in the list */ longHeaders[numLongHeaders] = NULL; break; case DT_DocumentTextGroup: if (text == NULL) /* create a new list */ { text = (WAISDocumentText**)s_malloc((size_t)sizeof(WAISDocumentText*) * 2); } else /* grow the list */ { text = (WAISDocumentText**)s_realloc((char*)text,(size_t)(sizeof(WAISDocumentText*) * (numText + 2))); } buf = readWAISDocumentText((WAISDocumentText**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); text[numText++] = (WAISDocumentText*)header; /* put it in the list */ text[numText] = NULL; break; case DT_DocumentHeadlineGroup: if (headlines == NULL) /* create a new list */ { headlines = (WAISDocumentHeadlines**)s_malloc((size_t)sizeof(WAISDocumentHeadlines*) * 2); } else /* grow the list */ { headlines = (WAISDocumentHeadlines**)s_realloc((char*)headlines,(size_t)(sizeof(WAISDocumentHeadlines*) * (numHeadlines + 2))); } buf = readWAISDocumentHeadlines((WAISDocumentHeadlines**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); headlines[numHeadlines++] = (WAISDocumentHeadlines*)header; /* put it in the list */ headlines[numHeadlines] = NULL; break; case DT_DocumentCodeGroup: if (codes == NULL) /* create a new list */ { codes = (WAISDocumentCodes**)s_malloc((size_t)sizeof(WAISDocumentCodes*) * 2); } else /* grow the list */ { codes = (WAISDocumentCodes**)s_realloc((char*)codes,(size_t)(sizeof(WAISDocumentCodes*) * (numCodes + 2))); } buf = readWAISDocumentCodes((WAISDocumentCodes**)&header,buf); cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); RETURN_ON_NULL(buf); codes[numCodes++] = (WAISDocumentCodes*)header; /* put it in the list */ codes[numCodes] = NULL; break; default: cleanUpWaisSearchResponse(buf,seedWordsUsed,docHeaders,shortHeaders,longHeaders,text,headlines,codes,diags); REPORT_READ_ERROR(buf); break; } } *info = (void *)makeWAISSearchResponse(seedWordsUsed,docHeaders,shortHeaders, longHeaders,text,headlines,codes,diags); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentText* makeWAISDocumentText(docID,versionNumber,documentText) any* docID; long versionNumber; any* documentText; { WAISDocumentText* docText = (WAISDocumentText*)s_malloc((size_t)sizeof(WAISDocumentText)); docText->DocumentID = docID; docText->VersionNumber = versionNumber; docText->DocumentText = documentText; return(docText); } /*----------------------------------------------------------------------*/ void freeWAISDocumentText(docText) WAISDocumentText* docText; { freeAny(docText->DocumentID); freeAny(docText->DocumentText); s_free(docText); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentText(docText,buffer,len) WAISDocumentText* docText; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentTextGroup, DefWAISDocTextSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docText->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docText->VersionNumber,DT_VersionNumber,buf,len); buf = writeAny(docText->DocumentText,DT_DocumentText,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentTextGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentText(docText,buffer) WAISDocumentText** docText; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any *docID,*documentText; long versionNumber; docID = documentText = NULL; versionNumber = UNUSED; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_DocumentText: buf = readAny(&documentText,buf); break; default: freeAny(docID); freeAny(documentText); REPORT_READ_ERROR(buf); break; } } *docText = makeWAISDocumentText(docID,versionNumber,documentText); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentHeadlines* makeWAISDocumentHeadlines(docID, versionNumber, source, date, headline, originCity) any* docID; long versionNumber; char* source; char* date; char* headline; char* originCity; { WAISDocumentHeadlines* docHeadline = (WAISDocumentHeadlines*)s_malloc((size_t)sizeof(WAISDocumentHeadlines)); docHeadline->DocumentID = docID; docHeadline->VersionNumber = versionNumber; docHeadline->Source = source; docHeadline->Date = date; docHeadline->Headline = headline; docHeadline->OriginCity = originCity; return(docHeadline); } /*----------------------------------------------------------------------*/ void freeWAISDocumentHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { freeAny(docHeadline->DocumentID); s_free(docHeadline->Source); s_free(docHeadline->Date); s_free(docHeadline->Headline); s_free(docHeadline->OriginCity); s_free(docHeadline); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentHeadlines(docHeadline,buffer,len) WAISDocumentHeadlines* docHeadline; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentHeadlineGroup, DefWAISDocHeadlineSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docHeadline->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docHeadline->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docHeadline->Source,DT_Source,buf,len); buf = writeString(docHeadline->Date,DT_Date,buf,len); buf = writeString(docHeadline->Headline,DT_Headline,buf,len); buf = writeString(docHeadline->OriginCity,DT_OriginCity,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentHeadlineGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentHeadlines(docHeadline,buffer) WAISDocumentHeadlines** docHeadline; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *source,*date,*headline,*originCity; docID = NULL; versionNumber = UNUSED; source = date = headline = originCity = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_Source: buf = readString(&source,buf); break; case DT_Date: buf = readString(&date,buf); break; case DT_Headline: buf = readString(&headline,buf); break; case DT_OriginCity: buf = readString(&originCity,buf); break; default: freeAny(docID); s_free(source); s_free(date); s_free(headline); s_free(originCity); REPORT_READ_ERROR(buf); break; } } *docHeadline = makeWAISDocumentHeadlines(docID,versionNumber,source,date, headline,originCity); return(buf); } /*----------------------------------------------------------------------*/ WAISDocumentCodes* makeWAISDocumentCodes(docID, versionNumber, stockCodes, companyCodes, industryCodes) any* docID; long versionNumber; char* stockCodes; char* companyCodes; char* industryCodes; { WAISDocumentCodes* docCodes = (WAISDocumentCodes*)s_malloc((size_t)sizeof(WAISDocumentCodes)); docCodes->DocumentID = docID; docCodes->VersionNumber = versionNumber; docCodes->StockCodes = stockCodes; docCodes->CompanyCodes = companyCodes; docCodes->IndustryCodes = industryCodes; return(docCodes); } /*----------------------------------------------------------------------*/ void freeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { freeAny(docCodes->DocumentID); s_free(docCodes->StockCodes); s_free(docCodes->CompanyCodes); s_free(docCodes->IndustryCodes); s_free(docCodes); } /*----------------------------------------------------------------------*/ char* writeWAISDocumentCodes(docCodes,buffer,len) WAISDocumentCodes* docCodes; char* buffer; long* len; { unsigned long header_len = userInfoTagSize(DT_DocumentCodeGroup , DefWAISDocCodeSize); char* buf = buffer + header_len; unsigned long size; RESERVE_SPACE_FOR_WAIS_HEADER(len); buf = writeAny(docCodes->DocumentID,DT_DocumentID,buf,len); buf = writeNum(docCodes->VersionNumber,DT_VersionNumber,buf,len); buf = writeString(docCodes->StockCodes,DT_StockCodes,buf,len); buf = writeString(docCodes->CompanyCodes,DT_CompanyCodes,buf,len); buf = writeString(docCodes->IndustryCodes,DT_IndustryCodes,buf,len); /* now write the header and size */ size = buf - buffer; buf = writeUserInfoHeader(DT_DocumentCodeGroup,size,header_len,buffer,len); return(buf); } /*----------------------------------------------------------------------*/ char* readWAISDocumentCodes(docCodes,buffer) WAISDocumentCodes** docCodes; char* buffer; { char* buf = buffer; unsigned long size; unsigned long headerSize; data_tag tag1; any* docID; long versionNumber; char *stockCodes,*companyCodes,*industryCodes; docID = NULL; versionNumber = UNUSED; stockCodes = companyCodes = industryCodes = NULL; buf = readUserInfoHeader(&tag1,&size,buf); headerSize = buf - buffer; while (buf < (buffer + size + headerSize)) { data_tag tag = peekTag(buf); switch (tag) { case DT_DocumentID: buf = readAny(&docID,buf); break; case DT_VersionNumber: buf = readNum(&versionNumber,buf); break; case DT_StockCodes: buf = readString(&stockCodes,buf); break; case DT_CompanyCodes: buf = readString(&companyCodes,buf); break; case DT_IndustryCodes: buf = readString(&industryCodes,buf); break; default: freeAny(docID); s_free(stockCodes); s_free(companyCodes); s_free(industryCodes); REPORT_READ_ERROR(buf); break; } } *docCodes = makeWAISDocumentCodes(docID,versionNumber,stockCodes, companyCodes,industryCodes); return(buf); } /*----------------------------------------------------------------------*/ char* writePresentInfo(present,buffer,len) PresentAPDU* present GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use present info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use present info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ char* writePresentResponseInfo(response,buffer,len) PresentResponseAPDU* response GCC_UNUSED; char* buffer; long* len GCC_UNUSED; { /* The WAIS protocol doesn't use presentResponse info */ return(buffer); } /*----------------------------------------------------------------------*/ char* readPresentResponseInfo(info,buffer) void** info; char* buffer; { /* The WAIS protocol doesn't use presentResponse info */ *info = NULL; return(buffer); } /*----------------------------------------------------------------------*/ /* support for type 1 queries */ /* new use values (for the chunk types) */ #define BYTE "wb" #define LINE "wl" #define PARAGRAPH "wp" #define DATA_TYPE "wt" /* WAIS supports the following semantics for type 1 queries: 1. retrieve the header/codes from a document: System_Control_Number = docID Data Type = type (optional) And 2. retrieve a fragment of the text of a document: System_Control_Number = docID Data Type = type (optional) And Chunk >= start And Chunk < end And Information from multiple documents may be requested by using groups of the above joined by: OR ( XXX does an OR come after every group but the first, or do they all come at the end? ) ( XXX return type could be in the element set) */ static query_term** makeWAISQueryTerms PARAMS((DocObj** docs)); static query_term** makeWAISQueryTerms(docs) DocObj** docs; /* given a null terminated list of docObjs, construct the appropriate query of the form given above */ { query_term** terms = NULL; long numTerms = 0; DocObj* doc = NULL; long i; if (docs == NULL) return((query_term**)NULL); terms = (query_term**)s_malloc((size_t)(sizeof(query_term*) * 1)); terms[numTerms] = NULL; /* loop through the docs making terms for them all */ for (i = 0,doc = docs[i]; doc != NULL; doc = docs[++i]) { any* type = NULL; if (doc->Type != NULL) type = stringToAny(doc->Type); if (doc->ChunkCode == CT_document) /* a whole document */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 3 + 1))); terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE,IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL, IGNORE,IGNORE,IGNORE, IGNORE,type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms] = NULL; } else /* a document fragment */ { char chunk_att[ATTRIBUTE_SIZE]; any* startChunk = NULL; any* endChunk = NULL; terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 7 + 1))); switch (doc->ChunkCode) { case CT_byte: case CT_line: { char start[20],end[20]; (doc->ChunkCode == CT_byte) ? strncpy(chunk_att,BYTE,ATTRIBUTE_SIZE) : strncpy(chunk_att,LINE,ATTRIBUTE_SIZE); sprintf(start,"%ld",doc->ChunkStart.Pos); startChunk = stringToAny(start); sprintf(end,"%ld",doc->ChunkEnd.Pos); endChunk = stringToAny(end); } break; case CT_paragraph: strncpy(chunk_att,PARAGRAPH,ATTRIBUTE_SIZE); startChunk = doc->ChunkStart.ID; endChunk = doc->ChunkEnd.ID; break; default: /* error */ break; } terms[numTerms++] = makeAttributeTerm(SYSTEM_CONTROL_NUMBER, EQUAL,IGNORE,IGNORE, IGNORE, IGNORE,doc->DocumentID); if (type != NULL) { terms[numTerms++] = makeAttributeTerm(DATA_TYPE,EQUAL,IGNORE, IGNORE,IGNORE,IGNORE, type); terms[numTerms++] = makeOperatorTerm(AND); } terms[numTerms++] = makeAttributeTerm(chunk_att, GREATER_THAN_OR_EQUAL, IGNORE,IGNORE,IGNORE, IGNORE, startChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms++] = makeAttributeTerm(chunk_att,LESS_THAN, IGNORE,IGNORE,IGNORE, IGNORE, endChunk); terms[numTerms++] = makeOperatorTerm(AND); terms[numTerms] = NULL; if (doc->ChunkCode == CT_byte || doc->ChunkCode == CT_line) { freeAny(startChunk); freeAny(endChunk); } } freeAny(type); if (i != 0) /* multiple independent queries, need a disjunction */ { terms = (query_term**)s_realloc((char*)terms, (size_t)(sizeof(query_term*) * (numTerms + 1 + 1))); terms[numTerms++] = makeOperatorTerm(OR); terms[numTerms] = NULL; } } return(terms); } /*----------------------------------------------------------------------*/ static DocObj** makeWAISQueryDocs PARAMS((query_term** terms)); static DocObj** makeWAISQueryDocs(terms) query_term** terms; /* given a list of terms in the form given above, convert them to DocObjs. */ { query_term* docTerm = NULL; query_term* fragmentTerm = NULL; DocObj** docs = NULL; DocObj* doc = NULL; long docNum,termNum; docNum = termNum = 0; docs = (DocObj**)s_malloc((size_t)(sizeof(DocObj*) * 1)); docs[docNum] = NULL; /* translate the terms into DocObjs */ while (true) { query_term* typeTerm = NULL; char* type = NULL; long startTermOffset; docTerm = terms[termNum]; if (docTerm == NULL) break; /* we're done converting */ typeTerm = terms[termNum + 1]; /* get the lead Term if it exists */ if (strcmp(typeTerm->Use,DATA_TYPE) == 0) /* we do have a type */ { startTermOffset = 3; type = anyToString(typeTerm->Term); } else /* no type */ { startTermOffset = 1; typeTerm = NULL; type = NULL; } /* grow the doc list */ docs = (DocObj**)s_realloc((char*)docs,(size_t)(sizeof(DocObj*) * (docNum + 1 + 1))); /* figure out what kind of docObj to build - and build it */ fragmentTerm = terms[termNum + startTermOffset]; if (fragmentTerm != NULL && fragmentTerm->TermType == TT_Attribute) { /* build a document fragment */ query_term* startTerm = fragmentTerm; query_term* endTerm = terms[termNum + startTermOffset + 2]; if (strcmp(startTerm->Use,BYTE) == 0){ /* a byte chunk */ doc = makeDocObjUsingBytes(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("byte"); }else if (strcmp(startTerm->Use,LINE) == 0){ /* a line chunk */ doc = makeDocObjUsingLines(duplicateAny(docTerm->Term), type, anyToLong(startTerm->Term), anyToLong(endTerm->Term)); log_write("line"); }else{ log_write("chunk"); /* a paragraph chunk */ doc = makeDocObjUsingParagraphs(duplicateAny(docTerm->Term), type, duplicateAny(startTerm->Term), duplicateAny(endTerm->Term)); } termNum += (startTermOffset + 4); /* point to next term */ } else /* build a full document */ { doc = makeDocObjUsingWholeDocument(duplicateAny(docTerm->Term), type); log_write("whole doc"); termNum += startTermOffset; /* point to next term */ } docs[docNum++] = doc; /* insert the new document */ docs[docNum] = NULL; /* keep the doc list terminated */ if (terms[termNum] != NULL) termNum++; /* skip the OR operator it necessary */ else break; /* we are done */ } return(docs); } /*----------------------------------------------------------------------*/ any* makeWAISTextQuery(docs) DocObj** docs; /* given a list of DocObjs, return an any whose contents is the corresponding type 1 query */ { any *buf = NULL; query_term** terms = NULL; terms = makeWAISQueryTerms(docs); buf = writeQuery(terms); doList((void**)terms,freeTerm); s_free(terms); return(buf); } /*----------------------------------------------------------------------*/ DocObj** readWAISTextQuery(buf) any* buf; /* given an any whose contents are type 1 queries of the WAIS sort, construct a list of the corresponding DocObjs */ { query_term** terms = NULL; DocObj** docs = NULL; terms = readQuery(buf); docs = makeWAISQueryDocs(terms); doList((void**)terms,freeTerm); s_free(terms); return(docs); } /*----------------------------------------------------------------------*/ /* Customized free WAIS object routines: */ /* */ /* This set of procedures is for applications to free a WAIS object */ /* which was made with makeWAISFOO. */ /* Each procedure frees only the memory that was allocated in its */ /* associated makeWAISFOO routine, thus it's not necessary for the */ /* caller to assign nulls to the pointer fields of the WAIS object. */ /*----------------------------------------------------------------------*/ void CSTFreeWAISInitResponse(init) WAISInitResponse* init; /* free an object made with makeWAISInitResponse */ { s_free(init); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearch(query) WAISSearch* query; /* destroy an object made with makeWAISSearch() */ { s_free(query); } /*----------------------------------------------------------------------*/ void CSTFreeDocObj(doc) DocObj* doc; /* free a docObj */ { s_free(doc); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentHeader(header) WAISDocumentHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentShortHeader(header) WAISDocumentShortHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentLongHeader(header) WAISDocumentLongHeader* header; { s_free(header); } /*----------------------------------------------------------------------*/ void CSTFreeWAISSearchResponse(response) WAISSearchResponse* response; { s_free(response); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentText(docText) WAISDocumentText* docText; { s_free(docText); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocHeadlines(docHeadline) WAISDocumentHeadlines* docHeadline; { s_free(docHeadline); } /*----------------------------------------------------------------------*/ void CSTFreeWAISDocumentCodes(docCodes) WAISDocumentCodes* docCodes; { s_free(docCodes); } /*----------------------------------------------------------------------*/ void CSTFreeWAISTextQuery(query) any* query; { freeAny(query); } /*----------------------------------------------------------------------*/ /* ** Routines originally from WMessage.c -- FM ** **----------------------------------------------------------------------*/ /* WIDE AREA INFORMATION SERVER SOFTWARE No guarantees or restrictions. See the readme file for the full standard disclaimer. 3.26.90 */ /* This file is for reading and writing the wais packet header. * [email protected] */ /* to do: * add check sum * what do you do when checksum is wrong? */ /*---------------------------------------------------------------------*/ void readWAISPacketHeader(msgBuffer,header_struct) char* msgBuffer; WAISMessage *header_struct; { /* msgBuffer is a string containing at least HEADER_LENGTH bytes. */ memmove(header_struct->msg_len,msgBuffer,(size_t)10); header_struct->msg_type = char_downcase((unsigned long)msgBuffer[10]); header_struct->hdr_vers = char_downcase((unsigned long)msgBuffer[11]); memmove(header_struct->server,(void*)(msgBuffer + 12),(size_t)10); header_struct->compression = char_downcase((unsigned long)msgBuffer[22]); header_struct->encoding = char_downcase((unsigned long)msgBuffer[23]); header_struct->msg_checksum = char_downcase((unsigned long)msgBuffer[24]); } /*---------------------------------------------------------------------*/ /* this modifies the header argument. See wais-message.h for the different * options for the arguments. */ void writeWAISPacketHeader(header, dataLen, type, server, compression, encoding, version) char* header; long dataLen; long type; char* server; long compression; long encoding; long version; /* Puts together the new wais before-the-z39-packet header. */ { char lengthBuf[11]; char serverBuf[11]; long serverLen = strlen(server); if (serverLen > 10) serverLen = 10; sprintf(lengthBuf, "%010ld", dataLen); strncpy(header,lengthBuf,10); header[10] = type & 0xFF; header[11] = version & 0xFF; strncpy(serverBuf,server,serverLen); strncpy((char*)(header + 12),serverBuf,serverLen); header[22] = compression & 0xFF; header[23] = encoding & 0xFF; header[24] = '0'; /* checkSum(header + HEADER_LENGTH,dataLen); XXX the result must be ascii */ } /*---------------------------------------------------------------------*/
avsm/openbsd-lynx
WWW/Library/Implementation/HTVMS_WaisProt.c
C
gpl-2.0
69,533
<?php defined('ABSPATH') OR exit; if(!class_exists('Picturefill_WP_Function_Helpers')){ class Picturefill_WP_Function_Helpers{ private $filter = ''; private $cache_duration = 86400; private $image_sizes_to_remove = array(); private $image_size_to_add = ''; private $insert_before = ''; private $image_size_array = array(); private $new_image_size_queue = array(); public $post_type_to_exclude = ''; public $post_id_to_exclude = ''; public $post_slug_to_exclude = ''; public $post_tag_to_exclude = ''; public $post_category_to_exclude = ''; public static function retina_only($default_image_sizes, $image_attributes){ if('full' === $image_attributes['size'][1]){ return array($image_attributes['size'][1]); }else{ return array( $image_attributes['size'][1], $image_attributes['size'][1] . '@2x' ); } } public static function remove_line_breaks($output){ return str_replace("\n", '', $output); } public static function min_template($template_file_path, $template, $template_path){ return $template_path . 'min/' . $template . '-template.php'; } public function apply_to_filter($filter){ $this->filter = $filter; add_filter($filter, array($this, '_apply_picturefill_wp_to_filter')); } public function set_cache_duration($cache_duration){ $this->cache_duration = $cache_duration; add_filter('picturefill_wp_cache_duration', array($this, '_set_cache_duration')); } public function remove_image_from_responsive_list($image_size){ if('string' === gettype($image_size)){ $this->image_sizes_to_remove = array($image_size, $image_size . '@2x'); }elseif('array' === gettype($image_size)){ $this->image_sizes_to_remove = array(); foreach($image_size as $size){ $this->image_sizes_to_remove[] = $size; $this->image_sizes_to_remove[] = $size . '@2x'; } } add_filter('picturefill_wp_image_sizes', array($this, '_remove_image_from_responsive_list'), 10, 2); } public function add_image_to_responsive_queue($image_size, $insert_before){ $this->image_size_to_add = $image_size; $this->insert_before = $insert_before; add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2); add_filter('picturefill_wp_image_sizes', array($this, '_add_size_to_responsive_image_list'), 11, 2); } public function set_responsive_image_sizes($image_size_array){ $this->image_size_array = $image_size_array; $this->new_image_size_queue = $this->setup_responsive_image_sizes($image_size_array); add_filter('picturefill_wp_image_sizes', array($this, '_set_responsive_image_sizes'), 10, 2); add_filter('picturefill_wp_image_attachment_data', array($this, '_set_new_responsive_image_attachment_data'), 10, 2); } public function apply_to_post_thumbnail(){ $this->image_size_to_add = 'post-thumbnail'; add_action('init', array($this, '_add_retina_post_thumbnail')); add_filter('post_thumbnail_html', array($this, '_add_size_to_post_thumbnail_class'), 9, 5); add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2); add_filter('picturefill_wp_image_sizes', array($this, '_post_thumbnail_sizes'), 10, 2); $this->apply_to_filter('post_thumbnail_html'); } public function exclude_post_type($post){ if($this->post_type_to_exclude === $post->post_type){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_id($post){ if($this->post_id_to_exclude === $post->ID){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_slug($post){ if($this->post_slug_to_exclude === $post->post_name){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_tag($post){ $post_tags = wp_get_post_tags($post->ID, array('fields' => 'names')); if(in_array($this->post_tag_to_exclude, $post_tags)){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function exclude_post_category($post){ $post_tags = wp_get_post_categories($post->ID, array('fields' => 'names')); if(in_array($this->post_category_to_exclude, $post_tags)){ remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11); } } public function _set_responsive_image_sizes($image_queue, $image_attributes){ $new_image_queue = array(); $minimum_reached = empty($image_attributes['min-size'][1]) ? true : false; foreach($this->new_image_size_queue as $image_name){ if($minimum_reached || $image_attributes['min-size'][1] === $image_name){ $minimum_reached = true; $new_image_queue[] = $image_name; $new_image_queue[] = $image_name . '@2x'; } if($image_attributes['size'][1] === $image_name){ return $new_image_queue; } } return !empty($new_image_queue) ? $new_image_queue : $image_queue; } public function _set_new_responsive_image_attachment_data($attachment_data, $id){ $new_attachment_data = array(); foreach($this->new_image_size_queue as $size){ $new_attachment_data[$size] = wp_get_attachment_image_src($id, $size); } return array_merge($attachment_data, $new_attachment_data); } public function _post_thumbnail_sizes($default_image_sizes, $image_attributes){ return 'post-thumbnail' === $image_attributes['size'][1] ? array( 'post-thumbnail', 'post-thumbnail@2x' ) : $default_image_sizes; } public function _add_retina_post_thumbnail(){ global $_wp_additional_image_sizes; add_image_size('post-thumbnail@2x', $_wp_additional_image_sizes['post-thumbnail']['width'] * 2, $_wp_additional_image_sizes['post-thumbnail']['height'] * 2, $_wp_additional_image_sizes['post-thumbnail']['crop']); } public function _add_size_to_post_thumbnail_class($html, $post_id, $post_thumbnail_id, $size, $attr){ return preg_replace('/class="([^"]+)"/', 'class="$1 size-' . $size . '"', $html); } public function _add_size_to_responsive_image_list($image_sizes, $image_attributes){ if('@2x' === substr($this->insert_before, -3)){ return $image_sizes; } $position = array_search($this->insert_before, $image_sizes); if($image_attributes['min_size'] !== $this->insert_before){ if(1 > $position){ return array_merge(array($this->image_size_to_add, $this->image_size_to_add . '@2x'), $image_sizes); }else{ array_splice($image_sizes, $position, 0, array($this->image_size_to_add, $this->image_size_to_add . '@2x')); return $image_sizes; } }else{ return $image_sizes; } } public function _add_size_attachment_data($attachment_data, $attachment_id){ $new_size_data = array( $this->image_size_to_add => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add), $this->image_size_to_add . '@2x' => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add . '@2x') ); return array_merge($attachment_data, $new_size_data); } public function _apply_picturefill_wp_to_filter($content){ return Picturefill_WP::get_instance()->cache_picturefill_output($content, $this->filter); } public function _set_cache_duration($old_cache_duration){ return $this->cache_duration; } public function _remove_image_from_responsive_list($image_sizes, $image_attributes){ return array_diff($image_sizes, $this->image_sizes_to_remove); } private function setup_responsive_image_sizes($image_size_array){ global $_wp_additional_image_sizes; $existing_image_sizes = get_intermediate_image_sizes(); $new_image_queue = array(); foreach($image_size_array as $image_name){ if('@2x' === substr($image_name, -3) || !in_array($image_name, $existing_image_sizes)){ return $new_image_queue; } if(!in_array($image_name . '@2x', $existing_image_sizes)){ add_image_size($image_name . '@2x', $_wp_additional_image_sizes[$image_name]['width'] * 2, $_wp_additional_image_sizes[$image_name]['height'] * 2, $_wp_additional_image_sizes[$image_name]['crop']); } $new_image_queue[] = $image_name; // $new_image_queue[] = $image_name . '@2x'; } return $new_image_queue; } } }
fndtn357/client
wp-content/plugins/picturefillwp/inc/class-picturefill-wp-function-helpers.php
PHP
gpl-2.0
8,987
/****************************************************************************** ** kjmp2 -- a minimal MPEG-1/2 Audio Layer II decoder library ** ** version 1.1 ** ******************************************************************************* ** Copyright (C) 2006-2013 Martin J. Fiedler <[email protected]> ** ** ** ** This software is provided 'as-is', without any express or implied ** ** warranty. In no event will the authors be held liable for any damages ** ** arising from the use of this software. ** ** ** ** Permission is granted to anyone to use this software for any purpose, ** ** including commercial applications, and to alter it and redistribute it ** ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** ** claim that you wrote the original software. If you use this software ** ** in a product, an acknowledgment in the product documentation would ** ** be appreciated but is not required. ** ** 2. Altered source versions must be plainly marked as such, and must not ** ** be misrepresented as being the original software. ** ** 3. This notice may not be removed or altered from any source ** ** distribution. ** ******************************************************************************/ // // Code adapted of the original code: // - it is made into a class for use within the framework // of the sdr-j DAB/DAB+ software // #include "mp2processor.h" #include "radio.h" #include "pad-handler.h" #ifdef _MSC_VER #define FASTCALL __fastcall #else #define FASTCALL #endif //////////////////////////////////////////////////////////////////////////////// // TABLES AND CONSTANTS // //////////////////////////////////////////////////////////////////////////////// // mode constants #define STEREO 0 #define JOINT_STEREO 1 #define DUAL_CHANNEL 2 #define MONO 3 // sample rate table static const unsigned short sample_rates[8] = { 44100, 48000, 32000, 0, // MPEG-1 22050, 24000, 16000, 0 // MPEG-2 }; // bitrate table static const short bitrates[28] = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, // MPEG-1 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 // MPEG-2 }; // scale factor base values (24-bit fixed-point) static const int scf_base [3] = {0x02000000, 0x01965FEA, 0x01428A30}; // synthesis window static const int D[512] = { 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,-0x00001, -0x00001,-0x00001,-0x00001,-0x00002,-0x00002,-0x00003,-0x00003,-0x00004, -0x00004,-0x00005,-0x00006,-0x00006,-0x00007,-0x00008,-0x00009,-0x0000A, -0x0000C,-0x0000D,-0x0000F,-0x00010,-0x00012,-0x00014,-0x00017,-0x00019, -0x0001C,-0x0001E,-0x00022,-0x00025,-0x00028,-0x0002C,-0x00030,-0x00034, -0x00039,-0x0003E,-0x00043,-0x00048,-0x0004E,-0x00054,-0x0005A,-0x00060, -0x00067,-0x0006E,-0x00074,-0x0007C,-0x00083,-0x0008A,-0x00092,-0x00099, -0x000A0,-0x000A8,-0x000AF,-0x000B6,-0x000BD,-0x000C3,-0x000C9,-0x000CF, 0x000D5, 0x000DA, 0x000DE, 0x000E1, 0x000E3, 0x000E4, 0x000E4, 0x000E3, 0x000E0, 0x000DD, 0x000D7, 0x000D0, 0x000C8, 0x000BD, 0x000B1, 0x000A3, 0x00092, 0x0007F, 0x0006A, 0x00053, 0x00039, 0x0001D,-0x00001,-0x00023, -0x00047,-0x0006E,-0x00098,-0x000C4,-0x000F3,-0x00125,-0x0015A,-0x00190, -0x001CA,-0x00206,-0x00244,-0x00284,-0x002C6,-0x0030A,-0x0034F,-0x00396, -0x003DE,-0x00427,-0x00470,-0x004B9,-0x00502,-0x0054B,-0x00593,-0x005D9, -0x0061E,-0x00661,-0x006A1,-0x006DE,-0x00718,-0x0074D,-0x0077E,-0x007A9, -0x007D0,-0x007EF,-0x00808,-0x0081A,-0x00824,-0x00826,-0x0081F,-0x0080E, 0x007F5, 0x007D0, 0x007A0, 0x00765, 0x0071E, 0x006CB, 0x0066C, 0x005FF, 0x00586, 0x00500, 0x0046B, 0x003CA, 0x0031A, 0x0025D, 0x00192, 0x000B9, -0x0002C,-0x0011F,-0x00220,-0x0032D,-0x00446,-0x0056B,-0x0069B,-0x007D5, -0x00919,-0x00A66,-0x00BBB,-0x00D16,-0x00E78,-0x00FDE,-0x01148,-0x012B3, -0x01420,-0x0158C,-0x016F6,-0x0185C,-0x019BC,-0x01B16,-0x01C66,-0x01DAC, -0x01EE5,-0x02010,-0x0212A,-0x02232,-0x02325,-0x02402,-0x024C7,-0x02570, -0x025FE,-0x0266D,-0x026BB,-0x026E6,-0x026ED,-0x026CE,-0x02686,-0x02615, -0x02577,-0x024AC,-0x023B2,-0x02287,-0x0212B,-0x01F9B,-0x01DD7,-0x01BDD, 0x019AE, 0x01747, 0x014A8, 0x011D1, 0x00EC0, 0x00B77, 0x007F5, 0x0043A, 0x00046,-0x003E5,-0x00849,-0x00CE3,-0x011B4,-0x016B9,-0x01BF1,-0x0215B, -0x026F6,-0x02CBE,-0x032B3,-0x038D3,-0x03F1A,-0x04586,-0x04C15,-0x052C4, -0x05990,-0x06075,-0x06771,-0x06E80,-0x0759F,-0x07CCA,-0x083FE,-0x08B37, -0x09270,-0x099A7,-0x0A0D7,-0x0A7FD,-0x0AF14,-0x0B618,-0x0BD05,-0x0C3D8, -0x0CA8C,-0x0D11D,-0x0D789,-0x0DDC9,-0x0E3DC,-0x0E9BD,-0x0EF68,-0x0F4DB, -0x0FA12,-0x0FF09,-0x103BD,-0x1082C,-0x10C53,-0x1102E,-0x113BD,-0x116FB, -0x119E8,-0x11C82,-0x11EC6,-0x120B3,-0x12248,-0x12385,-0x12467,-0x124EF, 0x1251E, 0x124F0, 0x12468, 0x12386, 0x12249, 0x120B4, 0x11EC7, 0x11C83, 0x119E9, 0x116FC, 0x113BE, 0x1102F, 0x10C54, 0x1082D, 0x103BE, 0x0FF0A, 0x0FA13, 0x0F4DC, 0x0EF69, 0x0E9BE, 0x0E3DD, 0x0DDCA, 0x0D78A, 0x0D11E, 0x0CA8D, 0x0C3D9, 0x0BD06, 0x0B619, 0x0AF15, 0x0A7FE, 0x0A0D8, 0x099A8, 0x09271, 0x08B38, 0x083FF, 0x07CCB, 0x075A0, 0x06E81, 0x06772, 0x06076, 0x05991, 0x052C5, 0x04C16, 0x04587, 0x03F1B, 0x038D4, 0x032B4, 0x02CBF, 0x026F7, 0x0215C, 0x01BF2, 0x016BA, 0x011B5, 0x00CE4, 0x0084A, 0x003E6, -0x00045,-0x00439,-0x007F4,-0x00B76,-0x00EBF,-0x011D0,-0x014A7,-0x01746, 0x019AE, 0x01BDE, 0x01DD8, 0x01F9C, 0x0212C, 0x02288, 0x023B3, 0x024AD, 0x02578, 0x02616, 0x02687, 0x026CF, 0x026EE, 0x026E7, 0x026BC, 0x0266E, 0x025FF, 0x02571, 0x024C8, 0x02403, 0x02326, 0x02233, 0x0212B, 0x02011, 0x01EE6, 0x01DAD, 0x01C67, 0x01B17, 0x019BD, 0x0185D, 0x016F7, 0x0158D, 0x01421, 0x012B4, 0x01149, 0x00FDF, 0x00E79, 0x00D17, 0x00BBC, 0x00A67, 0x0091A, 0x007D6, 0x0069C, 0x0056C, 0x00447, 0x0032E, 0x00221, 0x00120, 0x0002D,-0x000B8,-0x00191,-0x0025C,-0x00319,-0x003C9,-0x0046A,-0x004FF, -0x00585,-0x005FE,-0x0066B,-0x006CA,-0x0071D,-0x00764,-0x0079F,-0x007CF, 0x007F5, 0x0080F, 0x00820, 0x00827, 0x00825, 0x0081B, 0x00809, 0x007F0, 0x007D1, 0x007AA, 0x0077F, 0x0074E, 0x00719, 0x006DF, 0x006A2, 0x00662, 0x0061F, 0x005DA, 0x00594, 0x0054C, 0x00503, 0x004BA, 0x00471, 0x00428, 0x003DF, 0x00397, 0x00350, 0x0030B, 0x002C7, 0x00285, 0x00245, 0x00207, 0x001CB, 0x00191, 0x0015B, 0x00126, 0x000F4, 0x000C5, 0x00099, 0x0006F, 0x00048, 0x00024, 0x00002,-0x0001C,-0x00038,-0x00052,-0x00069,-0x0007E, -0x00091,-0x000A2,-0x000B0,-0x000BC,-0x000C7,-0x000CF,-0x000D6,-0x000DC, -0x000DF,-0x000E2,-0x000E3,-0x000E3,-0x000E2,-0x000E0,-0x000DD,-0x000D9, 0x000D5, 0x000D0, 0x000CA, 0x000C4, 0x000BE, 0x000B7, 0x000B0, 0x000A9, 0x000A1, 0x0009A, 0x00093, 0x0008B, 0x00084, 0x0007D, 0x00075, 0x0006F, 0x00068, 0x00061, 0x0005B, 0x00055, 0x0004F, 0x00049, 0x00044, 0x0003F, 0x0003A, 0x00035, 0x00031, 0x0002D, 0x00029, 0x00026, 0x00023, 0x0001F, 0x0001D, 0x0001A, 0x00018, 0x00015, 0x00013, 0x00011, 0x00010, 0x0000E, 0x0000D, 0x0000B, 0x0000A, 0x00009, 0x00008, 0x00007, 0x00007, 0x00006, 0x00005, 0x00005, 0x00004, 0x00004, 0x00003, 0x00003, 0x00002, 0x00002, 0x00002, 0x00002, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001 }; ///////////// Table 3-B.2: Possible quantization per subband /////////////////// // quantizer lookup, step 1: bitrate classes static uint8_t quant_lut_step1[2][16] = { // 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384 <- bitrate { 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, // mono // 16, 24, 28, 32, 40, 48, 56, 64, 80, 96,112,128,160,192 <- BR / chan { 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2 } // stereo }; // quantizer lookup, step 2: bitrate class, sample rate -> B2 table idx, sblimit #define QUANT_TAB_A (27 | 64) // Table 3-B.2a: high-rate, sblimit = 27 #define QUANT_TAB_B (30 | 64) // Table 3-B.2b: high-rate, sblimit = 30 #define QUANT_TAB_C 8 // Table 3-B.2c: low-rate, sblimit = 8 #define QUANT_TAB_D 12 // Table 3-B.2d: low-rate, sblimit = 12 static const char quant_lut_step2 [3][4] = { // 44.1 kHz, 48 kHz, 32 kHz { QUANT_TAB_C, QUANT_TAB_C, QUANT_TAB_D }, // 32 - 48 kbit/sec/ch { QUANT_TAB_A, QUANT_TAB_A, QUANT_TAB_A }, // 56 - 80 kbit/sec/ch { QUANT_TAB_B, QUANT_TAB_A, QUANT_TAB_B }, // 96+ kbit/sec/ch }; // quantizer lookup, step 3: B2 table, subband -> nbal, row index // (upper 4 bits: nbal, lower 4 bits: row index) static uint8_t quant_lut_step3 [3][32] = { // low-rate table (3-B.2c and 3-B.2d) { 0x44,0x44, // SB 0 - 1 0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34 // SB 2 - 12 }, // high-rate table (3-B.2a and 3-B.2b) { 0x43,0x43,0x43, // SB 0 - 2 0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42, // SB 3 - 10 0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31, // SB 11 - 22 0x20,0x20,0x20,0x20,0x20,0x20,0x20 // SB 23 - 29 }, // MPEG-2 LSR table (B.2 in ISO 13818-3) { 0x45,0x45,0x45,0x45, // SB 0 - 3 0x34,0x34,0x34,0x34,0x34,0x34,0x34, // SB 4 - 10 0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24, // SB 11 - 0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24 // - 29 } }; // quantizer lookup, step 4: table row, allocation[] value -> quant table index static const char quant_lut_step4 [6][16] = { { 0, 1, 2, 17 }, { 0, 1, 2, 3, 4, 5, 6, 17 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 }, { 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, { 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }; // quantizer table static struct quantizer_spec quantizer_table [17] = { { 3, 1, 5 }, // 1 { 5, 1, 7 }, // 2 { 7, 0, 3 }, // 3 { 9, 1, 10 }, // 4 { 15, 0, 4 }, // 5 { 31, 0, 5 }, // 6 { 63, 0, 6 }, // 7 { 127, 0, 7 }, // 8 { 255, 0, 8 }, // 9 { 511, 0, 9 }, // 10 { 1023, 0, 10 }, // 11 { 2047, 0, 11 }, // 12 { 4095, 0, 12 }, // 13 { 8191, 0, 13 }, // 14 { 16383, 0, 14 }, // 15 { 32767, 0, 15 }, // 16 { 65535, 0, 16 } // 17 }; //////////////////////////////////////////////////////////////////////////////// // The initialization is now done in the constructor // (J van Katwijk) //////////////////////////////////////////////////////////////////////////////// mp2Processor::mp2Processor (RadioInterface *mr, int16_t bitRate, RingBuffer<int16_t> *buffer, RingBuffer<uint8_t> *frameBuffer): my_padhandler (mr) { int16_t i, j; int16_t *nPtr = &N [0][0]; // compute N[i][j] for (i = 0; i < 64; i ++) for (j = 0; j < 32; ++j) *nPtr++ = (int16_t) (256.0 * cos(((16 + i) * ((j << 1) + 1)) * 0.0490873852123405)); // perform local initialization: for (i = 0; i < 2; ++i) for (j = 1023; j >= 0; j--) V [i][j] = 0; myRadioInterface = mr; this -> buffer = buffer; this -> bitRate = bitRate; connect (this, SIGNAL (show_frameErrors (int)), mr, SLOT (show_frameErrors (int))); connect (this, SIGNAL (newAudio (int, int)), mr, SLOT (newAudio (int, int))); connect (this, SIGNAL (isStereo (bool)), mr, SLOT (setStereo (bool))); Voffs = 0; baudRate = 48000; // default for DAB MP2framesize = 24 * bitRate; // may be changed MP2frame = new uint8_t [2 * MP2framesize]; MP2Header_OK = 0; MP2headerCount = 0; MP2bitCount = 0; numberofFrames = 0; errorFrames = 0; } mp2Processor::~mp2Processor() { delete[] MP2frame; } // #define valid(x) ((x == 48000) || (x == 24000)) void mp2Processor::setSamplerate (int32_t rate) { if (baudRate == rate) return; if (!valid (rate)) return; // ourSink -> setMode (0, rate); baudRate = rate; } //////////////////////////////////////////////////////////////////////////////// // INITIALIZATION: is moved into the constructor for the class // // //////////////////////////////////////////////////////////////////////////////// int32_t mp2Processor::mp2sampleRate (uint8_t *frame) { if (!frame) return 0; if (( frame[0] != 0xFF) // no valid syncword? || ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II? || ((frame[2] - 0x10) >= 0xE0)) // invalid bitrate? return 0; return sample_rates[(((frame[1] & 0x08) >> 1) ^ 4) // MPEG-1/2 switch + ((frame[2] >> 2) & 3)]; // actual rate } //////////////////////////////////////////////////////////////////////////////// // DECODE HELPER FUNCTIONS // //////////////////////////////////////////////////////////////////////////////// struct quantizer_spec* mp2Processor::read_allocation (int sb, int b2_table) { int table_idx = quant_lut_step3 [b2_table][sb]; table_idx = quant_lut_step4 [table_idx & 15] [get_bits(table_idx >> 4)]; return table_idx ? (&quantizer_table[table_idx - 1]) : nullptr; } void mp2Processor::read_samples (struct quantizer_spec *q, int scalefactor, int *sample) { int idx, adj, scale; int val; if (!q) { // no bits allocated for this subband sample[0] = sample[1] = sample[2] = 0; return; } // resolve scalefactor if (scalefactor == 63) { scalefactor = 0; } else { adj = scalefactor / 3; scalefactor = (scf_base[scalefactor % 3] + ((1 << adj) >> 1)) >> adj; } // decode samples adj = q -> nlevels; if (q -> grouping) { // decode grouped samples val = get_bits (q -> cw_bits); sample [0] = val % adj; val /= adj; sample [1] = val % adj; sample [2] = val / adj; } else { // decode direct samples for (idx = 0; idx < 3; ++idx) sample [idx] = get_bits (q -> cw_bits); } // postmultiply samples scale = 65536 / (adj + 1); adj = ((adj + 1) >> 1) - 1; for (idx = 0; idx < 3; ++idx) { // step 1: renormalization to [-1..1] val = (adj - sample[idx]) * scale; // step 2: apply scalefactor sample[idx] = ( val * (scalefactor >> 12) // upper part + ((val * (scalefactor & 4095) + 2048) >> 12)) // lower part >> 12; // scale adjust } } #define show_bits(bit_count) (bit_window >> (24 - (bit_count))) int32_t mp2Processor::get_bits (int32_t bit_count) { //int32_t result = show_bits (bit_count); int32_t result = bit_window >> (24 - bit_count); bit_window = (bit_window << bit_count) & 0xFFFFFF; bits_in_window -= bit_count; while (bits_in_window < 16) { bit_window |= (*frame_pos++) << (16 - bits_in_window); bits_in_window += 8; } return result; } //////////////////////////////////////////////////////////////////////////////// // FRAME DECODE FUNCTION // //////////////////////////////////////////////////////////////////////////////// int32_t mp2Processor::mp2decodeFrame (uint8_t *frame, int16_t *pcm) { uint32_t bit_rate_index_minus1; uint32_t sampling_frequency; uint32_t padding_bit; uint32_t mode; uint32_t frame_size; int32_t bound, sblimit; int32_t sb, ch, gr, part, idx, nch, i, j, sum; int32_t table_idx; numberofFrames ++; if (numberofFrames >= 25) { show_frameErrors (errorFrames); numberofFrames = 0; errorFrames = 0; } // check for valid header: syncword OK, MPEG-Audio Layer 2 if (( frame[0] != 0xFF) // no valid syncword? || ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II? || ((frame[2] - 0x10) >= 0xE0)) { // invalid bitrate? errorFrames ++; return 0; } // set up the bitstream reader bit_window = frame [2] << 16; bits_in_window = 8; frame_pos = &frame[3]; // read the rest of the header bit_rate_index_minus1 = get_bits(4) - 1; if (bit_rate_index_minus1 > 13) return 0; // invalid bit rate or 'free format' sampling_frequency = get_bits(2); if (sampling_frequency == 3) return 0; if ((frame[1] & 0x08) == 0) { // MPEG-2 sampling_frequency += 4; bit_rate_index_minus1 += 14; } padding_bit = get_bits(1); get_bits(1); // discard private_bit mode = get_bits(2); // parse the mode_extension, set up the stereo bound if (mode == JOINT_STEREO) bound = (get_bits(2) + 1) << 2; else { get_bits(2); bound = (mode == MONO) ? 0 : 32; } emit isStereo ((mode == JOINT_STEREO) || (mode == STEREO)); // discard the last 4 bits of the header and the CRC value, if present get_bits(4); if ((frame [1] & 1) == 0) get_bits(16); // compute the frame size frame_size = (144000 * bitrates[bit_rate_index_minus1] / sample_rates [sampling_frequency]) + padding_bit; if (!pcm) return frame_size; // no decoding // prepare the quantizer table lookups if (sampling_frequency & 4) { // MPEG-2 (LSR) table_idx = 2; sblimit = 30; } else { // MPEG-1 table_idx = (mode == MONO) ? 0 : 1; table_idx = quant_lut_step1[table_idx][bit_rate_index_minus1]; table_idx = quant_lut_step2[table_idx][sampling_frequency]; sblimit = table_idx & 63; table_idx >>= 6; } if (bound > sblimit) bound = sblimit; // read the allocation information for (sb = 0; sb < bound; ++sb) for (ch = 0; ch < 2; ++ch) allocation [ch][sb] = read_allocation(sb, table_idx); for (sb = bound; sb < sblimit; ++sb) allocation[0][sb] = allocation[1][sb] = read_allocation (sb, table_idx); // read scale factor selector information nch = (mode == MONO) ? 1 : 2; for (sb = 0; sb < sblimit; ++sb) { for (ch = 0; ch < nch; ++ch) if (allocation [ch][sb]) scfsi [ch][sb] = get_bits (2); if (mode == MONO) scfsi[1][sb] = scfsi[0][sb]; } // read scale factors for (sb = 0; sb < sblimit; ++sb) { for (ch = 0; ch < nch; ++ch) { if (allocation[ch][sb]) { switch (scfsi[ch][sb]) { case 0: scalefactor[ch][sb][0] = get_bits(6); scalefactor[ch][sb][1] = get_bits(6); scalefactor[ch][sb][2] = get_bits(6); break; case 1: scalefactor[ch][sb][0] = scalefactor[ch][sb][1] = get_bits(6); scalefactor[ch][sb][2] = get_bits(6); break; case 2: scalefactor[ch][sb][0] = scalefactor[ch][sb][1] = scalefactor[ch][sb][2] = get_bits(6); break; case 3: scalefactor[ch][sb][0] = get_bits(6); scalefactor[ch][sb][1] = scalefactor[ch][sb][2] = get_bits(6); break; } } } if (mode == MONO) for (part = 0; part < 3; ++part) scalefactor[1][sb][part] = scalefactor[0][sb][part]; } // coefficient input and reconstruction for (part = 0; part < 3; ++part) { for (gr = 0; gr < 4; ++gr) { // read the samples for (sb = 0; sb < bound; ++sb) for (ch = 0; ch < 2; ++ch) read_samples (allocation[ch][sb], scalefactor[ch][sb][part], &sample[ch][sb][0]); for (sb = bound; sb < sblimit; ++sb) { read_samples (allocation[0][sb], scalefactor[0][sb][part], &sample[0][sb][0]); for (idx = 0; idx < 3; ++idx) sample[1][sb][idx] = sample[0][sb][idx]; } for (ch = 0; ch < 2; ++ch) for (sb = sblimit; sb < 32; ++sb) for (idx = 0; idx < 3; ++idx) sample[ch][sb][idx] = 0; // synthesis loop for (idx = 0; idx < 3; ++idx) { // shifting step Voffs = table_idx = (Voffs - 64) & 1023; for (ch = 0; ch < 2; ++ch) { // matrixing for (i = 0; i < 64; ++i) { sum = 0; for (j = 0; j < 32; ++j) // 8b*15b=23b sum += N[i][j] * sample[ch][j][idx]; // intermediate value is 28 bit (23 + 5), clamp to 14b // V [ch][table_idx + i] = (sum + 8192) >> 14; } // construction of U for (i = 0; i < 8; ++i) for (j = 0; j < 32; ++j) { U [(i << 6) + j] = V [ch][(table_idx + (i << 7) + j) & 1023]; U [(i << 6) + j + 32] = V [ch][(table_idx + (i << 7) + j + 96) & 1023]; } // apply window for (i = 0; i < 512; ++i) U [i] = (U [i] * D [i] + 32) >> 6; // output samples for (j = 0; j < 32; ++j) { sum = 0; for (i = 0; i < 16; ++i) sum -= U [(i << 5) + j]; sum = (sum + 8) >> 4; if (sum < -32768) sum = -32768; if (sum > 32767) sum = 32767; pcm[(idx << 6) | (j << 1) | ch] = (uint16_t) sum; } } // end of synthesis channel loop } // end of synthesis sub-block loop // adjust PCM output pointer: decoded 3 * 32 = 96 stereo samples pcm += 192; } // decoding of the granule finished } return frame_size; } // // bits to MP2 frames, amount is amount of bits void mp2Processor::addtoFrame (std::vector<uint8_t> v) { int16_t i, j; int16_t lf = baudRate == 48000 ? MP2framesize : 2 * MP2framesize; int16_t amount = MP2framesize; uint8_t help [24 * bitRate / 8]; int16_t vLength = 24 * bitRate / 8; //fprintf (stderr, "baudrate = %d, inputsize = %d\n", // baudRate, v. size ()); // fprintf (stderr, "\n"); for (i = 0; i < 24 * bitRate / 8; i ++) { help [i] = 0; for (j = 0; j < 8; j ++) { help [i] <<= 1; help [i] |= v [8 * i + j] & 01; } } { uint8_t L0 = help [vLength - 1]; uint8_t L1 = help [vLength - 2]; int16_t down = bitRate * 1000 >= 56000 ? 4 : 2; my_padhandler. processPAD (help, vLength - 2 - down - 1, L1, L0); } for (i = 0; i < amount; i ++) { if (MP2Header_OK == 2) { addbittoMP2 (MP2frame, v [i], MP2bitCount ++); if (MP2bitCount >= lf) { int16_t sample_buf [KJMP2_SAMPLES_PER_FRAME * 2]; if (mp2decodeFrame (MP2frame, sample_buf)) { buffer -> putDataIntoBuffer (sample_buf, 2 * (int32_t)KJMP2_SAMPLES_PER_FRAME); if (buffer -> GetRingBufferReadAvailable () > baudRate / 8) newAudio (2 * (int32_t)KJMP2_SAMPLES_PER_FRAME, baudRate); } MP2Header_OK = 0; MP2headerCount = 0; MP2bitCount = 0; } } else if (MP2Header_OK == 0) { // apparently , we are not in sync yet if (v [i] == 01) { if (++ MP2headerCount == 12) { MP2bitCount = 0; for (j = 0; j < 12; j ++) addbittoMP2 (MP2frame, 1, MP2bitCount ++); MP2Header_OK = 1; } } else MP2headerCount = 0; } else if (MP2Header_OK == 1) { addbittoMP2 (MP2frame, v [i], MP2bitCount ++); if (MP2bitCount == 24) { setSamplerate (mp2sampleRate (MP2frame)); MP2Header_OK = 2; } } } } void mp2Processor::addbittoMP2 (uint8_t *v, uint8_t b, int16_t nm) { uint8_t byte = v [nm / 8]; int16_t bitnr = 7 - (nm & 7); uint8_t newbyte = (01 << bitnr); if (b == 0) byte &= ~newbyte; else byte |= newbyte; v [nm / 8] = byte; }
JvanKatwijk/qt-dab
src/backend/audio/mp2processor.cpp
C++
gpl-2.0
24,771
#include <QApplication> #include <QMenuBar> #include <QMessageBox> #include <QFileDialog> #include <QVBoxLayout> #include <QDockWidget> #include <QProgressDialog> #include <QDesktopWidget> #include "vfs_dialog.h" #include "save_manager_dialog.h" #include "kernel_explorer.h" #include "game_list_frame.h" #include "debugger_frame.h" #include "log_frame.h" #include "settings_dialog.h" #include "auto_pause_settings_dialog.h" #include "cg_disasm_window.h" #include "memory_string_searcher.h" #include "memory_viewer_panel.h" #include "rsx_debugger.h" #include "main_window.h" #include "emu_settings.h" #include "about_dialog.h" #include "gamepads_settings_dialog.h" #include <thread> #include "stdafx.h" #include "Emu/System.h" #include "Emu/Memory/Memory.h" #include "Crypto/unpkg.h" #include "Crypto/unself.h" #include "Loader/PUP.h" #include "Loader/TAR.h" #include "Utilities/Thread.h" #include "Utilities/StrUtil.h" #include "rpcs3_version.h" #include "Utilities/sysinfo.h" #include "ui_main_window.h" inline std::string sstr(const QString& _in) { return _in.toUtf8().toStdString(); } main_window::main_window(std::shared_ptr<gui_settings> guiSettings, QWidget *parent) : QMainWindow(parent), guiSettings(guiSettings), m_sys_menu_opened(false), ui(new Ui::main_window) { } main_window::~main_window() { delete ui; } auto Pause = []() { if (Emu.IsReady()) Emu.Run(); else if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsRunning()) Emu.Pause(); else if (!Emu.GetPath().empty()) Emu.Load(); }; /* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect). * Simplifies logic a bit. */ void main_window::Init() { ui->setupUi(this); m_appIcon = QIcon(":/rpcs3.ico"); // hide utilities from the average user ui->menuUtilities->menuAction()->setVisible(guiSettings->GetValue(GUI::m_showDebugTab).toBool()); // add toolbar widgets (crappy Qt designer is not able to) ui->toolBar->setObjectName("mw_toolbar"); ui->sizeSlider->setRange(0, GUI::gl_max_slider_pos); ui->sizeSlider->setSliderPosition(guiSettings->GetValue(GUI::gl_iconSize).toInt()); ui->toolBar->addWidget(ui->sizeSliderContainer); ui->toolBar->addSeparator(); ui->toolBar->addWidget(ui->mw_searchbar); // for highdpi resize toolbar icons and height dynamically // choose factors to mimic Gui-Design in main_window.ui // TODO: in case Qt::AA_EnableHighDpiScaling is enabled in main.cpp we only need the else branch #ifdef _WIN32 const int toolBarHeight = menuBar()->sizeHint().height() * 1.5; ui->toolBar->setIconSize(QSize(toolBarHeight, toolBarHeight)); #else const int toolBarHeight = ui->toolBar->iconSize().height(); #endif ui->sizeSliderContainer->setFixedWidth(toolBarHeight * 5); ui->sizeSlider->setFixedHeight(toolBarHeight * 0.65f); CreateActions(); CreateDockWindows(); setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10 CreateConnects(); setWindowTitle(QString::fromStdString("RPCS3 v" + rpcs3::version.to_string())); !m_appIcon.isNull() ? setWindowIcon(m_appIcon) : LOG_WARNING(GENERAL, "AppImage could not be loaded!"); Q_EMIT RequestGlobalStylesheetChange(guiSettings->GetCurrentStylesheetPath()); ConfigureGuiFromSettings(true); RepaintToolBarIcons(); m_gameListFrame->RepaintToolBarIcons(); if (!utils::has_ssse3()) { QMessageBox::critical(this, "SSSE3 Error (with three S, not two)", "Your system does not meet the minimum requirements needed to run RPCS3.\n" "Your CPU does not support SSSE3 (with three S, not two).\n"); std::exit(EXIT_FAILURE); } #ifdef BRANCH if ("RPCS3/rpcs3/master"s != STRINGIZE(BRANCH)) #elif _MSC_VER fs::stat_t st; if (!fs::stat(fs::get_config_dir() + "rpcs3.pdb", st) || st.is_directory || st.size < 1024 * 1024 * 100) #else if (false) #endif { LOG_WARNING(GENERAL, "Experimental Build Warning! Build origin: " STRINGIZE(BRANCH)); QMessageBox msg; msg.setWindowTitle("Experimental Build Warning"); msg.setWindowIcon(m_appIcon); msg.setIcon(QMessageBox::Critical); msg.setTextFormat(Qt::RichText); msg.setText("Please understand that this build is not an official RPCS3 release.<br>This build contains changes that may break games, or even <b>damage</b> your data.<br>It's recommended to download and use the official build from <a href='https://rpcs3.net/download'>RPCS3 website</a>.<br><br>Build origin: " STRINGIZE(BRANCH) "<br>Do you wish to use this build anyway?"); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setDefaultButton(QMessageBox::No); if (msg.exec() == QMessageBox::No) { std::exit(EXIT_SUCCESS); } } } void main_window::CreateThumbnailToolbar() { #ifdef _WIN32 m_icon_thumb_play = QIcon(":/Icons/play_blue.png"); m_icon_thumb_pause = QIcon(":/Icons/pause_blue.png"); m_icon_thumb_stop = QIcon(":/Icons/stop_blue.png"); m_icon_thumb_restart = QIcon(":/Icons/restart_blue.png"); m_thumb_bar = new QWinThumbnailToolBar(this); m_thumb_bar->setWindow(windowHandle()); m_thumb_playPause = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_playPause->setToolTip(tr("Pause")); m_thumb_playPause->setIcon(m_icon_thumb_pause); m_thumb_playPause->setEnabled(false); m_thumb_stop = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_stop->setToolTip(tr("Stop")); m_thumb_stop->setIcon(m_icon_thumb_stop); m_thumb_stop->setEnabled(false); m_thumb_restart = new QWinThumbnailToolButton(m_thumb_bar); m_thumb_restart->setToolTip(tr("Restart")); m_thumb_restart->setIcon(m_icon_thumb_restart); m_thumb_restart->setEnabled(false); m_thumb_bar->addButton(m_thumb_playPause); m_thumb_bar->addButton(m_thumb_stop); m_thumb_bar->addButton(m_thumb_restart); connect(m_thumb_stop, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); }); connect(m_thumb_restart, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); Emu.Load(); }); connect(m_thumb_playPause, &QWinThumbnailToolButton::clicked, Pause); #endif } // returns appIcon QIcon main_window::GetAppIcon() { return m_appIcon; } // loads the appIcon from path and embeds it centered into an empty square icon void main_window::SetAppIconFromPath(const std::string path) { // get Icon for the gs_frame from path. this handles presumably all possible use cases QString qpath = qstr(path); std::string icon_list[] = { "/ICON0.PNG", "/PS3_GAME/ICON0.PNG" }; std::string path_list[] = { path, sstr(qpath.section("/", 0, -2)), sstr(qpath.section("/", 0, -3)) }; for (std::string pth : path_list) { if (!fs::is_dir(pth)) continue; for (std::string ico : icon_list) { ico = pth + ico; if (fs::is_file(ico)) { // load the image from path. It will most likely be a rectangle QImage source = QImage(qstr(ico)); int edgeMax = std::max(source.width(), source.height()); // create a new transparent image with square size and same format as source (maybe handle other formats than RGB32 as well?) QImage::Format format = source.format() == QImage::Format_RGB32 ? QImage::Format_ARGB32 : source.format(); QImage dest = QImage(edgeMax, edgeMax, format); dest.fill(QColor("transparent")); // get the location to draw the source image centered within the dest image. QPoint destPos = source.width() > source.height() ? QPoint(0, (source.width() - source.height()) / 2) : QPoint((source.height() - source.width()) / 2, 0); // Paint the source into/over the dest QPainter painter(&dest); painter.drawImage(destPos, source); painter.end(); // set Icon m_appIcon = QIcon(QPixmap::fromImage(dest)); return; } } } // if nothing was found reset the icon to default m_appIcon = QIcon(":/rpcs3.ico"); } void main_window::BootElf() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_ELF = guiSettings->GetValue(GUI::fd_boot_elf).toString(); QString filePath = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_ELF, tr( "(S)ELF files (*BOOT.BIN *.elf *.self);;" "ELF files (BOOT.BIN *.elf);;" "SELF files (EBOOT.BIN *.self);;" "BOOT files (*BOOT.BIN);;" "BIN files (*.bin);;" "All files (*.*)"), Q_NULLPTR, QFileDialog::DontResolveSymlinks); if (filePath == NULL) { if (stopped) Emu.Resume(); return; } LOG_NOTICE(LOADER, "(S)ELF: booting..."); // If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted // game folder in case of having e.g. a Game Folder with collected links to elf files. // Don't set last path earlier in case of cancelled dialog guiSettings->SetValue(GUI::fd_boot_elf, filePath); const std::string path = sstr(QFileInfo(filePath).canonicalFilePath()); SetAppIconFromPath(path); Emu.Stop(); if (!Emu.BootGame(path, true)) { LOG_ERROR(GENERAL, "PS3 executable not found at path (%s)", path); } else { LOG_SUCCESS(LOADER, "(S)ELF: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::BootGame() { bool stopped = false; if (Emu.IsRunning()) { Emu.Pause(); stopped = true; } QString path_last_Game = guiSettings->GetValue(GUI::fd_boot_game).toString(); QString dirPath = QFileDialog::getExistingDirectory(this, tr("Select Game Folder"), path_last_Game, QFileDialog::ShowDirsOnly); if (dirPath == NULL) { if (stopped) Emu.Resume(); return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_boot_game, QFileInfo(dirPath).path()); const std::string path = sstr(dirPath); SetAppIconFromPath(path); if (!Emu.BootGame(path)) { LOG_ERROR(GENERAL, "PS3 executable not found in selected folder (%s)", path); } else { LOG_SUCCESS(LOADER, "Boot Game: boot done."); const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] "; AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle()))); m_gameListFrame->Refresh(true); } } void main_window::InstallPkg(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PKG = guiSettings->GetValue(GUI::fd_install_pkg).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PKG To Install"), path_last_PKG, tr("PKG files (*.pkg);;All files (*.*)")); } else { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Install package: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "PKG: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pkg, QFileInfo(filePath).path()); const std::string fileName = sstr(QFileInfo(filePath).fileName()); const std::string path = sstr(filePath); // Open PKG file fs::file pkg_f(path); if (!pkg_f || pkg_f.size() < 64) { LOG_ERROR(LOADER, "PKG: Failed to open %s", path); return; } //Check header u32 pkg_signature; pkg_f.seek(0); pkg_f.read(pkg_signature); if (pkg_signature != "\x7FPKG"_u32) { LOG_ERROR(LOADER, "PKG: %s is not a pkg file", fileName); return; } // Get title ID std::vector<char> title_id(9); pkg_f.seek(55); pkg_f.read(title_id); pkg_f.seek(0); // Get full path const auto& local_path = Emu.GetHddDir() + "game/" + std::string(std::begin(title_id), std::end(title_id)); if (!fs::create_dir(local_path)) { if (fs::is_dir(local_path)) { if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Another installation found. Do you want to overwrite it?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path); return; } } else { LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path); return; } } QProgressDialog pdlg(tr("Installing package ... please wait ..."), tr("Cancel"), 0, 1000, this); pdlg.setWindowTitle(tr("RPCS3 Package Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, 1000); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<double> progress(0.); { // Run PKG unpacking asynchronously scope_thread worker("PKG Installer", [&] { if (pkg_install(pkg_f, local_path + '/', progress, path)) { progress = 1.; return; } // TODO: Ask user to delete files on cancellation/failure? progress = -1.; }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < 1.) { if (pdlg.wasCanceled()) { progress -= 1.; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Remove incomplete folder?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { fs::remove_all(local_path); m_gameListFrame->Refresh(true); LOG_SUCCESS(LOADER, "PKG: removed incomplete installation in %s", local_path); return; } break; } // Update progress window pdlg.setValue(static_cast<int>(progress * pdlg.maximum())); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress * taskbar_progress->maximum())); #endif QCoreApplication::processEvents(); } if (progress > 0.) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress >= 1.) { m_gameListFrame->Refresh(true); LOG_SUCCESS(GENERAL, "Successfully installed %s.", fileName); guiSettings->ShowInfoBox(GUI::ib_pkg_success, tr("Success!"), tr("Successfully installed software from package!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } void main_window::InstallPup(const QString& dropPath) { QString filePath = dropPath; if (filePath.isEmpty()) { QString path_last_PUP = guiSettings->GetValue(GUI::fd_install_pup).toString(); filePath = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_PUP, tr("PS3 update file (PS3UPDAT.PUP)")); } else { if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(filePath), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { LOG_NOTICE(LOADER, "Firmware: Cancelled installation from drop. File: %s", sstr(filePath)); return; } } if (filePath == NULL) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_install_pup, QFileInfo(filePath).path()); const std::string path = sstr(filePath); fs::file pup_f(path); pup_object pup(pup_f); if (!pup) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP file is invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP file is invalid.")); return; } fs::file update_files_f = pup.get_file(0x300); tar_object update_files(update_files_f); auto updatefilenames = update_files.get_filenames(); updatefilenames.erase(std::remove_if( updatefilenames.begin(), updatefilenames.end(), [](std::string s) { return s.find("dev_flash_") == std::string::npos; }), updatefilenames.end()); std::string version_string = pup.get_file(0x100).to_string(); version_string.erase(version_string.find('\n')); const std::string cur_version = "4.81"; if (version_string < cur_version && QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromStdString(cur_version), QString::fromStdString(version_string)), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No) { return; } QProgressDialog pdlg(tr("Installing firmware version %1\nPlease wait...").arg(QString::fromStdString(version_string)), tr("Cancel"), 0, static_cast<int>(updatefilenames.size()), this); pdlg.setWindowTitle(tr("RPCS3 Firmware Installer")); pdlg.setWindowModality(Qt::WindowModal); pdlg.setFixedSize(500, pdlg.height()); pdlg.show(); #ifdef _WIN32 QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(); taskbar_button->setWindow(windowHandle()); QWinTaskbarProgress *taskbar_progress = taskbar_button->progress(); taskbar_progress->setRange(0, static_cast<int>(updatefilenames.size())); taskbar_progress->setVisible(true); #endif // Synchronization variable atomic_t<int> progress(0); { // Run asynchronously scope_thread worker("Firmware Installer", [&] { for (auto updatefilename : updatefilenames) { if (progress == -1) break; fs::file updatefile = update_files.get_file(updatefilename); SCEDecrypter self_dec(updatefile); self_dec.LoadHeaders(); self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV); self_dec.DecryptData(); auto dev_flash_tar_f = self_dec.MakeFile(); if (dev_flash_tar_f.size() < 3) { LOG_ERROR(GENERAL, "Error while installing firmware: PUP contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP contents are invalid.")); progress = -1; } tar_object dev_flash_tar(dev_flash_tar_f[2]); if (!dev_flash_tar.extract(fs::get_config_dir())) { LOG_ERROR(GENERAL, "Error while installing firmware: TAR contents are invalid."); QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: TAR contents are invalid.")); progress = -1; } if (progress >= 0) progress += 1; } }); // Wait for the completion while (std::this_thread::sleep_for(5ms), std::abs(progress) < pdlg.maximum()) { if (pdlg.wasCanceled()) { progress = -1; #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif break; } // Update progress window pdlg.setValue(static_cast<int>(progress)); #ifdef _WIN32 taskbar_progress->setValue(static_cast<int>(progress)); #endif QCoreApplication::processEvents(); } update_files_f.close(); pup_f.close(); if (progress > 0) { pdlg.setValue(pdlg.maximum()); #ifdef _WIN32 taskbar_progress->setValue(taskbar_progress->maximum()); #endif std::this_thread::sleep_for(100ms); } } if (progress > 0) { LOG_SUCCESS(GENERAL, "Successfully installed PS3 firmware version %s.", version_string); guiSettings->ShowInfoBox(GUI::ib_pup_success, tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), this); #ifdef _WIN32 taskbar_progress->hide(); taskbar_button->~QWinTaskbarButton(); #endif } } // This is ugly, but PS3 headers shall not be included there. extern void sysutil_send_system_cmd(u64 status, u64 param); void main_window::DecryptSPRXLibraries() { QString path_last_SPRX = guiSettings->GetValue(GUI::fd_decrypt_sprx).toString(); QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select SPRX files"), path_last_SPRX, tr("SPRX files (*.sprx)")); if (modules.isEmpty()) { return; } Emu.Stop(); guiSettings->SetValue(GUI::fd_decrypt_sprx, QFileInfo(modules.first()).path()); LOG_NOTICE(GENERAL, "Decrypting SPRX libraries..."); for (QString& module : modules) { std::string prx_path = sstr(module); const std::string& prx_dir = fs::get_parent_dir(prx_path); fs::file elf_file(prx_path); if (elf_file && elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32) { const std::size_t prx_ext_pos = prx_path.find_last_of('.'); const std::string& prx_name = prx_path.substr(prx_dir.size()); elf_file = decrypt_self(std::move(elf_file)); prx_path.erase(prx_path.size() - 4, 1); // change *.sprx to *.prx if (elf_file) { if (fs::file new_file{ prx_path, fs::rewrite }) { new_file.write(elf_file.to_string()); LOG_SUCCESS(GENERAL, "Decrypted %s", prx_dir + prx_name); } else { LOG_ERROR(GENERAL, "Failed to create %s", prx_path); } } else { LOG_ERROR(GENERAL, "Failed to decrypt %s", prx_dir + prx_name); } } } LOG_NOTICE(GENERAL, "Finished decrypting all SPRX libraries."); } /** Needed so that when a backup occurs of window state in guisettings, the state is current. * Also, so that on close, the window state is preserved. */ void main_window::SaveWindowState() { // Save gui settings guiSettings->SetValue(GUI::mw_geometry, saveGeometry()); guiSettings->SetValue(GUI::mw_windowState, saveState()); guiSettings->SetValue(GUI::mw_mwState, m_mw->saveState()); // Save column settings m_gameListFrame->SaveSettings(); // Save splitter state m_debuggerFrame->SaveSettings(); } void main_window::RepaintToolBarIcons() { QColor newColor; if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { newColor = guiSettings->GetValue(GUI::mw_toolIconColor).value<QColor>(); } else { newColor = GUI::get_Label_Color("toolbar_icon_color"); } auto icon = [&newColor](const QString& path) { return gui_settings::colorizedIcon(QIcon(path), GUI::mw_tool_icon_color, newColor); }; m_icon_play = icon(":/Icons/play.png"); m_icon_pause = icon(":/Icons/pause.png"); m_icon_stop = icon(":/Icons/stop.png"); m_icon_restart = icon(":/Icons/restart.png"); m_icon_fullscreen_on = icon(":/Icons/fullscreen.png"); m_icon_fullscreen_off = icon(":/Icons/fullscreen_invert.png"); ui->toolbar_config ->setIcon(icon(":/Icons/configure.png")); ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png")); ui->toolbar_disc ->setIcon(icon(":/Icons/disc.png")); ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png")); ui->toolbar_list ->setIcon(icon(":/Icons/list.png")); ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png")); ui->toolbar_snap ->setIcon(icon(":/Icons/screenshot.png")); ui->toolbar_sort ->setIcon(icon(":/Icons/sort.png")); ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png")); if (Emu.IsRunning()) { ui->toolbar_start->setIcon(m_icon_pause); } else if (Emu.IsStopped() && !Emu.GetPath().empty()) { ui->toolbar_start->setIcon(m_icon_restart); } else { ui->toolbar_start->setIcon(m_icon_play); } if (isFullScreen()) { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }") .arg(newColor.red()).arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha())); } void main_window::OnEmuRun() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); EnableMenus(true); } void main_window::OnEmuResume() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Pause emulation")); m_thumb_playPause->setIcon(m_icon_thumb_pause); #endif ui->sysPauseAct->setText(tr("&Pause\tCtrl+P")); ui->sysPauseAct->setIcon(m_icon_pause); ui->toolbar_start->setIcon(m_icon_pause); ui->toolbar_start->setToolTip(tr("Pause emulation")); } void main_window::OnEmuPause() { #ifdef _WIN32 m_thumb_playPause->setToolTip(tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(tr("Resume emulation")); } void main_window::OnEmuStop() { m_debuggerFrame->EnableButtons(false); m_debuggerFrame->ClearBreakpoints(); ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif EnableMenus(false); if (!Emu.GetPath().empty()) { ui->toolbar_start->setEnabled(true); ui->toolbar_start->setIcon(m_icon_restart); ui->toolbar_start->setToolTip(tr("Restart emulation")); ui->sysRebootAct->setEnabled(true); #ifdef _WIN32 m_thumb_restart->setEnabled(true); #endif } else { ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); } } void main_window::OnEmuReady() { m_debuggerFrame->EnableButtons(true); #ifdef _WIN32 m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); m_thumb_playPause->setIcon(m_icon_thumb_play); #endif ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E")); ui->sysPauseAct->setIcon(m_icon_play); ui->toolbar_start->setIcon(m_icon_play); ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation")); EnableMenus(true); } void main_window::EnableMenus(bool enabled) { // Thumbnail Buttons #ifdef _WIN32 m_thumb_playPause->setEnabled(enabled); m_thumb_stop->setEnabled(enabled); m_thumb_restart->setEnabled(enabled); #endif // Toolbar ui->toolbar_start->setEnabled(enabled); ui->toolbar_stop->setEnabled(enabled); // Emulation ui->sysPauseAct->setEnabled(enabled); ui->sysStopAct->setEnabled(enabled); ui->sysRebootAct->setEnabled(enabled); // PS3 Commands ui->sysSendOpenMenuAct->setEnabled(enabled); ui->sysSendExitAct->setEnabled(enabled); // Tools ui->toolskernel_explorerAct->setEnabled(enabled); ui->toolsmemory_viewerAct->setEnabled(enabled); ui->toolsRsxDebuggerAct->setEnabled(enabled); ui->toolsStringSearchAct->setEnabled(enabled); } void main_window::BootRecentAction(const QAction* act) { if (Emu.IsRunning()) { return; } const QString pth = act->data().toString(); QString nam; bool containsPath = false; int idx = -1; for (int i = 0; i < m_rg_entries.count(); i++) { if (m_rg_entries.at(i).first == pth) { idx = i; containsPath = true; nam = m_rg_entries.at(idx).second; } } // path is invalid: remove action from list return if ((containsPath && nam.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile())) { if (containsPath) { // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // remove action from list m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); LOG_ERROR(GENERAL, "Recent Game not valid, removed from Boot Recent list: %s", sstr(pth)); // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i + 1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } LOG_WARNING(GENERAL, "Boot Recent list refreshed"); return; } LOG_ERROR(GENERAL, "Path invalid and not in m_rg_paths: %s", sstr(pth)); return; } SetAppIconFromPath(sstr(pth)); Emu.Stop(); if (!Emu.BootGame(sstr(pth), true)) { LOG_ERROR(LOADER, "Failed to boot %s", sstr(pth)); } else { LOG_SUCCESS(LOADER, "Boot from Recent List: done"); AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), nam)); m_gameListFrame->Refresh(true); } }; QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx) { // if path is not valid remove from list if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile())) { if (m_rg_entries.contains(entry)) { LOG_ERROR(GENERAL, "Recent Game not valid, removing from Boot Recent list: %s", sstr(entry.first)); int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } return nullptr; } // if name is a path get filename QString shown_name = entry.second; if (QFileInfo(entry.second).isFile()) { shown_name = entry.second.section('/', -1); } // create new action QAction* act = new QAction(shown_name, this); act->setData(entry.first); act->setToolTip(entry.second); act->setShortcut(tr("Ctrl+%1").arg(sc_idx)); // truncate if too long if (shown_name.length() > 60) { act->setText(shown_name.left(27) + "(....)" + shown_name.right(27)); } // connect boot connect(act, &QAction::triggered, [=]() {BootRecentAction(act); }); return act; }; void main_window::AddRecentAction(const q_string_pair& entry) { // don't change list on freeze if (ui->freezeRecentAct->isChecked()) { return; } // create new action, return if not valid QAction* act = CreateRecentAction(entry, 1); if (!act) { return; } // clear menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } // if path already exists, remove it in order to get it to beginning if (m_rg_entries.contains(entry)) { int idx = m_rg_entries.indexOf(entry); m_rg_entries.removeAt(idx); m_recentGameActs.removeAt(idx); } // remove oldest action at the end if needed if (m_rg_entries.count() == 9) { m_rg_entries.removeLast(); m_recentGameActs.removeLast(); } else if (m_rg_entries.count() > 9) { LOG_ERROR(LOADER, "Recent games entrylist too big"); } if (m_rg_entries.count() < 9) { // add new action at the beginning m_rg_entries.prepend(entry); m_recentGameActs.prepend(act); } // refill menu with actions for (int i = 0; i < m_recentGameActs.count(); i++) { m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i+1)); m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second); ui->bootRecentMenu->addAction(m_recentGameActs[i]); } guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries)); } void main_window::RepaintGui() { m_gameListFrame->RepaintIcons(true); m_gameListFrame->RepaintToolBarIcons(); RepaintToolbar(); RepaintToolBarIcons(); } void main_window::RepaintToolbar() { if (guiSettings->GetValue(GUI::m_enableUIColors).toBool()) { QColor tbc = guiSettings->GetValue(GUI::mw_toolBarColor).value<QColor>(); ui->toolBar->setStyleSheet(GUI::stylesheet + QString( "QToolBar { background-color: rgba(%1, %2, %3, %4); }" "QToolBar::separator {background-color: rgba(%5, %6, %7, %8); width: 1px; margin-top: 2px; margin-bottom: 2px;}" "QSlider { background-color: rgba(%1, %2, %3, %4); }" "QLineEdit { background-color: rgba(%1, %2, %3, %4); }") .arg(tbc.red()).arg(tbc.green()).arg(tbc.blue()).arg(tbc.alpha()) .arg(tbc.red() - 20).arg(tbc.green() - 20).arg(tbc.blue() - 20).arg(tbc.alpha() - 20) ); } else { ui->toolBar->setStyleSheet(GUI::stylesheet); } } void main_window::CreateActions() { ui->exitAct->setShortcuts(QKeySequence::Quit); ui->toolbar_start->setEnabled(false); ui->toolbar_stop->setEnabled(false); m_categoryVisibleActGroup = new QActionGroup(this); m_categoryVisibleActGroup->addAction(ui->showCatHDDGameAct); m_categoryVisibleActGroup->addAction(ui->showCatDiscGameAct); m_categoryVisibleActGroup->addAction(ui->showCatHomeAct); m_categoryVisibleActGroup->addAction(ui->showCatAudioVideoAct); m_categoryVisibleActGroup->addAction(ui->showCatGameDataAct); m_categoryVisibleActGroup->addAction(ui->showCatUnknownAct); m_categoryVisibleActGroup->addAction(ui->showCatOtherAct); m_categoryVisibleActGroup->setExclusive(false); m_iconSizeActGroup = new QActionGroup(this); m_iconSizeActGroup->addAction(ui->setIconSizeTinyAct); m_iconSizeActGroup->addAction(ui->setIconSizeSmallAct); m_iconSizeActGroup->addAction(ui->setIconSizeMediumAct); m_iconSizeActGroup->addAction(ui->setIconSizeLargeAct); m_listModeActGroup = new QActionGroup(this); m_listModeActGroup->addAction(ui->setlistModeListAct); m_listModeActGroup->addAction(ui->setlistModeGridAct); } void main_window::CreateConnects() { connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf); connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame); connect(ui->bootRecentMenu, &QMenu::aboutToShow, [=] { // Enable/Disable Recent Games List const bool stopped = Emu.IsStopped(); for (auto act : ui->bootRecentMenu->actions()) { if (act != ui->freezeRecentAct && act != ui->clearRecentAct) { act->setEnabled(stopped); } } }); connect(ui->clearRecentAct, &QAction::triggered, [this] { if (ui->freezeRecentAct->isChecked()) { return; } m_rg_entries.clear(); for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(q_pair_list())); }); connect(ui->freezeRecentAct, &QAction::triggered, [=](bool checked) { guiSettings->SetValue(GUI::rg_freeze, checked); }); connect(ui->bootInstallPkgAct, &QAction::triggered, [this] {InstallPkg(); }); connect(ui->bootInstallPupAct, &QAction::triggered, [this] {InstallPup(); }); connect(ui->exitAct, &QAction::triggered, this, &QWidget::close); connect(ui->sysPauseAct, &QAction::triggered, Pause); connect(ui->sysStopAct, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->sysRebootAct, &QAction::triggered, [=]() { Emu.Stop(); Emu.Load(); }); connect(ui->sysSendOpenMenuAct, &QAction::triggered, [=] { sysutil_send_system_cmd(m_sys_menu_opened ? 0x0132 /* CELL_SYSUTIL_SYSTEM_MENU_CLOSE */ : 0x0131 /* CELL_SYSUTIL_SYSTEM_MENU_OPEN */, 0); m_sys_menu_opened = !m_sys_menu_opened; ui->sysSendOpenMenuAct->setText(tr("Send &%0 system menu cmd").arg(m_sys_menu_opened ? tr("close") : tr("open"))); }); connect(ui->sysSendExitAct, &QAction::triggered, [=] { sysutil_send_system_cmd(0x0101 /* CELL_SYSUTIL_REQUEST_EXITGAME */, 0); }); auto openSettings = [=](int tabIndex) { settings_dialog dlg(guiSettings, m_Render_Creator, tabIndex, this); connect(&dlg, &settings_dialog::GuiSettingsSaveRequest, this, &main_window::SaveWindowState); connect(&dlg, &settings_dialog::GuiSettingsSyncRequest, [=]() {ConfigureGuiFromSettings(true); }); connect(&dlg, &settings_dialog::GuiStylesheetRequest, this, &main_window::RequestGlobalStylesheetChange); connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui); dlg.exec(); }; connect(ui->confCPUAct, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->confGPUAct, &QAction::triggered, [=]() { openSettings(1); }); connect(ui->confAudioAct, &QAction::triggered, [=]() { openSettings(2); }); connect(ui->confIOAct, &QAction::triggered, [=]() { openSettings(3); }); connect(ui->confSystemAct, &QAction::triggered, [=]() { openSettings(4); }); connect(ui->confPadsAct, &QAction::triggered, this, [=] { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confAutopauseManagerAct, &QAction::triggered, [=] { auto_pause_settings_dialog dlg(this); dlg.exec(); }); connect(ui->confVFSDialogAct, &QAction::triggered, [=] { vfs_dialog dlg(this); dlg.exec(); m_gameListFrame->Refresh(true); // dev-hdd0 may have changed. Refresh just in case. }); connect(ui->confSavedataManagerAct, &QAction::triggered, [=] { save_manager_dialog* sdid = new save_manager_dialog(); sdid->show(); }); connect(ui->toolsCgDisasmAct, &QAction::triggered, [=] { cg_disasm_window* cgdw = new cg_disasm_window(guiSettings); cgdw->show(); }); connect(ui->toolskernel_explorerAct, &QAction::triggered, [=] { kernel_explorer* kernelExplorer = new kernel_explorer(this); kernelExplorer->show(); }); connect(ui->toolsmemory_viewerAct, &QAction::triggered, [=] { memory_viewer_panel* mvp = new memory_viewer_panel(this); mvp->show(); }); connect(ui->toolsRsxDebuggerAct, &QAction::triggered, [=] { rsx_debugger* rsx = new rsx_debugger(this); rsx->show(); }); connect(ui->toolsStringSearchAct, &QAction::triggered, [=] { memory_string_searcher* mss = new memory_string_searcher(this); mss->show(); }); connect(ui->toolsDecryptSprxLibsAct, &QAction::triggered, this, &main_window::DecryptSPRXLibraries); connect(ui->showDebuggerAct, &QAction::triggered, [=](bool checked) { checked ? m_debuggerFrame->show() : m_debuggerFrame->hide(); guiSettings->SetValue(GUI::mw_debugger, checked); }); connect(ui->showLogAct, &QAction::triggered, [=](bool checked) { checked ? m_logFrame->show() : m_logFrame->hide(); guiSettings->SetValue(GUI::mw_logger, checked); }); connect(ui->showGameListAct, &QAction::triggered, [=](bool checked) { checked ? m_gameListFrame->show() : m_gameListFrame->hide(); guiSettings->SetValue(GUI::mw_gamelist, checked); }); connect(ui->showToolBarAct, &QAction::triggered, [=](bool checked) { ui->toolBar->setVisible(checked); guiSettings->SetValue(GUI::mw_toolBarVisible, checked); }); connect(ui->showGameToolBarAct, &QAction::triggered, [=](bool checked) { m_gameListFrame->SetToolBarVisible(checked); }); connect(ui->refreshGameListAct, &QAction::triggered, [=] { m_gameListFrame->Refresh(true); }); connect(m_categoryVisibleActGroup, &QActionGroup::triggered, [=](QAction* act) { QStringList categories; int id; const bool& checked = act->isChecked(); if (act == ui->showCatHDDGameAct) categories += category::non_disc_games, id = Category::Non_Disc_Game; else if (act == ui->showCatDiscGameAct) categories += category::disc_Game, id = Category::Disc_Game; else if (act == ui->showCatHomeAct) categories += category::home, id = Category::Home; else if (act == ui->showCatAudioVideoAct) categories += category::media, id = Category::Media; else if (act == ui->showCatGameDataAct) categories += category::data, id = Category::Data; else if (act == ui->showCatUnknownAct) categories += category::unknown, id = Category::Unknown_Cat; else if (act == ui->showCatOtherAct) categories += category::others, id = Category::Others; else LOG_WARNING(GENERAL, "categoryVisibleActGroup: category action not found"); m_gameListFrame->SetCategoryActIcon(m_categoryVisibleActGroup->actions().indexOf(act), checked); m_gameListFrame->ToggleCategoryFilter(categories, checked); guiSettings->SetCategoryVisibility(id, checked); }); connect(ui->aboutAct, &QAction::triggered, [this] { about_dialog dlg(this); dlg.exec(); }); connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt); auto resizeIcons = [=](const int& index) { int val = ui->sizeSlider->value(); if (val != index) { ui->sizeSlider->setSliderPosition(index); } if (val != m_gameListFrame->GetSliderValue()) { if (m_save_slider_pos) { m_save_slider_pos = false; guiSettings->SetValue(GUI::gl_iconSize, index); } m_gameListFrame->ResizeIcons(index); } }; connect(m_iconSizeActGroup, &QActionGroup::triggered, [=](QAction* act) { int index; if (act == ui->setIconSizeTinyAct) index = 0; else if (act == ui->setIconSizeSmallAct) index = GUI::get_Index(GUI::gl_icon_size_small); else if (act == ui->setIconSizeMediumAct) index = GUI::get_Index(GUI::gl_icon_size_medium); else index = GUI::gl_max_slider_pos; resizeIcons(index); }); connect (m_gameListFrame, &game_list_frame::RequestIconSizeActSet, [=](const int& idx) { if (idx < GUI::get_Index((GUI::gl_icon_size_small + GUI::gl_icon_size_min) / 2)) ui->setIconSizeTinyAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_medium + GUI::gl_icon_size_small) / 2)) ui->setIconSizeSmallAct->setChecked(true); else if (idx < GUI::get_Index((GUI::gl_icon_size_max + GUI::gl_icon_size_medium) / 2)) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); resizeIcons(idx); }); connect(m_gameListFrame, &game_list_frame::RequestSaveSliderPos, [=](const bool& save) { Q_UNUSED(save); m_save_slider_pos = true; }); connect(m_gameListFrame, &game_list_frame::RequestListModeActSet, [=](const bool& isList) { isList ? ui->setlistModeListAct->trigger() : ui->setlistModeGridAct->trigger(); }); connect(m_gameListFrame, &game_list_frame::RequestCategoryActSet, [=](const int& id) { m_categoryVisibleActGroup->actions().at(id)->trigger(); }); connect(m_listModeActGroup, &QActionGroup::triggered, [=](QAction* act) { bool isList = act == ui->setlistModeListAct; m_gameListFrame->SetListMode(isList); m_categoryVisibleActGroup->setEnabled(isList); }); connect(ui->toolbar_disc, &QAction::triggered, this, &main_window::BootGame); connect(ui->toolbar_refresh, &QAction::triggered, [=]() { m_gameListFrame->Refresh(true); }); connect(ui->toolbar_stop, &QAction::triggered, [=]() { Emu.Stop(); }); connect(ui->toolbar_start, &QAction::triggered, Pause); connect(ui->toolbar_fullscreen, &QAction::triggered, [=] { if (isFullScreen()) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } else { showFullScreen(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off); } }); connect(ui->toolbar_controls, &QAction::triggered, [=]() { gamepads_settings_dialog dlg(this); dlg.exec(); }); connect(ui->toolbar_config, &QAction::triggered, [=]() { openSettings(0); }); connect(ui->toolbar_list, &QAction::triggered, [=]() { ui->setlistModeListAct->trigger(); }); connect(ui->toolbar_grid, &QAction::triggered, [=]() { ui->setlistModeGridAct->trigger(); }); connect(ui->sizeSlider, &QSlider::valueChanged, resizeIcons); connect(ui->sizeSlider, &QSlider::sliderReleased, this, [&] { guiSettings->SetValue(GUI::gl_iconSize, ui->sizeSlider->value()); }); connect(ui->sizeSlider, &QSlider::actionTriggered, [&](int action) { if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove) { // we only want to save on mouseclicks or slider release (the other connect handles this) m_save_slider_pos = true; // actionTriggered happens before the value was changed } }); connect(ui->mw_searchbar, &QLineEdit::textChanged, m_gameListFrame, &game_list_frame::SetSearchText); } void main_window::CreateDockWindows() { // new mainwindow widget because existing seems to be bugged for now m_mw = new QMainWindow(); m_gameListFrame = new game_list_frame(guiSettings, m_Render_Creator, m_mw); m_gameListFrame->setObjectName("gamelist"); m_debuggerFrame = new debugger_frame(guiSettings, m_mw); m_debuggerFrame->setObjectName("debugger"); m_logFrame = new log_frame(guiSettings, m_mw); m_logFrame->setObjectName("logger"); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_gameListFrame); m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_logFrame); m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debuggerFrame); m_mw->setDockNestingEnabled(true); setCentralWidget(m_mw); connect(m_logFrame, &log_frame::LogFrameClosed, [=]() { if (ui->showLogAct->isChecked()) { ui->showLogAct->setChecked(false); guiSettings->SetValue(GUI::mw_logger, false); } }); connect(m_debuggerFrame, &debugger_frame::DebugFrameClosed, [=]() { if (ui->showDebuggerAct->isChecked()) { ui->showDebuggerAct->setChecked(false); guiSettings->SetValue(GUI::mw_debugger, false); } }); connect(m_gameListFrame, &game_list_frame::GameListFrameClosed, [=]() { if (ui->showGameListAct->isChecked()) { ui->showGameListAct->setChecked(false); guiSettings->SetValue(GUI::mw_gamelist, false); } }); connect(m_gameListFrame, &game_list_frame::RequestIconPathSet, this, &main_window::SetAppIconFromPath); connect(m_gameListFrame, &game_list_frame::RequestAddRecentGame, this, &main_window::AddRecentAction); connect(m_gameListFrame, &game_list_frame::RequestPackageInstall, [this](const QStringList& paths) { for (const auto& path : paths) { InstallPkg(path); } }); connect(m_gameListFrame, &game_list_frame::RequestFirmwareInstall, this, &main_window::InstallPup); } void main_window::ConfigureGuiFromSettings(bool configureAll) { // Restore GUI state if needed. We need to if they exist. QByteArray geometry = guiSettings->GetValue(GUI::mw_geometry).toByteArray(); if (geometry.isEmpty() == false) { restoreGeometry(geometry); } else { // By default, set the window to 70% of the screen and the debugger frame is hidden. m_debuggerFrame->hide(); QSize defaultSize = QDesktopWidget().availableGeometry().size() * 0.7; resize(defaultSize); } restoreState(guiSettings->GetValue(GUI::mw_windowState).toByteArray()); m_mw->restoreState(guiSettings->GetValue(GUI::mw_mwState).toByteArray()); ui->freezeRecentAct->setChecked(guiSettings->GetValue(GUI::rg_freeze).toBool()); m_rg_entries = guiSettings->Var2List(guiSettings->GetValue(GUI::rg_entries)); // clear recent games menu of actions for (auto act : m_recentGameActs) { ui->bootRecentMenu->removeAction(act); } m_recentGameActs.clear(); // Fill the recent games menu for (int i = 0; i < m_rg_entries.count(); i++) { // adjust old unformatted entries (avoid duplication) m_rg_entries[i] = GUI::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second); // create new action QAction* act = CreateRecentAction(m_rg_entries[i], i + 1); // add action to menu if (act) { m_recentGameActs.append(act); ui->bootRecentMenu->addAction(act); } else { i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries } } ui->showLogAct->setChecked(guiSettings->GetValue(GUI::mw_logger).toBool()); ui->showGameListAct->setChecked(guiSettings->GetValue(GUI::mw_gamelist).toBool()); ui->showDebuggerAct->setChecked(guiSettings->GetValue(GUI::mw_debugger).toBool()); ui->showToolBarAct->setChecked(guiSettings->GetValue(GUI::mw_toolBarVisible).toBool()); ui->showGameToolBarAct->setChecked(guiSettings->GetValue(GUI::gl_toolBarVisible).toBool()); m_debuggerFrame->setVisible(ui->showDebuggerAct->isChecked()); m_logFrame->setVisible(ui->showLogAct->isChecked()); m_gameListFrame->setVisible(ui->showGameListAct->isChecked()); m_gameListFrame->SetToolBarVisible(ui->showGameToolBarAct->isChecked()); ui->toolBar->setVisible(ui->showToolBarAct->isChecked()); RepaintToolbar(); ui->showCatHDDGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Non_Disc_Game)); ui->showCatDiscGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Disc_Game)); ui->showCatHomeAct->setChecked(guiSettings->GetCategoryVisibility(Category::Home)); ui->showCatAudioVideoAct->setChecked(guiSettings->GetCategoryVisibility(Category::Media)); ui->showCatGameDataAct->setChecked(guiSettings->GetCategoryVisibility(Category::Data)); ui->showCatUnknownAct->setChecked(guiSettings->GetCategoryVisibility(Category::Unknown_Cat)); ui->showCatOtherAct->setChecked(guiSettings->GetCategoryVisibility(Category::Others)); int idx = guiSettings->GetValue(GUI::gl_iconSize).toInt(); int index = GUI::gl_max_slider_pos / 4; if (idx < index) ui->setIconSizeTinyAct->setChecked(true); else if (idx < index * 2) ui->setIconSizeSmallAct->setChecked(true); else if (idx < index * 3) ui->setIconSizeMediumAct->setChecked(true); else ui->setIconSizeLargeAct->setChecked(true); bool isListMode = guiSettings->GetValue(GUI::gl_listMode).toBool(); if (isListMode) ui->setlistModeListAct->setChecked(true); else ui->setlistModeGridAct->setChecked(true); m_categoryVisibleActGroup->setEnabled(isListMode); if (configureAll) { // Handle log settings m_logFrame->LoadSettings(); // Gamelist m_gameListFrame->LoadSettings(); } } void main_window::keyPressEvent(QKeyEvent *keyEvent) { if (((keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Return) || (isFullScreen() && keyEvent->key() == Qt::Key_Escape)) { ui->toolbar_fullscreen->trigger(); } if (keyEvent->modifiers() & Qt::ControlModifier) { switch (keyEvent->key()) { case Qt::Key_E: if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsReady()) Emu.Run(); return; case Qt::Key_P: if (Emu.IsRunning()) Emu.Pause(); return; case Qt::Key_S: if (!Emu.IsStopped()) Emu.Stop(); return; case Qt::Key_R: if (!Emu.GetPath().empty()) { Emu.Stop(); Emu.Run(); } return; } } } void main_window::mouseDoubleClickEvent(QMouseEvent *event) { if (isFullScreen()) { if (event->button() == Qt::LeftButton) { showNormal(); ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on); } } } /** Override the Qt close event to have the emulator stop and the application die. May add a warning dialog in future. */ void main_window::closeEvent(QCloseEvent* closeEvent) { Q_UNUSED(closeEvent); // Cleanly stop the emulator. Emu.Stop(); SaveWindowState(); // I need the gui settings to sync, and that means having the destructor called as guiSetting's parent is main_window. setAttribute(Qt::WA_DeleteOnClose); QMainWindow::close(); // It's possible to have other windows open, like games. So, force the application to die. QApplication::quit(); }
PeterMcteague/rpcs3
rpcs3/rpcs3qt/main_window.cpp
C++
gpl-2.0
49,565
<?php /** * Elgg Gifts plugin * Send gifts to you friends * * @package Gifts * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @author Christian Heckelmann * @copyright Christian Heckelmann * @link http://www.heckelmann.info * * updated by iionly ([email protected]) */ // Show your sent gifts elgg_push_breadcrumb(elgg_echo('gifts:menu'), 'gifts/' . elgg_get_logged_in_user_entity()->username. '/index'); $title = elgg_echo('gifts:sent'); elgg_push_breadcrumb($title); if (elgg_is_logged_in()) { elgg_register_menu_item('title', [ 'name' => 'sendgift', 'href' => "gifts/" . elgg_get_logged_in_user_entity()->username . "/sendgift", 'text' => elgg_echo('gifts:sendgifts'), 'link_class' => 'elgg-button elgg-button-action', ]); } $content = elgg_list_entities([ 'type' => 'object', 'subtype' => Gifts::SUBTYPE, 'owner_guid' => elgg_get_logged_in_user_guid(), 'no_results' => elgg_echo('gifts:nogifts'), ]); // Format page $body = elgg_view_layout('content', [ 'content' => $content, 'filter' => '', 'title' => $title, ]); // Draw it echo elgg_view_page($title, $body);
iionly/gifts
views/default/resources/gifts/sent.php
PHP
gpl-2.0
1,189
<?php /** * Checkout coupon form * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce; if ( ! WC()->cart->coupons_enabled() ) return; $info_message = apply_filters( 'woocommerce_checkout_coupon_message', __( 'Have a coupon?', 'woocommerce' ) ); $info_message .= ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>'; ?> <div class="box woocommerce-box border-box"> <?php echo $info_message;?> <form class="checkout_coupon brad-woocommerce-form" method="post" style="display:none"> <p class="form-row form-row-first"> <input type="text" name="coupon_code" class="input-text" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" /> </p> <p class="form-row form-row-last"> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> </p> <div class="clear"></div> </form> </div>
diegoschefer/fcp-wp
wp-content/themes/Akal/woocommerce/checkout/form-coupon.php
PHP
gpl-2.0
1,068
# Mikrotik scripts Here are specific instruction to scripts created for RouterOS platform and were tested across two sites, both running RouterOS of the same version. ## Prerequisites - Configure site-to-site IPsec tunnel across both sites. Public IP is a must for both endpoints. This [webpage](http://wiki.mikrotik.com/wiki/Manual:IP/IPsec) is a good place to start. I've been using IPsec in ESP tunnel mode, but other modes should in theory work just fine. - Set up account on dynamic DNS service provider. The scripts use [freedns.afraid.org](http://freedns.afraid.org/), but other services should work as well. You will just need to modify the scripts to work with different DNS service (make sure they have public API available). ## Description of scripts The scripts want to access specified interfaces or rules directly on the router. Interfaces are matched using _interface-name_, but rules are represented on router just as entries with number. To identify the specific rule with highest confidence, script finds the match using comment on the rule. Therefore make sure the rules and interfaces have proper comment and put this exact comment into scripts. ### mikrotik_dns_update.script This script tracks assigned IP address on WAN interface of the router. It assumes that the interface has assigned public IP address directly from your ISP. If the ISP assigns new IP address, on next scheduled run will the script update the dynamic DNS service. This script makes the assigned IP available as a global variable available to the whole system and other scripts. ### mikrotik_ipsec_update.script This script tracks for changes of locally asigned IP address as well as IP change on remote IPsec endpoint. In either cases it will update IPsec policies, peer information and firewall rules. ### mikrotik_ovpn_update.script This script is not needed in pure IPsec setup. However it may be useful in cases, where there is another VPN on endpoint with dynamic IP. It is running on a client router and is tracking for endpoint IP changes. ## Setup - Before you import the scripts, you should review them and modify to suit your needs. Albeit they are quite generic, some information should be updated. Put there your credentials to dynamic DNS service, domain names and DNS entry name for your sites. You should also configure, which router rules should be updated. You can find commented examples in the scripts. - Import the scripts and configure Scheduler to run them periodically. Alternative is to set up a trigger which tracks reachability of given IP.
vladimir-zahradnik/dynamic-ipsec-scripts
mikrotik/README.md
Markdown
gpl-2.0
2,574
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Wed Aug 31 13:06:32 CEST 2011 --> <TITLE> Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException </TITLE> <META NAME="date" CONTENT="2011-08-31"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.algebraweb.editor.shared.exceptions.SqlErrorException"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//class-useSqlErrorException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.algebraweb.editor.shared.exceptions.SqlErrorException</B></H2> </CENTER> No usage of com.algebraweb.editor.shared.exceptions.SqlErrorException <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/algebraweb/editor/shared/exceptions/SqlErrorException.html" title="class in com.algebraweb.editor.shared.exceptions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/algebraweb/editor/shared/exceptions//class-useSqlErrorException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SqlErrorException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
patrickbr/ferryleaks
doc/com/algebraweb/editor/shared/exceptions/class-use/SqlErrorException.html
HTML
gpl-2.0
6,166
<?php /** * * @package phpBB.de pastebin * @copyright (c) 2015 phpBB.de, gn#36 * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2 * */ namespace goztow\edit_has_topicreview\event; /** * @ignore */ use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Event listener */ class base_events implements EventSubscriberInterface { static public function getSubscribedEvents() { return array( 'core.posting_modify_template_vars' => 'edit_topicreview', ); } /* @var \phpbb\template\template */ protected $template; /** * Constructor * * @param \phpbb\controller\helper $helper Controller helper object * @param \phpbb\template\template $template Template object */ public function __construct(\phpbb\template\template $template) { $this->template = $template; } public function edit_topicreview($event) { if ($event['mode'] == 'edit' && topic_review($event['topic_id'], $event['forum_id'])) { $this->template->assign_var('S_DISPLAY_REVIEW', true); } } }
goztow/edit_has_topicreview
event/base_events.php
PHP
gpl-2.0
1,058
<?php /** * Custom template tags for this theme * * Eventually, some of the functionality here could be replaced by core features. * * @package UnlockingSilentHistories */ if ( ! function_exists( 'unlockingsilenthistories_posted_on' ) ) : /** * Prints HTML with meta information for the current post-date/time and author. */ function unlockingsilenthistories_posted_on() { $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>'; if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) { $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>'; } $time_string = sprintf( $time_string, esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), esc_attr( get_the_modified_date( 'c' ) ), esc_html( get_the_modified_date() ) ); $posted_on = sprintf( /* translators: %s: post date. */ esc_html_x( 'Posted on %s', 'post date', 'unlockingsilenthistories' ), '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>' ); $byline = sprintf( /* translators: %s: post author. */ esc_html_x( 'by %s', 'post author', 'unlockingsilenthistories' ), '<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>' ); echo '<span class="posted-on">' . $posted_on . '</span><span class="byline"> ' . $byline . '</span>'; // WPCS: XSS OK. } endif; if ( ! function_exists( 'unlockingsilenthistories_entry_footer' ) ) : /** * Prints HTML with meta information for the categories, tags and comments. */ function unlockingsilenthistories_entry_footer() { // Hide category and tag text for pages. if ( 'post' === get_post_type() ) { /* translators: used between list items, there is a space after the comma */ $categories_list = get_the_category_list( esc_html__( ', ', 'unlockingsilenthistories' ) ); if ( $categories_list ) { /* translators: 1: list of categories. */ printf( '<span class="cat-links">' . esc_html__( 'Posted in %1$s', 'unlockingsilenthistories' ) . '</span>', $categories_list ); // WPCS: XSS OK. } /* translators: used between list items, there is a space after the comma */ $tags_list = get_the_tag_list( '', esc_html_x( ', ', 'list item separator', 'unlockingsilenthistories' ) ); if ( $tags_list ) { /* translators: 1: list of tags. */ printf( '<span class="tags-links">' . esc_html__( 'Tagged %1$s', 'unlockingsilenthistories' ) . '</span>', $tags_list ); // WPCS: XSS OK. } } if ( ! is_single() && ! post_password_required() && ( comments_open() || get_comments_number() ) ) { echo '<span class="comments-link">'; comments_popup_link( sprintf( wp_kses( /* translators: %s: post title */ __( 'Leave a Comment<span class="screen-reader-text"> on %s</span>', 'unlockingsilenthistories' ), array( 'span' => array( 'class' => array(), ), ) ), get_the_title() ) ); echo '</span>'; } edit_post_link( sprintf( wp_kses( /* translators: %s: Name of current post. Only visible to screen readers */ __( 'Edit <span class="screen-reader-text">%s</span>', 'unlockingsilenthistories' ), array( 'span' => array( 'class' => array(), ), ) ), get_the_title() ), '<span class="edit-link">', '</span>' ); } endif;
jhyun94/WP-USH
inc/template-tags.php
PHP
gpl-2.0
3,526
package uq.androidhack.flashspeak; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.File; import java.io.InputStream; import java.net.URI; import uq.androidhack.flashspeak.interfaces.TargetFileListener; import uq.androidhack.flashspeak.interfaces.TrialFileListener; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link VisualisationFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link VisualisationFragment#newInstance} factory method to * create an instance of this fragment. */ public class VisualisationFragment extends Fragment implements TargetFileListener,TrialFileListener{ private OnFragmentInteractionListener mListener; //Here is your URL defined String url = "http://vprbbc.streamguys.net/vprbbc24.mp3"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment VisualisationFragment. */ public static VisualisationFragment newInstance() { VisualisationFragment fragment = new VisualisationFragment(); Bundle args = new Bundle(); //args.putString(ARG_PARAM1, param1); //args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public VisualisationFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_visualisation, container, false); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onFileChange(String uri) { File file = new File (uri); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); ogAudioSampleImageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath())); } @Override public void onRecording(URI uri) { ImageView targetAudioSampleImageView = (ImageView)getView().findViewById(R.id.usersAudioSampleVisualisation); targetAudioSampleImageView.setImageResource(android.R.color.transparent); } @Override public void onFinishProcessing(String b) { Log.i("VISUALIZER", "in HERE!"); ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation); //ogAudioSampleImageView.setImageURI(new URI(b)); new DownloadImageTask(ogAudioSampleImageView).execute(b); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { public void onFragmentInteraction(Bitmap uri); } }
andyepx/flashspeak
app/src/main/java/uq/androidhack/flashspeak/VisualisationFragment.java
Java
gpl-2.0
5,028
using System; using System.IO; static class App{ static void PrintRunningGC(int n){ Console.WriteLine("Running GC for generation " + n); GC.Collect(n); } public static void Main(){ // // Uma instância de FileStream mantém um handle para um recurso nativo, i.e. um ficheiro. // FileStream fs = new FileStream("out.txt", FileMode.Create); // Wait for user to hit <Enter> Console.WriteLine("Wait for user to hit <Enter>"); Console.ReadLine(); PrintRunningGC(0); Console.WriteLine("Wait for user to hit <Enter>"); Console.ReadLine(); } }
isel-leic-ave/ave-2015-16-sem1-i41n
aula34-gc/Finalization01.cs
C#
gpl-2.0
655
package jrpsoft; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Ellipse2D; import java.util.Random; public class Fantasma extends Actor { protected static final int FANTASMA_SPEED = 1; public boolean up, down, right, left; static Boolean[] dir = new Boolean[4]; int avazarA = 0; Random random; public Fantasma(Point puntoIncio, Color colorPrincipal) { super(puntoIncio, colorPrincipal); random = new Random(); } public Point getPoint() { return p; } public void paint(Graphics2D g2) { g2.setColor(color); Point pixelPoint = Director.getPxOfCell(p); Ellipse2D fantasma = new Ellipse2D.Float(pixelPoint.x, pixelPoint.y, diametro, diametro); g2.fill(fantasma); g2.fill(new Ellipse2D.Float(pixelPoint.x - 1, pixelPoint.y + 12, diametro / 2, diametro / 2)); g2.fill(new Ellipse2D.Float(pixelPoint.x + 5, pixelPoint.y + 12, diametro / 2, diametro / 2)); g2.fill(new Ellipse2D.Float(pixelPoint.x + 11, pixelPoint.y + 12, diametro / 2, diametro / 2)); } public void mover(Pacman pacman, Tablero tablero) { /* * System.out.println("ee "+(random.nextInt(5))); * if(random.nextInt(5)==0){ avanzar((random.nextInt(4)+1),tablero); } */ // avazarA=movAleatorio(tablero); //System.err.println(p); // avazarA=0; Astar.getAstar().getPath(p, pacman.p); Point nextPoint=Astar.getAstar().getNextPoint(); avanzar(getDirToPoint(nextPoint), tablero); } /*@SuppressWarnings("unused") private int movAleatorio(Tablero tablero) { Point aux = (Point) p.clone(); int randDir = 0; do { aux = reverseTranslateDir(aux, randDir); randDir = random.nextInt(4) + 1; translateDir(aux, randDir); // System.out.print("\nwhiling"+randDir+" px:"+aux.x+" py:"+aux.y); } while (!tablero.isWalkable(aux)); return randDir; }*/ private void avanzar(int dir, Tablero tablero) { p=translateDir(p,dir); /*Point anterior = (Point) p.clone(); translateDir(p, dir); if (!tablero.isWalkable(p)) { p = anterior; }*/ } public Point translateDir(Point p, int dir) { switch (dir) { case DUP: p.y += UP; break; case DDOWN: p.y += DOWN; break; case DLEFT: p.x += LEFT; break; case DRIGHT: p.x += RIGHT; break; default: break; } return p; } /* public Point reverseTranslateDir(Point p, int dir) { switch (dir) { case DUP: p.y -= UP; break; case DDOWN: p.y -= DOWN; break; case DLEFT: p.x -= LEFT; break; case DRIGHT: p.x -= RIGHT; break; default: break; } return p; } */ }
jesusnoseq/JComococos
src/jrpsoft/Fantasma.java
Java
gpl-2.0
2,570
ALTER TABLE `characters` ADD `i_equip_s` INT NOT NULL DEFAULT 24 AFTER `mesos`; ALTER TABLE `characters` ADD `i_use_s` INT NOT NULL DEFAULT 24 AFTER `i_equip_s`; ALTER TABLE `characters` ADD `i_setup_s` INT NOT NULL DEFAULT 24 AFTER `i_use_s`; ALTER TABLE `characters` ADD `i_etc_s` INT NOT NULL DEFAULT 24 AFTER `i_setup_s`; ALTER TABLE `characters` ADD `i_cash_s` INT NOT NULL DEFAULT 48 AFTER `i_etc_s`;
MinoaveDev/EccoDev
sql/0030_inventoryslots.sql
SQL
gpl-2.0
406
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the Graphics Dojo project on Qt Labs. ** ** This file may be used under the terms of the GNU General Public ** License version 2.0 or 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of ** this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QtGui> #include <QtWidgets> #include <QtNetwork> #include <iostream> // for the explanation of the trick, check out: // http://www.virtualdub.org/blog/pivot/entry.php?id=116 // http://www.compuphase.com/graphic/scale3.htm #define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) ) QImage halfSized(const QImage &source) { QImage dest(source.size() * 0.5, QImage::Format_ARGB32_Premultiplied); const quint32 *src = reinterpret_cast<const quint32*>(source.bits()); int sx = source.bytesPerLine() >> 2; int sx2 = sx << 1; quint32 *dst = reinterpret_cast<quint32*>(dest.bits()); int dx = dest.bytesPerLine() >> 2; int ww = dest.width(); int hh = dest.height(); for (int y = hh; y; --y, dst += dx, src += sx2) { const quint32 *p1 = src; const quint32 *p2 = src + sx; quint32 *q = dst; for (int x = ww; x; --x, q++, p1 += 2, p2 += 2) * q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1])); } return dest; } class HalfScaler: public QWidget { Q_OBJECT private: int m_method; QNetworkAccessManager m_manager; QImage m_fastScaled; QImage m_smoothScaled; QImage m_optimizedScaled; public: HalfScaler(): QWidget(), m_method(0) { setAcceptDrops(true); connect(&m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleNetworkData(QNetworkReply*))); setWindowTitle("Drag and drop an image here!"); resize(512, 256); } void loadImage(const QImage &image) { QImage img = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); if (img.isNull()) { resize(512, 256); setWindowTitle("Can't load the image. Please drag and drop an new image."); } else { // we crop the image so that the width and height are even int ww = img.width() >> 1; int hh = img.height() >> 1; img = img.copy(0, 0, ww << 1, hh << 1); m_fastScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::FastTransformation); m_smoothScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); m_optimizedScaled = halfSized(img); resize(20 + ww * 2 + 50, hh * 2 + 30 + 2 * 40); } update(); } public slots: void handleNetworkData(QNetworkReply *networkReply) { m_fastScaled = QImage(); m_smoothScaled = QImage(); m_optimizedScaled = QImage(); QUrl url = networkReply->url(); if (networkReply->error()) { setWindowTitle(QString("Can't download %1: %2").arg(url.toString()).arg(networkReply->errorString())); } else { QImage image; image.load(networkReply, 0); QString fileName = QFileInfo(url.path()).fileName(); setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName)); loadImage(image); } networkReply->deleteLater(); } protected: void dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.count()) { QUrl url = urls[0]; if (event->mimeData()->hasImage()) { QImage img = qvariant_cast<QImage>(event->mimeData()->imageData()); QString fileName = QFileInfo(url.path()).fileName(); setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName)); loadImage(img); } else { m_manager.get(QNetworkRequest(url)); setWindowTitle(QString("Loading %1...").arg(url.toString())); } event->acceptProposedAction(); } } void keyPressEvent(QKeyEvent*) { m_method = (m_method + 1) % 3; update(); } void paintEvent(QPaintEvent*) { if (m_fastScaled.isNull()) return; int w = m_fastScaled.width(); int h = m_optimizedScaled.height(); QPainter painter; painter.begin(this); // top left image: fast painter.translate(10, 40); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::FastTransformation"); if (m_method == 0) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w + 2, h + 2, w + 50 - 10, h + 50 - 10); } painter.drawImage(0, 0, m_fastScaled); // top right image: smooth painter.translate(w + 50, 0); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::SmoothTransformation"); if (m_method == 1) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w / 2, h + 2, w / 2, h + 50 - 10); } painter.drawImage(0, 0, m_smoothScaled); // bottom left image: optimized painter.translate(-w - 50, h + 50); painter.setPen(Qt::black); painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Optimized"); if (m_method == 2) { painter.setPen(QPen(Qt::red, 2)); painter.drawRect(-2, -2, w + 4, h + 4); painter.drawLine(w + 2, h / 2, w + 50 - 10, h / 2); } painter.drawImage(0, 0, m_optimizedScaled); // bottom right image: chosen by the user QImage img = (m_method == 0) ? m_fastScaled : (m_method == 1) ? m_smoothScaled : m_optimizedScaled; painter.translate(w + 50, 0); painter.drawImage(0, 0, img); painter.end(); } }; #include "halfscale.moc" int main(int argc, char *argv[]) { QApplication app(argc, argv); HalfScaler widget; widget.show(); return app.exec(); }
anak10thn/graphics-dojo-qt5
halfscale/halfscale.cpp
C++
gpl-2.0
7,095
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.clients.http; ////import org.tanukisoftware.wrapper.WrapperManager; import freenet.client.filter.HTMLFilter; import freenet.client.filter.LinkFilterExceptionProvider; import freenet.clients.http.FProxyFetchInProgress.REFILTER_POLICY; import freenet.clients.http.PageMaker.THEME; import freenet.clients.http.bookmark.BookmarkManager; import freenet.clients.http.updateableelements.PushDataManager; import freenet.config.EnumerableOptionCallback; import freenet.config.InvalidConfigValueException; import freenet.config.NodeNeedRestartException; import freenet.config.SubConfig; import freenet.crypt.SSL; import freenet.io.AllowedHosts; import freenet.io.NetworkInterface; import freenet.io.SSLNetworkInterface; import freenet.keys.FreenetURI; import freenet.l10n.NodeL10n; import freenet.node.Node; import freenet.node.NodeClientCore; import freenet.node.PrioRunnable; import freenet.node.SecurityLevelListener; import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL; import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL; import freenet.node.useralerts.UserAlertManager; import freenet.pluginmanager.FredPluginL10n; import freenet.support.*; import freenet.support.Logger.LogLevel; import freenet.support.api.*; import freenet.support.io.ArrayBucketFactory; import freenet.support.io.NativeThread; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.Random; /** * The Toadlet (HTTP) Server * * Provide a HTTP server for FProxy */ public final class SimpleToadletServer implements ToadletContainer, Runnable, LinkFilterExceptionProvider { /** List of urlPrefix / Toadlet */ private final LinkedList<ToadletElement> toadlets; private static class ToadletElement { public ToadletElement(Toadlet t2, String urlPrefix, String menu, String name) { t = t2; prefix = urlPrefix; this.menu = menu; this.name = name; } Toadlet t; String prefix; String menu; String name; } // Socket / Binding private final int port; private String bindTo; private String allowedHosts; private NetworkInterface networkInterface; private boolean ssl = false; public static final int DEFAULT_FPROXY_PORT = 8888; // ACL private final AllowedHosts allowedFullAccess; private boolean publicGatewayMode; private final boolean wasPublicGatewayMode; // Theme private THEME cssTheme; private File cssOverride; private boolean sendAllThemes; private boolean advancedModeEnabled; private final PageMaker pageMaker; // Control private Thread myThread; private final Executor executor; private final Random random; private BucketFactory bf; private volatile NodeClientCore core; // HTTP Option private boolean doRobots; private boolean enablePersistentConnections; private boolean enableInlinePrefetch; private boolean enableActivelinks; private boolean enableExtendedMethodHandling; // Something does not really belongs to here volatile static boolean isPanicButtonToBeShown; // move to QueueToadlet ? volatile static boolean noConfirmPanic; public BookmarkManager bookmarkManager; // move to WelcomeToadlet / BookmarkEditorToadlet ? private volatile boolean fProxyJavascriptEnabled; // ugh? private volatile boolean fProxyWebPushingEnabled; // ugh? private volatile boolean fproxyHasCompletedWizard; // hmmm.. private volatile boolean disableProgressPage; private int maxFproxyConnections; private int fproxyConnections; private boolean finishedStartup; /** The PushDataManager handles all the pushing tasks*/ public PushDataManager pushDataManager; /** The IntervalPusherManager handles interval pushing*/ public IntervalPusherManager intervalPushManager; private static volatile boolean logMINOR; static { Logger.registerLogThresholdCallback(new LogThresholdCallback(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); } }); } // Config Callbacks private class FProxySSLCallback extends BooleanCallback { @Override public Boolean get() { return ssl; } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; if(!SSL.available()) { throw new InvalidConfigValueException("Enable SSL support before use ssl with Fproxy"); } ssl = val; throw new InvalidConfigValueException("Cannot change SSL on the fly, please restart freenet"); } @Override public boolean isReadOnly() { return true; } } private static class FProxyPassthruMaxSizeNoProgress extends LongCallback { @Override public Long get() { return FProxyToadlet.MAX_LENGTH_NO_PROGRESS; } @Override public void set(Long val) throws InvalidConfigValueException { if (get().equals(val)) return; FProxyToadlet.MAX_LENGTH_NO_PROGRESS = val; } } private static class FProxyPassthruMaxSizeProgress extends LongCallback { @Override public Long get() { return FProxyToadlet.MAX_LENGTH_WITH_PROGRESS; } @Override public void set(Long val) throws InvalidConfigValueException { if (get().equals(val)) return; FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = val; } } private class FProxyPortCallback extends IntCallback { @Override public Integer get() { return port; } @Override public void set(Integer newPort) throws NodeNeedRestartException { if(port != newPort) { throw new NodeNeedRestartException("Port cannot change on the fly"); } } } private class FProxyBindtoCallback extends StringCallback { @Override public String get() { return bindTo; } @Override public void set(String bindTo) throws InvalidConfigValueException { String oldValue = get(); if(!bindTo.equals(oldValue)) { String[] failedAddresses = networkInterface.setBindTo(bindTo, false); if(failedAddresses == null) { SimpleToadletServer.this.bindTo = bindTo; } else { // This is an advanced option for reasons of reducing clutter, // but it is expected to be used by regular users, not devs. // So we translate the error messages. networkInterface.setBindTo(oldValue, false); throw new InvalidConfigValueException(l10n("couldNotChangeBindTo", "failedInterfaces", Arrays.toString(failedAddresses))); } } } } private class FProxyAllowedHostsCallback extends StringCallback { @Override public String get() { return networkInterface.getAllowedHosts(); } @Override public void set(String allowedHosts) throws InvalidConfigValueException { if (!allowedHosts.equals(get())) { try { networkInterface.setAllowedHosts(allowedHosts); } catch(IllegalArgumentException e) { throw new InvalidConfigValueException(e); } } } } private class FProxyCSSNameCallback extends StringCallback implements EnumerableOptionCallback { @Override public String get() { return cssTheme.code; } @Override public void set(String CSSName) throws InvalidConfigValueException { if((CSSName.indexOf(':') != -1) || (CSSName.indexOf('/') != -1)) throw new InvalidConfigValueException(l10n("illegalCSSName")); cssTheme = THEME.themeFromName(CSSName); pageMaker.setTheme(cssTheme); NodeClientCore core = SimpleToadletServer.this.core; if (core.node.pluginManager != null) core.node.pluginManager.setFProxyTheme(cssTheme); } @Override public String[] getPossibleValues() { return THEME.possibleValues; } } private class FProxyCSSOverrideCallback extends StringCallback { @Override public String get() { return (cssOverride == null ? "" : cssOverride.toString()); } @Override public void set(String val) throws InvalidConfigValueException { NodeClientCore core = SimpleToadletServer.this.core; if(core == null) return; if(val.equals(get()) || val.equals("")) cssOverride = null; else { File tmp = new File(val.trim()); if(!core.allowUploadFrom(tmp)) throw new InvalidConfigValueException(l10n("cssOverrideNotInUploads", "filename", tmp.toString())); else if(!tmp.canRead() || !tmp.isFile()) throw new InvalidConfigValueException(l10n("cssOverrideCantRead", "filename", tmp.toString())); File parent = tmp.getParentFile(); // Basic sanity check. // Prevents user from specifying root dir. // They can still shoot themselves in the foot, but only when developing themes/using custom themes. // Because of the .. check above, any malicious thing cannot break out of the dir anyway. if(parent.getParentFile() == null) throw new InvalidConfigValueException(l10n("cssOverrideCantUseRootDir", "filename", parent.toString())); cssOverride = tmp; } if(cssOverride == null) pageMaker.setOverride(null); else { pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName()); } } } private class FProxyEnabledCallback extends BooleanCallback { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return myThread != null; } } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; synchronized(SimpleToadletServer.this) { if(val) { // Start it myThread = new Thread(SimpleToadletServer.this, "SimpleToadletServer"); } else { myThread.interrupt(); myThread = null; SimpleToadletServer.this.notifyAll(); return; } } createFproxy(); myThread.setDaemon(true); myThread.start(); } } private static class FProxyAdvancedModeEnabledCallback extends BooleanCallback { private final SimpleToadletServer ts; FProxyAdvancedModeEnabledCallback(SimpleToadletServer ts){ this.ts = ts; } @Override public Boolean get() { return ts.isAdvancedModeEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException { ts.setAdvancedMode(val); } } private static class FProxyJavascriptEnabledCallback extends BooleanCallback { private final SimpleToadletServer ts; FProxyJavascriptEnabledCallback(SimpleToadletServer ts){ this.ts = ts; } @Override public Boolean get() { return ts.isFProxyJavascriptEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException { if (get().equals(val)) return; ts.enableFProxyJavascript(val); } } private static class FProxyWebPushingEnabledCallback extends BooleanCallback{ private final SimpleToadletServer ts; FProxyWebPushingEnabledCallback(SimpleToadletServer ts){ this.ts=ts; } @Override public Boolean get() { return ts.isFProxyWebPushingEnabled(); } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if (get().equals(val)) return; ts.enableFProxyWebPushing(val); } } private boolean haveCalledFProxy = false; // FIXME factor this out to a global helper class somehow? private class ReFilterCallback extends StringCallback implements EnumerableOptionCallback { @Override public String[] getPossibleValues() { REFILTER_POLICY[] possible = REFILTER_POLICY.values(); String[] ret = new String[possible.length]; for(int i=0;i<possible.length;i++) ret[i] = possible[i].name(); return ret; } @Override public String get() { return refilterPolicy.name(); } @Override public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException { refilterPolicy = REFILTER_POLICY.valueOf(val); } }; public void createFproxy() { NodeClientCore core = this.core; Node node = core.node; synchronized(this) { if(haveCalledFProxy) return; haveCalledFProxy = true; } pushDataManager=new PushDataManager(getTicker()); intervalPushManager=new IntervalPusherManager(getTicker(), pushDataManager); bookmarkManager = new BookmarkManager(core, publicGatewayMode()); try { FProxyToadlet.maybeCreateFProxyEtc(core, node, node.config, this); } catch (IOException e) { Logger.error(this, "Could not start fproxy: "+e, e); System.err.println("Could not start fproxy:"); e.printStackTrace(); } } public void setCore(NodeClientCore core) { this.core = core; } /** * Create a SimpleToadletServer, using the settings from the SubConfig (the fproxy.* * config). */ public SimpleToadletServer(SubConfig fproxyConfig, BucketFactory bucketFactory, Executor executor, Node node) throws IOException, InvalidConfigValueException { this.executor = executor; this.core = null; // setCore() will be called later. this.random = new Random(); int configItemOrder = 0; fproxyConfig.register("enabled", true, configItemOrder++, true, true, "SimpleToadletServer.enabled", "SimpleToadletServer.enabledLong", new FProxyEnabledCallback()); boolean enabled = fproxyConfig.getBoolean("enabled"); fproxyConfig.register("ssl", false, configItemOrder++, true, true, "SimpleToadletServer.ssl", "SimpleToadletServer.sslLong", new FProxySSLCallback()); fproxyConfig.register("port", DEFAULT_FPROXY_PORT, configItemOrder++, true, true, "SimpleToadletServer.port", "SimpleToadletServer.portLong", new FProxyPortCallback(), false); fproxyConfig.register("bindTo", NetworkInterface.DEFAULT_BIND_TO, configItemOrder++, true, true, "SimpleToadletServer.bindTo", "SimpleToadletServer.bindToLong", new FProxyBindtoCallback()); fproxyConfig.register("css", "clean-dropdown", configItemOrder++, false, false, "SimpleToadletServer.cssName", "SimpleToadletServer.cssNameLong", new FProxyCSSNameCallback()); fproxyConfig.register("CSSOverride", "", configItemOrder++, true, false, "SimpleToadletServer.cssOverride", "SimpleToadletServer.cssOverrideLong", new FProxyCSSOverrideCallback()); fproxyConfig.register("sendAllThemes", false, configItemOrder++, true, false, "SimpleToadletServer.sendAllThemes", "SimpleToadletServer.sendAllThemesLong", new BooleanCallback() { @Override public Boolean get() { return sendAllThemes; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { sendAllThemes = val; } }); sendAllThemes = fproxyConfig.getBoolean("sendAllThemes"); fproxyConfig.register("advancedModeEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.advancedMode", "SimpleToadletServer.advancedModeLong", new FProxyAdvancedModeEnabledCallback(this)); fproxyConfig.register("enableExtendedMethodHandling", false, configItemOrder++, true, false, "SimpleToadletServer.enableExtendedMethodHandling", "SimpleToadletServer.enableExtendedMethodHandlingLong", new BooleanCallback() { @Override public Boolean get() { return enableExtendedMethodHandling; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(get().equals(val)) return; enableExtendedMethodHandling = val; } }); fproxyConfig.register("javascriptEnabled", true, configItemOrder++, true, false, "SimpleToadletServer.enableJS", "SimpleToadletServer.enableJSLong", new FProxyJavascriptEnabledCallback(this)); fproxyConfig.register("webPushingEnabled", false, configItemOrder++, true, false, "SimpleToadletServer.enableWP", "SimpleToadletServer.enableWPLong", new FProxyWebPushingEnabledCallback(this)); fproxyConfig.register("hasCompletedWizard", false, configItemOrder++, true, false, "SimpleToadletServer.hasCompletedWizard", "SimpleToadletServer.hasCompletedWizardLong", new BooleanCallback() { @Override public Boolean get() { return fproxyHasCompletedWizard; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(get().equals(val)) return; fproxyHasCompletedWizard = val; } }); fproxyConfig.register("disableProgressPage", false, configItemOrder++, true, false, "SimpleToadletServer.disableProgressPage", "SimpleToadletServer.disableProgressPageLong", new BooleanCallback() { @Override public Boolean get() { return disableProgressPage; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { disableProgressPage = val; } }); fproxyHasCompletedWizard = fproxyConfig.getBoolean("hasCompletedWizard"); fProxyJavascriptEnabled = fproxyConfig.getBoolean("javascriptEnabled"); fProxyWebPushingEnabled = fproxyConfig.getBoolean("webPushingEnabled"); disableProgressPage = fproxyConfig.getBoolean("disableProgressPage"); enableExtendedMethodHandling = fproxyConfig.getBoolean("enableExtendedMethodHandling"); fproxyConfig.register("showPanicButton", false, configItemOrder++, true, true, "SimpleToadletServer.panicButton", "SimpleToadletServer.panicButtonLong", new BooleanCallback(){ @Override public Boolean get() { return SimpleToadletServer.isPanicButtonToBeShown; } @Override public void set(Boolean value) { if(value == SimpleToadletServer.isPanicButtonToBeShown) return; else SimpleToadletServer.isPanicButtonToBeShown = value; } }); fproxyConfig.register("noConfirmPanic", false, configItemOrder++, true, true, "SimpleToadletServer.noConfirmPanic", "SimpleToadletServer.noConfirmPanicLong", new BooleanCallback() { @Override public Boolean get() { return SimpleToadletServer.noConfirmPanic; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(val == SimpleToadletServer.noConfirmPanic) return; else SimpleToadletServer.noConfirmPanic = val; } }); fproxyConfig.register("publicGatewayMode", false, configItemOrder++, true, true, "SimpleToadletServer.publicGatewayMode", "SimpleToadletServer.publicGatewayModeLong", new BooleanCallback() { @Override public Boolean get() { return publicGatewayMode; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if(publicGatewayMode == val) return; publicGatewayMode = val; throw new NodeNeedRestartException(l10n("publicGatewayModeNeedsRestart")); } }); wasPublicGatewayMode = publicGatewayMode = fproxyConfig.getBoolean("publicGatewayMode"); // This is OFF BY DEFAULT because for example firefox has a limit of 2 persistent // connections per server, but 8 non-persistent connections per server. We need 8 conns // more than we need the efficiency gain of reusing connections - especially on first // install. fproxyConfig.register("enablePersistentConnections", false, configItemOrder++, true, false, "SimpleToadletServer.enablePersistentConnections", "SimpleToadletServer.enablePersistentConnectionsLong", new BooleanCallback() { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return enablePersistentConnections; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(SimpleToadletServer.this) { enablePersistentConnections = val; } } }); enablePersistentConnections = fproxyConfig.getBoolean("enablePersistentConnections"); // Off by default. // I had hoped it would yield a significant performance boost to bootstrap performance // on browsers with low numbers of simultaneous connections. Unfortunately the bottleneck // appears to be that the node does very few local requests compared to external requests // (for anonymity's sake). fproxyConfig.register("enableInlinePrefetch", false, configItemOrder++, true, false, "SimpleToadletServer.enableInlinePrefetch", "SimpleToadletServer.enableInlinePrefetchLong", new BooleanCallback() { @Override public Boolean get() { synchronized(SimpleToadletServer.this) { return enableInlinePrefetch; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(SimpleToadletServer.this) { enableInlinePrefetch = val; } } }); enableInlinePrefetch = fproxyConfig.getBoolean("enableInlinePrefetch"); fproxyConfig.register("enableActivelinks", false, configItemOrder++, false, false, "SimpleToadletServer.enableActivelinks", "SimpleToadletServer.enableActivelinksLong", new BooleanCallback() { @Override public Boolean get() { return enableActivelinks; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { enableActivelinks = val; } }); enableActivelinks = fproxyConfig.getBoolean("enableActivelinks"); fproxyConfig.register("passthroughMaxSize", FProxyToadlet.MAX_LENGTH_NO_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSize", "SimpleToadletServer.passthroughMaxSizeLong", new FProxyPassthruMaxSizeNoProgress(), true); FProxyToadlet.MAX_LENGTH_NO_PROGRESS = fproxyConfig.getLong("passthroughMaxSize"); fproxyConfig.register("passthroughMaxSizeProgress", FProxyToadlet.MAX_LENGTH_WITH_PROGRESS, configItemOrder++, true, false, "SimpleToadletServer.passthroughMaxSizeProgress", "SimpleToadletServer.passthroughMaxSizeProgressLong", new FProxyPassthruMaxSizeProgress(), true); FProxyToadlet.MAX_LENGTH_WITH_PROGRESS = fproxyConfig.getLong("passthroughMaxSizeProgress"); System.out.println("Set fproxy max length to "+FProxyToadlet.MAX_LENGTH_NO_PROGRESS+" and max length with progress to "+FProxyToadlet.MAX_LENGTH_WITH_PROGRESS+" = "+fproxyConfig.getLong("passthroughMaxSizeProgress")); fproxyConfig.register("allowedHosts", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedHosts", "SimpleToadletServer.allowedHostsLong", new FProxyAllowedHostsCallback()); fproxyConfig.register("allowedHostsFullAccess", "127.0.0.1,0:0:0:0:0:0:0:1", configItemOrder++, true, true, "SimpleToadletServer.allowedFullAccess", "SimpleToadletServer.allowedFullAccessLong", new StringCallback() { @Override public String get() { return allowedFullAccess.getAllowedHosts(); } @Override public void set(String val) throws InvalidConfigValueException { try { allowedFullAccess.setAllowedHosts(val); } catch(IllegalArgumentException e) { throw new InvalidConfigValueException(e); } } }); allowedFullAccess = new AllowedHosts(fproxyConfig.getString("allowedHostsFullAccess")); fproxyConfig.register("doRobots", false, configItemOrder++, true, false, "SimpleToadletServer.doRobots", "SimpleToadletServer.doRobotsLong", new BooleanCallback() { @Override public Boolean get() { return doRobots; } @Override public void set(Boolean val) throws InvalidConfigValueException { doRobots = val; } }); doRobots = fproxyConfig.getBoolean("doRobots"); // We may not know what the overall thread limit is yet so just set it to 100. fproxyConfig.register("maxFproxyConnections", 100, configItemOrder++, true, false, "SimpleToadletServer.maxFproxyConnections", "SimpleToadletServer.maxFproxyConnectionsLong", new IntCallback() { @Override public Integer get() { synchronized(SimpleToadletServer.this) { return maxFproxyConnections; } } @Override public void set(Integer val) { synchronized(SimpleToadletServer.this) { maxFproxyConnections = val; SimpleToadletServer.this.notifyAll(); } } }, false); maxFproxyConnections = fproxyConfig.getInt("maxFproxyConnections"); fproxyConfig.register("metaRefreshSamePageInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshSamePageInterval", "SimpleToadletServer.metaRefreshSamePageIntervalLong", new IntCallback() { @Override public Integer get() { return HTMLFilter.metaRefreshSamePageMinInterval; } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n HTMLFilter.metaRefreshSamePageMinInterval = val; } }, false); HTMLFilter.metaRefreshSamePageMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshSamePageInterval")); fproxyConfig.register("metaRefreshRedirectInterval", 1, configItemOrder++, true, false, "SimpleToadletServer.metaRefreshRedirectInterval", "SimpleToadletServer.metaRefreshRedirectIntervalLong", new IntCallback() { @Override public Integer get() { return HTMLFilter.metaRefreshRedirectMinInterval; } @Override public void set(Integer val) throws InvalidConfigValueException, NodeNeedRestartException { if(val < -1) throw new InvalidConfigValueException("-1 = disabled, 0+ = set a minimum interval"); // FIXME l10n HTMLFilter.metaRefreshRedirectMinInterval = val; } }, false); HTMLFilter.metaRefreshRedirectMinInterval = Math.max(-1, fproxyConfig.getInt("metaRefreshRedirectInterval")); fproxyConfig.register("refilterPolicy", "RE_FILTER", configItemOrder++, true, false, "SimpleToadletServer.refilterPolicy", "SimpleToadletServer.refilterPolicyLong", new ReFilterCallback()); this.refilterPolicy = REFILTER_POLICY.valueOf(fproxyConfig.getString("refilterPolicy")); // Network seclevel not physical seclevel because bad filtering can cause network level anonymity breaches. SimpleToadletServer.isPanicButtonToBeShown = fproxyConfig.getBoolean("showPanicButton"); SimpleToadletServer.noConfirmPanic = fproxyConfig.getBoolean("noConfirmPanic"); this.bf = bucketFactory; port = fproxyConfig.getInt("port"); bindTo = fproxyConfig.getString("bindTo"); String cssName = fproxyConfig.getString("css"); if((cssName.indexOf(':') != -1) || (cssName.indexOf('/') != -1)) throw new InvalidConfigValueException("CSS name must not contain slashes or colons!"); cssTheme = THEME.themeFromName(cssName); pageMaker = new PageMaker(cssTheme, node); if(!fproxyConfig.getOption("CSSOverride").isDefault()) { cssOverride = new File(fproxyConfig.getString("CSSOverride")); pageMaker.setOverride(StaticToadlet.OVERRIDE_URL + cssOverride.getName()); } else { cssOverride = null; pageMaker.setOverride(null); } this.advancedModeEnabled = fproxyConfig.getBoolean("advancedModeEnabled"); toadlets = new LinkedList<ToadletElement>(); if(SSL.available()) { ssl = fproxyConfig.getBoolean("ssl"); } this.allowedHosts=fproxyConfig.getString("allowedHosts"); if(!enabled) { Logger.normal(SimpleToadletServer.this, "Not starting FProxy as it's disabled"); System.out.println("Not starting FProxy as it's disabled"); } else { maybeGetNetworkInterface(); myThread = new Thread(this, "SimpleToadletServer"); myThread.setDaemon(true); } // Register static toadlet and startup toadlet StaticToadlet statictoadlet = new StaticToadlet(); register(statictoadlet, null, "/static/", false, false); // "Freenet is starting up..." page, to be removed at #removeStartupToadlet() startupToadlet = new StartupToadlet(statictoadlet); register(startupToadlet, null, "/", false, false); } public StartupToadlet startupToadlet; public void removeStartupToadlet() { // setCore() must have been called first. It is in fact called much earlier on. synchronized(this) { unregister(startupToadlet); // Ready to be GCed startupToadlet = null; // Not in the navbar. } } private void maybeGetNetworkInterface() throws IOException { if (this.networkInterface!=null) return; if(ssl) { this.networkInterface = SSLNetworkInterface.create(port, this.bindTo, allowedHosts, executor, true); } else { this.networkInterface = NetworkInterface.create(port, this.bindTo, allowedHosts, executor, true); } } @Override public boolean doRobots() { return doRobots; } @Override public boolean publicGatewayMode() { return wasPublicGatewayMode; } public void start() { if(myThread != null) try { maybeGetNetworkInterface(); myThread.start(); Logger.normal(this, "Starting FProxy on "+bindTo+ ':' +port); System.out.println("Starting FProxy on "+bindTo+ ':' +port); } catch (IOException e) { Logger.error(this, "Could not bind network port for FProxy?", e); } } public void finishStart() { core.node.securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { @Override public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { // At LOW, we do ACCEPT_OLD. // Otherwise we do RE_FILTER. // But we don't change it unless it changes from LOW to not LOW. if(newLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) { refilterPolicy = REFILTER_POLICY.ACCEPT_OLD; } else if(oldLevel == NETWORK_THREAT_LEVEL.LOW && newLevel != oldLevel) { refilterPolicy = REFILTER_POLICY.RE_FILTER; } } }); core.node.securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL> () { @Override public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) { if(newLevel != oldLevel && newLevel == PHYSICAL_THREAT_LEVEL.LOW) { isPanicButtonToBeShown = false; } else if(newLevel != oldLevel) { isPanicButtonToBeShown = true; } } }); synchronized(this) { finishedStartup = true; } } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, boolean fullOnly) { register(t, menu, urlPrefix, atFront, null, null, fullOnly, null, null); } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb) { register(t, menu, urlPrefix, atFront, name, title, fullOnly, cb, null); } @Override public void register(Toadlet t, String menu, String urlPrefix, boolean atFront, String name, String title, boolean fullOnly, LinkEnabledCallback cb, FredPluginL10n l10n) { ToadletElement te = new ToadletElement(t, urlPrefix, menu, name); synchronized(toadlets) { if(atFront) toadlets.addFirst(te); else toadlets.addLast(te); t.container = this; } if (menu != null && name != null) { pageMaker.addNavigationLink(menu, urlPrefix, name, title, fullOnly, cb, l10n); } } public void registerMenu(String link, String name, String title, FredPluginL10n plugin) { pageMaker.addNavigationCategory(link, name, title, plugin); } @Override public void unregister(Toadlet t) { ToadletElement e = null; synchronized(toadlets) { for(Iterator<ToadletElement> i=toadlets.iterator();i.hasNext();) { e = i.next(); if(e.t == t) { i.remove(); break; } } } if(e != null && e.t == t) { if(e.menu != null && e.name != null) { pageMaker.removeNavigationLink(e.menu, e.name); } } } public StartupToadlet getStartupToadlet() { return startupToadlet; } @Override public boolean fproxyHasCompletedWizard() { return fproxyHasCompletedWizard; } @Override public Toadlet findToadlet(URI uri) throws PermanentRedirectException { String path = uri.getPath(); // Show the wizard until dismissed by the user (See bug #2624) NodeClientCore core = this.core; if(core != null && core.node != null && !fproxyHasCompletedWizard) { //If the user has not completed the wizard, only allow access to the wizard and static //resources. Anything else redirects to the first page of the wizard. if (!(path.startsWith(FirstTimeWizardToadlet.TOADLET_URL) || path.startsWith(StaticToadlet.ROOT_URL) || path.startsWith(ExternalLinkToadlet.PATH) || path.equals("/favicon.ico"))) { try { throw new PermanentRedirectException(new URI(null, null, null, -1, FirstTimeWizardToadlet.TOADLET_URL, uri.getQuery(), null)); } catch(URISyntaxException e) { throw new Error(e); } } } synchronized(toadlets) { for(ToadletElement te: toadlets) { if(path.startsWith(te.prefix)) return te.t; if(te.prefix.length() > 0 && te.prefix.charAt(te.prefix.length()-1) == '/') { if(path.equals(te.prefix.substring(0, te.prefix.length()-1))) { URI newURI; try { newURI = new URI(te.prefix); } catch (URISyntaxException e) { throw new Error(e); } throw new PermanentRedirectException(newURI); } } } } return null; } @Override public void run() { boolean finishedStartup = false; while(true) { synchronized(this) { while(fproxyConnections > maxFproxyConnections) { try { wait(); } catch (InterruptedException e) { // Ignore } } if((!finishedStartup) && this.finishedStartup) finishedStartup = true; if(myThread == null) return; } Socket conn = networkInterface.accept(); //if (WrapperManager.hasShutdownHookBeenTriggered()) //return; if(conn == null) continue; // timeout if(logMINOR) Logger.minor(this, "Accepted connection"); SocketHandler sh = new SocketHandler(conn, finishedStartup); sh.start(); } } public class SocketHandler implements PrioRunnable { Socket sock; final boolean finishedStartup; public SocketHandler(Socket conn, boolean finishedStartup) { this.sock = conn; this.finishedStartup = finishedStartup; } void start() { if(finishedStartup) executor.execute(this, "HTTP socket handler@"+hashCode()); else new Thread(this).start(); synchronized(SimpleToadletServer.this) { fproxyConnections++; } } @Override public void run() { freenet.support.Logger.OSThread.logPID(this); if(logMINOR) Logger.minor(this, "Handling connection"); try { ToadletContextImpl.handle(sock, SimpleToadletServer.this, pageMaker, getUserAlertManager(), bookmarkManager); } catch (Throwable t) { System.err.println("Caught in SimpleToadletServer: "+t); t.printStackTrace(); Logger.error(this, "Caught in SimpleToadletServer: "+t, t); } finally { synchronized(SimpleToadletServer.this) { fproxyConnections--; SimpleToadletServer.this.notifyAll(); } } if(logMINOR) Logger.minor(this, "Handled connection"); } @Override public int getPriority() { return NativeThread.HIGH_PRIORITY-1; } } @Override public THEME getTheme() { return this.cssTheme; } public UserAlertManager getUserAlertManager() { NodeClientCore core = this.core; if(core == null) return null; return core.alerts; } public void setCSSName(THEME theme) { this.cssTheme = theme; } @Override public synchronized boolean sendAllThemes() { return this.sendAllThemes; } @Override public synchronized boolean isAdvancedModeEnabled() { return this.advancedModeEnabled; } @Override public void setAdvancedMode(boolean enabled) { synchronized(this) { if(advancedModeEnabled == enabled) return; advancedModeEnabled = enabled; } core.node.config.store(); } @Override public synchronized boolean isFProxyJavascriptEnabled() { return this.fProxyJavascriptEnabled; } public synchronized void enableFProxyJavascript(boolean b){ fProxyJavascriptEnabled = b; } @Override public synchronized boolean isFProxyWebPushingEnabled() { return this.fProxyWebPushingEnabled; } public synchronized void enableFProxyWebPushing(boolean b){ fProxyWebPushingEnabled = b; } @Override public String getFormPassword() { if(core == null) return ""; return core.formPassword; } @Override public boolean isAllowedFullAccess(InetAddress remoteAddr) { return this.allowedFullAccess.allowed(remoteAddr); } private static String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("SimpleToadletServer."+key, pattern, value); } private static String l10n(String key) { return NodeL10n.getBase().getString("SimpleToadletServer."+key); } @Override public HTMLNode addFormChild(HTMLNode parentNode, String target, String id) { HTMLNode formNode = parentNode.addChild("div") .addChild("form", new String[] { "action", "method", "enctype", "id", "accept-charset" }, new String[] { target, "post", "multipart/form-data", id, "utf-8"} ); formNode.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "formPassword", getFormPassword() }); return formNode; } public void setBucketFactory(BucketFactory tempBucketFactory) { this.bf = tempBucketFactory; } public boolean isEnabled() { return myThread != null; } public BookmarkManager getBookmarks() { return bookmarkManager; } public FreenetURI[] getBookmarkURIs() { if(bookmarkManager == null) return new FreenetURI[0]; return bookmarkManager.getBookmarkURIs(); } @Override public boolean enablePersistentConnections() { return enablePersistentConnections; } @Override public boolean enableInlinePrefetch() { return enableInlinePrefetch; } @Override public boolean enableExtendedMethodHandling() { return enableExtendedMethodHandling; } @Override public synchronized boolean allowPosts() { return !(bf instanceof ArrayBucketFactory); } @Override public synchronized BucketFactory getBucketFactory() { return bf; } @Override public boolean enableActivelinks() { return enableActivelinks; } @Override public boolean disableProgressPage() { return disableProgressPage; } @Override public PageMaker getPageMaker() { return pageMaker; } public Ticker getTicker(){ return core.node.getTicker(); } public NodeClientCore getCore(){ return core; } private REFILTER_POLICY refilterPolicy; @Override public REFILTER_POLICY getReFilterPolicy() { return refilterPolicy; } @Override public File getOverrideFile() { return cssOverride; } @Override public String getURL() { return getURL(null); } @Override public String getURL(String host) { StringBuffer sb = new StringBuffer(); if(ssl) sb.append("https"); else sb.append("http"); sb.append("://"); if(host == null) host = "127.0.0.1"; sb.append(host); sb.append(":"); sb.append(this.port); sb.append("/"); return sb.toString(); } @Override public boolean isSSL() { return ssl; } // // LINKFILTEREXCEPTIONPROVIDER METHODS // /** * {@inheritDoc} */ @Override public boolean isLinkExcepted(URI link) { Toadlet toadlet = null; try { toadlet = findToadlet(link); } catch (PermanentRedirectException pre1) { /* ignore. */ } if (toadlet instanceof LinkFilterExceptedToadlet) { return ((LinkFilterExceptedToadlet) toadlet).isLinkExcepted(link); } return false; } @Override public long generateUniqueID() { // FIXME increment a counter? return random.nextLong(); } }
deepstupid/fred
src/freenet/clients/http/SimpleToadletServer.java
Java
gpl-2.0
39,516
--- layout: default title: (unrecognied function)(FIXME!) --- [Top](../index.html) --- ### 定義場所(file name) hotspot/src/share/vm/prims/jvmtiEnvBase.cpp ### 説明(description) ``` // update the access_flags for the field in the klass ``` ### 名前(function name) ``` void JvmtiEnvBase::update_klass_field_access_flag(fieldDescriptor *fd) { ``` ### 本体部(body) ``` {- ------------------------------------------- (1) fd 引数で指定された fieldDescriptor オブジェクトの _access_flags 情報を, 対応する instanceKlass の fields の中にコピーする ---------------------------------------- -} instanceKlass* ik = instanceKlass::cast(fd->field_holder()); typeArrayOop fields = ik->fields(); fields->ushort_at_put(fd->index(), (jushort)fd->access_flags().as_short()); } ```
hsmemo/hsmemo.github.com
articles/no2935oaP.md
Markdown
gpl-2.0
841
<?php defined('_JEXEC') or die(); /** * * Description * * @package VirtueMart * @subpackage Calculation tool * @author Max Milbers * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id: default.php 6475 2012-09-21 11:54:21Z Milbo $ */ // Check to ensure this file is included in Joomla! ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <?php AdminUIHelper::startAdminArea(); ?> <div id="filter-bar" class="btn-toolbar"> <?php echo $this->displayDefaultViewSearch() ?> </div> <div class="clearfix"> </div> <div id="results"> <?php // split to use ajax search echo $this->loadTemplate('results'); ?> </div> <?php AdminUIHelper::endAdminArea(true); ?> </form>
cuongnd/test_pro
administrator/components/com_virtuemart1/views/calc/tmpl/default.php
PHP
gpl-2.0
1,115
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>Automated Translation Tries: File Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Automated Translation Tries </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li class="current"><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('globals_defs.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160;<ul> <li>A : <a class="el" href="_hashing_utils_8hpp.html#a955f504eccf76b4eb2489c0adab03121">HashingUtils.hpp</a> </li> <li>B : <a class="el" href="_hashing_utils_8hpp.html#a111da81ae5883147168bbb8366377b10">HashingUtils.hpp</a> </li> <li>BYTES_ONE_MB : <a class="el" href="_globals_8hpp.html#a52055f2355a2ec4d1e883f04023bbf61">Globals.hpp</a> </li> <li>C : <a class="el" href="_hashing_utils_8hpp.html#ac4cf4b2ab929bd23951a8676eeac086b">HashingUtils.hpp</a> </li> <li>DEBUG_OPTION_VALUES : <a class="el" href="_globals_8hpp.html#aafab43b38b1f0088e435452166a53e26">Globals.hpp</a> </li> <li>DEBUG_PARAM_VALUE : <a class="el" href="_globals_8hpp.html#ab433fe232979981ca13d4abc88018217">Globals.hpp</a> </li> <li>EXPECTED_NUMBER_OF_ARGUMENTS : <a class="el" href="_globals_8hpp.html#ab6387e50755e46ace53cb75b6289eba8">Globals.hpp</a> </li> <li>EXPECTED_USER_NUMBER_OF_ARGUMENTS : <a class="el" href="_globals_8hpp.html#a2a9338760b64ba064b8446917f669ed8">Globals.hpp</a> </li> <li>HASHMAPTRIE_HPP : <a class="el" href="_hash_map_trie_8hpp.html#a44555afdc39259ebd960834e39096cee">HashMapTrie.hpp</a> </li> <li>INFO_PARAM_VALUE : <a class="el" href="_globals_8hpp.html#a71979fc65a21e2bf27f0df1f7c9d4721">Globals.hpp</a> </li> <li>LOGER_MAX_LEVEL : <a class="el" href="_logger_8hpp.html#ac44bfa0883a8e25bcc4b05d7b5835054">Logger.hpp</a> </li> <li>LOGGER : <a class="el" href="_logger_8hpp.html#a8909731db6798bb18ac697c179b4dedd">Logger.hpp</a> </li> <li>LOGGER_HPP : <a class="el" href="_logger_8hpp.html#a46c5641c9a0192f415a133917f57b01a">Logger.hpp</a> </li> <li>N_GRAM_PARAM : <a class="el" href="_globals_8hpp.html#a5f3826bb70e91d12acce8d68c346c07b">Globals.hpp</a> </li> <li>PATH_SEPARATION_SYMBOLS : <a class="el" href="_globals_8hpp.html#aa14a56d9d266e780483319faf0a803c1">Globals.hpp</a> </li> <li>PROGRESS_UPDATE_PERIOD : <a class="el" href="_logger_8hpp.html#a6a29bf797538ea7ba250e7ccbc0f9082">Logger.hpp</a> </li> <li>TOKEN_DELIMITER_CHAR : <a class="el" href="_globals_8hpp.html#a63fb6fc7e044c2456baec320d9472899">Globals.hpp</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
ivan-zapreev/Automated-Translation-Tries
doxygen/html/globals_defs.html
HTML
gpl-2.0
6,898
/******************************************************************************* * This file contains iSCSI extentions for RDMA (iSER) Verbs * * (c) Copyright 2013 RisingTide Systems LLC. * * Nicholas A. Bellinger <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. ****************************************************************************/ #include <linux/string.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/in6.h> #include <rdma/ib_verbs.h> #include <rdma/rdma_cm.h> #include <target/target_core_base.h> #include <target/target_core_fabric.h> #include <target/iscsi/iscsi_transport.h> #include "isert_proto.h" #include "ib_isert.h" #define ISERT_MAX_CONN 8 #define ISER_MAX_RX_CQ_LEN (ISERT_QP_MAX_RECV_DTOS * ISERT_MAX_CONN) #define ISER_MAX_TX_CQ_LEN (ISERT_QP_MAX_REQ_DTOS * ISERT_MAX_CONN) static DEFINE_MUTEX(device_list_mutex); static LIST_HEAD(device_list); static struct workqueue_struct *isert_rx_wq; static struct workqueue_struct *isert_comp_wq; static struct kmem_cache *isert_cmd_cache; static void isert_release_work(struct work_struct *work); static void isert_qp_event_callback(struct ib_event *e, void *context) { struct isert_conn *isert_conn = (struct isert_conn *)context; pr_err("isert_qp_event_callback event: %d\n", e->event); switch (e->event) { case IB_EVENT_COMM_EST: rdma_notify(isert_conn->conn_cm_id, IB_EVENT_COMM_EST); break; case IB_EVENT_QP_LAST_WQE_REACHED: pr_warn("Reached TX IB_EVENT_QP_LAST_WQE_REACHED:\n"); break; default: break; } } static int isert_query_device(struct ib_device *ib_dev, struct ib_device_attr *devattr) { int ret; ret = ib_query_device(ib_dev, devattr); if (ret) { pr_err("ib_query_device() failed: %d\n", ret); return ret; } pr_debug("devattr->max_sge: %d\n", devattr->max_sge); pr_debug("devattr->max_sge_rd: %d\n", devattr->max_sge_rd); return 0; } static int isert_conn_setup_qp(struct isert_conn *isert_conn, struct rdma_cm_id *cma_id) { struct isert_device *device = isert_conn->conn_device; struct ib_qp_init_attr attr; struct ib_device_attr devattr; int ret, index, min_index = 0; memset(&devattr, 0, sizeof(struct ib_device_attr)); ret = isert_query_device(cma_id->device, &devattr); if (ret) return ret; mutex_lock(&device_list_mutex); for (index = 0; index < device->cqs_used; index++) if (device->cq_active_qps[index] < device->cq_active_qps[min_index]) min_index = index; device->cq_active_qps[min_index]++; pr_debug("isert_conn_setup_qp: Using min_index: %d\n", min_index); mutex_unlock(&device_list_mutex); memset(&attr, 0, sizeof(struct ib_qp_init_attr)); attr.event_handler = isert_qp_event_callback; attr.qp_context = isert_conn; attr.send_cq = device->dev_tx_cq[min_index]; attr.recv_cq = device->dev_rx_cq[min_index]; attr.cap.max_send_wr = ISERT_QP_MAX_REQ_DTOS; attr.cap.max_recv_wr = ISERT_QP_MAX_RECV_DTOS; /* * FIXME: Use devattr.max_sge - 2 for max_send_sge as * work-around for RDMA_READ.. */ attr.cap.max_send_sge = devattr.max_sge - 2; isert_conn->max_sge = attr.cap.max_send_sge; attr.cap.max_recv_sge = 1; attr.sq_sig_type = IB_SIGNAL_REQ_WR; attr.qp_type = IB_QPT_RC; pr_debug("isert_conn_setup_qp cma_id->device: %p\n", cma_id->device); pr_debug("isert_conn_setup_qp conn_pd->device: %p\n", isert_conn->conn_pd->device); ret = rdma_create_qp(cma_id, isert_conn->conn_pd, &attr); if (ret) { pr_err("rdma_create_qp failed for cma_id %d\n", ret); return ret; } isert_conn->conn_qp = cma_id->qp; pr_debug("rdma_create_qp() returned success >>>>>>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static void isert_cq_event_callback(struct ib_event *e, void *context) { pr_debug("isert_cq_event_callback event: %d\n", e->event); } static int isert_alloc_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_rx_desc *rx_desc; struct ib_sge *rx_sg; u64 dma_addr; int i, j; isert_conn->conn_rx_descs = kzalloc(ISERT_QP_MAX_RECV_DTOS * sizeof(struct iser_rx_desc), GFP_KERNEL); if (!isert_conn->conn_rx_descs) goto fail; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { dma_addr = ib_dma_map_single(ib_dev, (void *)rx_desc, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) goto dma_map_fail; rx_desc->dma_addr = dma_addr; rx_sg = &rx_desc->rx_sg; rx_sg->addr = rx_desc->dma_addr; rx_sg->length = ISER_RX_PAYLOAD_SIZE; rx_sg->lkey = isert_conn->conn_mr->lkey; } isert_conn->conn_rx_desc_head = 0; return 0; dma_map_fail: rx_desc = isert_conn->conn_rx_descs; for (j = 0; j < i; j++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; fail: return -ENOMEM; } static void isert_free_rx_descriptors(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_device->ib_device; struct iser_rx_desc *rx_desc; int i; if (!isert_conn->conn_rx_descs) return; rx_desc = isert_conn->conn_rx_descs; for (i = 0; i < ISERT_QP_MAX_RECV_DTOS; i++, rx_desc++) { ib_dma_unmap_single(ib_dev, rx_desc->dma_addr, ISER_RX_PAYLOAD_SIZE, DMA_FROM_DEVICE); } kfree(isert_conn->conn_rx_descs); isert_conn->conn_rx_descs = NULL; } static void isert_cq_tx_callback(struct ib_cq *, void *); static void isert_cq_rx_callback(struct ib_cq *, void *); static int isert_create_device_ib_res(struct isert_device *device) { struct ib_device *ib_dev = device->ib_device; struct isert_cq_desc *cq_desc; int ret = 0, i, j; device->cqs_used = min_t(int, num_online_cpus(), device->ib_device->num_comp_vectors); device->cqs_used = min(ISERT_MAX_CQ, device->cqs_used); pr_debug("Using %d CQs, device %s supports %d vectors\n", device->cqs_used, device->ib_device->name, device->ib_device->num_comp_vectors); device->cq_desc = kzalloc(sizeof(struct isert_cq_desc) * device->cqs_used, GFP_KERNEL); if (!device->cq_desc) { pr_err("Unable to allocate device->cq_desc\n"); return -ENOMEM; } cq_desc = device->cq_desc; device->dev_pd = ib_alloc_pd(ib_dev); if (IS_ERR(device->dev_pd)) { ret = PTR_ERR(device->dev_pd); pr_err("ib_alloc_pd failed for dev_pd: %d\n", ret); goto out_cq_desc; } for (i = 0; i < device->cqs_used; i++) { cq_desc[i].device = device; cq_desc[i].cq_index = i; device->dev_rx_cq[i] = ib_create_cq(device->ib_device, isert_cq_rx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_RX_CQ_LEN, i); if (IS_ERR(device->dev_rx_cq[i])) { ret = PTR_ERR(device->dev_rx_cq[i]); device->dev_rx_cq[i] = NULL; goto out_cq; } device->dev_tx_cq[i] = ib_create_cq(device->ib_device, isert_cq_tx_callback, isert_cq_event_callback, (void *)&cq_desc[i], ISER_MAX_TX_CQ_LEN, i); if (IS_ERR(device->dev_tx_cq[i])) { ret = PTR_ERR(device->dev_tx_cq[i]); device->dev_tx_cq[i] = NULL; goto out_cq; } ret = ib_req_notify_cq(device->dev_rx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; ret = ib_req_notify_cq(device->dev_tx_cq[i], IB_CQ_NEXT_COMP); if (ret) goto out_cq; } device->dev_mr = ib_get_dma_mr(device->dev_pd, IB_ACCESS_LOCAL_WRITE); if (IS_ERR(device->dev_mr)) { ret = PTR_ERR(device->dev_mr); pr_err("ib_get_dma_mr failed for dev_mr: %d\n", ret); goto out_cq; } return 0; out_cq: for (j = 0; j < i; j++) { cq_desc = &device->cq_desc[j]; if (device->dev_rx_cq[j]) { cancel_work_sync(&cq_desc->cq_rx_work); ib_destroy_cq(device->dev_rx_cq[j]); } if (device->dev_tx_cq[j]) { cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_tx_cq[j]); } } ib_dealloc_pd(device->dev_pd); out_cq_desc: kfree(device->cq_desc); return ret; } static void isert_free_device_ib_res(struct isert_device *device) { struct isert_cq_desc *cq_desc; int i; for (i = 0; i < device->cqs_used; i++) { cq_desc = &device->cq_desc[i]; cancel_work_sync(&cq_desc->cq_rx_work); cancel_work_sync(&cq_desc->cq_tx_work); ib_destroy_cq(device->dev_rx_cq[i]); ib_destroy_cq(device->dev_tx_cq[i]); device->dev_rx_cq[i] = NULL; device->dev_tx_cq[i] = NULL; } ib_dereg_mr(device->dev_mr); ib_dealloc_pd(device->dev_pd); kfree(device->cq_desc); } static void isert_device_try_release(struct isert_device *device) { mutex_lock(&device_list_mutex); device->refcount--; if (!device->refcount) { isert_free_device_ib_res(device); list_del(&device->dev_node); kfree(device); } mutex_unlock(&device_list_mutex); } static struct isert_device * isert_device_find_by_ib_dev(struct rdma_cm_id *cma_id) { struct isert_device *device; int ret; mutex_lock(&device_list_mutex); list_for_each_entry(device, &device_list, dev_node) { if (device->ib_device->node_guid == cma_id->device->node_guid) { device->refcount++; mutex_unlock(&device_list_mutex); return device; } } device = kzalloc(sizeof(struct isert_device), GFP_KERNEL); if (!device) { mutex_unlock(&device_list_mutex); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&device->dev_node); device->ib_device = cma_id->device; ret = isert_create_device_ib_res(device); if (ret) { kfree(device); mutex_unlock(&device_list_mutex); return ERR_PTR(ret); } device->refcount++; list_add_tail(&device->dev_node, &device_list); mutex_unlock(&device_list_mutex); return device; } static int isert_connect_request(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { struct isert_np *isert_np = cma_id->context; struct iscsi_np *np = isert_np->np; struct isert_conn *isert_conn; struct isert_device *device; struct ib_device *ib_dev = cma_id->device; int ret = 0; spin_lock_bh(&np->np_thread_lock); if (!np->enabled) { spin_unlock_bh(&np->np_thread_lock); pr_debug("iscsi_np is not enabled, reject connect request\n"); return rdma_reject(cma_id, NULL, 0); } spin_unlock_bh(&np->np_thread_lock); pr_debug("Entering isert_connect_request cma_id: %p, context: %p\n", cma_id, cma_id->context); isert_conn = kzalloc(sizeof(struct isert_conn), GFP_KERNEL); if (!isert_conn) { pr_err("Unable to allocate isert_conn\n"); return -ENOMEM; } isert_conn->state = ISER_CONN_INIT; INIT_LIST_HEAD(&isert_conn->conn_accept_node); init_completion(&isert_conn->conn_login_comp); init_completion(&isert_conn->conn_wait); init_completion(&isert_conn->conn_wait_comp_err); kref_init(&isert_conn->conn_kref); kref_get(&isert_conn->conn_kref); mutex_init(&isert_conn->conn_mutex); INIT_WORK(&isert_conn->release_work, isert_release_work); cma_id->context = isert_conn; isert_conn->conn_cm_id = cma_id; isert_conn->responder_resources = event->param.conn.responder_resources; isert_conn->initiator_depth = event->param.conn.initiator_depth; pr_debug("Using responder_resources: %u initiator_depth: %u\n", isert_conn->responder_resources, isert_conn->initiator_depth); isert_conn->login_buf = kzalloc(ISCSI_DEF_MAX_RECV_SEG_LEN + ISER_RX_LOGIN_SIZE, GFP_KERNEL); if (!isert_conn->login_buf) { pr_err("Unable to allocate isert_conn->login_buf\n"); ret = -ENOMEM; goto out; } isert_conn->login_req_buf = isert_conn->login_buf; isert_conn->login_rsp_buf = isert_conn->login_buf + ISCSI_DEF_MAX_RECV_SEG_LEN; pr_debug("Set login_buf: %p login_req_buf: %p login_rsp_buf: %p\n", isert_conn->login_buf, isert_conn->login_req_buf, isert_conn->login_rsp_buf); isert_conn->login_req_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_req_buf, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_req_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_req_dma: %d\n", ret); isert_conn->login_req_dma = 0; goto out_login_buf; } isert_conn->login_rsp_dma = ib_dma_map_single(ib_dev, (void *)isert_conn->login_rsp_buf, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ret = ib_dma_mapping_error(ib_dev, isert_conn->login_rsp_dma); if (ret) { pr_err("ib_dma_mapping_error failed for login_rsp_dma: %d\n", ret); isert_conn->login_rsp_dma = 0; goto out_req_dma_map; } device = isert_device_find_by_ib_dev(cma_id); if (IS_ERR(device)) { ret = PTR_ERR(device); goto out_rsp_dma_map; } isert_conn->conn_device = device; isert_conn->conn_pd = device->dev_pd; isert_conn->conn_mr = device->dev_mr; ret = isert_conn_setup_qp(isert_conn, cma_id); if (ret) goto out_conn_dev; mutex_lock(&isert_np->np_accept_mutex); list_add_tail(&isert_np->np_accept_list, &isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); pr_debug("isert_connect_request() waking up np_accept_wq: %p\n", np); wake_up(&isert_np->np_accept_wq); return 0; out_conn_dev: isert_device_try_release(device); out_rsp_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); out_req_dma_map: ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); out_login_buf: kfree(isert_conn->login_buf); out: kfree(isert_conn); return ret; } static void isert_connect_release(struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_device *device = isert_conn->conn_device; int cq_index; pr_debug("Entering isert_connect_release(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); if (isert_conn->conn_qp) { cq_index = ((struct isert_cq_desc *) isert_conn->conn_qp->recv_cq->cq_context)->cq_index; pr_debug("isert_connect_release: cq_index: %d\n", cq_index); isert_conn->conn_device->cq_active_qps[cq_index]--; rdma_destroy_qp(isert_conn->conn_cm_id); } isert_free_rx_descriptors(isert_conn); rdma_destroy_id(isert_conn->conn_cm_id); if (isert_conn->login_buf) { ib_dma_unmap_single(ib_dev, isert_conn->login_rsp_dma, ISER_RX_LOGIN_SIZE, DMA_TO_DEVICE); ib_dma_unmap_single(ib_dev, isert_conn->login_req_dma, ISCSI_DEF_MAX_RECV_SEG_LEN, DMA_FROM_DEVICE); kfree(isert_conn->login_buf); } kfree(isert_conn); if (device) isert_device_try_release(device); pr_debug("Leaving isert_connect_release >>>>>>>>>>>>\n"); } static void isert_connected_handler(struct rdma_cm_id *cma_id) { struct isert_conn *isert_conn = cma_id->context; kref_get(&isert_conn->conn_kref); } static void isert_release_conn_kref(struct kref *kref) { struct isert_conn *isert_conn = container_of(kref, struct isert_conn, conn_kref); pr_debug("Calling isert_connect_release for final kref %s/%d\n", current->comm, current->pid); isert_connect_release(isert_conn); } static void isert_put_conn(struct isert_conn *isert_conn) { kref_put(&isert_conn->conn_kref, isert_release_conn_kref); } static void isert_disconnect_work(struct work_struct *work) { struct isert_conn *isert_conn = container_of(work, struct isert_conn, conn_logout_work); pr_debug("isert_disconnect_work(): >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; if (isert_conn->post_recv_buf_count == 0 && atomic_read(&isert_conn->post_send_buf_count) == 0) { mutex_unlock(&isert_conn->conn_mutex); goto wake_up; } if (!isert_conn->conn_cm_id) { mutex_unlock(&isert_conn->conn_mutex); isert_put_conn(isert_conn); return; } if (isert_conn->disconnect) { /* Send DREQ/DREP towards our initiator */ rdma_disconnect(isert_conn->conn_cm_id); } mutex_unlock(&isert_conn->conn_mutex); wake_up: complete(&isert_conn->conn_wait); } static int isert_disconnected_handler(struct rdma_cm_id *cma_id, bool disconnect) { struct isert_conn *isert_conn; bool terminating = false; if (!cma_id->qp) { struct isert_np *isert_np = cma_id->context; isert_np->np_cm_id = NULL; break; case RDMA_CM_EVENT_ADDR_CHANGE: isert_np->np_cm_id = isert_setup_id(isert_np); if (IS_ERR(isert_np->np_cm_id)) { pr_err("isert np %p setup id failed: %ld\n", isert_np, PTR_ERR(isert_np->np_cm_id)); isert_np->np_cm_id = NULL; } break; default: pr_err("isert np %p Unexpected event %d\n", isert_np, event); } isert_conn = (struct isert_conn *)cma_id->context; isert_conn->disconnect = disconnect; INIT_WORK(&isert_conn->conn_logout_work, isert_disconnect_work); schedule_work(&isert_conn->conn_logout_work); return 0; } static int isert_cma_handler(struct rdma_cm_id *cma_id, struct rdma_cm_event *event) { int ret = 0; bool disconnect = false; pr_debug("isert_cma_handler: event %d status %d conn %p id %p\n", event->event, event->status, cma_id->context, cma_id); switch (event->event) { case RDMA_CM_EVENT_CONNECT_REQUEST: ret = isert_connect_request(cma_id, event); if (ret) pr_err("isert_cma_handler failed RDMA_CM_EVENT: 0x%08x %d\n", event->event, ret); break; case RDMA_CM_EVENT_ESTABLISHED: isert_connected_handler(cma_id); break; case RDMA_CM_EVENT_ADDR_CHANGE: /* FALLTHRU */ case RDMA_CM_EVENT_DISCONNECTED: /* FALLTHRU */ case RDMA_CM_EVENT_DEVICE_REMOVAL: /* FALLTHRU */ disconnect = true; case RDMA_CM_EVENT_TIMEWAIT_EXIT: /* FALLTHRU */ ret = isert_disconnected_handler(cma_id, disconnect); break; case RDMA_CM_EVENT_CONNECT_ERROR: default: pr_err("Unhandled RDMA CMA event: %d\n", event->event); break; } return ret; } static int isert_post_recv(struct isert_conn *isert_conn, u32 count) { struct ib_recv_wr *rx_wr, *rx_wr_failed; int i, ret; unsigned int rx_head = isert_conn->conn_rx_desc_head; struct iser_rx_desc *rx_desc; for (rx_wr = isert_conn->conn_rx_wr, i = 0; i < count; i++, rx_wr++) { rx_desc = &isert_conn->conn_rx_descs[rx_head]; rx_wr->wr_id = (unsigned long)rx_desc; rx_wr->sg_list = &rx_desc->rx_sg; rx_wr->num_sge = 1; rx_wr->next = rx_wr + 1; rx_head = (rx_head + 1) & (ISERT_QP_MAX_RECV_DTOS - 1); } rx_wr--; rx_wr->next = NULL; /* mark end of work requests list */ isert_conn->post_recv_buf_count += count; ret = ib_post_recv(isert_conn->conn_qp, isert_conn->conn_rx_wr, &rx_wr_failed); if (ret) { pr_err("ib_post_recv() failed with ret: %d\n", ret); isert_conn->post_recv_buf_count -= count; } else { pr_debug("isert_post_recv(): Posted %d RX buffers\n", count); isert_conn->conn_rx_desc_head = rx_head; } return ret; } static int isert_post_send(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_send_wr send_wr, *send_wr_failed; int ret; ib_dma_sync_single_for_device(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); send_wr.next = NULL; send_wr.wr_id = (unsigned long)tx_desc; send_wr.sg_list = tx_desc->tx_sg; send_wr.num_sge = tx_desc->num_sge; send_wr.opcode = IB_WR_SEND; send_wr.send_flags = IB_SEND_SIGNALED; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &send_wr, &send_wr_failed); if (ret) { pr_err("ib_post_send() failed, ret: %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); } return ret; } static void isert_create_send_desc(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; ib_dma_sync_single_for_cpu(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); memset(&tx_desc->iser_header, 0, sizeof(struct iser_hdr)); tx_desc->iser_header.flags = ISER_VER; tx_desc->num_sge = 1; tx_desc->isert_cmd = isert_cmd; if (tx_desc->tx_sg[0].lkey != isert_conn->conn_mr->lkey) { tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("tx_desc %p lkey mismatch, fixing\n", tx_desc); } } static int isert_init_tx_hdrs(struct isert_conn *isert_conn, struct iser_tx_desc *tx_desc) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u64 dma_addr; dma_addr = ib_dma_map_single(ib_dev, (void *)tx_desc, ISER_HEADERS_LEN, DMA_TO_DEVICE); if (ib_dma_mapping_error(ib_dev, dma_addr)) { pr_err("ib_dma_mapping_error() failed\n"); return -ENOMEM; } tx_desc->dma_addr = dma_addr; tx_desc->tx_sg[0].addr = tx_desc->dma_addr; tx_desc->tx_sg[0].length = ISER_HEADERS_LEN; tx_desc->tx_sg[0].lkey = isert_conn->conn_mr->lkey; pr_debug("isert_init_tx_hdrs: Setup tx_sg[0].addr: 0x%llx length: %u" " lkey: 0x%08x\n", tx_desc->tx_sg[0].addr, tx_desc->tx_sg[0].length, tx_desc->tx_sg[0].lkey); return 0; } static void isert_init_send_wr(struct isert_cmd *isert_cmd, struct ib_send_wr *send_wr) { isert_cmd->rdma_wr.iser_ib_op = ISER_IB_SEND; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; send_wr->opcode = IB_WR_SEND; send_wr->send_flags = IB_SEND_SIGNALED; send_wr->sg_list = &isert_cmd->tx_desc.tx_sg[0]; send_wr->num_sge = isert_cmd->tx_desc.num_sge; } static int isert_rdma_post_recvl(struct isert_conn *isert_conn) { struct ib_recv_wr rx_wr, *rx_wr_fail; struct ib_sge sge; int ret; memset(&sge, 0, sizeof(struct ib_sge)); sge.addr = isert_conn->login_req_dma; sge.length = ISER_RX_LOGIN_SIZE; sge.lkey = isert_conn->conn_mr->lkey; pr_debug("Setup sge: addr: %llx length: %d 0x%08x\n", sge.addr, sge.length, sge.lkey); memset(&rx_wr, 0, sizeof(struct ib_recv_wr)); rx_wr.wr_id = (unsigned long)isert_conn->login_req_buf; rx_wr.sg_list = &sge; rx_wr.num_sge = 1; isert_conn->post_recv_buf_count++; ret = ib_post_recv(isert_conn->conn_qp, &rx_wr, &rx_wr_fail); if (ret) { pr_err("ib_post_recv() failed: %d\n", ret); isert_conn->post_recv_buf_count--; } pr_debug("ib_post_recv(): returned success >>>>>>>>>>>>>>>>>>>>>>>>\n"); return ret; } static int isert_put_login_tx(struct iscsi_conn *conn, struct iscsi_login *login, u32 length) { struct isert_conn *isert_conn = conn->context; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iser_tx_desc *tx_desc = &isert_conn->conn_login_tx_desc; int ret; isert_create_send_desc(isert_conn, NULL, tx_desc); memcpy(&tx_desc->iscsi_header, &login->rsp[0], sizeof(struct iscsi_hdr)); isert_init_tx_hdrs(isert_conn, tx_desc); if (length > 0) { struct ib_sge *tx_dsg = &tx_desc->tx_sg[1]; ib_dma_sync_single_for_cpu(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); memcpy(isert_conn->login_rsp_buf, login->rsp_buf, length); ib_dma_sync_single_for_device(ib_dev, isert_conn->login_rsp_dma, length, DMA_TO_DEVICE); tx_dsg->addr = isert_conn->login_rsp_dma; tx_dsg->length = length; tx_dsg->lkey = isert_conn->conn_mr->lkey; tx_desc->num_sge = 2; } if (!login->login_failed) { if (login->login_complete) { ret = isert_alloc_rx_descriptors(isert_conn); if (ret) return ret; ret = isert_post_recv(isert_conn, ISERT_MIN_POSTED_RX); if (ret) return ret; isert_conn->state = ISER_CONN_UP; goto post_send; } ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; } post_send: ret = isert_post_send(isert_conn, tx_desc); if (ret) return ret; return 0; } static void isert_rx_login_req(struct iser_rx_desc *rx_desc, int rx_buflen, struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; struct iscsi_login *login = conn->conn_login; int size; if (!login) { pr_err("conn->conn_login is NULL\n"); dump_stack(); return; } if (login->first_request) { struct iscsi_login_req *login_req = (struct iscsi_login_req *)&rx_desc->iscsi_header; /* * Setup the initial iscsi_login values from the leading * login request PDU. */ login->leading_connection = (!login_req->tsih) ? 1 : 0; login->current_stage = (login_req->flags & ISCSI_FLAG_LOGIN_CURRENT_STAGE_MASK) >> 2; login->version_min = login_req->min_version; login->version_max = login_req->max_version; memcpy(login->isid, login_req->isid, 6); login->cmd_sn = be32_to_cpu(login_req->cmdsn); login->init_task_tag = login_req->itt; login->initial_exp_statsn = be32_to_cpu(login_req->exp_statsn); login->cid = be16_to_cpu(login_req->cid); login->tsih = be16_to_cpu(login_req->tsih); } memcpy(&login->req[0], (void *)&rx_desc->iscsi_header, ISCSI_HDR_LEN); size = min(rx_buflen, MAX_KEY_VALUE_PAIRS); pr_debug("Using login payload size: %d, rx_buflen: %d MAX_KEY_VALUE_PAIRS: %d\n", size, rx_buflen, MAX_KEY_VALUE_PAIRS); memcpy(login->req_buf, &rx_desc->data[0], size); complete(&isert_conn->conn_login_comp); } static void isert_release_cmd(struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); pr_debug("Entering isert_release_cmd %p >>>>>>>>>>>>>>>.\n", isert_cmd); kfree(cmd->buf_ptr); kfree(cmd->tmr_req); kmem_cache_free(isert_cmd_cache, isert_cmd); } static struct iscsi_cmd *isert_alloc_cmd(struct iscsi_conn *conn, gfp_t gfp) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct isert_cmd *isert_cmd; isert_cmd = kmem_cache_zalloc(isert_cmd_cache, gfp); if (!isert_cmd) { pr_err("Unable to allocate isert_cmd\n"); return NULL; } isert_cmd->conn = isert_conn; isert_cmd->iscsi_cmd.release_cmd = &isert_release_cmd; return &isert_cmd->iscsi_cmd; } static int isert_handle_scsi_cmd(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_scsi_req *hdr = (struct iscsi_scsi_req *)buf; struct scatterlist *sg; int imm_data, imm_data_len, unsol_data, sg_nents, rc; bool dump_payload = false; rc = iscsit_setup_scsi_cmd(conn, cmd, buf); if (rc < 0) return rc; imm_data = cmd->immediate_data; imm_data_len = cmd->first_burst_len; unsol_data = cmd->unsolicited_data; rc = iscsit_process_scsi_cmd(conn, cmd, hdr); if (rc < 0) { return 0; } else if (rc > 0) { dump_payload = true; goto sequence_cmd; } if (!imm_data) return 0; sg = &cmd->se_cmd.t_data_sg[0]; sg_nents = max(1UL, DIV_ROUND_UP(imm_data_len, PAGE_SIZE)); pr_debug("Copying Immediate SG: %p sg_nents: %u from %p imm_data_len: %d\n", sg, sg_nents, &rx_desc->data[0], imm_data_len); sg_copy_from_buffer(sg, sg_nents, &rx_desc->data[0], imm_data_len); cmd->write_data_done += imm_data_len; if (cmd->write_data_done == cmd->se_cmd.data_length) { spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); } sequence_cmd: rc = iscsit_sequence_cmd(conn, cmd, buf, hdr->cmdsn); if (!rc && dump_payload == false && unsol_data) iscsit_set_unsoliticed_dataout(cmd); else if (dump_payload && imm_data) target_put_sess_cmd(conn->sess->se_sess, &cmd->se_cmd); return 0; } static int isert_handle_iscsi_dataout(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, unsigned char *buf) { struct scatterlist *sg_start; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd = NULL; struct iscsi_data *hdr = (struct iscsi_data *)buf; u32 unsol_data_len = ntoh24(hdr->dlength); int rc, sg_nents, sg_off, page_off; rc = iscsit_check_dataout_hdr(conn, buf, &cmd); if (rc < 0) return rc; else if (!cmd) return 0; /* * FIXME: Unexpected unsolicited_data out */ if (!cmd->unsolicited_data) { pr_err("Received unexpected solicited data payload\n"); dump_stack(); return -1; } pr_debug("Unsolicited DataOut unsol_data_len: %u, write_data_done: %u, data_length: %u\n", unsol_data_len, cmd->write_data_done, cmd->se_cmd.data_length); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = max(1UL, DIV_ROUND_UP(unsol_data_len, PAGE_SIZE)); page_off = cmd->write_data_done % PAGE_SIZE; /* * FIXME: Non page-aligned unsolicited_data out */ if (page_off) { pr_err("Received unexpected non-page aligned data payload\n"); dump_stack(); return -1; } pr_debug("Copying DataOut: sg_start: %p, sg_off: %u sg_nents: %u from %p %u\n", sg_start, sg_off, sg_nents, &rx_desc->data[0], unsol_data_len); sg_copy_from_buffer(sg_start, sg_nents, &rx_desc->data[0], unsol_data_len); rc = iscsit_check_dataout_payload(cmd, hdr, false); if (rc < 0) return rc; return 0; } static int isert_rx_opcode(struct isert_conn *isert_conn, struct iser_rx_desc *rx_desc, uint32_t read_stag, uint64_t read_va, uint32_t write_stag, uint64_t write_va) { struct iscsi_hdr *hdr = &rx_desc->iscsi_header; struct iscsi_conn *conn = isert_conn->conn; struct iscsi_cmd *cmd; struct isert_cmd *isert_cmd; int ret = -EINVAL; u8 opcode = (hdr->opcode & ISCSI_OPCODE_MASK); switch (opcode) { case ISCSI_OP_SCSI_CMD: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); isert_cmd->read_stag = read_stag; isert_cmd->read_va = read_va; isert_cmd->write_stag = write_stag; isert_cmd->write_va = write_va; ret = isert_handle_scsi_cmd(isert_conn, isert_cmd, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_NOOP_OUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_nop_out(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_DATA_OUT: ret = isert_handle_iscsi_dataout(isert_conn, rx_desc, (unsigned char *)hdr); break; case ISCSI_OP_SCSI_TMFUNC: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_task_mgt_cmd(conn, cmd, (unsigned char *)hdr); break; case ISCSI_OP_LOGOUT: cmd = iscsit_allocate_cmd(conn, GFP_KERNEL); if (!cmd) break; ret = iscsit_handle_logout_cmd(conn, cmd, (unsigned char *)hdr); if (ret > 0) wait_for_completion_timeout(&conn->conn_logout_comp, SECONDS_FOR_LOGOUT_COMP * HZ); break; default: pr_err("Got unknown iSCSI OpCode: 0x%02x\n", opcode); dump_stack(); break; } return ret; } static void isert_rx_do_work(struct iser_rx_desc *rx_desc, struct isert_conn *isert_conn) { struct iser_hdr *iser_hdr = &rx_desc->iser_header; uint64_t read_va = 0, write_va = 0; uint32_t read_stag = 0, write_stag = 0; int rc; switch (iser_hdr->flags & 0xF0) { case ISCSI_CTRL: if (iser_hdr->flags & ISER_RSV) { read_stag = be32_to_cpu(iser_hdr->read_stag); read_va = be64_to_cpu(iser_hdr->read_va); pr_debug("ISER_RSV: read_stag: 0x%08x read_va: 0x%16llx\n", read_stag, (unsigned long long)read_va); } if (iser_hdr->flags & ISER_WSV) { write_stag = be32_to_cpu(iser_hdr->write_stag); write_va = be64_to_cpu(iser_hdr->write_va); pr_debug("ISER_WSV: write__stag: 0x%08x write_va: 0x%16llx\n", write_stag, (unsigned long long)write_va); } pr_debug("ISER ISCSI_CTRL PDU\n"); break; case ISER_HELLO: pr_err("iSER Hello message\n"); break; default: pr_warn("Unknown iSER hdr flags: 0x%02x\n", iser_hdr->flags); break; } rc = isert_rx_opcode(isert_conn, rx_desc, read_stag, read_va, write_stag, write_va); } static void isert_rx_completion(struct iser_rx_desc *desc, struct isert_conn *isert_conn, unsigned long xfer_len) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_hdr *hdr; u64 rx_dma; int rx_buflen, outstanding; if ((char *)desc == isert_conn->login_req_buf) { rx_dma = isert_conn->login_req_dma; rx_buflen = ISER_RX_LOGIN_SIZE; pr_debug("ISER login_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } else { rx_dma = desc->dma_addr; rx_buflen = ISER_RX_PAYLOAD_SIZE; pr_debug("ISER req_buf: Using rx_dma: 0x%llx, rx_buflen: %d\n", rx_dma, rx_buflen); } ib_dma_sync_single_for_cpu(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); hdr = &desc->iscsi_header; pr_debug("iSCSI opcode: 0x%02x, ITT: 0x%08x, flags: 0x%02x dlen: %d\n", hdr->opcode, hdr->itt, hdr->flags, (int)(xfer_len - ISER_HEADERS_LEN)); if ((char *)desc == isert_conn->login_req_buf) isert_rx_login_req(desc, xfer_len - ISER_HEADERS_LEN, isert_conn); else isert_rx_do_work(desc, isert_conn); ib_dma_sync_single_for_device(ib_dev, rx_dma, rx_buflen, DMA_FROM_DEVICE); isert_conn->post_recv_buf_count--; pr_debug("iSERT: Decremented post_recv_buf_count: %d\n", isert_conn->post_recv_buf_count); if ((char *)desc == isert_conn->login_req_buf) return; outstanding = isert_conn->post_recv_buf_count; if (outstanding + ISERT_MIN_POSTED_RX <= ISERT_QP_MAX_RECV_DTOS) { int err, count = min(ISERT_QP_MAX_RECV_DTOS - outstanding, ISERT_MIN_POSTED_RX); err = isert_post_recv(isert_conn, count); if (err) { pr_err("isert_post_recv() count: %d failed, %d\n", count, err); } } } static void isert_unmap_cmd(struct isert_cmd *isert_cmd, struct isert_conn *isert_conn) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; pr_debug("isert_unmap_cmd >>>>>>>>>>>>>>>>>>>>>>>\n"); if (wr->sge) { ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } kfree(wr->send_wr); wr->send_wr = NULL; kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } static void isert_put_cmd(struct isert_cmd *isert_cmd, bool comp_err) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_conn *isert_conn = isert_cmd->conn; struct iscsi_conn *conn = isert_conn->conn; pr_debug("Entering isert_put_cmd: %p\n", isert_cmd); switch (cmd->iscsi_opcode) { case ISCSI_OP_SCSI_CMD: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); if (cmd->data_direction == DMA_TO_DEVICE) { iscsit_stop_dataout_timer(cmd); /* * Check for special case during comp_err where * WRITE_PENDING has been handed off from core, * but requires an extra target_put_sess_cmd() * before transport_generic_free_cmd() below. */ if (comp_err && cmd->se_cmd.t_state == TRANSPORT_WRITE_PENDING) { struct se_cmd *se_cmd = &cmd->se_cmd; target_put_sess_cmd(se_cmd->se_sess, se_cmd); } } isert_unmap_cmd(isert_cmd, isert_conn); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_SCSI_TMFUNC: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); transport_generic_free_cmd(&cmd->se_cmd, 0); break; case ISCSI_OP_REJECT: case ISCSI_OP_NOOP_OUT: spin_lock_bh(&conn->cmd_lock); if (!list_empty(&cmd->i_conn_node)) list_del_init(&cmd->i_conn_node); spin_unlock_bh(&conn->cmd_lock); /* * Handle special case for REJECT when iscsi_add_reject*() has * overwritten the original iscsi_opcode assignment, and the * associated cmd->se_cmd needs to be released. */ if (cmd->se_cmd.se_tfo != NULL) { pr_debug("Calling transport_generic_free_cmd from" " isert_put_cmd for 0x%02x\n", cmd->iscsi_opcode); transport_generic_free_cmd(&cmd->se_cmd, 0); break; } /* * Fall-through */ default: isert_release_cmd(cmd); break; } } static void isert_unmap_tx_desc(struct iser_tx_desc *tx_desc, struct ib_device *ib_dev) { if (tx_desc->dma_addr != 0) { pr_debug("Calling ib_dma_unmap_single for tx_desc->dma_addr\n"); ib_dma_unmap_single(ib_dev, tx_desc->dma_addr, ISER_HEADERS_LEN, DMA_TO_DEVICE); tx_desc->dma_addr = 0; } } static void isert_completion_put(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct ib_device *ib_dev, bool comp_err) { if (isert_cmd->sense_buf_dma != 0) { pr_debug("Calling ib_dma_unmap_single for isert_cmd->sense_buf_dma\n"); ib_dma_unmap_single(ib_dev, isert_cmd->sense_buf_dma, isert_cmd->sense_buf_len, DMA_TO_DEVICE); isert_cmd->sense_buf_dma = 0; } isert_unmap_tx_desc(tx_desc, ib_dev); isert_put_cmd(isert_cmd, comp_err); } static void isert_completion_rdma_read(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd) { struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct se_cmd *se_cmd = &cmd->se_cmd; struct ib_device *ib_dev = isert_cmd->conn->conn_cm_id->device; iscsit_stop_dataout_timer(cmd); if (wr->sge) { pr_debug("isert_do_rdma_read_comp: Unmapping wr->sge from t_data_sg\n"); ib_dma_unmap_sg(ib_dev, wr->sge, wr->num_sge, DMA_TO_DEVICE); wr->sge = NULL; } if (isert_cmd->ib_sge) { pr_debug("isert_do_rdma_read_comp: Freeing isert_cmd->ib_sge\n"); kfree(isert_cmd->ib_sge); isert_cmd->ib_sge = NULL; } cmd->write_data_done = se_cmd->data_length; wr->send_wr_num = 0; pr_debug("isert_do_rdma_read_comp, calling target_execute_cmd\n"); spin_lock_bh(&cmd->istate_lock); cmd->cmd_flags |= ICF_GOT_LAST_DATAOUT; cmd->i_state = ISTATE_RECEIVED_LAST_DATAOUT; spin_unlock_bh(&cmd->istate_lock); target_execute_cmd(se_cmd); } static void isert_do_control_comp(struct work_struct *work) { struct isert_cmd *isert_cmd = container_of(work, struct isert_cmd, comp_work); struct isert_conn *isert_conn = isert_cmd->conn; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; switch (cmd->i_state) { case ISTATE_SEND_TASKMGTRSP: pr_debug("Calling iscsit_tmr_post_handler >>>>>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_tmr_post_handler(cmd, cmd->conn); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_REJECT: pr_debug("Got isert_do_control_comp ISTATE_SEND_REJECT: >>>\n"); atomic_dec(&isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(&isert_cmd->tx_desc, isert_cmd, ib_dev, false); break; case ISTATE_SEND_LOGOUTRSP: pr_debug("Calling iscsit_logout_post_handler >>>>>>>>>>>>>>\n"); atomic_dec(&isert_conn->post_send_buf_count); iscsit_logout_post_handler(cmd, cmd->conn); break; default: pr_err("Unknown do_control_comp i_state %d\n", cmd->i_state); dump_stack(); break; } } static void isert_response_completion(struct iser_tx_desc *tx_desc, struct isert_cmd *isert_cmd, struct isert_conn *isert_conn, struct ib_device *ib_dev) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; if (cmd->i_state == ISTATE_SEND_TASKMGTRSP || cmd->i_state == ISTATE_SEND_LOGOUTRSP || cmd->i_state == ISTATE_SEND_REJECT) { isert_unmap_tx_desc(tx_desc, ib_dev); INIT_WORK(&isert_cmd->comp_work, isert_do_control_comp); queue_work(isert_comp_wq, &isert_cmd->comp_work); return; } atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); cmd->i_state = ISTATE_SENT_STATUS; isert_completion_put(tx_desc, isert_cmd, ib_dev, false); } static void isert_send_completion(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; struct isert_rdma_wr *wr; if (!isert_cmd) { atomic_dec(&isert_conn->post_send_buf_count); isert_unmap_tx_desc(tx_desc, ib_dev); return; } wr = &isert_cmd->rdma_wr; switch (wr->iser_ib_op) { case ISER_IB_RECV: pr_err("isert_send_completion: Got ISER_IB_RECV\n"); dump_stack(); break; case ISER_IB_SEND: pr_debug("isert_send_completion: Got ISER_IB_SEND\n"); isert_response_completion(tx_desc, isert_cmd, isert_conn, ib_dev); break; case ISER_IB_RDMA_WRITE: pr_err("isert_send_completion: Got ISER_IB_RDMA_WRITE\n"); dump_stack(); break; case ISER_IB_RDMA_READ: pr_debug("isert_send_completion: Got ISER_IB_RDMA_READ:\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); isert_completion_rdma_read(tx_desc, isert_cmd); break; default: pr_err("Unknown wr->iser_ib_op: 0x%02x\n", wr->iser_ib_op); dump_stack(); break; } } static void isert_cq_tx_comp_err(struct iser_tx_desc *tx_desc, struct isert_conn *isert_conn) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct isert_cmd *isert_cmd = tx_desc->isert_cmd; if (!isert_cmd) isert_unmap_tx_desc(tx_desc, ib_dev); else isert_completion_put(tx_desc, isert_cmd, ib_dev, true); } static void isert_cq_rx_comp_err(struct isert_conn *isert_conn) { struct iscsi_conn *conn = isert_conn->conn; if (isert_conn->post_recv_buf_count) return; if (conn->sess) { target_sess_cmd_list_set_waiting(conn->sess->se_sess); target_wait_for_sess_cmds(conn->sess->se_sess); } while (atomic_read(&isert_conn->post_send_buf_count)) msleep(3000); mutex_lock(&isert_conn->conn_mutex); isert_conn->state = ISER_CONN_DOWN; mutex_unlock(&isert_conn->conn_mutex); iscsit_cause_connection_reinstatement(isert_conn->conn, 0); complete(&isert_conn->conn_wait_comp_err); } static void isert_cq_tx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_tx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *tx_cq = device->dev_tx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_tx_desc *tx_desc; struct ib_wc wc; while (ib_poll_cq(tx_cq, 1, &wc) == 1) { tx_desc = (struct iser_tx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { isert_send_completion(tx_desc, isert_conn); } else { pr_debug("TX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); pr_debug("TX wc.status: 0x%08x\n", wc.status); atomic_dec(&isert_conn->post_send_buf_count); isert_cq_tx_comp_err(tx_desc, isert_conn); } } ib_req_notify_cq(tx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_tx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_tx_work, isert_cq_tx_work); queue_work(isert_comp_wq, &cq_desc->cq_tx_work); } static void isert_cq_rx_work(struct work_struct *work) { struct isert_cq_desc *cq_desc = container_of(work, struct isert_cq_desc, cq_rx_work); struct isert_device *device = cq_desc->device; int cq_index = cq_desc->cq_index; struct ib_cq *rx_cq = device->dev_rx_cq[cq_index]; struct isert_conn *isert_conn; struct iser_rx_desc *rx_desc; struct ib_wc wc; unsigned long xfer_len; while (ib_poll_cq(rx_cq, 1, &wc) == 1) { rx_desc = (struct iser_rx_desc *)(unsigned long)wc.wr_id; isert_conn = wc.qp->qp_context; if (wc.status == IB_WC_SUCCESS) { xfer_len = (unsigned long)wc.byte_len; isert_rx_completion(rx_desc, isert_conn, xfer_len); } else { pr_debug("RX wc.status != IB_WC_SUCCESS >>>>>>>>>>>>>>\n"); if (wc.status != IB_WC_WR_FLUSH_ERR) pr_debug("RX wc.status: 0x%08x\n", wc.status); isert_conn->post_recv_buf_count--; isert_cq_rx_comp_err(isert_conn); } } ib_req_notify_cq(rx_cq, IB_CQ_NEXT_COMP); } static void isert_cq_rx_callback(struct ib_cq *cq, void *context) { struct isert_cq_desc *cq_desc = (struct isert_cq_desc *)context; INIT_WORK(&cq_desc->cq_rx_work, isert_cq_rx_work); queue_work(isert_rx_wq, &cq_desc->cq_rx_work); } static int isert_post_response(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd) { struct ib_send_wr *wr_failed; int ret; atomic_inc(&isert_conn->post_send_buf_count); ret = ib_post_send(isert_conn->conn_qp, &isert_cmd->tx_desc.send_wr, &wr_failed); if (ret) { pr_err("ib_post_send failed with %d\n", ret); atomic_dec(&isert_conn->post_send_buf_count); return ret; } return ret; } static int isert_put_response(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct iscsi_scsi_rsp *hdr = (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, true, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); /* * Attach SENSE DATA payload to iSCSI Response PDU */ if (cmd->se_cmd.sense_buffer && ((cmd->se_cmd.se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) || (cmd->se_cmd.se_cmd_flags & SCF_EMULATED_TASK_SENSE))) { struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; u32 padding, sense_len; put_unaligned_be16(cmd->se_cmd.scsi_sense_length, cmd->sense_buffer); cmd->se_cmd.scsi_sense_length += sizeof(__be16); padding = -(cmd->se_cmd.scsi_sense_length) & 3; hton24(hdr->dlength, (u32)cmd->se_cmd.scsi_sense_length); sense_len = cmd->se_cmd.scsi_sense_length + padding; isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->sense_buffer, sense_len, DMA_TO_DEVICE); isert_cmd->sense_buf_len = sense_len; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = sense_len; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; } isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting SCSI Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_nopin(struct iscsi_cmd *cmd, struct iscsi_conn *conn, bool nopout_response) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_nopin_rsp(cmd, conn, (struct iscsi_nopin *) &isert_cmd->tx_desc.iscsi_header, nopout_response); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting NOPIN Reponse IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_logout_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_logout_rsp(cmd, conn, (struct iscsi_logout_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Logout Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_tm_rsp(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_task_mgt_rsp(cmd, conn, (struct iscsi_tm_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Task Management Response IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_put_reject(struct iscsi_cmd *cmd, struct iscsi_conn *conn) { struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *send_wr = &isert_cmd->tx_desc.send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *tx_dsg = &isert_cmd->tx_desc.tx_sg[1]; struct iscsi_reject *hdr = (struct iscsi_reject *)&isert_cmd->tx_desc.iscsi_header; isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_reject(cmd, conn, hdr); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); hton24(hdr->dlength, ISCSI_HDR_LEN); isert_cmd->sense_buf_dma = ib_dma_map_single(ib_dev, (void *)cmd->buf_ptr, ISCSI_HDR_LEN, DMA_TO_DEVICE); isert_cmd->sense_buf_len = ISCSI_HDR_LEN; tx_dsg->addr = isert_cmd->sense_buf_dma; tx_dsg->length = ISCSI_HDR_LEN; tx_dsg->lkey = isert_conn->conn_mr->lkey; isert_cmd->tx_desc.num_sge = 2; isert_init_send_wr(isert_cmd, send_wr); pr_debug("Posting Reject IB_WR_SEND >>>>>>>>>>>>>>>>>>>>>>\n"); return isert_post_response(isert_conn, isert_cmd); } static int isert_build_rdma_wr(struct isert_conn *isert_conn, struct isert_cmd *isert_cmd, struct ib_sge *ib_sge, struct ib_send_wr *send_wr, u32 data_left, u32 offset) { struct iscsi_cmd *cmd = &isert_cmd->iscsi_cmd; struct scatterlist *sg_start, *tmp_sg; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; u32 sg_off, page_off; int i = 0, sg_nents; sg_off = offset / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; sg_nents = min(cmd->se_cmd.t_data_nents - sg_off, isert_conn->max_sge); page_off = offset % PAGE_SIZE; send_wr->sg_list = ib_sge; send_wr->num_sge = sg_nents; send_wr->wr_id = (unsigned long)&isert_cmd->tx_desc; /* * Perform mapping of TCM scatterlist memory ib_sge dma_addr. */ for_each_sg(sg_start, tmp_sg, sg_nents, i) { pr_debug("ISER RDMA from SGL dma_addr: 0x%16llx dma_len: %u, page_off: %u\n", (unsigned long long)tmp_sg->dma_address, tmp_sg->length, page_off); ib_sge->addr = ib_sg_dma_address(ib_dev, tmp_sg) + page_off; ib_sge->length = min_t(u32, data_left, ib_sg_dma_len(ib_dev, tmp_sg) - page_off); ib_sge->lkey = isert_conn->conn_mr->lkey; pr_debug("RDMA ib_sge: addr: 0x%16llx length: %u\n", ib_sge->addr, ib_sge->length); page_off = 0; data_left -= ib_sge->length; ib_sge++; pr_debug("Incrementing ib_sge pointer to %p\n", ib_sge); } pr_debug("Set outgoing sg_list: %p num_sg: %u from TCM SGLs\n", send_wr->sg_list, send_wr->num_sge); return sg_nents; } static int isert_put_datain(struct iscsi_conn *conn, struct iscsi_cmd *cmd) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct ib_sge *ib_sge; struct scatterlist *sg; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, sg_nents, i, ib_sge_cnt; pr_debug("RDMA_WRITE: data_length: %u\n", se_cmd->data_length); sg = &se_cmd->t_data_sg[0]; sg_nents = se_cmd->t_data_nents; count = ib_dma_map_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); if (unlikely(!count)) { pr_err("Unable to map put_datain SGs\n"); return -EINVAL; } wr->sge = sg; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg: %p sg_nents: %u for RDMA_WRITE\n", count, sg, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate datain ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Allocated ib_sge: %p from t_data_ents: %d for RDMA_WRITE\n", ib_sge, se_cmd->t_data_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_err("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); iscsit_increment_maxcmdsn(cmd, conn->sess); cmd->stat_sn = conn->stat_sn++; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; data_left = se_cmd->data_length; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_WRITE; send_wr->send_flags = 0; send_wr->wr.rdma.remote_addr = isert_cmd->read_va + offset; send_wr->wr.rdma.rkey = isert_cmd->read_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->next = &isert_cmd->tx_desc.send_wr; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; data_left -= data_len; } /* * Build isert_conn->tx_desc for iSCSI response PDU and attach */ isert_create_send_desc(isert_conn, isert_cmd, &isert_cmd->tx_desc); iscsit_build_rsp_pdu(cmd, conn, false, (struct iscsi_scsi_rsp *) &isert_cmd->tx_desc.iscsi_header); isert_init_tx_hdrs(isert_conn, &isert_cmd->tx_desc); isert_init_send_wr(isert_cmd, &isert_cmd->tx_desc.send_wr); atomic_add(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_WRITE\n"); atomic_sub(wr->send_wr_num + 1, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_WRITE + Response for iSER Data READ\n"); return 1; unmap_sg: ib_dma_unmap_sg(ib_dev, sg, sg_nents, DMA_TO_DEVICE); return ret; } static int isert_get_dataout(struct iscsi_conn *conn, struct iscsi_cmd *cmd, bool recovery) { struct se_cmd *se_cmd = &cmd->se_cmd; struct isert_cmd *isert_cmd = container_of(cmd, struct isert_cmd, iscsi_cmd); struct isert_rdma_wr *wr = &isert_cmd->rdma_wr; struct isert_conn *isert_conn = (struct isert_conn *)conn->context; struct ib_send_wr *wr_failed, *send_wr; struct ib_sge *ib_sge; struct ib_device *ib_dev = isert_conn->conn_cm_id->device; struct scatterlist *sg_start; u32 sg_off, sg_nents, page_off, va_offset = 0; u32 offset = 0, data_len, data_left, rdma_write_max; int rc, ret = 0, count, i, ib_sge_cnt; pr_debug("RDMA_READ: data_length: %u write_data_done: %u\n", se_cmd->data_length, cmd->write_data_done); sg_off = cmd->write_data_done / PAGE_SIZE; sg_start = &cmd->se_cmd.t_data_sg[sg_off]; page_off = cmd->write_data_done % PAGE_SIZE; pr_debug("RDMA_READ: sg_off: %d, sg_start: %p page_off: %d\n", sg_off, sg_start, page_off); data_left = se_cmd->data_length - cmd->write_data_done; sg_nents = se_cmd->t_data_nents - sg_off; pr_debug("RDMA_READ: data_left: %d, sg_nents: %d\n", data_left, sg_nents); count = ib_dma_map_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); if (unlikely(!count)) { pr_err("Unable to map get_dataout SGs\n"); return -EINVAL; } wr->sge = sg_start; wr->num_sge = sg_nents; pr_debug("Mapped IB count: %u sg_start: %p sg_nents: %u for RDMA_READ\n", count, sg_start, sg_nents); ib_sge = kzalloc(sizeof(struct ib_sge) * sg_nents, GFP_KERNEL); if (!ib_sge) { pr_warn("Unable to allocate dataout ib_sge\n"); ret = -ENOMEM; goto unmap_sg; } isert_cmd->ib_sge = ib_sge; pr_debug("Using ib_sge: %p from sg_ents: %d for RDMA_READ\n", ib_sge, sg_nents); wr->send_wr_num = DIV_ROUND_UP(sg_nents, isert_conn->max_sge); wr->send_wr = kzalloc(sizeof(struct ib_send_wr) * wr->send_wr_num, GFP_KERNEL); if (!wr->send_wr) { pr_debug("Unable to allocate wr->send_wr\n"); ret = -ENOMEM; goto unmap_sg; } pr_debug("Allocated wr->send_wr: %p wr->send_wr_num: %u\n", wr->send_wr, wr->send_wr_num); isert_cmd->tx_desc.isert_cmd = isert_cmd; wr->iser_ib_op = ISER_IB_RDMA_READ; wr->isert_cmd = isert_cmd; rdma_write_max = isert_conn->max_sge * PAGE_SIZE; offset = cmd->write_data_done; for (i = 0; i < wr->send_wr_num; i++) { send_wr = &isert_cmd->rdma_wr.send_wr[i]; data_len = min(data_left, rdma_write_max); send_wr->opcode = IB_WR_RDMA_READ; send_wr->wr.rdma.remote_addr = isert_cmd->write_va + va_offset; send_wr->wr.rdma.rkey = isert_cmd->write_stag; ib_sge_cnt = isert_build_rdma_wr(isert_conn, isert_cmd, ib_sge, send_wr, data_len, offset); ib_sge += ib_sge_cnt; if (i + 1 == wr->send_wr_num) send_wr->send_flags = IB_SEND_SIGNALED; else send_wr->next = &wr->send_wr[i + 1]; offset += data_len; va_offset += data_len; data_left -= data_len; } atomic_add(wr->send_wr_num, &isert_conn->post_send_buf_count); rc = ib_post_send(isert_conn->conn_qp, wr->send_wr, &wr_failed); if (rc) { pr_warn("ib_post_send() failed for IB_WR_RDMA_READ\n"); atomic_sub(wr->send_wr_num, &isert_conn->post_send_buf_count); } pr_debug("Posted RDMA_READ memory for ISER Data WRITE\n"); return 0; unmap_sg: ib_dma_unmap_sg(ib_dev, sg_start, sg_nents, DMA_FROM_DEVICE); return ret; } static int isert_immediate_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_NOPIN_WANT_RESPONSE: ret = isert_put_nopin(cmd, conn, false); break; default: pr_err("Unknown immediate state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } static int isert_response_queue(struct iscsi_conn *conn, struct iscsi_cmd *cmd, int state) { int ret; switch (state) { case ISTATE_SEND_LOGOUTRSP: ret = isert_put_logout_rsp(cmd, conn); if (!ret) { pr_debug("Returning iSER Logout -EAGAIN\n"); ret = -EAGAIN; } break; case ISTATE_SEND_NOPIN: ret = isert_put_nopin(cmd, conn, true); break; case ISTATE_SEND_TASKMGTRSP: ret = isert_put_tm_rsp(cmd, conn); break; case ISTATE_SEND_REJECT: ret = isert_put_reject(cmd, conn); break; case ISTATE_SEND_STATUS: /* * Special case for sending non GOOD SCSI status from TX thread * context during pre se_cmd excecution failure. */ ret = isert_put_response(conn, cmd); break; default: pr_err("Unknown response state: 0x%02x\n", state); ret = -EINVAL; break; } return ret; } struct rdma_cm_id * isert_setup_id(struct isert_np *isert_np) { struct iscsi_np *np = isert_np->np; struct rdma_cm_id *id; struct sockaddr *sa; int ret; sa = (struct sockaddr *)&np->np_sockaddr; pr_debug("ksockaddr: %p, sa: %p\n", &np->np_sockaddr, sa); id = rdma_create_id(isert_cma_handler, isert_np, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(id)) { pr_err("rdma_create_id() failed: %ld\n", PTR_ERR(id)); ret = PTR_ERR(id); goto out; } pr_debug("id %p context %p\n", id, id->context); ret = rdma_bind_addr(id, sa); if (ret) { pr_err("rdma_bind_addr() failed: %d\n", ret); goto out_id; } ret = rdma_listen(id, ISERT_RDMA_LISTEN_BACKLOG); if (ret) { pr_err("rdma_listen() failed: %d\n", ret); goto out_id; } return id; out_id: rdma_destroy_id(id); out: return ERR_PTR(ret); } static int isert_setup_np(struct iscsi_np *np, struct __kernel_sockaddr_storage *ksockaddr) { struct isert_np *isert_np; struct rdma_cm_id *isert_lid; int ret; isert_np = kzalloc(sizeof(struct isert_np), GFP_KERNEL); if (!isert_np) { pr_err("Unable to allocate struct isert_np\n"); return -ENOMEM; } init_waitqueue_head(&isert_np->np_accept_wq); mutex_init(&isert_np->np_accept_mutex); INIT_LIST_HEAD(&isert_np->np_accept_list); init_completion(&isert_np->np_login_comp); isert_np->np = np; /* * Setup the np->np_sockaddr from the passed sockaddr setup * in iscsi_target_configfs.c code.. */ memcpy(&np->np_sockaddr, ksockaddr, sizeof(struct __kernel_sockaddr_storage)); isert_lid = isert_setup_id(isert_np); if (IS_ERR(isert_lid)) { ret = PTR_ERR(isert_lid); goto out; } isert_np->np_cm_id = isert_lid; np->np_context = isert_np; return 0; out: kfree(isert_np); return ret; } static int isert_check_accept_queue(struct isert_np *isert_np) { int empty; mutex_lock(&isert_np->np_accept_mutex); empty = list_empty(&isert_np->np_accept_list); mutex_unlock(&isert_np->np_accept_mutex); return empty; } static int isert_rdma_accept(struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_conn_param cp; int ret; memset(&cp, 0, sizeof(struct rdma_conn_param)); cp.responder_resources = isert_conn->responder_resources; cp.initiator_depth = isert_conn->initiator_depth; cp.retry_count = 7; cp.rnr_retry_count = 7; pr_debug("Before rdma_accept >>>>>>>>>>>>>>>>>>>>.\n"); ret = rdma_accept(cm_id, &cp); if (ret) { pr_err("rdma_accept() failed with: %d\n", ret); return ret; } pr_debug("After rdma_accept >>>>>>>>>>>>>>>>>>>>>.\n"); return 0; } static int isert_get_login_rx(struct iscsi_conn *conn, struct iscsi_login *login) { struct isert_conn *isert_conn = (struct isert_conn *)conn->context; int ret; pr_debug("isert_get_login_rx before conn_login_comp conn: %p\n", conn); ret = wait_for_completion_interruptible(&isert_conn->conn_login_comp); if (ret) return ret; pr_debug("isert_get_login_rx processing login->req: %p\n", login->req); return 0; } static void isert_set_conn_info(struct iscsi_np *np, struct iscsi_conn *conn, struct isert_conn *isert_conn) { struct rdma_cm_id *cm_id = isert_conn->conn_cm_id; struct rdma_route *cm_route = &cm_id->route; struct sockaddr_in *sock_in; struct sockaddr_in6 *sock_in6; conn->login_family = np->np_sockaddr.ss_family; if (np->np_sockaddr.ss_family == AF_INET6) { sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.dst_addr; snprintf(conn->login_ip, sizeof(conn->login_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->login_port = ntohs(sock_in6->sin6_port); sock_in6 = (struct sockaddr_in6 *)&cm_route->addr.src_addr; snprintf(conn->local_ip, sizeof(conn->local_ip), "%pI6c", &sock_in6->sin6_addr.in6_u); conn->local_port = ntohs(sock_in6->sin6_port); } else { sock_in = (struct sockaddr_in *)&cm_route->addr.dst_addr; sprintf(conn->login_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->login_port = ntohs(sock_in->sin_port); sock_in = (struct sockaddr_in *)&cm_route->addr.src_addr; sprintf(conn->local_ip, "%pI4", &sock_in->sin_addr.s_addr); conn->local_port = ntohs(sock_in->sin_port); } } static int isert_accept_np(struct iscsi_np *np, struct iscsi_conn *conn) { struct isert_np *isert_np = (struct isert_np *)np->np_context; struct isert_conn *isert_conn; int max_accept = 0, ret; accept_wait: ret = wait_event_interruptible(isert_np->np_accept_wq, !isert_check_accept_queue(isert_np) || np->np_thread_state == ISCSI_NP_THREAD_RESET); if (max_accept > 5) return -ENODEV; spin_lock_bh(&np->np_thread_lock); if (np->np_thread_state >= ISCSI_NP_THREAD_RESET) { spin_unlock_bh(&np->np_thread_lock); pr_debug("np_thread_state %d for isert_accept_np\n", np->np_thread_state); /** * No point in stalling here when np_thread * is in state RESET/SHUTDOWN/EXIT - bail **/ return -ENODEV; } spin_unlock_bh(&np->np_thread_lock); mutex_lock(&isert_np->np_accept_mutex); if (list_empty(&isert_np->np_accept_list)) { mutex_unlock(&isert_np->np_accept_mutex); max_accept++; goto accept_wait; } isert_conn = list_first_entry(&isert_np->np_accept_list, struct isert_conn, conn_accept_node); list_del_init(&isert_conn->conn_accept_node); mutex_unlock(&isert_np->np_accept_mutex); conn->context = isert_conn; isert_conn->conn = conn; max_accept = 0; ret = isert_rdma_post_recvl(isert_conn); if (ret) return ret; ret = isert_rdma_accept(isert_conn); if (ret) return ret; isert_set_conn_info(np, conn, isert_conn); pr_debug("Processing isert_accept_np: isert_conn: %p\n", isert_conn); return 0; } static void isert_free_np(struct iscsi_np *np) { struct isert_np *isert_np = (struct isert_np *)np->np_context; if (isert_np->np_cm_id) rdma_destroy_id(isert_np->np_cm_id); np->np_context = NULL; kfree(isert_np); } static void isert_wait_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; pr_debug("isert_wait_conn: Starting \n"); mutex_lock(&isert_conn->conn_mutex); if (isert_conn->conn_cm_id) { pr_debug("Calling rdma_disconnect from isert_wait_conn\n"); rdma_disconnect(isert_conn->conn_cm_id); } /* * Only wait for conn_wait_comp_err if the isert_conn made it * into full feature phase.. */ if (isert_conn->state == ISER_CONN_INIT) { mutex_unlock(&isert_conn->conn_mutex); return; } if (isert_conn->state == ISER_CONN_UP) isert_conn->state = ISER_CONN_TERMINATING; mutex_unlock(&isert_conn->conn_mutex); wait_for_completion(&isert_conn->conn_wait_comp_err); wait_for_completion(&isert_conn->conn_wait); isert_put_conn(isert_conn); } static void isert_free_conn(struct iscsi_conn *conn) { struct isert_conn *isert_conn = conn->context; isert_put_conn(isert_conn); } static struct iscsit_transport iser_target_transport = { .name = "IB/iSER", .transport_type = ISCSI_INFINIBAND, .owner = THIS_MODULE, .iscsit_setup_np = isert_setup_np, .iscsit_accept_np = isert_accept_np, .iscsit_free_np = isert_free_np, .iscsit_wait_conn = isert_wait_conn, .iscsit_free_conn = isert_free_conn, .iscsit_alloc_cmd = isert_alloc_cmd, .iscsit_get_login_rx = isert_get_login_rx, .iscsit_put_login_tx = isert_put_login_tx, .iscsit_immediate_queue = isert_immediate_queue, .iscsit_response_queue = isert_response_queue, .iscsit_get_dataout = isert_get_dataout, .iscsit_queue_data_in = isert_put_datain, .iscsit_queue_status = isert_put_response, }; static int __init isert_init(void) { int ret; isert_rx_wq = alloc_workqueue("isert_rx_wq", 0, 0); if (!isert_rx_wq) { pr_err("Unable to allocate isert_rx_wq\n"); return -ENOMEM; } isert_comp_wq = alloc_workqueue("isert_comp_wq", 0, 0); if (!isert_comp_wq) { pr_err("Unable to allocate isert_comp_wq\n"); ret = -ENOMEM; goto destroy_rx_wq; } isert_cmd_cache = kmem_cache_create("isert_cmd_cache", sizeof(struct isert_cmd), __alignof__(struct isert_cmd), 0, NULL); if (!isert_cmd_cache) { pr_err("Unable to create isert_cmd_cache\n"); ret = -ENOMEM; goto destroy_tx_cq; } iscsit_register_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Loaded iser_target_transport\n"); return 0; destroy_tx_cq: destroy_workqueue(isert_comp_wq); destroy_rx_wq: destroy_workqueue(isert_rx_wq); return ret; } static void __exit isert_exit(void) { flush_scheduled_work(); kmem_cache_destroy(isert_cmd_cache); destroy_workqueue(isert_comp_wq); destroy_workqueue(isert_rx_wq); iscsit_unregister_transport(&iser_target_transport); pr_debug("iSER_TARGET[0] - Released iser_target_transport\n"); } MODULE_DESCRIPTION("iSER-Target for mainline target infrastructure"); MODULE_VERSION("0.1"); MODULE_AUTHOR("[email protected]"); MODULE_LICENSE("GPL"); module_init(isert_init); module_exit(isert_exit);
crimsonthunder/kernel_samsung_trlte_5.1.1
drivers/infiniband/ulp/isert/ib_isert.c
C
gpl-2.0
67,213
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org) // // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include <string> #include <utility> /// Base class for controls with a tooltip class ctrlBaseTooltip { public: ctrlBaseTooltip(std::string tooltip = "") : tooltip_(std::move(tooltip)) {} virtual ~ctrlBaseTooltip(); void SetTooltip(const std::string& tooltip) { tooltip_ = tooltip; } const std::string& GetTooltip() const { return tooltip_; } /// Swap the tooltips of those controls void SwapTooltip(ctrlBaseTooltip& other); void ShowTooltip() const; /// Show a temporary tooltip void ShowTooltip(const std::string& tooltip) const; void HideTooltip() const; protected: std::string tooltip_; };
Return-To-The-Roots/s25client
libs/s25main/controls/ctrlBaseTooltip.h
C
gpl-2.0
777
// // Microsoft.VisualBasic.* Test Cases // // Authors: // Gert Driesen ([email protected]) // // (c) 2006 Novell // using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Globalization; using System.IO; using System.Text; using NUnit.Framework; namespace MonoTests.Microsoft.VisualBasic { /// <summary> /// Test ICodeGenerator's GenerateCodeFromNamespace, along with a /// minimal set CodeDom components. /// </summary> [TestFixture] public class CodeGeneratorFromNamespaceTest : CodeGeneratorTestBase { CodeNamespace codeNamespace = null; [SetUp] public void Init () { InitBase (); codeNamespace = new CodeNamespace (); } protected override string Generate (CodeGeneratorOptions options) { StringWriter writer = new StringWriter (); writer.NewLine = NewLine; generator.GenerateCodeFromNamespace (codeNamespace, writer, options); writer.Close (); return writer.ToString (); } [Test] [ExpectedException (typeof (NullReferenceException))] public void NullNamespaceTest () { codeNamespace = null; Generate (); } [Test] public void NullNamespaceNameTest () { codeNamespace.Name = null; Assert.AreEqual ("\n", Generate ()); } [Test] public void DefaultNamespaceTest () { Assert.AreEqual ("\n", Generate ()); } [Test] public void SimpleNamespaceTest () { codeNamespace.Name = "A"; Assert.AreEqual ("\nNamespace A\nEnd Namespace\n", Generate ()); } [Test] public void InvalidNamespaceTest () { codeNamespace.Name = "A,B"; Assert.AreEqual ("\nNamespace A,B\nEnd Namespace\n", Generate ()); } [Test] public void CommentOnlyNamespaceTest () { CodeCommentStatement comment = new CodeCommentStatement ("a"); codeNamespace.Comments.Add (comment); Assert.AreEqual ("\n'a\n", Generate ()); } [Test] public void ImportsTest () { codeNamespace.Imports.Add (new CodeNamespaceImport ("System")); codeNamespace.Imports.Add (new CodeNamespaceImport ("System.Collections")); Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}", NewLine), Generate (), "#1"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "Namespace A{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); codeNamespace.Name = null; codeNamespace.Comments.Add (new CodeCommentStatement ("a")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "'a{0}", NewLine), Generate (), "#3"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "Imports System{0}" + "Imports System.Collections{0}" + "{0}" + "'a{0}" + "Namespace A{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void TypeTest () { codeNamespace.Types.Add (new CodeTypeDeclaration ("Person")); Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "{0}" + "Public Class Person{0}" + "End Class{0}", NewLine), Generate (), "#A1"); CodeGeneratorOptions options = new CodeGeneratorOptions (); options.BlankLinesBetweenMembers = false; Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "Public Class Person{0}" + "End Class{0}", NewLine), Generate (options), "#A2"); codeNamespace.Name = "A"; Assert.AreEqual (string.Format(CultureInfo.InvariantCulture, "{0}" + "Namespace A{0}" + " {0}" + " Public Class Person{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#B1"); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace A{0}" + " Public Class Person{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (options), "#B2"); } [Test] public void Type_TypeParameters () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); type.TypeParameters.Add (new CodeTypeParameter ("T")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); type.TypeParameters.Add (new CodeTypeParameter ("As")); type.TypeParameters.Add (new CodeTypeParameter ("New")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable))); type.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New, R As System.IComparable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); type.TypeParameters.Add (new CodeTypeParameter ("S")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T, As, New, R As System.IComparable, S){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void Type_TypeParameters_Constraints () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeTypeParameter typeParamT = new CodeTypeParameter ("T"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable))); type.TypeParameters.Add (typeParamT); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As System.IComparable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable))); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable}}){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); typeParamT.HasConstructorConstraint = true; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); CodeTypeParameter typeParamS = new CodeTypeParameter ("S"); typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable))); type.TypeParameters.Add (typeParamS); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.HasConstructorConstraint = true; type.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#5"); } [Test] public void Type_TypeParameters_ConstructorConstraint () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeTypeParameter typeParam = new CodeTypeParameter ("T"); typeParam.HasConstructorConstraint = true; type.TypeParameters.Add (typeParam); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass(Of T As New){0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate ()); } [Test] public void Method_TypeParameters () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); method.TypeParameters.Add (new CodeTypeParameter ("T")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); method.TypeParameters.Add (new CodeTypeParameter ("As")); method.TypeParameters.Add (new CodeTypeParameter ("New")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable))); method.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New, R As System.IComparable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); method.TypeParameters.Add (new CodeTypeParameter ("S")); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T, As, New, R As System.IComparable, S)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); } [Test] public void Method_TypeParameters_Constraints () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); CodeTypeParameter typeParamT = new CodeTypeParameter ("T"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable))); method.TypeParameters.Add (typeParamT); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As System.IComparable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#1"); typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable))); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable}})(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#2"); typeParamT.HasConstructorConstraint = true; Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}})(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#3"); CodeTypeParameter typeParamS = new CodeTypeParameter ("S"); typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable))); method.TypeParameters.Add (typeParamS); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#4"); CodeTypeParameter typeParamR = new CodeTypeParameter ("R"); typeParamR.HasConstructorConstraint = true; method.TypeParameters.Add (typeParamR); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate (), "#5"); } [Test] public void Method_TypeParameters_ConstructorConstraint () { codeNamespace.Name = "SomeNS"; CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass"); codeNamespace.Types.Add (type); CodeMemberMethod method = new CodeMemberMethod (); method.Name = "SomeMethod"; type.Members.Add (method); CodeTypeParameter typeParam = new CodeTypeParameter ("T"); typeParam.HasConstructorConstraint = true; method.TypeParameters.Add (typeParam); Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "{0}" + "Namespace SomeNS{0}" + " {0}" + " Public Class SomeClass{0}" + " {0}" + " Private Sub SomeMethod(Of T As New)(){0}" + " End Sub{0}" + " End Class{0}" + "End Namespace{0}", NewLine), Generate ()); } } }
hardvain/mono-compiler
class/System/Test/Microsoft.VisualBasic/CodeGeneratorFromNamespaceTest.cs
C#
gpl-2.0
14,626
<div class="patient-details container ng-cloak" ng-cloak> <div ng-if="vm.patient == null"> Es wurde kein Patient ausgewählt! </div> <div ng-if="vm.patient != null"> <h1 class="header">Patient</h1> <div class="clearfix"> <div class="patient-personal patient-abstract"> <h2 class="sub-header">Persönliche Daten</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Vorname</span> <span class="table-cell">{{ vm.patient.firstname }}</span> </span> <span class="table-row"> <span class="table-cell">Nachname</span> <span class="table-cell">{{ vm.patient.lastname }}</span> </span> <span class="table-row"> <span class="table-cell">Straße</span> <span class="table-cell">{{ vm.patient.street }}</span> </span> <span class="table-row"> <span class="table-cell">PLZ / Ort</span> <span class="table-cell">{{ vm.patient.postal }} {{ vm.patient.city }}</span> </span> </span> <span class="table list"> <span class="table-row"> <span class="table-cell">Telefon</span> <span class="table-cell">{{ vm.patient.phone }}</span> </span> <span class="table-row"> <span class="table-cell">Geschäftlich</span> <span class="table-cell">{{ vm.patient.office }}</span> </span> <span class="table-row"> <span class="table-cell">Mobil</span> <span class="table-cell">{{ vm.patient.mobile }}</span> </span> </span> <a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-hide="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details anzeigen</a> <a ng-click="vm.showPersonalDetails = !vm.showPersonalDetails" ng-show="vm.showPersonalDetails" style="display: block; margin-bottom: 0.3em;">Details verbergen</a> <span class="table list" ng-show="vm.showPersonalDetails"> <span class="table-row"> <span class="table-cell">Geburtstag</span> <span class="table-cell">{{ vm.patient.birthday }}</span> </span> <span class="table-row"> <span class="table-cell">Familienstatus</span> <span class="table-cell">{{ vm.patient.status }}</span> </span> <span class="table-row"> <span class="table-cell">Beruf</span> <span class="table-cell">{{ vm.patient.profession }}</span> </span> <span class="table-row"> <span class="table-cell">Versicherung</span> <span class="table-cell">{{ vm.patient.insurance.type }} {{ vm.patient.insurance.name }}</span> </span> <span class="table-row"> <span class="table-cell">Bemerkungen</span> <span class="table-cell">{{ vm.patient.notes }}</span> </span> </span> </div> <div class="patient-attributes patient-abstract"> <div class="patient-attention"> <h2 class="sub-header">Vermerk</h2> <span>{{ vm.patient.attention }}</span> </div> <span class="table list"> <span class="table-row"> <span class="table-cell">Referenz durch</span> <span class="table-cell">{{ vm.patient.reference }}</span> </span> <span class="table-row"> <span class="table-cell">Behandelnder Arzt</span> <span class="table-cell">{{ vm.patient.doctor }}</span> </span> <span class="table-row"> <span class="table-cell">Papierakte?</span> <span class="table-cell"> <span ng-if="vm.patient.paperfile">Ja</span> <span ng-if="!vm.patient.paperfile">Nein</span> </span> </span> </span> </div> </div> <div class="patient-abstract"> <h2 class="sub-header">Aktuelles</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Befunde</span> <span class="table-cell">{{ vm.patient.findings }}</span> </span> <span class="table-row"> <span class="table-cell">Therapie</span> <span class="table-cell">{{ vm.patient.therapy }}</span> </span> </span> </div> <div class="patient-abstract"> <h2 class="sub-header">Krankengeschichte</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Operationen </span> <span class="table-cell">{{ vm.patient.history.operations }}</span> </span> <span class="table-row"> <span class="table-cell">Unfälle</span> <span class="table-cell">{{ vm.patient.history.accidents }}</span> </span> <span class="table-row"> <span class="table-cell">Vorerkrankungen</span> <span class="table-cell">{{ vm.patient.history.disease }}</span> </span> </span> </div> <div class="patient-abstract"> <div class="patient-current"> <h2 class="sub-header">Risikofaktoren</h2> <span class="table list"> <span class="table-row"> <span class="table-cell">Allergien</span> <span class="table-cell">{{ vm.patient.risks.allergy }}</span> </span> <span class="table-row"> <span class="table-cell">Medikation</span> <span class="table-cell">{{ vm.patient.risks.medicine }}</span> </span> </span> </div> </div> </div> </div> <div class="footer"> <a class="button" ng-click="vm.goBack()">Zurück</a> <a class="button" ng-click="vm.editPatient()">Editieren</a> <a class="button" ng-click="vm.showTreatment()">Behandlungsakte</a> </div>
clowdfish/my-patients
app/scripts/patient/detail/patient-detail.html
HTML
gpl-2.0
5,956
/*CXXR $Id$ *CXXR *CXXR This file is part of CXXR, a project to refactor the R interpreter *CXXR into C++. It may consist in whole or in part of program code and *CXXR documentation taken from the R project itself, incorporated into *CXXR CXXR (and possibly MODIFIED) under the terms of the GNU General Public *CXXR Licence. *CXXR *CXXR CXXR is Copyright (C) 2008-14 Andrew R. Runnalls, subject to such other *CXXR copyrights and copyright restrictions as may be stated below. *CXXR *CXXR CXXR is not part of the R project, and bugs and other issues should *CXXR not be reported via r-bugs or other R project channels; instead refer *CXXR to the CXXR website. *CXXR */ /* * R : A Computer Language for Statistical Data Analysis * Copyright (C) 2001--2012 The R Core Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * http://www.r-project.org/Licenses/ */ #include <R_ext/Complex.h> #include <R_ext/RS.h> /* use declarations in R_ext/Lapack.h (instead of having them there *and* here) but ``delete'' the 'extern' there : */ #define La_extern #define BLAS_extern #include <R_ext/Lapack.h> #undef La_extern #undef BLAS_extern
cxxr-devel/cxxr-svn-mirror
src/modules/lapack/Lapack.h
C
gpl-2.0
1,757
/* $Id: tstCAPIGlue.c 109358 2016-07-31 17:11:31Z bird $ */ /** @file tstCAPIGlue.c * Demonstrator program to illustrate use of C bindings of Main API. * * It has sample code showing how to retrieve all available error information, * and how to handle active (event delivery through callbacks) or passive * (event delivery through a polling mechanism) event listeners. */ /* * Copyright (C) 2009-2016 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /** @todo * Our appologies for the 256+ missing return code checks in this sample file. * * We strongly recomment users of the VBoxCAPI to check all return codes! */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include "VBoxCAPIGlue.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef WIN32 # include <signal.h> # include <unistd.h> # include <sys/poll.h> #endif #ifdef ___iprt_cdefs_h # error "not supposed to involve any IPRT or VBox headers here." #endif /** * Select between active event listener (defined) and passive event listener * (undefined). The active event listener case needs much more code, and * additionally requires a lot more platform dependent code. */ #undef USE_ACTIVE_EVENT_LISTENER /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ /** Set by Ctrl+C handler. */ static volatile int g_fStop = 0; #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 /** The COM type information for IEventListener, for implementing IDispatch. */ static ITypeInfo *g_pTInfoIEventListener = NULL; # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ static const char *GetStateName(MachineState_T machineState) { switch (machineState) { case MachineState_Null: return "<null>"; case MachineState_PoweredOff: return "PoweredOff"; case MachineState_Saved: return "Saved"; case MachineState_Teleported: return "Teleported"; case MachineState_Aborted: return "Aborted"; case MachineState_Running: return "Running"; case MachineState_Paused: return "Paused"; case MachineState_Stuck: return "Stuck"; case MachineState_Teleporting: return "Teleporting"; case MachineState_LiveSnapshotting: return "LiveSnapshotting"; case MachineState_Starting: return "Starting"; case MachineState_Stopping: return "Stopping"; case MachineState_Saving: return "Saving"; case MachineState_Restoring: return "Restoring"; case MachineState_TeleportingPausedVM: return "TeleportingPausedVM"; case MachineState_TeleportingIn: return "TeleportingIn"; case MachineState_FaultTolerantSyncing: return "FaultTolerantSyncing"; case MachineState_DeletingSnapshotOnline: return "DeletingSnapshotOnline"; case MachineState_DeletingSnapshotPaused: return "DeletingSnapshotPaused"; case MachineState_RestoringSnapshot: return "RestoringSnapshot"; case MachineState_DeletingSnapshot: return "DeletingSnapshot"; case MachineState_SettingUp: return "SettingUp"; default: return "no idea"; } } /** * Ctrl+C handler, terminate event listener. * * Remember that most function calls are not allowed in this context (including * printf!), so make sure that this does as little as possible. * * @param iInfo Platform dependent detail info (ignored). */ static BOOL VBOX_WINAPI ctrlCHandler(DWORD iInfo) { (void)iInfo; g_fStop = 1; return TRUE; } /** * Sample event processing function, dumping some event information. * Shared between active and passive event demo, to highlight that this part * is identical between the two. */ static HRESULT EventListenerDemoProcessEvent(IEvent *event) { VBoxEventType_T evType; HRESULT rc; if (!event) { printf("event null\n"); return S_OK; } evType = VBoxEventType_Invalid; rc = IEvent_get_Type(event, &evType); if (FAILED(rc)) { printf("cannot get event type, rc=%#x\n", rc); return S_OK; } switch (evType) { case VBoxEventType_OnMousePointerShapeChanged: printf("OnMousePointerShapeChanged\n"); break; case VBoxEventType_OnMouseCapabilityChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnKeyboardLedsChanged: printf("OnMouseCapabilityChanged\n"); break; case VBoxEventType_OnStateChanged: { IStateChangedEvent *ev = NULL; enum MachineState state; rc = IEvent_QueryInterface(event, &IID_IStateChangedEvent, (void **)&ev); if (FAILED(rc)) { printf("cannot get StateChangedEvent interface, rc=%#x\n", rc); return S_OK; } if (!ev) { printf("StateChangedEvent reference null\n"); return S_OK; } rc = IStateChangedEvent_get_State(ev, &state); if (FAILED(rc)) printf("warning: cannot get state, rc=%#x\n", rc); IStateChangedEvent_Release(ev); printf("OnStateChanged: %s\n", GetStateName(state)); fflush(stdout); if ( state == MachineState_PoweredOff || state == MachineState_Saved || state == MachineState_Teleported || state == MachineState_Aborted ) g_fStop = 1; break; } case VBoxEventType_OnAdditionsStateChanged: printf("OnAdditionsStateChanged\n"); break; case VBoxEventType_OnNetworkAdapterChanged: printf("OnNetworkAdapterChanged\n"); break; case VBoxEventType_OnSerialPortChanged: printf("OnSerialPortChanged\n"); break; case VBoxEventType_OnParallelPortChanged: printf("OnParallelPortChanged\n"); break; case VBoxEventType_OnStorageControllerChanged: printf("OnStorageControllerChanged\n"); break; case VBoxEventType_OnMediumChanged: printf("OnMediumChanged\n"); break; case VBoxEventType_OnVRDEServerChanged: printf("OnVRDEServerChanged\n"); break; case VBoxEventType_OnUSBControllerChanged: printf("OnUSBControllerChanged\n"); break; case VBoxEventType_OnUSBDeviceStateChanged: printf("OnUSBDeviceStateChanged\n"); break; case VBoxEventType_OnSharedFolderChanged: printf("OnSharedFolderChanged\n"); break; case VBoxEventType_OnRuntimeError: printf("OnRuntimeError\n"); break; case VBoxEventType_OnCanShowWindow: printf("OnCanShowWindow\n"); break; case VBoxEventType_OnShowWindow: printf("OnShowWindow\n"); break; default: printf("unknown event: %d\n", evType); } return S_OK; } #ifdef USE_ACTIVE_EVENT_LISTENER struct IEventListenerDemo; typedef struct IEventListenerDemo IEventListenerDemo; typedef struct IEventListenerDemoVtbl { HRESULT (*QueryInterface)(IEventListenerDemo *pThis, REFIID riid, void **ppvObject); ULONG (*AddRef)(IEventListenerDemo *pThis); ULONG (*Release)(IEventListenerDemo *pThis); #ifdef WIN32 HRESULT (*GetTypeInfoCount)(IEventListenerDemo *pThis, UINT *pctinfo); HRESULT (*GetTypeInfo)(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo); HRESULT (*GetIDsOfNames)(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId); HRESULT (*Invoke)(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); #endif HRESULT (*HandleEvent)(IEventListenerDemo *pThis, IEvent *aEvent); } IEventListenerDemoVtbl; typedef struct IEventListenerDemo { struct IEventListenerDemoVtbl *lpVtbl; int cRef; #ifdef WIN32 /* Active event delivery needs a free threaded marshaler, as the default * proxy marshaling cannot deal correctly with this case. */ IUnknown *pUnkMarshaler; #endif } IEventListenerDemo; /* Defines for easily calling IEventListenerDemo functions. */ /* IUnknown functions. */ #define IEventListenerDemo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl->QueryInterface(This,riid,ppvObject) ) #define IEventListenerDemo_AddRef(This) \ ( (This)->lpVtbl->AddRef(This) ) #define IEventListenerDemo_Release(This) \ ( (This)->lpVtbl->Release(This) ) #ifdef WIN32 /* IDispatch functions. */ #define IEventListenerDemo_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl->GetTypeInfoCount(This,pctinfo) ) #define IEventListenerDemo_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl->GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IEventListenerDemo_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl->GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IEventListenerDemo_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl->Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* IEventListener functions. */ #define IEventListenerDemo_HandleEvent(This,aEvent) \ ( (This)->lpVtbl->HandleEvent(This,aEvent) ) /** * Event handler function, for active event processing. */ static HRESULT IEventListenerDemoImpl_HandleEvent(IEventListenerDemo *pThis, IEvent *event) { return EventListenerDemoProcessEvent(event); } static HRESULT IEventListenerDemoImpl_QueryInterface(IEventListenerDemo *pThis, const IID *iid, void **resultp) { /* match iid */ if ( !memcmp(iid, &IID_IEventListener, sizeof(IID)) || !memcmp(iid, &IID_IDispatch, sizeof(IID)) || !memcmp(iid, &IID_IUnknown, sizeof(IID))) { IEventListenerDemo_AddRef(pThis); *resultp = pThis; return S_OK; } #ifdef WIN32 if (!memcmp(iid, &IID_IMarshal, sizeof(IID))) return IUnknown_QueryInterface(pThis->pUnkMarshaler, iid, resultp); #endif return E_NOINTERFACE; } static HRESULT IEventListenerDemoImpl_AddRef(IEventListenerDemo *pThis) { return ++(pThis->cRef); } static HRESULT IEventListenerDemoImpl_Release(IEventListenerDemo *pThis) { HRESULT c; c = --(pThis->cRef); if (!c) free(pThis); return c; } #ifdef WIN32 static HRESULT IEventListenerDemoImpl_GetTypeInfoCount(IEventListenerDemo *pThis, UINT *pctinfo) { if (!pctinfo) return E_POINTER; *pctinfo = 1; return S_OK; } static HRESULT IEventListenerDemoImpl_GetTypeInfo(IEventListenerDemo *pThis, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo) { if (!ppTInfo) return E_POINTER; ITypeInfo_AddRef(g_pTInfoIEventListener); *ppTInfo = g_pTInfoIEventListener; return S_OK; } static HRESULT IEventListenerDemoImpl_GetIDsOfNames(IEventListenerDemo *pThis, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return ITypeInfo_GetIDsOfNames(g_pTInfoIEventListener, rgszNames, cNames, rgDispId); } static HRESULT IEventListenerDemoImpl_Invoke(IEventListenerDemo *pThis, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return ITypeInfo_Invoke(g_pTInfoIEventListener, (IDispatch *)pThis, dispIdMember, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } static HRESULT LoadTypeInfo(REFIID riid, ITypeInfo **pTInfo) { HRESULT rc; ITypeLib *pTypeLib; rc = LoadRegTypeLib(&LIBID_VirtualBox, 1 /* major */, 0 /* minor */, 0 /* lcid */, &pTypeLib); if (FAILED(rc)) return rc; rc = ITypeLib_GetTypeInfoOfGuid(pTypeLib, riid, pTInfo); /* No longer need access to the type lib, release it. */ ITypeLib_Release(pTypeLib); return rc; } #endif #ifdef __GNUC__ typedef struct IEventListenerDemoVtblInt { ptrdiff_t offset_to_top; void *typeinfo; IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { 0, /* offset_to_top */ NULL, /* typeinfo, not vital */ { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #elif defined(_MSC_VER) typedef struct IEventListenerDemoVtblInt { IEventListenerDemoVtbl lpVtbl; } IEventListenerDemoVtblInt; static IEventListenerDemoVtblInt g_IEventListenerDemoVtblInt = { { IEventListenerDemoImpl_QueryInterface, IEventListenerDemoImpl_AddRef, IEventListenerDemoImpl_Release, #ifdef WIN32 IEventListenerDemoImpl_GetTypeInfoCount, IEventListenerDemoImpl_GetTypeInfo, IEventListenerDemoImpl_GetIDsOfNames, IEventListenerDemoImpl_Invoke, #endif IEventListenerDemoImpl_HandleEvent } }; #else # error Port me! #endif /** * Register active event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerActiveEventListener(IVirtualBox *virtualBox, ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if ((SUCCEEDED(rc)) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListenerDemo *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); consoleListener = calloc(1, sizeof(IEventListenerDemo)); if (consoleListener) { consoleListener->lpVtbl = &(g_IEventListenerDemoVtblInt.lpVtbl); #ifdef WIN32 CoCreateFreeThreadedMarshaler((IUnknown *)consoleListener, &consoleListener->pUnkMarshaler); #endif IEventListenerDemo_AddRef(consoleListener); rc = IEventSource_RegisterListener(es, (IEventListener *)consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 1 /* active */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) g_pVBoxFuncs->pfnProcessEventQueue(250); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); #ifdef WIN32 if (consoleListener->pUnkMarshaler) IUnknown_Release(consoleListener->pUnkMarshaler); #endif IEventListenerDemo_Release(consoleListener); } else printf("Failed while allocating memory for console event listener.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #else /* !USE_ACTIVE_EVENT_LISTENER */ /** * Register passive event listener for the selected VM. * * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void registerPassiveEventListener(ISession *session) { IConsole *console = NULL; HRESULT rc; rc = ISession_get_Console(session, &console); if (SUCCEEDED(rc) && console) { IEventSource *es = NULL; rc = IConsole_get_EventSource(console, &es); if (SUCCEEDED(rc) && es) { static const ULONG s_auInterestingEvents[] = { VBoxEventType_OnMousePointerShapeChanged, VBoxEventType_OnMouseCapabilityChanged, VBoxEventType_OnKeyboardLedsChanged, VBoxEventType_OnStateChanged, VBoxEventType_OnAdditionsStateChanged, VBoxEventType_OnNetworkAdapterChanged, VBoxEventType_OnSerialPortChanged, VBoxEventType_OnParallelPortChanged, VBoxEventType_OnStorageControllerChanged, VBoxEventType_OnMediumChanged, VBoxEventType_OnVRDEServerChanged, VBoxEventType_OnUSBControllerChanged, VBoxEventType_OnUSBDeviceStateChanged, VBoxEventType_OnSharedFolderChanged, VBoxEventType_OnRuntimeError, VBoxEventType_OnCanShowWindow, VBoxEventType_OnShowWindow }; SAFEARRAY *interestingEventsSA = NULL; IEventListener *consoleListener = NULL; /* The VirtualBox API expects enum values as VT_I4, which in the * future can be hopefully relaxed. */ interestingEventsSA = g_pVBoxFuncs->pfnSafeArrayCreateVector(VT_I4, 0, sizeof(s_auInterestingEvents) / sizeof(s_auInterestingEvents[0])); g_pVBoxFuncs->pfnSafeArrayCopyInParamHelper(interestingEventsSA, &s_auInterestingEvents, sizeof(s_auInterestingEvents)); rc = IEventSource_CreateListener(es, &consoleListener); if (SUCCEEDED(rc) && consoleListener) { rc = IEventSource_RegisterListener(es, consoleListener, ComSafeArrayAsInParam(interestingEventsSA), 0 /* passive */); if (SUCCEEDED(rc)) { /* Just wait here for events, no easy way to do this better * as there's not much to do after this completes. */ printf("Entering event loop, PowerOff the machine to exit or press Ctrl-C to terminate\n"); fflush(stdout); #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, TRUE); #else signal(SIGINT, (void (*)(int))ctrlCHandler); #endif while (!g_fStop) { IEvent *ev = NULL; rc = IEventSource_GetEvent(es, consoleListener, 250, &ev); if (FAILED(rc)) { printf("Failed getting event: %#x\n", rc); g_fStop = 1; continue; } /* handle timeouts, resulting in NULL events */ if (!ev) continue; rc = EventListenerDemoProcessEvent(ev); if (FAILED(rc)) { printf("Failed processing event: %#x\n", rc); g_fStop = 1; /* finish processing the event */ } rc = IEventSource_EventProcessed(es, consoleListener, ev); if (FAILED(rc)) { printf("Failed to mark event as processed: %#x\n", rc); g_fStop = 1; /* continue with event release */ } if (ev) { IEvent_Release(ev); ev = NULL; } } #ifdef WIN32 SetConsoleCtrlHandler(ctrlCHandler, FALSE); #else signal(SIGINT, SIG_DFL); #endif } else printf("Failed to register event listener.\n"); IEventSource_UnregisterListener(es, (IEventListener *)consoleListener); IEventListener_Release(consoleListener); } else printf("Failed to create an event listener instance.\n"); g_pVBoxFuncs->pfnSafeArrayDestroy(interestingEventsSA); IEventSource_Release(es); } else printf("Failed to get the event source instance.\n"); IConsole_Release(console); } } #endif /* !USE_ACTIVE_EVENT_LISTENER */ /** * Print detailed error information if available. * @param pszExecutable string with the executable name * @param pszErrorMsg string containing the code location specific error message * @param rc COM/XPCOM result code */ static void PrintErrorInfo(const char *pszExecutable, const char *pszErrorMsg, HRESULT rc) { IErrorInfo *ex; HRESULT rc2; fprintf(stderr, "%s: %s (rc=%#010x)\n", pszExecutable, pszErrorMsg, (unsigned)rc); rc2 = g_pVBoxFuncs->pfnGetException(&ex); if (SUCCEEDED(rc2) && ex) { IVirtualBoxErrorInfo *ei; rc2 = IErrorInfo_QueryInterface(ex, &IID_IVirtualBoxErrorInfo, (void **)&ei); if (SUCCEEDED(rc2) && ei != NULL) { /* got extended error info, maybe multiple infos */ do { LONG resultCode = S_OK; BSTR componentUtf16 = NULL; char *component = NULL; BSTR textUtf16 = NULL; char *text = NULL; IVirtualBoxErrorInfo *ei_next = NULL; fprintf(stderr, "Extended error info (IVirtualBoxErrorInfo):\n"); IVirtualBoxErrorInfo_get_ResultCode(ei, &resultCode); fprintf(stderr, " resultCode=%#010x\n", (unsigned)resultCode); IVirtualBoxErrorInfo_get_Component(ei, &componentUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(componentUtf16, &component); g_pVBoxFuncs->pfnComUnallocString(componentUtf16); fprintf(stderr, " component=%s\n", component); g_pVBoxFuncs->pfnUtf8Free(component); IVirtualBoxErrorInfo_get_Text(ei, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); fprintf(stderr, " text=%s\n", text); g_pVBoxFuncs->pfnUtf8Free(text); rc2 = IVirtualBoxErrorInfo_get_Next(ei, &ei_next); if (FAILED(rc2)) ei_next = NULL; IVirtualBoxErrorInfo_Release(ei); ei = ei_next; } while (ei); } IErrorInfo_Release(ex); g_pVBoxFuncs->pfnClearException(); } } /** * Start a VM. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object * @param id identifies the machine to start */ static void startVM(const char *argv0, IVirtualBox *virtualBox, ISession *session, BSTR id) { HRESULT rc; IMachine *machine = NULL; IProgress *progress = NULL; BSTR env = NULL; BSTR sessionType; SAFEARRAY *groupsSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); rc = IVirtualBox_FindMachine(virtualBox, id, &machine); if (FAILED(rc) || !machine) { PrintErrorInfo(argv0, "Error: Couldn't get the Machine reference", rc); return; } rc = IMachine_get_Groups(machine, ComSafeArrayAsOutTypeParam(groupsSA, BSTR)); if (SUCCEEDED(rc)) { BSTR *groups = NULL; ULONG cbGroups = 0; ULONG i, cGroups; g_pVBoxFuncs->pfnSafeArrayCopyOutParamHelper((void **)&groups, &cbGroups, VT_BSTR, groupsSA); g_pVBoxFuncs->pfnSafeArrayDestroy(groupsSA); cGroups = cbGroups / sizeof(groups[0]); for (i = 0; i < cGroups; ++i) { /* Note that the use of %S might be tempting, but it is not * available on all platforms, and even where it is usable it * may depend on correct compiler options to make wchar_t a * 16 bit number. So better play safe and use UTF-8. */ char *group; g_pVBoxFuncs->pfnUtf16ToUtf8(groups[i], &group); printf("Groups[%d]: %s\n", i, group); g_pVBoxFuncs->pfnUtf8Free(group); } for (i = 0; i < cGroups; ++i) g_pVBoxFuncs->pfnComUnallocString(groups[i]); g_pVBoxFuncs->pfnArrayOutFree(groups); } g_pVBoxFuncs->pfnUtf8ToUtf16("gui", &sessionType); rc = IMachine_LaunchVMProcess(machine, session, sessionType, env, &progress); g_pVBoxFuncs->pfnUtf16Free(sessionType); if (SUCCEEDED(rc)) { BOOL completed; LONG resultCode; printf("Waiting for the remote session to open...\n"); IProgress_WaitForCompletion(progress, -1); rc = IProgress_get_Completed(progress, &completed); if (FAILED(rc)) fprintf(stderr, "Error: GetCompleted status failed\n"); IProgress_get_ResultCode(progress, &resultCode); if (FAILED(resultCode)) { IVirtualBoxErrorInfo *errorInfo; BSTR textUtf16; char *text; IProgress_get_ErrorInfo(progress, &errorInfo); IVirtualBoxErrorInfo_get_Text(errorInfo, &textUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(textUtf16, &text); printf("Error: %s\n", text); g_pVBoxFuncs->pfnComUnallocString(textUtf16); g_pVBoxFuncs->pfnUtf8Free(text); IVirtualBoxErrorInfo_Release(errorInfo); } else { fprintf(stderr, "VM process has been successfully started\n"); /* Kick off the event listener demo part, which is quite separate. * Ignore it if you need a more basic sample. */ #ifdef USE_ACTIVE_EVENT_LISTENER registerActiveEventListener(virtualBox, session); #else registerPassiveEventListener(session); #endif } IProgress_Release(progress); } else PrintErrorInfo(argv0, "Error: LaunchVMProcess failed", rc); /* It's important to always release resources. */ IMachine_Release(machine); } /** * List the registered VMs. * * @param argv0 executable name * @param virtualBox ptr to IVirtualBox object * @param session ptr to ISession object */ static void listVMs(const char *argv0, IVirtualBox *virtualBox, ISession *session) { HRESULT rc; SAFEARRAY *machinesSA = g_pVBoxFuncs->pfnSafeArrayOutParamAlloc(); IMachine **machines = NULL; ULONG machineCnt = 0; ULONG i; unsigned start_id; /* * Get the list of all registered VMs. */ rc = IVirtualBox_get_Machines(virtualBox, ComSafeArrayAsOutIfaceParam(machinesSA, IMachine *)); if (FAILED(rc)) { PrintErrorInfo(argv0, "could not get list of machines", rc); return; } /* * Extract interface pointers from machinesSA, and update the reference * counter of each object, as destroying machinesSA would call Release. */ g_pVBoxFuncs->pfnSafeArrayCopyOutIfaceParamHelper((IUnknown ***)&machines, &machineCnt, machinesSA); g_pVBoxFuncs->pfnSafeArrayDestroy(machinesSA); if (!machineCnt) { g_pVBoxFuncs->pfnArrayOutFree(machines); printf("\tNo VMs\n"); return; } printf("VM List:\n\n"); /* * Iterate through the collection. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; BOOL isAccessible = FALSE; printf("\tMachine #%u\n", (unsigned)i); if (!machine) { printf("\t(skipped, NULL)\n"); continue; } IMachine_get_Accessible(machine, &isAccessible); if (isAccessible) { BSTR machineNameUtf16; char *machineName; IMachine_get_Name(machine, &machineNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(machineNameUtf16,&machineName); g_pVBoxFuncs->pfnComUnallocString(machineNameUtf16); printf("\tName: %s\n", machineName); g_pVBoxFuncs->pfnUtf8Free(machineName); } else printf("\tName: <inaccessible>\n"); { BSTR uuidUtf16; char *uuidUtf8; IMachine_get_Id(machine, &uuidUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(uuidUtf16, &uuidUtf8); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); printf("\tUUID: %s\n", uuidUtf8); g_pVBoxFuncs->pfnUtf8Free(uuidUtf8); } if (isAccessible) { { BSTR configFileUtf16; char *configFileUtf8; IMachine_get_SettingsFilePath(machine, &configFileUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(configFileUtf16, &configFileUtf8); g_pVBoxFuncs->pfnComUnallocString(configFileUtf16); printf("\tConfig file: %s\n", configFileUtf8); g_pVBoxFuncs->pfnUtf8Free(configFileUtf8); } { ULONG memorySize; IMachine_get_MemorySize(machine, &memorySize); printf("\tMemory size: %uMB\n", memorySize); } { BSTR typeId; BSTR osNameUtf16; char *osName; IGuestOSType *osType = NULL; IMachine_get_OSTypeId(machine, &typeId); IVirtualBox_GetGuestOSType(virtualBox, typeId, &osType); g_pVBoxFuncs->pfnComUnallocString(typeId); IGuestOSType_get_Description(osType, &osNameUtf16); g_pVBoxFuncs->pfnUtf16ToUtf8(osNameUtf16,&osName); g_pVBoxFuncs->pfnComUnallocString(osNameUtf16); printf("\tGuest OS: %s\n\n", osName); g_pVBoxFuncs->pfnUtf8Free(osName); IGuestOSType_Release(osType); } } } /* * Let the user chose a machine to start. */ printf("Type Machine# to start (0 - %u) or 'quit' to do nothing: ", (unsigned)(machineCnt - 1)); fflush(stdout); if (scanf("%u", &start_id) == 1 && start_id < machineCnt) { IMachine *machine = machines[start_id]; if (machine) { BSTR uuidUtf16 = NULL; IMachine_get_Id(machine, &uuidUtf16); startVM(argv0, virtualBox, session, uuidUtf16); g_pVBoxFuncs->pfnComUnallocString(uuidUtf16); } } /* * Don't forget to release the objects in the array. */ for (i = 0; i < machineCnt; ++i) { IMachine *machine = machines[i]; if (machine) IMachine_Release(machine); } g_pVBoxFuncs->pfnArrayOutFree(machines); } /* Main - Start the ball rolling. */ int main(int argc, char **argv) { IVirtualBoxClient *vboxclient = NULL; IVirtualBox *vbox = NULL; ISession *session = NULL; ULONG revision = 0; BSTR versionUtf16 = NULL; BSTR homefolderUtf16 = NULL; HRESULT rc; /* Result code of various function (method) calls. */ (void)argc; printf("Starting main()\n"); if (VBoxCGlueInit()) { fprintf(stderr, "%s: FATAL: VBoxCGlueInit failed: %s\n", argv[0], g_szVBoxErrMsg); return EXIT_FAILURE; } { unsigned ver = g_pVBoxFuncs->pfnGetVersion(); printf("VirtualBox version: %u.%u.%u\n", ver / 1000000, ver / 1000 % 1000, ver % 1000); ver = g_pVBoxFuncs->pfnGetAPIVersion(); printf("VirtualBox API version: %u.%u\n", ver / 1000, ver % 1000); } g_pVBoxFuncs->pfnClientInitialize(NULL, &vboxclient); if (!vboxclient) { fprintf(stderr, "%s: FATAL: could not get VirtualBoxClient reference\n", argv[0]); return EXIT_FAILURE; } printf("----------------------------------------------------\n"); rc = IVirtualBoxClient_get_VirtualBox(vboxclient, &vbox); if (FAILED(rc) || !vbox) { PrintErrorInfo(argv[0], "FATAL: could not get VirtualBox reference", rc); return EXIT_FAILURE; } rc = IVirtualBoxClient_get_Session(vboxclient, &session); if (FAILED(rc) || !session) { PrintErrorInfo(argv[0], "FATAL: could not get Session reference", rc); return EXIT_FAILURE; } #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 rc = LoadTypeInfo(&IID_IEventListener, &g_pTInfoIEventListener); if (FAILED(rc) || !g_pTInfoIEventListener) { PrintErrorInfo(argv[0], "FATAL: could not get type information for IEventListener", rc); return EXIT_FAILURE; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ /* * Now ask for revision, version and home folder information of * this vbox. Were not using fancy macros here so it * remains easy to see how we access C++'s vtable. */ /* 1. Revision */ rc = IVirtualBox_get_Revision(vbox, &revision); if (SUCCEEDED(rc)) printf("\tRevision: %u\n", revision); else PrintErrorInfo(argv[0], "GetRevision() failed", rc); /* 2. Version */ rc = IVirtualBox_get_Version(vbox, &versionUtf16); if (SUCCEEDED(rc)) { char *version = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(versionUtf16, &version); printf("\tVersion: %s\n", version); g_pVBoxFuncs->pfnUtf8Free(version); g_pVBoxFuncs->pfnComUnallocString(versionUtf16); } else PrintErrorInfo(argv[0], "GetVersion() failed", rc); /* 3. Home Folder */ rc = IVirtualBox_get_HomeFolder(vbox, &homefolderUtf16); if (SUCCEEDED(rc)) { char *homefolder = NULL; g_pVBoxFuncs->pfnUtf16ToUtf8(homefolderUtf16, &homefolder); printf("\tHomeFolder: %s\n", homefolder); g_pVBoxFuncs->pfnUtf8Free(homefolder); g_pVBoxFuncs->pfnComUnallocString(homefolderUtf16); } else PrintErrorInfo(argv[0], "GetHomeFolder() failed", rc); listVMs(argv[0], vbox, session); ISession_UnlockMachine(session); printf("----------------------------------------------------\n"); /* * Do as mom told us: always clean up after yourself. */ #ifdef USE_ACTIVE_EVENT_LISTENER # ifdef WIN32 if (g_pTInfoIEventListener) { ITypeInfo_Release(g_pTInfoIEventListener); g_pTInfoIEventListener = NULL; } # endif /* WIN32 */ #endif /* USE_ACTIVE_EVENT_LISTENER */ if (session) { ISession_Release(session); session = NULL; } if (vbox) { IVirtualBox_Release(vbox); vbox = NULL; } if (vboxclient) { IVirtualBoxClient_Release(vboxclient); vboxclient = NULL; } g_pVBoxFuncs->pfnClientUninitialize(); VBoxCGlueTerm(); printf("Finished main()\n"); return 0; } /* vim: set ts=4 sw=4 et: */
ARL-UTEP-OC/emubox
workshop-manager/bin/VirtualBoxSDK-5.1.20-114628/sdk/bindings/c/samples/tstCAPIGlue.c
C
gpl-2.0
39,034
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.graphics3d.polyhedron.MaestroIcosahedron</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.graphics3d-module.html">Package&nbsp;graphics3d</a> :: <a href="schrodinger.graphics3d.polyhedron-module.html">Module&nbsp;polyhedron</a> :: Class&nbsp;MaestroIcosahedron </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class MaestroIcosahedron</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="object-class.html">object</a> --+ | <a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a> --+ | <a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a> --+ | <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a> --+ | <strong class="uidshort">MaestroIcosahedron</strong> </pre> <dl><dt>Known Subclasses:</dt> <dd> <ul class="subclass-list"> <li><a href="schrodinger.graphics3d.polyhedron.Icosahedron-class.html">Icosahedron</a></li> </ul> </dd></dl> <hr /> <p>Class to draw a 3D icosahedron in Maestro's Workspace.</p> <p>See <a href="schrodinger.graphics3d.polyhedron.Tetrahedron-class.html" class="link">Tetrahedron</a> doc string for more details.</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">center</span>, <span class="summary-sig-arg">mode</span>, <span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">color</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>, <span class="summary-sig-arg">opacity</span>=<span class="summary-sig-default">1.0</span>, <span class="summary-sig-arg">style</span>=<span class="summary-sig-default">1</span>)</span><br /> Create a polyhedron centered at <code>center</code>.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#getVertices" class="summary-sig-name">getVertices</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">center</span>, <span class="summary-sig-arg">length</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">radius</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">volume</span>=<span class="summary-sig-default">None</span>)</span><br /> Get a list of vertices.</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html#getIndices" class="summary-sig-name">getIndices</a>(<span class="summary-sig-arg">self</span>)</span><br /> @return The indices of the faces</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getFaces">getFaces</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#updateVertices">updateVertices</a></code> </p> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html">MaestroPolyhedronCore</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#_checkSizeArgs" onclick="show_private();">_checkSizeArgs</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#_handleOpenGLLevelChange" onclick="show_private();">_handleOpenGLLevelChange</a></code> </p></div> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#setStyle">setStyle</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#update">update</a></code> </p> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_calculateBoundingBox" onclick="show_private();">_calculateBoundingBox</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_draw" onclick="show_private();">_draw</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_setNormals" onclick="show_private();">_setNormals</a></code> </p></div> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.common.Primitive-class.html">common.Primitive</a></code></b>: <code><a href="schrodinger.graphics3d.common.Primitive-class.html#__del__">__del__</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupHidden">groupHidden</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#groupShown">groupShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#hide">hide</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#isGroupShown">isGroupShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#isShown">isShown</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#setEntryID">setEntryID</a></code>, <code><a href="schrodinger.graphics3d.common.Primitive-class.html#show">show</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__delattr__">__delattr__</a></code>, <code><a href="object-class.html#__format__">__format__</a></code>, <code><a href="object-class.html#__getattribute__">__getattribute__</a></code>, <code><a href="object-class.html#__hash__">__hash__</a></code>, <code><a href="object-class.html#__new__">__new__</a></code>, <code><a href="object-class.html#__reduce__">__reduce__</a></code>, <code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>, <code><a href="object-class.html#__repr__">__repr__</a></code>, <code><a href="object-class.html#__setattr__">__setattr__</a></code>, <code><a href="object-class.html#__sizeof__">__sizeof__</a></code>, <code><a href="object-class.html#__str__">__str__</a></code>, <code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code> </p> </td> </tr> </table> <!-- ==================== STATIC METHODS ==================== --> <a name="section-StaticMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Static Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-StaticMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glReset" onclick="show_private();">_glReset</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_glSetup" onclick="show_private();">_glSetup</a></code> </p></div> </td> </tr> </table> <!-- ==================== CLASS VARIABLES ==================== --> <a name="section-ClassVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Class Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-ClassVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <div class="private"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b> (private): <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_blend" onclick="show_private();">_blend</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_cull" onclick="show_private();">_cull</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting" onclick="show_private();">_lighting</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_lighting_model" onclick="show_private();">_lighting_model</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_polygon_mode" onclick="show_private();">_polygon_mode</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_shading_model" onclick="show_private();">_shading_model</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#_smooth_point" onclick="show_private();">_smooth_point</a></code> </p></div> </td> </tr> </table> <!-- ==================== INSTANCE VARIABLES ==================== --> <a name="section-InstanceVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html">Polyhedron</a></code></b>: <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#faces">faces</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#normals">normals</a></code>, <code><a href="schrodinger.graphics3d.polyhedron.Polyhedron-class.html#vertices">vertices</a></code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__class__">__class__</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">center</span>, <span class="sig-arg">mode</span>, <span class="sig-arg">length</span>=<span class="sig-default">None</span>, <span class="sig-arg">radius</span>=<span class="sig-default">None</span>, <span class="sig-arg">volume</span>=<span class="sig-default">None</span>, <span class="sig-arg">color</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">red</code><code class="variable-quote">'</code></span>, <span class="sig-arg">opacity</span>=<span class="sig-default">1.0</span>, <span class="sig-arg">style</span>=<span class="sig-default">1</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Create a polyhedron centered at <code>center</code>. Note that one of <code>length</code>, <code>radius</code>, <code>volume</code> is needed to create the shape.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>center</code></strong> - List of 3 Angstrom values indicating the center coordinate of the tetrahedron.</li> <li><strong class="pname"><code>length</code></strong> - Length in Angstroms of each of the edges of the tetrahedron.</li> <li><strong class="pname"><code>radius</code></strong> - Circumsphere radius in Angstroms from center of tetrahedron.</li> <li><strong class="pname"><code>volume</code></strong> - Volume in cubed Angstroms of the object.</li> <li><strong class="pname"><code>color</code></strong> - One of - Color object, Color name (string), or Tuple of (R, G, B) (each 0.0-1.0)</li> <li><strong class="pname"><code>opacity</code></strong> - 0.0 (invisible) through 1.0 (opaque). Defaults to 1.0</li> <li><strong class="pname"><code>style</code></strong> - LINE or FILL. Default is FILL.</li> </ul></dd> <dt>Raises:</dt> <dd><ul class="nomargin-top"> <li><code><strong class='fraise'>RuntimeError</strong></code> - If a single option from <code>length</code>, <code>radius</code>, and <code>volume</code> does not have a value.</li> <li><code><strong class='fraise'>ValueError</strong></code> - If the size parameter (<code>length</code>, <code>radius</code>, or <code>volume</code>) is not a float.</li> <li><code><strong class='fraise'>NotImplementedError</strong></code> - If the initiating subclass does not have a <code>getVertices</code> or <code>getFaces</code> method.</li> </ul></dd> <dt>Overrides: object.__init__ </dt> </dl> <div class="fields"> <p><strong>See Also:</strong> <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#__init__" class="link">MaestroPolyhedronCore.__init__</a> </p> </div></td></tr></table> </div> <a name="getVertices"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getVertices</span>(<span class="sig-arg">self</span>, <span class="sig-arg">center</span>, <span class="sig-arg">length</span>=<span class="sig-default">None</span>, <span class="sig-arg">radius</span>=<span class="sig-default">None</span>, <span class="sig-arg">volume</span>=<span class="sig-default">None</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>Get a list of vertices. If the center coordinates are considered the origin the vertices will have a base on the y-plane, a vertex on the x-axis and a vertex directly in the +z-axis from the <code>center</code>.</p> <dl class="fields"> <dt>Parameters:</dt> <dd><ul class="nomargin-top"> <li><strong class="pname"><code>center</code></strong> (List) - List of 3 Angstrom values indicating the center coordinate of the icosahedron.</li> <li><strong class="pname"><code>length</code></strong> (float) - Length in Angstroms of each of the sides of the icosahedron. Note: <code>length</code> or <code>radius</code> must be specified to create icosahedron.</li> <li><strong class="pname"><code>radius</code></strong> (float) - Circumsphere radius in Angstroms from center of icosahedron. Note: <code>length</code> or <code>radius</code> must be specified to create icosahedron.</li> <li><strong class="pname"><code>volume</code></strong> (float) - Volume in cubed Angstroms of the object.</li> </ul></dd> <dt>Overrides: <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getVertices">MaestroPolyhedronCore.getVertices</a> </dt> </dl> </td></tr></table> </div> <a name="getIndices"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getIndices</span>(<span class="sig-arg">self</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>@return The indices of the faces</p> <dl class="fields"> <dt>Overrides: <a href="schrodinger.graphics3d.polyhedron.MaestroPolyhedronCore-class.html#getIndices">MaestroPolyhedronCore.getIndices</a> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat May 9 06:31:22 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2015-2_docs/python_api/api/schrodinger.graphics3d.polyhedron.MaestroIcosahedron-class.html
HTML
gpl-2.0
25,072
#!/usr/bin/env python """ Grid time ============= """ from datetime import timedelta import numpy as np from opendrift.readers import reader_global_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift # Seeding at a grid at regular interval o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') #%% # Landmask reader_landmask = reader_global_landmask.Reader( extent=[4.0, 5.5, 59.9, 61.2]) o.add_reader([reader_landmask, reader_norkyst]) #%% # Seeding some particles lons = np.linspace(4.4, 4.6, 10) lats = np.linspace(60.0, 60.1, 10) lons, lats = np.meshgrid(lons, lats) lons = lons.ravel() lats = lats.ravel() #%% # Seed oil elements on a grid at regular time interval start_time = reader_norkyst.start_time time_step = timedelta(hours=6) num_steps = 10 for i in range(num_steps+1): o.seed_elements(lons, lats, radius=0, number=100, time=start_time + i*time_step) #%% # Running model for 60 hours o.run(steps=60*4, time_step=900, time_step_output=3600) #%% # Print and plot results print(o) o.animation(fast=True) #%% # .. image:: /gallery/animations/example_grid_time_0.gif
OpenDrift/opendrift
examples/example_grid_time.py
Python
gpl-2.0
1,348
/* * setting.h * * Created on: 2015. 2. 3. * Author: asran */ #ifndef INCLUDE_SETTING_H_ #define INCLUDE_SETTING_H_ //#define MATRIX //#define MATRIX_CSR //#define MATRIX_VECTOR #define MATRIX_MAP #define COL_SIZE (1000) #define ROW_SIZE (1000) #define VAL_RANGE_START (1) #define VAL_RANGE_END (10) #define VAL_PER_COL (6) #ifdef MATRIX #include <matrix.h> typedef matrix::Matrix matrix_t; #define TEST_MULTI_THREAD (0) #endif #ifdef MATRIX_CSR #include <matrix_csr.h> typedef matrix::MatrixCSR matrix_t; #define TEST_MULTI_THREAD (0) #endif #ifdef MATRIX_MAP #include <sparse_matrix2.h> typedef matrix::SparseMatrix2 matrix_t; #define TEST_MULTI_THREAD (1) #endif #ifdef MATRIX_VECTOR #include <sparse_matrix.h> typedef matrix::SparseMatrix matrix_t; #define TEST_MULTI_THREAD (1) #endif #include "matrix_error.h" #endif /* INCLUDE_SETTING_H_ */
kim5257/matrix
matrix_example09/include/setting.h
C
gpl-2.0
906
/* * Copyright (C) 1997 by Stephan Kulow <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA. * */ #ifndef KTIMETRACKER_TASK_H #define KTIMETRACKER_TASK_H #include "desktoplist.h" // Required b/c DesktopList is a typedef not a class. #include "taskview.h" // Required b/c of static cast below. #include <KCalCore/Todo> #include <QDateTime> #include <QPixmap> #include <QVector> class QObject; class QPixmap; class QString; class timetrackerstorage; /** \brief A class representing a task * * A "Task" object stores information about a task such as it's name, * total and session times. * * It can log when the task is started, stoped or deleted. * * If a task is associated with some desktop's activity it can remember that * too. * * It can also contain subtasks - these are managed using the * QListViewItem class. */ class Task : public QObject, public QTreeWidgetItem { Q_OBJECT public: Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime, DesktopList desktops, TaskView* parent = 0, bool konsolemode=false ); Task( const QString& taskname, const QString& taskdescription, long minutes, long sessionTime, DesktopList desktops, Task* parent = 0); Task( const KCalCore::Todo::Ptr &incident, TaskView* parent, bool konsolemode=false ); /* destructor */ ~Task(); /** return parent Task or null in case of TaskView. * same as QListViewItem::parent() */ Task* parent() const { return (Task*)QTreeWidgetItem::parent(); } /** Return task view for this task */ TaskView* taskView() const { return static_cast<TaskView *>( treeWidget() ); } /** Return unique iCalendar Todo ID for this task. */ QString uid() const; int depth(); void delete_recursive(); /** * Set unique id for the task. * * The uid is the key used to update the storage. * * @param uid The new unique id. */ void setUid( const QString &uid ); /** cut Task out of parent Task or the TaskView */ void cut(); /** cut Task out of parent Task or the TaskView and into the * destination Task */ void move(Task* destination); /** insert Task into the destination Task */ void paste(Task* destination); //@{ timing related functions /** * Change task time. Adds minutes to both total time and session time by adding an event. * * @param minutes minutes to add to - may be negative * @param storage Pointer to timetrackerstorage instance. * If zero, don't save changes. */ void changeTime( long minutes, timetrackerstorage* storage ); /** * Add minutes to time and session time by adding an event, and write to storage. * * @param minutesSession minutes to add to task session time * @param minutes minutes to add to task time * @param storage Pointer to timetrackerstorage instance. * If zero, don't save changes. */ void changeTimes ( long minutesSession, long minutes, timetrackerstorage* storage=0 ); /** adds minutes to total and session time by adding an event * * @param minutesSession minutes to add to task total session time * @param minutes minutes to add to task total time */ void changeTotalTimes( long minutesSession, long minutes ); /** Adds minutes to the time of the task and the total time of its supertasks. This does not add an event. * * @param minutes minutes to add to the time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTime( long minutes ); /** Adds minutes to the total time of the task and its supertasks. This does not add an event. * * @param minutes minutes to add to the time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTotalTime( long minutes ); /** Adds minutes to the task's session time and its supertasks' total session time. This does not add an event. * * @param minutes minutes to add to the session time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addSessionTime( long minutes ); /** Adds minutes to the task's and its supertasks' total session time. This does not add an event. * * @param minutes minutes to add to the session time * @returns A QString with the error message, in case of no error an empty QString. * */ QString addTotalSessionTime( long minutes ); /** Sets the time (not session time). This does not add an event. * * @param minutes minutes to set time to * */ QString setTime( long minutes ); /** Sets the total time, does not change the parent's total time. This means the parent's total time can run out of sync. */ void setTotalTime( long minutes ) { mTotalTime=minutes; }; /** Sets the total session time, does not change the parent's total session time. This means the parent's total session time can run out of sync. */ void setTotalSessionTime( long minutes ) { mTotalSessionTime=minutes; }; /** A recursive function to calculate the total time of a task. */ QString recalculatetotaltime(); /** A recursive function to calculate the total session time of a task. */ QString recalculatetotalsessiontime(); /** Sets the session time. * Set the session time without changing totalTime nor sessionTime. * Do not change the parent's totalTime. * Do not add an event. * See also: changeTimes(long, long) and resetTimes * * @param minutes minutes to set session time to * */ QString setSessionTime( long minutes ); /** * Reset all times to 0 and adjust parent task's totalTiMes. */ void resetTimes(); /** @return time in minutes */ long time() const; /** @return total time in minutes */ long totalTime() const { return mTotalTime; }; long sessionTime() const; long totalSessionTime() const { return mTotalSessionTime; }; KDateTime sessionStartTiMe() const; /** * Return time the task was started. */ QDateTime startTime() const; /** sets session time to zero. */ void startNewSession(); //@} //@{ desktop related functions void setDesktopList ( DesktopList dl ); DesktopList desktops() const; QString getDesktopStr() const; //@} //@{ name related functions /** sets the name of the task * @param name a pointer to the name. A deep copy will be made. * @param storage a pointer to a timetrackerstorage object. */ void setName( const QString& name, timetrackerstorage* storage ); /** sets the description of the task */ void setDescription( const QString& description); /** returns the name of this task. * @return a pointer to the name. */ QString name() const; /** returns the description of this task. * @return a pointer to the description. */ QString description() const; /** * Returns that task name, prefixed by parent tree up to root. * * Task names are separated by a forward slash: / */ QString fullName() const; //@} /** Update the display of the task (all columns) in the UI. */ void update(); //@{ the state of a Task - stopped, running /** starts or stops a task * @param on true or false for starting or stopping a task * @param storage a pointer to a timetrackerstorage object. * @param when time when the task was started or stopped. Normally QDateTime::currentDateTime, but if calendar has been changed by another program and being reloaded the task is set to running with another start date */ void setRunning( bool on, timetrackerstorage* storage, const QDateTime &when = QDateTime::currentDateTime() ); /** Resume the running state of a task. * This is the same as setrunning, but the storage is not modified. */ void resumeRunning(); /** return the state of a task - if it's running or not * @return true or false depending on whether the task is running */ bool isRunning() const; //@} /** * Parses an incidence. This is needed e.g. when you create a task out of a todo. * You read the todo, extract its custom properties (like session time) * and use these data to initialize the task. */ bool parseIncidence( const KCalCore::Incidence::Ptr &, long& sessionMinutes); /** * Load the todo passed in with this tasks info. */ KCalCore::Todo::Ptr asTodo(KCalCore::Todo::Ptr &calendar) const; /** * Set a task's description * A description is a comment. */ void setDescription( QString desc, timetrackerstorage* storage ); /** * Add a comment to this task. * A comment is called "description" in the context of KCalCore::ToDo */ void addComment( const QString &comment, timetrackerstorage* storage ); /** Retrieve the entire comment for the task. */ QString comment() const; /** tells you whether this task is the root of the task tree */ bool isRoot() const { return parent() == 0; } /** remove Task with all it's children * @param storage a pointer to a timetrackerstorage object. */ bool remove( timetrackerstorage* storage ); /** * Update percent complete for this task. * * Tasks that are complete (i.e., percent = 100) do not show up in * taskview. If percent NULL, set to zero. If greater than 100, set to * 100. If less than zero, set to zero. */ void setPercentComplete(const int percent, timetrackerstorage *storage); int percentComplete() const; /** * Update priority for this task. * * Priority is allowed from 0 to 9. 0 unspecified, 1 highest and 9 lowest. */ void setPriority( int priority ); int priority() const; /** Sets an appropriate icon for this task based on its level of * completion */ void setPixmapProgress(); /** Return true if task is complete (percent complete equals 100). */ bool isComplete(); protected: void changeParentTotalTimes( long minutesSession, long minutes ); Q_SIGNALS: void totalTimesChanged( long minutesSession, long minutes); /** signal that we're about to delete a task */ void deletingTask(Task* thisTask); protected Q_SLOTS: /** animate the active icon */ void updateActiveIcon(); private: // Original KCalCore::Todo object KCalCore::Todo::Ptr taskTodo; /** if the time or session time is negative set them to zero */ void noNegativeTimes(); /** populate a ToDo with provided data */ void populateTodo(const QString& taskName, const QString& taskDescription, long minutes, long sessionTime, DesktopList desktops); /** initialize a task */ void init(bool konsolemode=false); static QVector<QPixmap*> *icons; /** Last time this task was started. */ QDateTime mLastStart; /** totals of the whole subtree including self */ long mTotalTime; long mTotalSessionTime; QTimer *mTimer; int mCurrentPic; /** Don't need to update storage when deleting task from list. */ bool mRemoving; }; #endif // KTIMETRACKER_TASK_H
chusopr/kdepim-ktimetracker-akonadi
ktimetracker/task.h
C
gpl-2.0
12,760
# ###### # CONFIG ROOTPWD="1234" USERNAME="cubie" USERPASS="1234" ########################### #Main Section ########################### if [[ $EUID -ne 0 ]]; then echo "You must be a root user" 2>&1 exit 1 fi useradd -m -U -d /home/$USERNAME -s /bin/bash $USERNAME # set User password to 1234 (echo $USERPASS;echo $USERPASS;) | passwd $USERNAME # Do NOT force password change upon first login as it will prevent autologin :( adduser $USERNAME sudo DEST_LANG="en_US" DEST_LANGUAGE="en" echo -e $DEST_LANG'.UTF-8 UTF-8\n' >> /etc/locale.gen echo -e 'fr_FR.UTF-8 UTF-8\n' >> /etc/locale.gen echo -e 'LANG="'$DEST_LANG'.UTF-8"\nLANGUAGE="'$DEST_LANG':'$DEST_LANGUAGE'"\n' > /etc/default/locale dpkg-reconfigure -f noninteractive locales update-locale # Setup apt-sources sourcesFile="/etc/apt/sources.list" rm $sourcesFile touch $sourcesFile #Get all info running : sudo netselect-apt -a armhf -n -s -c fr jessie # Or : sudo netselect-apt -a armhf -n -s -c fr wheezy #Edit output file to add wheezy updates and uncomment security + backports #Jessie echo "# Debian packages for Jessie" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ jessie main contrib non-free" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ jessie-updates main contrib non-free" >> $sourcesFile echo "#Security updates for stable" >> $sourcesFile echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile echo "deb http://ftp.debian.org/debian/ jessie-backports main contrib non-free" >> $sourcesFile # Wheezy echo "# Debian packages for wheezy" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ wheezy main contrib non-free" >> $sourcesFile echo "deb http://debian.mirrors.ovh.net/debian/ wheezy-updates main contrib non-free" >> $sourcesFile echo "#Security updates for stable" >> $sourcesFile echo "deb http://security.debian.org/ stable/updates main contrib non-free" >> $sourcesFile echo "deb http://ftp.debian.org/debian/ wheezy-backports main contrib non-free" >> $sourcesFile apt-get update #Change Timezones echo "Europe/Paris" > /etc/timezone dpkg-reconfigure -f noninteractive tzdata #UnusedTo configure keyboard : #apt-get install console-data # Install packages #Put all packages here :) INSTPKG="hdparm hddtemp console-setup console-data netselect-apt" INSTPKG+=" bash-completion parted cpufrequtils unzip mosh" INSTPKG+=" vim tmux htop sudo locate tree ncdu toilet figlet git mosh" INSTPKG+=" xorg ttf-mscorefonts-installer openbox xterm xinit obconf xscreensaver xscreensaver-gl menu obmenu" INSTPKG+=" lightdm iceweasel x11vnc" echo $INSTPKG apt-get -y upgrade export DEBIAN_FRONTEND=noninteractive; apt-get -y install $INSTPKG #For wheezy only export DEBIAN_FRONTEND=noninteractive; apt-get -y install -t wheezy-backports $INSTPKG #Disable Sshd root login #sed -e "s/PermitRootLogin no/PermitRootLogin yes/g" -i /etc/ssh/sshd_config # Overclock - DANGER #sudo sed -i "s/echo -n 1100000/echo -n 1008000/g" /etc/init.d/cpufrequtils # Install RAMLOG - No ramlog in Jessie #dpkg -i /tmp/ramlog_2.0.0_all.deb #if ! grep -q "TMPFS_RAMFS_SIZE=256m" /etc/default/ramlog; then # sed -e 's/TMPFS_RAMFS_SIZE=/TMPFS_RAMFS_SIZE=256m/g' -i /etc/default/ramlog # sed -e 's/# Required-Start: $remote_fs $time/# Required-Start: $remote_fs $time ramlog/g' -i /etc/init.d/rsyslog # sed -e 's/# Required-Stop: umountnfs $time/# Required-Stop: umountnfs $time ramlog/g' -i /etc/init.d/rsyslog #fi #rm /tmp/ramlog_2.0.0_all.deb #insserv # Cleanup APT apt-get -y clean # set root password to 1234 (echo $ROOTPWD;echo $ROOTPWD;) | passwd root # force password change upon first login chage -d 0 root #Configure Xserver autostart dpkg-reconfigure keyboard-configuration adduser $USERNAME video if ! grep -q $USERNAME /etc/lightdm/lightdm.conf; then sed -i "s/#autologin-user=/autologin-user=$USERNAME/g" /etc/lightdm/lightdm.conf sed -i "s/#autologin-user-timeout=0/autologin-user-timeout=0/g" /etc/lightdm/lightdm.conf fi #To enable connexion using crontab on DISPLAY :0.0 sed -i "s/xserver-allow-tcp=false/xserver-allow-tcp=true/g" /etc/lightdm/lightdm.conf mkdir -p /home/$USERNAME/.config/openbox echo "xhost +localhost &" > /home/$USERNAME/.config/openbox/autostart echo "setxkbmap fr &" >> /home/$USERNAME/.config/openbox/autostart echo "xterm -e '/sbin/ifconfig eth0 && read a' &" >> /home/$USERNAME/.config/openbox/autostart echo "xset -dpms &" >> /home/$USERNAME/.config/openbox/autostart echo "xset s noblank;xset s 0 0;xset s off" >> /home/$USERNAME/.config/openbox/autostart chown -R $USERNAME:$USERNAME /home/$USERNAME/.config/openbox/autostart chmod 755 /home/$USERNAME/.config/openbox/autostart #Setup tmpfs for firefox profiles - All profiles will be in RAMDISK mkdir -p /home/$USERNAME/.mozilla/firefox/ chown -R $USERNAME:$USERNAME /home/cubie/.mozilla/firefox mkdir -p /media/ramdrive if ! grep -q ramdrive /etc/fstab then echo "adding line to fstab" echo 'ramdrive /media/ramdrive tmpfs size=225M,user,auto,exec,rw 0 0' | tee -a /etc/fstab mount -a fi #Screensaver & Screen blanking stuff #export DISPLAY=":0.0" #xset -dpms xset s noblank;xset s 0 0;xset s off #xset + dpms #A inverser pour les xset s #xset s activate #xset s reset #xset dpms force on off suspend standby #For Cubie2 Jessie #Config export DISPLAY=":0.0" xhost +localhost & xset s off xset -dpms #Turn Off xset dpms force off #Turn On reboot #For rpi2 (some commands need root others don't) #https://www.freshrelevance.com/blog/server-monitoring-with-a-raspberry-pi-and-graphite #config export DISPLAY=":0.0" xhost +localhost & xset s off xset -dpms #Turn off tvservice --off > /dev/null #Turn on tvservice --preferred > /dev/null fbset -depth 8; fbset -depth 16; xrefresh
gargamel007/SimpleCarousel
jessieCarousel.sh
Shell
gpl-2.0
6,004