code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2008 Maxime Bizon <mbizon@freebox.fr> * Copyright (C) 2009 Florian Fainelli <florian@openwrt.org> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/cpu.h> #include <asm/cpu.h> #include <asm/cpu-info.h> #include <asm/mipsregs.h> #include <bcm63xx_cpu.h> #include <bcm63xx_regs.h> #include <bcm63xx_io.h> #include <bcm63xx_irq.h> const unsigned long *bcm63xx_regs_base; EXPORT_SYMBOL(bcm63xx_regs_base); const int *bcm63xx_irqs; EXPORT_SYMBOL(bcm63xx_irqs); static u16 bcm63xx_cpu_id; static u16 bcm63xx_cpu_rev; static unsigned int bcm63xx_cpu_freq; static unsigned int bcm63xx_memory_size; static const unsigned long bcm6338_regs_base[] = { __GEN_CPU_REGS_TABLE(6338) }; static const int bcm6338_irqs[] = { __GEN_CPU_IRQ_TABLE(6338) }; static const unsigned long bcm6345_regs_base[] = { __GEN_CPU_REGS_TABLE(6345) }; static const int bcm6345_irqs[] = { __GEN_CPU_IRQ_TABLE(6345) }; static const unsigned long bcm6348_regs_base[] = { __GEN_CPU_REGS_TABLE(6348) }; static const int bcm6348_irqs[] = { __GEN_CPU_IRQ_TABLE(6348) }; static const unsigned long bcm6358_regs_base[] = { __GEN_CPU_REGS_TABLE(6358) }; static const int bcm6358_irqs[] = { __GEN_CPU_IRQ_TABLE(6358) }; static const unsigned long bcm6368_regs_base[] = { __GEN_CPU_REGS_TABLE(6368) }; static const int bcm6368_irqs[] = { __GEN_CPU_IRQ_TABLE(6368) }; u16 __bcm63xx_get_cpu_id(void) { return bcm63xx_cpu_id; } EXPORT_SYMBOL(__bcm63xx_get_cpu_id); u16 bcm63xx_get_cpu_rev(void) { return bcm63xx_cpu_rev; } EXPORT_SYMBOL(bcm63xx_get_cpu_rev); unsigned int bcm63xx_get_cpu_freq(void) { return bcm63xx_cpu_freq; } unsigned int bcm63xx_get_memory_size(void) { return bcm63xx_memory_size; } static unsigned int detect_cpu_clock(void) { switch (bcm63xx_get_cpu_id()) { case BCM6338_CPU_ID: return 240000000; case BCM6345_CPU_ID: return 140000000; case BCM6348_CPU_ID: { unsigned int tmp, n1, n2, m1; tmp = bcm_perf_readl(PERF_MIPSPLLCTL_REG); n1 = (tmp & MIPSPLLCTL_N1_MASK) >> MIPSPLLCTL_N1_SHIFT; n2 = (tmp & MIPSPLLCTL_N2_MASK) >> MIPSPLLCTL_N2_SHIFT; m1 = (tmp & MIPSPLLCTL_M1CPU_MASK) >> MIPSPLLCTL_M1CPU_SHIFT; n1 += 1; n2 += 2; m1 += 1; return (16 * 1000000 * n1 * n2) / m1; } case BCM6358_CPU_ID: { unsigned int tmp, n1, n2, m1; tmp = bcm_ddr_readl(DDR_DMIPSPLLCFG_REG); n1 = (tmp & DMIPSPLLCFG_N1_MASK) >> DMIPSPLLCFG_N1_SHIFT; n2 = (tmp & DMIPSPLLCFG_N2_MASK) >> DMIPSPLLCFG_N2_SHIFT; m1 = (tmp & DMIPSPLLCFG_M1_MASK) >> DMIPSPLLCFG_M1_SHIFT; return (16 * 1000000 * n1 * n2) / m1; } case BCM6368_CPU_ID: { unsigned int tmp, p1, p2, ndiv, m1; tmp = bcm_ddr_readl(DDR_DMIPSPLLCFG_6368_REG); p1 = (tmp & DMIPSPLLCFG_6368_P1_MASK) >> DMIPSPLLCFG_6368_P1_SHIFT; p2 = (tmp & DMIPSPLLCFG_6368_P2_MASK) >> DMIPSPLLCFG_6368_P2_SHIFT; ndiv = (tmp & DMIPSPLLCFG_6368_NDIV_MASK) >> DMIPSPLLCFG_6368_NDIV_SHIFT; tmp = bcm_ddr_readl(DDR_DMIPSPLLDIV_6368_REG); m1 = (tmp & DMIPSPLLDIV_6368_MDIV_MASK) >> DMIPSPLLDIV_6368_MDIV_SHIFT; return (((64 * 1000000) / p1) * p2 * ndiv) / m1; } default: BUG(); } } static unsigned int detect_memory_size(void) { unsigned int cols = 0, rows = 0, is_32bits = 0, banks = 0; u32 val; if (BCMCPU_IS_6345()) { val = bcm_sdram_readl(SDRAM_MBASE_REG); return (val * 8 * 1024 * 1024); } if (BCMCPU_IS_6338() || BCMCPU_IS_6348()) { val = bcm_sdram_readl(SDRAM_CFG_REG); rows = (val & SDRAM_CFG_ROW_MASK) >> SDRAM_CFG_ROW_SHIFT; cols = (val & SDRAM_CFG_COL_MASK) >> SDRAM_CFG_COL_SHIFT; is_32bits = (val & SDRAM_CFG_32B_MASK) ? 1 : 0; banks = (val & SDRAM_CFG_BANK_MASK) ? 2 : 1; } if (BCMCPU_IS_6358() || BCMCPU_IS_6368()) { val = bcm_memc_readl(MEMC_CFG_REG); rows = (val & MEMC_CFG_ROW_MASK) >> MEMC_CFG_ROW_SHIFT; cols = (val & MEMC_CFG_COL_MASK) >> MEMC_CFG_COL_SHIFT; is_32bits = (val & MEMC_CFG_32B_MASK) ? 0 : 1; banks = 2; } rows += 11; cols += 8; return 1 << (cols + rows + (is_32bits + 1) + banks); } void __init bcm63xx_cpu_init(void) { unsigned int tmp, expected_cpu_id; struct cpuinfo_mips *c = &current_cpu_data; unsigned int cpu = smp_processor_id(); expected_cpu_id = 0; switch (c->cputype) { case CPU_BMIPS3300: if ((read_c0_prid() & 0xff00) == PRID_IMP_BMIPS3300_ALT) { expected_cpu_id = BCM6348_CPU_ID; bcm63xx_regs_base = bcm6348_regs_base; bcm63xx_irqs = bcm6348_irqs; } else { __cpu_name[cpu] = "Broadcom BCM6338"; expected_cpu_id = BCM6338_CPU_ID; bcm63xx_regs_base = bcm6338_regs_base; bcm63xx_irqs = bcm6338_irqs; } break; case CPU_BMIPS32: expected_cpu_id = BCM6345_CPU_ID; bcm63xx_regs_base = bcm6345_regs_base; bcm63xx_irqs = bcm6345_irqs; break; case CPU_BMIPS4350: switch (read_c0_prid() & 0xf0) { case 0x10: expected_cpu_id = BCM6358_CPU_ID; bcm63xx_regs_base = bcm6358_regs_base; bcm63xx_irqs = bcm6358_irqs; break; case 0x30: expected_cpu_id = BCM6368_CPU_ID; bcm63xx_regs_base = bcm6368_regs_base; bcm63xx_irqs = bcm6368_irqs; break; } break; } if (!expected_cpu_id) panic("unsupported Broadcom CPU"); tmp = bcm_perf_readl(PERF_REV_REG); bcm63xx_cpu_id = (tmp & REV_CHIPID_MASK) >> REV_CHIPID_SHIFT; bcm63xx_cpu_rev = (tmp & REV_REVID_MASK) >> REV_REVID_SHIFT; if (bcm63xx_cpu_id != expected_cpu_id) panic("bcm63xx CPU id mismatch"); bcm63xx_cpu_freq = detect_cpu_clock(); bcm63xx_memory_size = detect_memory_size(); printk(KERN_INFO "Detected Broadcom 0x%04x CPU revision %02x\n", bcm63xx_cpu_id, bcm63xx_cpu_rev); printk(KERN_INFO "CPU frequency is %u MHz\n", bcm63xx_cpu_freq / 1000000); printk(KERN_INFO "%uMB of RAM installed\n", bcm63xx_memory_size >> 20); }
jameshilliard/m8-3.4.0-gb1fa77f
arch/mips/bcm63xx/cpu.c
C
gpl-2.0
5,924
/* * Freescale PWM Register Definitions * * Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved. * Copyright 2008-2010 Freescale Semiconductor, Inc. * * 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 * * This file is created by xml file. Don't Edit it. * * Xml Revision: 1.23 * Template revision: 26195 */ #ifndef __ARCH_ARM___PWM_H #define __ARCH_ARM___PWM_H #define HW_PWM_CTRL (0x00000000) #define HW_PWM_CTRL_SET (0x00000004) #define HW_PWM_CTRL_CLR (0x00000008) #define HW_PWM_CTRL_TOG (0x0000000c) #define BM_PWM_CTRL_SFTRST 0x80000000 #define BM_PWM_CTRL_CLKGATE 0x40000000 #define BM_PWM_CTRL_PWM4_PRESENT 0x20000000 #define BM_PWM_CTRL_PWM3_PRESENT 0x10000000 #define BM_PWM_CTRL_PWM2_PRESENT 0x08000000 #define BM_PWM_CTRL_PWM1_PRESENT 0x04000000 #define BM_PWM_CTRL_PWM0_PRESENT 0x02000000 #define BP_PWM_CTRL_RSRVD1 7 #define BM_PWM_CTRL_RSRVD1 0x01FFFF80 #define BF_PWM_CTRL_RSRVD1(v) \ (((v) << 7) & BM_PWM_CTRL_RSRVD1) #define BM_PWM_CTRL_OUTPUT_CUTOFF_EN 0x00000040 #define BM_PWM_CTRL_PWM2_ANA_CTRL_ENABLE 0x00000020 #define BM_PWM_CTRL_PWM4_ENABLE 0x00000010 #define BM_PWM_CTRL_PWM3_ENABLE 0x00000008 #define BM_PWM_CTRL_PWM2_ENABLE 0x00000004 #define BM_PWM_CTRL_PWM1_ENABLE 0x00000002 #define BM_PWM_CTRL_PWM0_ENABLE 0x00000001 /* * multi-register-define name HW_PWM_ACTIVEn * base 0x00000010 * count 5 * offset 0x20 */ #define HW_PWM_ACTIVEn(n) (0x00000010 + (n) * 0x20) #define HW_PWM_ACTIVEn_SET(n) (0x00000014 + (n) * 0x20) #define HW_PWM_ACTIVEn_CLR(n) (0x00000018 + (n) * 0x20) #define HW_PWM_ACTIVEn_TOG(n) (0x0000001c + (n) * 0x20) #define BP_PWM_ACTIVEn_INACTIVE 16 #define BM_PWM_ACTIVEn_INACTIVE 0xFFFF0000 #define BF_PWM_ACTIVEn_INACTIVE(v) \ (((v) << 16) & BM_PWM_ACTIVEn_INACTIVE) #define BP_PWM_ACTIVEn_ACTIVE 0 #define BM_PWM_ACTIVEn_ACTIVE 0x0000FFFF #define BF_PWM_ACTIVEn_ACTIVE(v) \ (((v) << 0) & BM_PWM_ACTIVEn_ACTIVE) /* * multi-register-define name HW_PWM_PERIODn * base 0x00000020 * count 5 * offset 0x20 */ #define HW_PWM_PERIODn(n) (0x00000020 + (n) * 0x20) #define HW_PWM_PERIODn_SET(n) (0x00000024 + (n) * 0x20) #define HW_PWM_PERIODn_CLR(n) (0x00000028 + (n) * 0x20) #define HW_PWM_PERIODn_TOG(n) (0x0000002c + (n) * 0x20) #define BP_PWM_PERIODn_RSRVD2 25 #define BM_PWM_PERIODn_RSRVD2 0xFE000000 #define BF_PWM_PERIODn_RSRVD2(v) \ (((v) << 25) & BM_PWM_PERIODn_RSRVD2) #define BM_PWM_PERIODn_MATT_SEL 0x01000000 #define BM_PWM_PERIODn_MATT 0x00800000 #define BP_PWM_PERIODn_CDIV 20 #define BM_PWM_PERIODn_CDIV 0x00700000 #define BF_PWM_PERIODn_CDIV(v) \ (((v) << 20) & BM_PWM_PERIODn_CDIV) #define BV_PWM_PERIODn_CDIV__DIV_1 0x0 #define BV_PWM_PERIODn_CDIV__DIV_2 0x1 #define BV_PWM_PERIODn_CDIV__DIV_4 0x2 #define BV_PWM_PERIODn_CDIV__DIV_8 0x3 #define BV_PWM_PERIODn_CDIV__DIV_16 0x4 #define BV_PWM_PERIODn_CDIV__DIV_64 0x5 #define BV_PWM_PERIODn_CDIV__DIV_256 0x6 #define BV_PWM_PERIODn_CDIV__DIV_1024 0x7 #define BP_PWM_PERIODn_INACTIVE_STATE 18 #define BM_PWM_PERIODn_INACTIVE_STATE 0x000C0000 #define BF_PWM_PERIODn_INACTIVE_STATE(v) \ (((v) << 18) & BM_PWM_PERIODn_INACTIVE_STATE) #define BV_PWM_PERIODn_INACTIVE_STATE__HI_Z 0x0 #define BV_PWM_PERIODn_INACTIVE_STATE__0 0x2 #define BV_PWM_PERIODn_INACTIVE_STATE__1 0x3 #define BP_PWM_PERIODn_ACTIVE_STATE 16 #define BM_PWM_PERIODn_ACTIVE_STATE 0x00030000 #define BF_PWM_PERIODn_ACTIVE_STATE(v) \ (((v) << 16) & BM_PWM_PERIODn_ACTIVE_STATE) #define BV_PWM_PERIODn_ACTIVE_STATE__HI_Z 0x0 #define BV_PWM_PERIODn_ACTIVE_STATE__0 0x2 #define BV_PWM_PERIODn_ACTIVE_STATE__1 0x3 #define BP_PWM_PERIODn_PERIOD 0 #define BM_PWM_PERIODn_PERIOD 0x0000FFFF #define BF_PWM_PERIODn_PERIOD(v) \ (((v) << 0) & BM_PWM_PERIODn_PERIOD) #define HW_PWM_VERSION (0x000000b0) #define BP_PWM_VERSION_MAJOR 24 #define BM_PWM_VERSION_MAJOR 0xFF000000 #define BF_PWM_VERSION_MAJOR(v) \ (((v) << 24) & BM_PWM_VERSION_MAJOR) #define BP_PWM_VERSION_MINOR 16 #define BM_PWM_VERSION_MINOR 0x00FF0000 #define BF_PWM_VERSION_MINOR(v) \ (((v) << 16) & BM_PWM_VERSION_MINOR) #define BP_PWM_VERSION_STEP 0 #define BM_PWM_VERSION_STEP 0x0000FFFF #define BF_PWM_VERSION_STEP(v) \ (((v) << 0) & BM_PWM_VERSION_STEP) #endif /* __ARCH_ARM___PWM_H */
marek-g/kobo-kernel-2.6.35.3-marek
arch/arm/mach-mx23/include/mach/regs-pwm.h
C
gpl-2.0
4,960
#include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/vmalloc.h> #include <linux/platform_device.h> #include <linux/miscdevice.h> #include <linux/wait.h> #include <linux/spinlock.h> #include <linux/ctype.h> #include <linux/semaphore.h> #include <asm/uaccess.h> #include <asm/io.h> #include <linux/workqueue.h> #include <linux/switch.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/kdev_t.h> #include <linux/fs.h> #include <linux/cdev.h> #include <asm/uaccess.h> #include <linux/kthread.h> #include <linux/input.h> #include <linux/wakelock.h> #include <linux/time.h> #include <linux/string.h> #include <mach/mt_typedefs.h> #include <mach/mt_reg_base.h> #include <mach/irqs.h> #include <mach/reg_accdet.h> #include <accdet_custom.h> #include <accdet_custom_def.h> /*---------------------------------------------------------------------- IOCTL ----------------------------------------------------------------------*/ #define ACCDET_DEVNAME "accdet" #define ACCDET_IOC_MAGIC 'A' #define ACCDET_INIT _IO(ACCDET_IOC_MAGIC,0) #define SET_CALL_STATE _IO(ACCDET_IOC_MAGIC,1) #define GET_BUTTON_STATUS _IO(ACCDET_IOC_MAGIC,2) /*define for phone call state*/ #define CALL_IDLE 0 #define CALL_RINGING 1 #define CALL_ACTIVE 2 #define KEY_CALL KEY_SEND #define KEY_ENDCALL KEY_HANGEUL /**************************************************** globle ACCDET variables ****************************************************/ enum accdet_report_state { NO_DEVICE =0, HEADSET_MIC = 1, HEADSET_NO_MIC = 2, //HEADSET_ILEGAL = 3, //DOUBLE_CHECK_TV = 4 }; enum accdet_status { PLUG_OUT = 0, MIC_BIAS = 1, //DOUBLE_CHECK = 2, HOOK_SWITCH = 2, //MIC_BIAS_ILLEGAL =3, //TV_OUT = 5, STAND_BY =4 }; char *accdet_status_string[5]= { "Plug_out", "Headset_plug_in", //"Double_check", "Hook_switch", //"Tvout_plug_in", "Stand_by" }; char *accdet_report_string[4]= { "No_device", "Headset_mic", "Headset_no_mic", //"HEADSET_illegal", // "Double_check" }; enum hook_switch_result { DO_NOTHING =0, ANSWER_CALL = 1, REJECT_CALL = 2 }; /* typedef enum { TVOUT_STATUS_OK = 0, TVOUT_STATUS_ALREADY_SET, TVOUT_STATUS_ERROR, } TVOUT_STATUS; */
rimistri/mediatek
mt6592/mediatek/platform/mt6592/kernel/drivers/accdet/accdet.h
C
gpl-2.0
2,410
/* * SoftDog: A Software Watchdog Device * * (c) Copyright 1996 Alan Cox <alan@lxorguk.ukuu.org.uk>, * All Rights Reserved. * * 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. * * Neither Alan Cox nor CymruNet Ltd. admit liability nor provide * warranty for any of this software. This material is provided * "AS-IS" and at no charge. * * (c) Copyright 1995 Alan Cox <alan@lxorguk.ukuu.org.uk> * * Software only watchdog driver. Unlike its big brother the WDT501P * driver this won't always recover a failed machine. * * 03/96: Angelo Haritsis <ah@doc.ic.ac.uk> : * Modularised. * Added soft_margin; use upon insmod to change the timer delay. * NB: uses same minor as wdt (WATCHDOG_MINOR); we could use separate * minors. * * 19980911 Alan Cox * Made SMP safe for 2.3.x * * 20011127 Joel Becker (jlbec@evilplan.org> * Added soft_noboot; Allows testing the softdog trigger without * requiring a recompile. * Added WDIOC_GETTIMEOUT and WDIOC_SETTIMOUT. * * 20020530 Joel Becker <joel.becker@oracle.com> * Added Matt Domsch's nowayout module option. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/timer.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/jiffies.h> #include <linux/kernel.h> #define TIMER_MARGIN 60 static unsigned int soft_margin = TIMER_MARGIN; module_param(soft_margin, uint, 0); MODULE_PARM_DESC(soft_margin, "Watchdog soft_margin in seconds. (0 < soft_margin < 65536, default=" __MODULE_STRING(TIMER_MARGIN) ")"); static bool nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, bool, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); static int soft_noboot = 0; module_param(soft_noboot, int, 0); MODULE_PARM_DESC(soft_noboot, "Softdog action, set to 1 to ignore reboots, 0 to reboot (default=0)"); static int soft_panic; module_param(soft_panic, int, 0); MODULE_PARM_DESC(soft_panic, "Softdog action, set to 1 to panic, 0 to reboot (default=0)"); static void watchdog_fire(unsigned long); static struct timer_list watchdog_ticktock = TIMER_INITIALIZER(watchdog_fire, 0, 0); static void watchdog_fire(unsigned long data) { if (soft_noboot) pr_crit("Triggered - Reboot ignored\n"); else if (soft_panic) { pr_crit("Initiating panic\n"); panic("Software Watchdog Timer expired"); } else { pr_crit("Initiating system reboot\n"); emergency_restart(); pr_crit("Reboot didn't ?????\n"); } } static int softdog_ping(struct watchdog_device *w) { mod_timer(&watchdog_ticktock, jiffies+(w->timeout*HZ)); return 0; } static int softdog_stop(struct watchdog_device *w) { del_timer(&watchdog_ticktock); return 0; } static int softdog_set_timeout(struct watchdog_device *w, unsigned int t) { w->timeout = t; return 0; } static int softdog_notify_sys(struct notifier_block *this, unsigned long code, void *unused) { if (code == SYS_DOWN || code == SYS_HALT) softdog_stop(NULL); return NOTIFY_DONE; } static struct notifier_block softdog_notifier = { .notifier_call = softdog_notify_sys, }; static struct watchdog_info softdog_info = { .identity = "Software Watchdog", .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, }; static struct watchdog_ops softdog_ops = { .owner = THIS_MODULE, .start = softdog_ping, .stop = softdog_stop, .ping = softdog_ping, .set_timeout = softdog_set_timeout, }; static struct watchdog_device softdog_dev = { .info = &softdog_info, .ops = &softdog_ops, .min_timeout = 1, .max_timeout = 0xFFFF }; static int __init watchdog_init(void) { int ret; if (soft_margin < 1 || soft_margin > 65535) { pr_info("soft_margin must be 0 < soft_margin < 65536, using %d\n", TIMER_MARGIN); return -EINVAL; } softdog_dev.timeout = soft_margin; watchdog_set_nowayout(&softdog_dev, nowayout); ret = register_reboot_notifier(&softdog_notifier); if (ret) { pr_err("cannot register reboot notifier (err=%d)\n", ret); return ret; } ret = watchdog_register_device(&softdog_dev); if (ret) { unregister_reboot_notifier(&softdog_notifier); return ret; } pr_info("Software Watchdog Timer: 0.08 initialized. soft_noboot=%d soft_margin=%d sec soft_panic=%d (nowayout=%d)\n", soft_noboot, soft_margin, soft_panic, nowayout); return 0; } static void __exit watchdog_exit(void) { watchdog_unregister_device(&softdog_dev); unregister_reboot_notifier(&softdog_notifier); } module_init(watchdog_init); module_exit(watchdog_exit); MODULE_AUTHOR("Alan Cox"); MODULE_DESCRIPTION("Software Watchdog Device Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
jameshilliard/m8-3.4.0-gb1fa77f
drivers/watchdog/softdog.c
C
gpl-2.0
5,039
#include <linux/kernel.h> #include <linux/ip.h> #include <linux/sctp.h> #include <net/ip.h> #include <net/ip6_checksum.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <net/sctp/checksum.h> #include <net/ip_vs.h> static int sctp_conn_schedule(int af, struct sk_buff *skb, struct ip_vs_proto_data *pd, int *verdict, struct ip_vs_conn **cpp) { struct net *net; struct ip_vs_service *svc; sctp_chunkhdr_t _schunkh, *sch; sctp_sctphdr_t *sh, _sctph; struct ip_vs_iphdr iph; ip_vs_fill_iphdr(af, skb_network_header(skb), &iph); sh = skb_header_pointer(skb, iph.len, sizeof(_sctph), &_sctph); if (sh == NULL) return 0; sch = skb_header_pointer(skb, iph.len + sizeof(sctp_sctphdr_t), sizeof(_schunkh), &_schunkh); if (sch == NULL) return 0; net = skb_net(skb); if ((sch->type == SCTP_CID_INIT) && (svc = ip_vs_service_get(net, af, skb->mark, iph.protocol, &iph.daddr, sh->dest))) { int ignored; if (ip_vs_todrop(net_ipvs(net))) { ip_vs_service_put(svc); *verdict = NF_DROP; return 0; } *cpp = ip_vs_schedule(svc, skb, pd, &ignored); if (!*cpp && ignored <= 0) { if (!ignored) *verdict = ip_vs_leave(svc, skb, pd); else { ip_vs_service_put(svc); *verdict = NF_DROP; } return 0; } ip_vs_service_put(svc); } return 1; } static int sctp_snat_handler(struct sk_buff *skb, struct ip_vs_protocol *pp, struct ip_vs_conn *cp) { sctp_sctphdr_t *sctph; unsigned int sctphoff; struct sk_buff *iter; __be32 crc32; #ifdef CONFIG_IP_VS_IPV6 if (cp->af == AF_INET6) sctphoff = sizeof(struct ipv6hdr); else #endif sctphoff = ip_hdrlen(skb); if (!skb_make_writable(skb, sctphoff + sizeof(*sctph))) return 0; if (unlikely(cp->app != NULL)) { if (pp->csum_check && !pp->csum_check(cp->af, skb, pp)) return 0; if (!ip_vs_app_pkt_out(cp, skb)) return 0; } sctph = (void *) skb_network_header(skb) + sctphoff; sctph->source = cp->vport; crc32 = sctp_start_cksum((u8 *) sctph, skb_headlen(skb) - sctphoff); skb_walk_frags(skb, iter) crc32 = sctp_update_cksum((u8 *) iter->data, skb_headlen(iter), crc32); crc32 = sctp_end_cksum(crc32); sctph->checksum = crc32; return 1; } static int sctp_dnat_handler(struct sk_buff *skb, struct ip_vs_protocol *pp, struct ip_vs_conn *cp) { sctp_sctphdr_t *sctph; unsigned int sctphoff; struct sk_buff *iter; __be32 crc32; #ifdef CONFIG_IP_VS_IPV6 if (cp->af == AF_INET6) sctphoff = sizeof(struct ipv6hdr); else #endif sctphoff = ip_hdrlen(skb); if (!skb_make_writable(skb, sctphoff + sizeof(*sctph))) return 0; if (unlikely(cp->app != NULL)) { if (pp->csum_check && !pp->csum_check(cp->af, skb, pp)) return 0; if (!ip_vs_app_pkt_in(cp, skb)) return 0; } sctph = (void *) skb_network_header(skb) + sctphoff; sctph->dest = cp->dport; crc32 = sctp_start_cksum((u8 *) sctph, skb_headlen(skb) - sctphoff); skb_walk_frags(skb, iter) crc32 = sctp_update_cksum((u8 *) iter->data, skb_headlen(iter), crc32); crc32 = sctp_end_cksum(crc32); sctph->checksum = crc32; return 1; } static int sctp_csum_check(int af, struct sk_buff *skb, struct ip_vs_protocol *pp) { unsigned int sctphoff; struct sctphdr *sh, _sctph; struct sk_buff *iter; __le32 cmp; __le32 val; __u32 tmp; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) sctphoff = sizeof(struct ipv6hdr); else #endif sctphoff = ip_hdrlen(skb); sh = skb_header_pointer(skb, sctphoff, sizeof(_sctph), &_sctph); if (sh == NULL) return 0; cmp = sh->checksum; tmp = sctp_start_cksum((__u8 *) sh, skb_headlen(skb)); skb_walk_frags(skb, iter) tmp = sctp_update_cksum((__u8 *) iter->data, skb_headlen(iter), tmp); val = sctp_end_cksum(tmp); if (val != cmp) { IP_VS_DBG_RL_PKT(0, af, pp, skb, 0, "Failed checksum for"); return 0; } return 1; } struct ipvs_sctp_nextstate { int next_state; }; enum ipvs_sctp_event_t { IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_DATA_SER, IP_VS_SCTP_EVE_INIT_CLI, IP_VS_SCTP_EVE_INIT_SER, IP_VS_SCTP_EVE_INIT_ACK_CLI, IP_VS_SCTP_EVE_INIT_ACK_SER, IP_VS_SCTP_EVE_COOKIE_ECHO_CLI, IP_VS_SCTP_EVE_COOKIE_ECHO_SER, IP_VS_SCTP_EVE_COOKIE_ACK_CLI, IP_VS_SCTP_EVE_COOKIE_ACK_SER, IP_VS_SCTP_EVE_ABORT_CLI, IP_VS_SCTP_EVE__ABORT_SER, IP_VS_SCTP_EVE_SHUT_CLI, IP_VS_SCTP_EVE_SHUT_SER, IP_VS_SCTP_EVE_SHUT_ACK_CLI, IP_VS_SCTP_EVE_SHUT_ACK_SER, IP_VS_SCTP_EVE_SHUT_COM_CLI, IP_VS_SCTP_EVE_SHUT_COM_SER, IP_VS_SCTP_EVE_LAST }; static enum ipvs_sctp_event_t sctp_events[255] = { IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_INIT_CLI, IP_VS_SCTP_EVE_INIT_ACK_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_ABORT_CLI, IP_VS_SCTP_EVE_SHUT_CLI, IP_VS_SCTP_EVE_SHUT_ACK_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_COOKIE_ECHO_CLI, IP_VS_SCTP_EVE_COOKIE_ACK_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_DATA_CLI, IP_VS_SCTP_EVE_SHUT_COM_CLI, }; static struct ipvs_sctp_nextstate sctp_states_table[IP_VS_SCTP_S_LAST][IP_VS_SCTP_EVE_LAST] = { {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_ACK_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_INIT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_INIT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_ECHO_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_ACK_SER }, {IP_VS_SCTP_S_ECHO_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_ACK_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_ECHO_CLI }, {IP_VS_SCTP_S_ECHO_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_ECHO_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_ECHO_SER }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_SHUT_ACK_CLI }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_ESTABLISHED }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_CLI }, {IP_VS_SCTP_S_SHUT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_SHUT_ACK_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } }, {{IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_INIT_CLI }, {IP_VS_SCTP_S_INIT_SER }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED }, {IP_VS_SCTP_S_CLOSED } } }; static const int sctp_timeouts[IP_VS_SCTP_S_LAST + 1] = { [IP_VS_SCTP_S_NONE] = 2 * HZ, [IP_VS_SCTP_S_INIT_CLI] = 1 * 60 * HZ, [IP_VS_SCTP_S_INIT_SER] = 1 * 60 * HZ, [IP_VS_SCTP_S_INIT_ACK_CLI] = 1 * 60 * HZ, [IP_VS_SCTP_S_INIT_ACK_SER] = 1 * 60 * HZ, [IP_VS_SCTP_S_ECHO_CLI] = 1 * 60 * HZ, [IP_VS_SCTP_S_ECHO_SER] = 1 * 60 * HZ, [IP_VS_SCTP_S_ESTABLISHED] = 15 * 60 * HZ, [IP_VS_SCTP_S_SHUT_CLI] = 1 * 60 * HZ, [IP_VS_SCTP_S_SHUT_SER] = 1 * 60 * HZ, [IP_VS_SCTP_S_SHUT_ACK_CLI] = 1 * 60 * HZ, [IP_VS_SCTP_S_SHUT_ACK_SER] = 1 * 60 * HZ, [IP_VS_SCTP_S_CLOSED] = 10 * HZ, [IP_VS_SCTP_S_LAST] = 2 * HZ, }; static const char *sctp_state_name_table[IP_VS_SCTP_S_LAST + 1] = { [IP_VS_SCTP_S_NONE] = "NONE", [IP_VS_SCTP_S_INIT_CLI] = "INIT_CLI", [IP_VS_SCTP_S_INIT_SER] = "INIT_SER", [IP_VS_SCTP_S_INIT_ACK_CLI] = "INIT_ACK_CLI", [IP_VS_SCTP_S_INIT_ACK_SER] = "INIT_ACK_SER", [IP_VS_SCTP_S_ECHO_CLI] = "COOKIE_ECHO_CLI", [IP_VS_SCTP_S_ECHO_SER] = "COOKIE_ECHO_SER", [IP_VS_SCTP_S_ESTABLISHED] = "ESTABISHED", [IP_VS_SCTP_S_SHUT_CLI] = "SHUTDOWN_CLI", [IP_VS_SCTP_S_SHUT_SER] = "SHUTDOWN_SER", [IP_VS_SCTP_S_SHUT_ACK_CLI] = "SHUTDOWN_ACK_CLI", [IP_VS_SCTP_S_SHUT_ACK_SER] = "SHUTDOWN_ACK_SER", [IP_VS_SCTP_S_CLOSED] = "CLOSED", [IP_VS_SCTP_S_LAST] = "BUG!" }; static const char *sctp_state_name(int state) { if (state >= IP_VS_SCTP_S_LAST) return "ERR!"; if (sctp_state_name_table[state]) return sctp_state_name_table[state]; return "?"; } static inline void set_sctp_state(struct ip_vs_proto_data *pd, struct ip_vs_conn *cp, int direction, const struct sk_buff *skb) { sctp_chunkhdr_t _sctpch, *sch; unsigned char chunk_type; int event, next_state; int ihl; #ifdef CONFIG_IP_VS_IPV6 ihl = cp->af == AF_INET ? ip_hdrlen(skb) : sizeof(struct ipv6hdr); #else ihl = ip_hdrlen(skb); #endif sch = skb_header_pointer(skb, ihl + sizeof(sctp_sctphdr_t), sizeof(_sctpch), &_sctpch); if (sch == NULL) return; chunk_type = sch->type; if ((sch->type == SCTP_CID_COOKIE_ECHO) || (sch->type == SCTP_CID_COOKIE_ACK)) { sch = skb_header_pointer(skb, (ihl + sizeof(sctp_sctphdr_t) + sch->length), sizeof(_sctpch), &_sctpch); if (sch) { if (sch->type == SCTP_CID_ABORT) chunk_type = sch->type; } } event = sctp_events[chunk_type]; if (direction == IP_VS_DIR_OUTPUT) event++; next_state = sctp_states_table[cp->state][event].next_state; if (next_state != cp->state) { struct ip_vs_dest *dest = cp->dest; IP_VS_DBG_BUF(8, "%s %s %s:%d->" "%s:%d state: %s->%s conn->refcnt:%d\n", pd->pp->name, ((direction == IP_VS_DIR_OUTPUT) ? "output " : "input "), IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport), IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport), sctp_state_name(cp->state), sctp_state_name(next_state), atomic_read(&cp->refcnt)); if (dest) { if (!(cp->flags & IP_VS_CONN_F_INACTIVE) && (next_state != IP_VS_SCTP_S_ESTABLISHED)) { atomic_dec(&dest->activeconns); atomic_inc(&dest->inactconns); cp->flags |= IP_VS_CONN_F_INACTIVE; } else if ((cp->flags & IP_VS_CONN_F_INACTIVE) && (next_state == IP_VS_SCTP_S_ESTABLISHED)) { atomic_inc(&dest->activeconns); atomic_dec(&dest->inactconns); cp->flags &= ~IP_VS_CONN_F_INACTIVE; } } } if (likely(pd)) cp->timeout = pd->timeout_table[cp->state = next_state]; else cp->timeout = sctp_timeouts[cp->state = next_state]; } static void sctp_state_transition(struct ip_vs_conn *cp, int direction, const struct sk_buff *skb, struct ip_vs_proto_data *pd) { spin_lock(&cp->lock); set_sctp_state(pd, cp, direction, skb); spin_unlock(&cp->lock); } static inline __u16 sctp_app_hashkey(__be16 port) { return (((__force u16)port >> SCTP_APP_TAB_BITS) ^ (__force u16)port) & SCTP_APP_TAB_MASK; } static int sctp_register_app(struct net *net, struct ip_vs_app *inc) { struct ip_vs_app *i; __u16 hash; __be16 port = inc->port; int ret = 0; struct netns_ipvs *ipvs = net_ipvs(net); struct ip_vs_proto_data *pd = ip_vs_proto_data_get(net, IPPROTO_SCTP); hash = sctp_app_hashkey(port); spin_lock_bh(&ipvs->sctp_app_lock); list_for_each_entry(i, &ipvs->sctp_apps[hash], p_list) { if (i->port == port) { ret = -EEXIST; goto out; } } list_add(&inc->p_list, &ipvs->sctp_apps[hash]); atomic_inc(&pd->appcnt); out: spin_unlock_bh(&ipvs->sctp_app_lock); return ret; } static void sctp_unregister_app(struct net *net, struct ip_vs_app *inc) { struct netns_ipvs *ipvs = net_ipvs(net); struct ip_vs_proto_data *pd = ip_vs_proto_data_get(net, IPPROTO_SCTP); spin_lock_bh(&ipvs->sctp_app_lock); atomic_dec(&pd->appcnt); list_del(&inc->p_list); spin_unlock_bh(&ipvs->sctp_app_lock); } static int sctp_app_conn_bind(struct ip_vs_conn *cp) { struct netns_ipvs *ipvs = net_ipvs(ip_vs_conn_net(cp)); int hash; struct ip_vs_app *inc; int result = 0; if (IP_VS_FWD_METHOD(cp) != IP_VS_CONN_F_MASQ) return 0; hash = sctp_app_hashkey(cp->vport); spin_lock(&ipvs->sctp_app_lock); list_for_each_entry(inc, &ipvs->sctp_apps[hash], p_list) { if (inc->port == cp->vport) { if (unlikely(!ip_vs_app_inc_get(inc))) break; spin_unlock(&ipvs->sctp_app_lock); IP_VS_DBG_BUF(9, "%s: Binding conn %s:%u->" "%s:%u to app %s on port %u\n", __func__, IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport), IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport), inc->name, ntohs(inc->port)); cp->app = inc; if (inc->init_conn) result = inc->init_conn(inc, cp); goto out; } } spin_unlock(&ipvs->sctp_app_lock); out: return result; } static int __ip_vs_sctp_init(struct net *net, struct ip_vs_proto_data *pd) { struct netns_ipvs *ipvs = net_ipvs(net); ip_vs_init_hash_table(ipvs->sctp_apps, SCTP_APP_TAB_SIZE); spin_lock_init(&ipvs->sctp_app_lock); pd->timeout_table = ip_vs_create_timeout_table((int *)sctp_timeouts, sizeof(sctp_timeouts)); if (!pd->timeout_table) return -ENOMEM; return 0; } static void __ip_vs_sctp_exit(struct net *net, struct ip_vs_proto_data *pd) { kfree(pd->timeout_table); } struct ip_vs_protocol ip_vs_protocol_sctp = { .name = "SCTP", .protocol = IPPROTO_SCTP, .num_states = IP_VS_SCTP_S_LAST, .dont_defrag = 0, .init = NULL, .exit = NULL, .init_netns = __ip_vs_sctp_init, .exit_netns = __ip_vs_sctp_exit, .register_app = sctp_register_app, .unregister_app = sctp_unregister_app, .conn_schedule = sctp_conn_schedule, .conn_in_get = ip_vs_conn_in_get_proto, .conn_out_get = ip_vs_conn_out_get_proto, .snat_handler = sctp_snat_handler, .dnat_handler = sctp_dnat_handler, .csum_check = sctp_csum_check, .state_name = sctp_state_name, .state_transition = sctp_state_transition, .app_conn_bind = sctp_app_conn_bind, .debug_packet = ip_vs_tcpudp_debug_packet, .timeout_change = NULL, };
jameshilliard/m8-3.4.0-gb1fa77f
net/netfilter/ipvs/ip_vs_proto_sctp.c
C
gpl-2.0
18,826
/* * OMAP2+ MPU WD_TIMER-specific code * * 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. */ #include <linux/kernel.h> #include <linux/io.h> #include <linux/err.h> #include <plat/omap_hwmod.h> #include "wd_timer.h" #define OMAP_WDT_WPS 0x34 #define OMAP_WDT_SPR 0x48 int omap2_wd_timer_disable(struct omap_hwmod *oh) { void __iomem *base; if (!oh) { pr_err("%s: Could not look up wdtimer_hwmod\n", __func__); return -EINVAL; } base = omap_hwmod_get_mpu_rt_va(oh); if (!base) { pr_err("%s: Could not get the base address for %s\n", oh->name, __func__); return -EINVAL; } __raw_writel(0xAAAA, base + OMAP_WDT_SPR); while (__raw_readl(base + OMAP_WDT_WPS) & 0x10) cpu_relax(); __raw_writel(0x5555, base + OMAP_WDT_SPR); while (__raw_readl(base + OMAP_WDT_WPS) & 0x10) cpu_relax(); return 0; }
jameshilliard/m8-3.4.0-gb1fa77f
arch/arm/mach-omap2/wd_timer.c
C
gpl-2.0
1,039
/* * MobiCore client library device management. * * Device and Trustlet Session management Functions. * * <-- Copyright Giesecke & Devrient GmbH 2009 - 2012 --> * * 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/list.h> #include <linux/slab.h> #include <linux/device.h> #include "mc_kernel_api.h" #include "public/mobicore_driver_api.h" #include "device.h" #include "common.h" struct wsm *wsm_create(void *virt_addr, uint32_t len, uint32_t handle, void *phys_addr) { struct wsm *wsm; wsm = kzalloc(sizeof(*wsm), GFP_KERNEL); wsm->virt_addr = virt_addr; wsm->len = len; wsm->handle = handle; wsm->phys_addr = phys_addr; return wsm; } struct mcore_device_t *mcore_device_create(uint32_t device_id, struct connection *connection) { struct mcore_device_t *dev; dev = kzalloc(sizeof(*dev), GFP_KERNEL); dev->device_id = device_id; dev->connection = connection; INIT_LIST_HEAD(&dev->session_vector); INIT_LIST_HEAD(&dev->wsm_l2_vector); return dev; } void mcore_device_cleanup(struct mcore_device_t *dev) { struct session *tmp; struct wsm *wsm; struct list_head *pos, *q; list_for_each_safe(pos, q, &dev->session_vector) { tmp = list_entry(pos, struct session, list); list_del(pos); session_cleanup(tmp); } list_for_each_safe(pos, q, &dev->wsm_l2_vector) { wsm = list_entry(pos, struct wsm, list); list_del(pos); kfree(wsm); } connection_cleanup(dev->connection); mcore_device_close(dev); kfree(dev); } bool mcore_device_open(struct mcore_device_t *dev, const char *deviceName) { dev->instance = mobicore_open(); return (dev->instance != NULL); } void mcore_device_close(struct mcore_device_t *dev) { mobicore_release(dev->instance); } bool mcore_device_has_sessions(struct mcore_device_t *dev) { return !list_empty(&dev->session_vector); } bool mcore_device_create_new_session(struct mcore_device_t *dev, uint32_t session_id, struct connection *connection) { if (mcore_device_resolve_session_id(dev, session_id)) { MCDRV_DBG_ERROR(mc_kapi, " session %u already exists", session_id); return false; } struct session *session = session_create(session_id, dev->instance, connection); list_add_tail(&(session->list), &(dev->session_vector)); return true; } bool mcore_device_remove_session(struct mcore_device_t *dev, uint32_t session_id) { bool ret = false; struct session *tmp; struct list_head *pos, *q; list_for_each_safe(pos, q, &dev->session_vector) { tmp = list_entry(pos, struct session, list); if (tmp->session_id == session_id) { list_del(pos); session_cleanup(tmp); ret = true; break; } } return ret; } struct session *mcore_device_resolve_session_id(struct mcore_device_t *dev, uint32_t session_id) { struct session *ret = NULL; struct session *tmp; struct list_head *pos; list_for_each(pos, &dev->session_vector) { tmp = list_entry(pos, struct session, list); if (tmp->session_id == session_id) { ret = tmp; break; } } return ret; } struct wsm *mcore_device_allocate_contiguous_wsm(struct mcore_device_t *dev, uint32_t len) { struct wsm *wsm = NULL; do { if (len == 0) break; void *virt_addr; uint32_t handle; void *phys_addr; int ret = mobicore_allocate_wsm(dev->instance, len, &handle, &virt_addr, &phys_addr); if (ret != 0) break; wsm = wsm_create(virt_addr, len, handle, phys_addr); list_add_tail(&(wsm->list), &(dev->wsm_l2_vector)); } while (0); return wsm; } bool mcore_device_free_contiguous_wsm(struct mcore_device_t *dev, struct wsm *wsm) { bool ret = false; struct wsm *tmp; struct list_head *pos; list_for_each(pos, &dev->wsm_l2_vector) { tmp = list_entry(pos, struct wsm, list); if (tmp == wsm) { ret = true; break; } } if (ret) { MCDRV_DBG_VERBOSE(mc_kapi, "freeWsm virt_addr=0x%p, handle=%d", wsm->virt_addr, wsm->handle); mobicore_free_wsm(dev->instance, wsm->handle); list_del(pos); kfree(wsm); } return ret; } struct wsm *mcore_device_find_contiguous_wsm(struct mcore_device_t *dev, void *virt_addr) { struct wsm *wsm; struct list_head *pos; list_for_each(pos, &dev->wsm_l2_vector) { wsm = list_entry(pos, struct wsm, list); if (virt_addr == wsm->virt_addr) return wsm; } return NULL; }
jameshilliard/m8-3.4.0-gb1fa77f
drivers/gud/mobicore_kernelapi/device.c
C
gpl-2.0
4,475
#ifndef _OZURBPARANOIA_H #define _OZURBPARANOIA_H /* ----------------------------------------------------------------------------- * Released under the GNU General Public License Version 2 (GPLv2). * Copyright (c) 2011 Ozmo Inc * ----------------------------------------------------------------------------- */ #ifdef WANT_URB_PARANOIA void oz_remember_urb(struct urb *urb); int oz_forget_urb(struct urb *urb); #else #define oz_remember_urb(__x) #define oz_forget_urb(__x) 0 #endif #endif
jameshilliard/m8-3.4.0-gb1fa77f
drivers/staging/ozwpan/ozurbparanoia.h
C
gpl-2.0
499
<!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"/> <title>ATC: fix_modify AtC output</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li class="current"><a href="pages.html"><span>Related&nbsp;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><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> </div> <div class="contents"> <h1><a class="anchor" id="man_output">fix_modify AtC output </a></h1><h2><a class="anchor" id="syntax"> syntax</a></h2> <p>fix_modify AtC output &lt;filename_prefix&gt; &lt;frequency&gt; [text | full_text | binary | vector_components | tensor_components ] fix_modify AtC output index [step | time ]</p> <ul> <li>filename_prefix (string) = prefix for data files</li> <li>frequency (integer) = frequency of output in time-steps</li> <li>options (keyword/s): <br/> text = creates text output of index, step and nodal variable values for unique nodes <br/> full_text = creates text output index, nodal id, step, nodal coordinates and nodal variable values for unique and image nodes <br/> binary = creates binary Ensight output <br/> vector_components = outputs vectors as scalar components <br/> tensor_components = outputs tensor as scalar components (use this for Paraview)<br/> </li> </ul> <h2><a class="anchor" id="examples"> examples</a></h2> <p><code> fix_modify AtC output heatFE 100 </code> <br/> <code> fix_modify AtC output hardyFE 1 text tensor_components </code> <br/> <code> fix_modify AtC output hardyFE 10 text binary tensor_components </code> <br/> <code> fix_modify AtC output index step </code> <br/> </p> <h2><a class="anchor" id="description"> description</a></h2> <p>Creates text and/or binary (Ensight, "gold" format) output of nodal/mesh data which is transfer/physics specific. Output indexed by step or time is possible. </p> <h2><a class="anchor" id="restrictions"> restrictions</a></h2> <h2><a class="anchor" id="related"> related</a></h2> <p>see <a class="el" href="man_fix_atc.html">fix atc command</a> </p> <h2><a class="anchor" id="default"> default</a></h2> <p>no default format output indexed by time </p> </div> <hr size="1"/><address style="text-align: right;"><small>Generated on 21 Aug 2013 for ATC by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
ovilab/atomify-lammps
libs/lammps/doc/src/USER/atc/man_output.html
HTML
gpl-3.0
2,975
// // InviteViewController.h // Funner // // Created by highjump on 14-11-9. // // #import <UIKit/UIKit.h> @interface InviteViewController : UIViewController @end
srsman/leya
Funner-2/Funner/View/ChatViewController/FriendViewController/InviteViewController/InviteViewController.h
C
unlicense
169
// Copyright JS Foundation and other contributors, http://js.foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. assert ((1 / 0*(-1)) == -Infinity); assert ((1 / 0*1) == Infinity);
grgustaf/jerryscript
tests/jerry/regression-test-issue-1855.js
JavaScript
apache-2.0
698
/* * Copyright (C) 2010 The Guava Authors * * 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.google.common.collect.testing; import java.io.Serializable; /** * Simple base class to verify that we handle generics correctly. * * @author Kevin Bourrillion */ public class BaseComparable implements Comparable<BaseComparable>, Serializable { private final String s; public BaseComparable(String s) { this.s = s; } @Override public int hashCode() { // delegate to 's' return s.hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof BaseComparable) { return s.equals(((BaseComparable) other).s); } else { return false; } } @Override public int compareTo(BaseComparable o) { return s.compareTo(o.s); } private static final long serialVersionUID = 0; }
lshain-android-source/external-guava
guava-testlib/src/com/google/common/collect/testing/BaseComparable.java
Java
apache-2.0
1,415
local wrk = { scheme = "http", host = "localhost", port = nil, method = "GET", path = "/", headers = {}, body = nil, thread = nil, } function wrk.resolve(host, service) local addrs = wrk.lookup(host, service) for i = #addrs, 1, -1 do if not wrk.connect(addrs[i]) then table.remove(addrs, i) end end wrk.addrs = addrs end function wrk.setup(thread) thread.addr = wrk.addrs[1] if type(setup) == "function" then setup(thread) end end function wrk.init(args) if not wrk.headers["Host"] then local host = wrk.host local port = wrk.port host = host:find(":") and ("[" .. host .. "]") or host host = port and (host .. ":" .. port) or host wrk.headers["Host"] = host end if type(init) == "function" then init(args) end local req = wrk.format() wrk.request = function() return req end end function wrk.format(method, path, headers, body) local method = method or wrk.method local path = path or wrk.path local headers = headers or wrk.headers local body = body or wrk.body local s = {} if not headers["Host"] then headers["Host"] = wrk.headers["Host"] end headers["Content-Length"] = body and string.len(body) s[1] = string.format("%s %s HTTP/1.1", method, path) for name, value in pairs(headers) do s[#s+1] = string.format("%s: %s", name, value) end s[#s+1] = "" s[#s+1] = body or "" return table.concat(s, "\r\n") end return wrk
mneumann/wrk
src/wrk.lua
Lua
apache-2.0
1,571
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQNullType : RQType { public static readonly RQNullType Singleton = new RQNullType(); private RQNullType() { } public override SimpleTreeNode ToSimpleTree() { return new SimpleLeafNode(RQNameStrings.Null); } } }
mmitche/roslyn
src/Features/Core/Portable/RQName/Nodes/RQNullType.cs
C#
apache-2.0
572
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeClass2))] public sealed class CodeClass : AbstractCodeType, EnvDTE.CodeClass, EnvDTE80.CodeClass2, ICodeClassBase { private static readonly SymbolDisplayFormat s_BaseNameFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal static EnvDTE.CodeClass Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeClass(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeClass CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeClass(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return this.CodeModelService.GetElementKind(LookupNode()); } } public bool IsAbstract { get { return (InheritanceKind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) != 0; } set { var inheritanceKind = InheritanceKind; var newInheritanceKind = inheritanceKind; if (value) { newInheritanceKind |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed; } else { newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; } if (inheritanceKind != newInheritanceKind) { InheritanceKind = newInheritanceKind; } } } public EnvDTE80.vsCMClassKind ClassKind { get { return CodeModelService.GetClassKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateClassKind, value); } } public EnvDTE80.vsCMInheritanceKind InheritanceKind { get { return CodeModelService.GetInheritanceKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateInheritanceKind, value); } } public EnvDTE.CodeElements PartialClasses { get { return PartialTypeCollection.Create(State, FileCodeModel, this); } } public EnvDTE.CodeElements Parts { get { return PartialTypeCollection.Create(State, FileCodeModel, this); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddClass(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddDelegate(LookupNode(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnum(LookupNode(), name, position, bases, access); }); } public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEvent(LookupNode(), name, fullDelegateName, createPropertyStyleEvent, location, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddFunction(LookupNode(), name, kind, type, position, access); }); } public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddProperty(LookupNode(), getterName, putterName, type, position, access); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddStruct(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { // NOTE: C# ignores this location parameter. return FileCodeModel.AddVariable(LookupNode(), name, type, position, access); }); } public int GetBaseName(out string pBaseName) { var typeSymbol = LookupTypeSymbol(); if (typeSymbol?.BaseType == null) { pBaseName = null; return VSConstants.E_FAIL; } pBaseName = typeSymbol.BaseType.ToDisplayString(s_BaseNameFormat); return VSConstants.S_OK; } } }
mmitche/roslyn
src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeClass.cs
C#
apache-2.0
7,917
<blockquote> <h2>header</h2> <p>paragraph</p> <ul> <li>li</li> </ul> <hr /> <p>paragraph</p> </blockquote>
Urbannet/cleanclean
yii2/vendor/erusev/parsedown/test/data/compound_blockquote.html
HTML
bsd-3-clause
106
YUI.add('anim-base', function(Y) { /** * The Animation Utility provides an API for creating advanced transitions. * @module anim */ /** * Provides the base Anim class, for animating numeric properties. * * @module anim * @submodule anim-base */ /** * A class for constructing animation instances. * @class Anim * @for Anim * @constructor * @extends Base */ var RUNNING = 'running', START_TIME = 'startTime', ELAPSED_TIME = 'elapsedTime', /** * @for Anim * @event start * @description fires when an animation begins. * @param {Event} ev The start event. * @type Event.Custom */ START = 'start', /** * @event tween * @description fires every frame of the animation. * @param {Event} ev The tween event. * @type Event.Custom */ TWEEN = 'tween', /** * @event end * @description fires after the animation completes. * @param {Event} ev The end event. * @type Event.Custom */ END = 'end', NODE = 'node', PAUSED = 'paused', REVERSE = 'reverse', // TODO: cleanup ITERATION_COUNT = 'iterationCount', NUM = Number; var _running = {}, _timer; Y.Anim = function() { Y.Anim.superclass.constructor.apply(this, arguments); Y.Anim._instances[Y.stamp(this)] = this; }; Y.Anim.NAME = 'anim'; Y.Anim._instances = {}; /** * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i; /** * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ Y.Anim.DEFAULT_UNIT = 'px'; Y.Anim.DEFAULT_EASING = function (t, b, c, d) { return c * t / d + b; // linear easing }; /** * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ Y.Anim._intervalTime = 20; /** * Bucket for custom getters and setters * * @property behaviors * @static */ Y.Anim.behaviors = { left: { get: function(anim, attr) { return anim._getOffset(attr); } } }; Y.Anim.behaviors.top = Y.Anim.behaviors.left; /** * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) { var node = anim._node, domNode = node._node, val = fn(elapsed, NUM(from), NUM(to) - NUM(from), duration); if (domNode) { if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) { unit = unit || ''; node.setStyle(att, val + unit); } else if ('attributes' in domNode && att in domNode.attributes) { node.setAttribute(att, val); } else if (att in domNode) { domNode[att] = val; } } else if (node.set) { node.set(att, val); } else if (att in node) { node[att] = val; } }; /** * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ Y.Anim.DEFAULT_GETTER = function(anim, att) { var node = anim._node, domNode = node._node, val = ''; if (domNode) { if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) { val = node.getComputedStyle(att); } else if ('attributes' in domNode && att in domNode.attributes) { val = node.getAttribute(att); } else if (att in domNode) { val = domNode[att]; } } else if (node.get) { val = node.get(att); } else if (att in node) { val = node[att]; } return val; }; Y.Anim.ATTRS = { /** * The object to be animated. * @attribute node * @type Node */ node: { setter: function(node) { if (node) { if (typeof node == 'string' || node.nodeType) { node = Y.one(node); } } this._node = node; if (!node) { Y.log(node + ' is not a valid node', 'warn', 'Anim'); } return node; } }, /** * The length of the animation. Defaults to "1" (second). * @attribute duration * @type NUM */ duration: { value: 1 }, /** * The method that will provide values to the attribute(s) during the animation. * Defaults to "Easing.easeNone". * @attribute easing * @type Function */ easing: { value: Y.Anim.DEFAULT_EASING, setter: function(val) { if (typeof val === 'string' && Y.Easing) { return Y.Easing[val]; } } }, /** * The starting values for the animated properties. * * Fields may be strings, numbers, or functions. * If a function is used, the return value becomes the from value. * If no from value is specified, the DEFAULT_GETTER will be used. * Supports any unit, provided it matches the "to" (or default) * unit (e.g. `{width: '10em', color: 'rgb(0, 0, 0)', borderColor: '#ccc'}`). * * If using the default ('px' for length-based units), the unit may be omitted * (e.g. `{width: 100}, borderColor: 'ccc'}`, which defaults to pixels * and hex, respectively). * * @attribute from * @type Object */ from: {}, /** * The ending values for the animated properties. * * Fields may be strings, numbers, or functions. * Supports any unit, provided it matches the "from" (or default) * unit (e.g. `{width: '50%', color: 'red', borderColor: '#ccc'}`). * * If using the default ('px' for length-based units), the unit may be omitted * (e.g. `{width: 100, borderColor: 'ccc'}`, which defaults to pixels * and hex, respectively). * * @attribute to * @type Object */ to: {}, /** * Date stamp for the first frame of the animation. * @attribute startTime * @type Int * @default 0 * @readOnly */ startTime: { value: 0, readOnly: true }, /** * Current time the animation has been running. * @attribute elapsedTime * @type Int * @default 0 * @readOnly */ elapsedTime: { value: 0, readOnly: true }, /** * Whether or not the animation is currently running. * @attribute running * @type Boolean * @default false * @readOnly */ running: { getter: function() { return !!_running[Y.stamp(this)]; }, value: false, readOnly: true }, /** * The number of times the animation should run * @attribute iterations * @type Int * @default 1 */ iterations: { value: 1 }, /** * The number of iterations that have occurred. * Resets when an animation ends (reaches iteration count or stop() called). * @attribute iterationCount * @type Int * @default 0 * @readOnly */ iterationCount: { value: 0, readOnly: true }, /** * How iterations of the animation should behave. * Possible values are "normal" and "alternate". * Normal will repeat the animation, alternate will reverse on every other pass. * * @attribute direction * @type String * @default "normal" */ direction: { value: 'normal' // | alternate (fwd on odd, rev on even per spec) }, /** * Whether or not the animation is currently paused. * @attribute paused * @type Boolean * @default false * @readOnly */ paused: { readOnly: true, value: false }, /** * If true, animation begins from last frame * @attribute reverse * @type Boolean * @default false */ reverse: { value: false } }; /** * Runs all animation instances. * @method run * @static */ Y.Anim.run = function() { var instances = Y.Anim._instances; for (var i in instances) { if (instances[i].run) { instances[i].run(); } } }; /** * Pauses all animation instances. * @method pause * @static */ Y.Anim.pause = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].pause) { _running[i].pause(); } } Y.Anim._stopTimer(); }; /** * Stops all animation instances. * @method stop * @static */ Y.Anim.stop = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].stop) { _running[i].stop(); } } Y.Anim._stopTimer(); }; Y.Anim._startTimer = function() { if (!_timer) { _timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime); } }; Y.Anim._stopTimer = function() { clearInterval(_timer); _timer = 0; }; /** * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ Y.Anim._runFrame = function() { var done = true; for (var anim in _running) { if (_running[anim]._runFrame) { done = false; _running[anim]._runFrame(); } } if (done) { Y.Anim._stopTimer(); } }; Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/; var proto = { /** * Starts or resumes an animation. * @method run * @chainable */ run: function() { if (this.get(PAUSED)) { this._resume(); } else if (!this.get(RUNNING)) { this._start(); } return this; }, /** * Pauses the animation and * freezes it in its current state and time. * Calling run() will continue where it left off. * @method pause * @chainable */ pause: function() { if (this.get(RUNNING)) { this._pause(); } return this; }, /** * Stops the animation and resets its time. * @method stop * @param {Boolean} finish If true, the animation will move to the last frame * @chainable */ stop: function(finish) { if (this.get(RUNNING) || this.get(PAUSED)) { this._end(finish); } return this; }, _added: false, _start: function() { this._set(START_TIME, new Date() - this.get(ELAPSED_TIME)); this._actualFrames = 0; if (!this.get(PAUSED)) { this._initAnimAttr(); } _running[Y.stamp(this)] = this; Y.Anim._startTimer(); this.fire(START); }, _pause: function() { this._set(START_TIME, null); this._set(PAUSED, true); delete _running[Y.stamp(this)]; /** * @event pause * @description fires when an animation is paused. * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('pause'); }, _resume: function() { this._set(PAUSED, false); _running[Y.stamp(this)] = this; this._set(START_TIME, new Date() - this.get(ELAPSED_TIME)); Y.Anim._startTimer(); /** * @event resume * @description fires when an animation is resumed (run from pause). * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('resume'); }, _end: function(finish) { var duration = this.get('duration') * 1000; if (finish) { // jump to last frame this._runAttrs(duration, duration, this.get(REVERSE)); } this._set(START_TIME, null); this._set(ELAPSED_TIME, 0); this._set(PAUSED, false); delete _running[Y.stamp(this)]; this.fire(END, {elapsed: this.get(ELAPSED_TIME)}); }, _runFrame: function() { var d = this._runtimeAttr.duration, t = new Date() - this.get(START_TIME), reverse = this.get(REVERSE), done = (t >= d), attribute, setter; this._runAttrs(t, d, reverse); this._actualFrames += 1; this._set(ELAPSED_TIME, t); this.fire(TWEEN); if (done) { this._lastFrame(); } }, _runAttrs: function(t, d, reverse) { var attr = this._runtimeAttr, customAttr = Y.Anim.behaviors, easing = attr.easing, lastFrame = d, done = false, attribute, setter, i; if (t >= d) { done = true; } if (reverse) { t = d - t; lastFrame = 0; } for (i in attr) { if (attr[i].to) { attribute = attr[i]; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Y.Anim.DEFAULT_SETTER; if (!done) { setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit); } else { setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit); } } } }, _lastFrame: function() { var iter = this.get('iterations'), iterCount = this.get(ITERATION_COUNT); iterCount += 1; if (iter === 'infinite' || iterCount < iter) { if (this.get('direction') === 'alternate') { this.set(REVERSE, !this.get(REVERSE)); // flip it } /** * @event iteration * @description fires when an animation begins an iteration. * @param {Event} ev The iteration event. * @type Event.Custom */ this.fire('iteration'); } else { iterCount = 0; this._end(); } this._set(START_TIME, new Date()); this._set(ITERATION_COUNT, iterCount); }, _initAnimAttr: function() { var from = this.get('from') || {}, to = this.get('to') || {}, attr = { duration: this.get('duration') * 1000, easing: this.get('easing') }, customAttr = Y.Anim.behaviors, node = this.get(NODE), // implicit attr init unit, begin, end; Y.each(to, function(val, name) { if (typeof val === 'function') { val = val.call(this, node); } begin = from[name]; if (begin === undefined) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name); } else if (typeof begin === 'function') { begin = begin.call(this, node); } var mFrom = Y.Anim.RE_UNITS.exec(begin); var mTo = Y.Anim.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) { unit = Y.Anim.DEFAULT_UNIT; } if (!begin || !end) { Y.error('invalid "from" or "to" for "' + name + '"', 'Anim'); return; } attr[name] = { from: begin, to: end, unit: unit }; }, this); this._runtimeAttr = attr; }, // TODO: move to computedStyle? (browsers dont agree on default computed offsets) _getOffset: function(attr) { var node = this._node, val = node.getComputedStyle(attr), get = (attr === 'left') ? 'getX': 'getY', set = (attr === 'left') ? 'setX': 'setY'; if (val === 'auto') { var position = node.getStyle('position'); if (position === 'absolute' || position === 'fixed') { val = node[get](); node[set](val); } else { val = 0; } } return val; }, destructor: function() { delete Y.Anim._instances[Y.stamp(this)]; } }; Y.extend(Y.Anim, Y.Base, proto); }, '@VERSION@' ,{requires:['base-base', 'node-style']});
jonathantneal/cdnjs
ajax/libs/yui/3.7.0pr1/anim-base/anim-base-debug.js
JavaScript
mit
18,949
// Copyright 2014 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // SSE2 variant of methods for lossless decoder // // Author: Skal (pascal.massimino@gmail.com) #include "./dsp.h" #if defined(WEBP_USE_SSE2) #include "./common_sse2.h" #include "./lossless.h" #include "./lossless_common.h" #include <assert.h> #include <emmintrin.h> //------------------------------------------------------------------------------ // Predictor Transform static WEBP_INLINE uint32_t ClampedAddSubtractFull(uint32_t c0, uint32_t c1, uint32_t c2) { const __m128i zero = _mm_setzero_si128(); const __m128i C0 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c0), zero); const __m128i C1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c1), zero); const __m128i C2 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c2), zero); const __m128i V1 = _mm_add_epi16(C0, C1); const __m128i V2 = _mm_sub_epi16(V1, C2); const __m128i b = _mm_packus_epi16(V2, V2); const uint32_t output = _mm_cvtsi128_si32(b); return output; } static WEBP_INLINE uint32_t ClampedAddSubtractHalf(uint32_t c0, uint32_t c1, uint32_t c2) { const __m128i zero = _mm_setzero_si128(); const __m128i C0 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c0), zero); const __m128i C1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c1), zero); const __m128i B0 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(c2), zero); const __m128i avg = _mm_add_epi16(C1, C0); const __m128i A0 = _mm_srli_epi16(avg, 1); const __m128i A1 = _mm_sub_epi16(A0, B0); const __m128i BgtA = _mm_cmpgt_epi16(B0, A0); const __m128i A2 = _mm_sub_epi16(A1, BgtA); const __m128i A3 = _mm_srai_epi16(A2, 1); const __m128i A4 = _mm_add_epi16(A0, A3); const __m128i A5 = _mm_packus_epi16(A4, A4); const uint32_t output = _mm_cvtsi128_si32(A5); return output; } static WEBP_INLINE uint32_t Select(uint32_t a, uint32_t b, uint32_t c) { int pa_minus_pb; const __m128i zero = _mm_setzero_si128(); const __m128i A0 = _mm_cvtsi32_si128(a); const __m128i B0 = _mm_cvtsi32_si128(b); const __m128i C0 = _mm_cvtsi32_si128(c); const __m128i AC0 = _mm_subs_epu8(A0, C0); const __m128i CA0 = _mm_subs_epu8(C0, A0); const __m128i BC0 = _mm_subs_epu8(B0, C0); const __m128i CB0 = _mm_subs_epu8(C0, B0); const __m128i AC = _mm_or_si128(AC0, CA0); const __m128i BC = _mm_or_si128(BC0, CB0); const __m128i pa = _mm_unpacklo_epi8(AC, zero); // |a - c| const __m128i pb = _mm_unpacklo_epi8(BC, zero); // |b - c| const __m128i diff = _mm_sub_epi16(pb, pa); { int16_t out[8]; _mm_storeu_si128((__m128i*)out, diff); pa_minus_pb = out[0] + out[1] + out[2] + out[3]; } return (pa_minus_pb <= 0) ? a : b; } static WEBP_INLINE void Average2_m128i(const __m128i* const a0, const __m128i* const a1, __m128i* const avg) { // (a + b) >> 1 = ((a + b + 1) >> 1) - ((a ^ b) & 1) const __m128i ones = _mm_set1_epi8(1); const __m128i avg1 = _mm_avg_epu8(*a0, *a1); const __m128i one = _mm_and_si128(_mm_xor_si128(*a0, *a1), ones); *avg = _mm_sub_epi8(avg1, one); } static WEBP_INLINE void Average2_uint32(const uint32_t a0, const uint32_t a1, __m128i* const avg) { // (a + b) >> 1 = ((a + b + 1) >> 1) - ((a ^ b) & 1) const __m128i ones = _mm_set1_epi8(1); const __m128i A0 = _mm_cvtsi32_si128(a0); const __m128i A1 = _mm_cvtsi32_si128(a1); const __m128i avg1 = _mm_avg_epu8(A0, A1); const __m128i one = _mm_and_si128(_mm_xor_si128(A0, A1), ones); *avg = _mm_sub_epi8(avg1, one); } static WEBP_INLINE __m128i Average2_uint32_16(uint32_t a0, uint32_t a1) { const __m128i zero = _mm_setzero_si128(); const __m128i A0 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(a0), zero); const __m128i A1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(a1), zero); const __m128i sum = _mm_add_epi16(A1, A0); return _mm_srli_epi16(sum, 1); } static WEBP_INLINE uint32_t Average2(uint32_t a0, uint32_t a1) { __m128i output; Average2_uint32(a0, a1, &output); return _mm_cvtsi128_si32(output); } static WEBP_INLINE uint32_t Average3(uint32_t a0, uint32_t a1, uint32_t a2) { const __m128i zero = _mm_setzero_si128(); const __m128i avg1 = Average2_uint32_16(a0, a2); const __m128i A1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(a1), zero); const __m128i sum = _mm_add_epi16(avg1, A1); const __m128i avg2 = _mm_srli_epi16(sum, 1); const __m128i A2 = _mm_packus_epi16(avg2, avg2); const uint32_t output = _mm_cvtsi128_si32(A2); return output; } static WEBP_INLINE uint32_t Average4(uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3) { const __m128i avg1 = Average2_uint32_16(a0, a1); const __m128i avg2 = Average2_uint32_16(a2, a3); const __m128i sum = _mm_add_epi16(avg2, avg1); const __m128i avg3 = _mm_srli_epi16(sum, 1); const __m128i A0 = _mm_packus_epi16(avg3, avg3); const uint32_t output = _mm_cvtsi128_si32(A0); return output; } static uint32_t Predictor5_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average3(left, top[0], top[1]); return pred; } static uint32_t Predictor6_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average2(left, top[-1]); return pred; } static uint32_t Predictor7_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average2(left, top[0]); return pred; } static uint32_t Predictor8_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average2(top[-1], top[0]); (void)left; return pred; } static uint32_t Predictor9_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average2(top[0], top[1]); (void)left; return pred; } static uint32_t Predictor10_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Average4(left, top[-1], top[0], top[1]); return pred; } static uint32_t Predictor11_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = Select(top[0], left, top[-1]); return pred; } static uint32_t Predictor12_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = ClampedAddSubtractFull(left, top[0], top[-1]); return pred; } static uint32_t Predictor13_SSE2(uint32_t left, const uint32_t* const top) { const uint32_t pred = ClampedAddSubtractHalf(left, top[0], top[-1]); return pred; } // Batch versions of those functions. // Predictor0: ARGB_BLACK. static void PredictorAdd0_SSE2(const uint32_t* in, const uint32_t* upper, int num_pixels, uint32_t* out) { int i; const __m128i black = _mm_set1_epi32(ARGB_BLACK); for (i = 0; i + 4 <= num_pixels; i += 4) { const __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); const __m128i res = _mm_add_epi8(src, black); _mm_storeu_si128((__m128i*)&out[i], res); } if (i != num_pixels) { VP8LPredictorsAdd_C[0](in + i, upper + i, num_pixels - i, out + i); } } // Predictor1: left. static void PredictorAdd1_SSE2(const uint32_t* in, const uint32_t* upper, int num_pixels, uint32_t* out) { int i; __m128i prev = _mm_set1_epi32(out[-1]); for (i = 0; i + 4 <= num_pixels; i += 4) { // a | b | c | d const __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); // 0 | a | b | c const __m128i shift0 = _mm_slli_si128(src, 4); // a | a + b | b + c | c + d const __m128i sum0 = _mm_add_epi8(src, shift0); // 0 | 0 | a | a + b const __m128i shift1 = _mm_slli_si128(sum0, 8); // a | a + b | a + b + c | a + b + c + d const __m128i sum1 = _mm_add_epi8(sum0, shift1); const __m128i res = _mm_add_epi8(sum1, prev); _mm_storeu_si128((__m128i*)&out[i], res); // replicate prev output on the four lanes prev = _mm_shuffle_epi32(res, (3 << 0) | (3 << 2) | (3 << 4) | (3 << 6)); } if (i != num_pixels) { VP8LPredictorsAdd_C[1](in + i, upper + i, num_pixels - i, out + i); } } // Macro that adds 32-bit integers from IN using mod 256 arithmetic // per 8 bit channel. #define GENERATE_PREDICTOR_1(X, IN) \ static void PredictorAdd##X##_SSE2(const uint32_t* in, const uint32_t* upper, \ int num_pixels, uint32_t* out) { \ int i; \ for (i = 0; i + 4 <= num_pixels; i += 4) { \ const __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); \ const __m128i other = _mm_loadu_si128((const __m128i*)&(IN)); \ const __m128i res = _mm_add_epi8(src, other); \ _mm_storeu_si128((__m128i*)&out[i], res); \ } \ if (i != num_pixels) { \ VP8LPredictorsAdd_C[(X)](in + i, upper + i, num_pixels - i, out + i); \ } \ } // Predictor2: Top. GENERATE_PREDICTOR_1(2, upper[i]) // Predictor3: Top-right. GENERATE_PREDICTOR_1(3, upper[i + 1]) // Predictor4: Top-left. GENERATE_PREDICTOR_1(4, upper[i - 1]) #undef GENERATE_PREDICTOR_1 // Due to averages with integers, values cannot be accumulated in parallel for // predictors 5 to 7. GENERATE_PREDICTOR_ADD(Predictor5_SSE2, PredictorAdd5_SSE2) GENERATE_PREDICTOR_ADD(Predictor6_SSE2, PredictorAdd6_SSE2) GENERATE_PREDICTOR_ADD(Predictor7_SSE2, PredictorAdd7_SSE2) #define GENERATE_PREDICTOR_2(X, IN) \ static void PredictorAdd##X##_SSE2(const uint32_t* in, const uint32_t* upper, \ int num_pixels, uint32_t* out) { \ int i; \ for (i = 0; i + 4 <= num_pixels; i += 4) { \ const __m128i Tother = _mm_loadu_si128((const __m128i*)&(IN)); \ const __m128i T = _mm_loadu_si128((const __m128i*)&upper[i]); \ const __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); \ __m128i avg, res; \ Average2_m128i(&T, &Tother, &avg); \ res = _mm_add_epi8(avg, src); \ _mm_storeu_si128((__m128i*)&out[i], res); \ } \ if (i != num_pixels) { \ VP8LPredictorsAdd_C[(X)](in + i, upper + i, num_pixels - i, out + i); \ } \ } // Predictor8: average TL T. GENERATE_PREDICTOR_2(8, upper[i - 1]) // Predictor9: average T TR. GENERATE_PREDICTOR_2(9, upper[i + 1]) #undef GENERATE_PREDICTOR_2 // Predictor10: average of (average of (L,TL), average of (T, TR)). static void PredictorAdd10_SSE2(const uint32_t* in, const uint32_t* upper, int num_pixels, uint32_t* out) { int i, j; __m128i L = _mm_cvtsi32_si128(out[-1]); for (i = 0; i + 4 <= num_pixels; i += 4) { __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); __m128i TL = _mm_loadu_si128((const __m128i*)&upper[i - 1]); const __m128i T = _mm_loadu_si128((const __m128i*)&upper[i]); const __m128i TR = _mm_loadu_si128((const __m128i*)&upper[i + 1]); __m128i avgTTR; Average2_m128i(&T, &TR, &avgTTR); for (j = 0; j < 4; ++j) { __m128i avgLTL, avg; Average2_m128i(&L, &TL, &avgLTL); Average2_m128i(&avgTTR, &avgLTL, &avg); L = _mm_add_epi8(avg, src); out[i + j] = _mm_cvtsi128_si32(L); // Rotate the pre-computed values for the next iteration. avgTTR = _mm_srli_si128(avgTTR, 4); TL = _mm_srli_si128(TL, 4); src = _mm_srli_si128(src, 4); } } if (i != num_pixels) { VP8LPredictorsAdd_C[10](in + i, upper + i, num_pixels - i, out + i); } } // Predictor11: select. static void GetSumAbsDiff32(const __m128i* const A, const __m128i* const B, __m128i* const out) { // We can unpack with any value on the upper 32 bits, provided it's the same // on both operands (to that their sum of abs diff is zero). Here we use *A. const __m128i A_lo = _mm_unpacklo_epi32(*A, *A); const __m128i B_lo = _mm_unpacklo_epi32(*B, *A); const __m128i A_hi = _mm_unpackhi_epi32(*A, *A); const __m128i B_hi = _mm_unpackhi_epi32(*B, *A); const __m128i s_lo = _mm_sad_epu8(A_lo, B_lo); const __m128i s_hi = _mm_sad_epu8(A_hi, B_hi); *out = _mm_packs_epi32(s_lo, s_hi); } static void PredictorAdd11_SSE2(const uint32_t* in, const uint32_t* upper, int num_pixels, uint32_t* out) { int i, j; __m128i L = _mm_cvtsi32_si128(out[-1]); for (i = 0; i + 4 <= num_pixels; i += 4) { __m128i T = _mm_loadu_si128((const __m128i*)&upper[i]); __m128i TL = _mm_loadu_si128((const __m128i*)&upper[i - 1]); __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); __m128i pa; GetSumAbsDiff32(&T, &TL, &pa); // pa = sum |T-TL| for (j = 0; j < 4; ++j) { const __m128i L_lo = _mm_unpacklo_epi32(L, L); const __m128i TL_lo = _mm_unpacklo_epi32(TL, L); const __m128i pb = _mm_sad_epu8(L_lo, TL_lo); // pb = sum |L-TL| const __m128i mask = _mm_cmpgt_epi32(pb, pa); const __m128i A = _mm_and_si128(mask, L); const __m128i B = _mm_andnot_si128(mask, T); const __m128i pred = _mm_or_si128(A, B); // pred = (L > T)? L : T L = _mm_add_epi8(src, pred); out[i + j] = _mm_cvtsi128_si32(L); // Shift the pre-computed value for the next iteration. T = _mm_srli_si128(T, 4); TL = _mm_srli_si128(TL, 4); src = _mm_srli_si128(src, 4); pa = _mm_srli_si128(pa, 4); } } if (i != num_pixels) { VP8LPredictorsAdd_C[11](in + i, upper + i, num_pixels - i, out + i); } } // Predictor12: ClampedAddSubtractFull. #define DO_PRED12(DIFF, LANE, OUT) \ do { \ const __m128i all = _mm_add_epi16(L, (DIFF)); \ const __m128i alls = _mm_packus_epi16(all, all); \ const __m128i res = _mm_add_epi8(src, alls); \ out[i + (OUT)] = _mm_cvtsi128_si32(res); \ L = _mm_unpacklo_epi8(res, zero); \ /* Shift the pre-computed value for the next iteration.*/ \ if (LANE == 0) (DIFF) = _mm_srli_si128((DIFF), 8); \ src = _mm_srli_si128(src, 4); \ } while (0) static void PredictorAdd12_SSE2(const uint32_t* in, const uint32_t* upper, int num_pixels, uint32_t* out) { int i; const __m128i zero = _mm_setzero_si128(); const __m128i L8 = _mm_cvtsi32_si128(out[-1]); __m128i L = _mm_unpacklo_epi8(L8, zero); for (i = 0; i + 4 <= num_pixels; i += 4) { // Load 4 pixels at a time. __m128i src = _mm_loadu_si128((const __m128i*)&in[i]); const __m128i T = _mm_loadu_si128((const __m128i*)&upper[i]); const __m128i T_lo = _mm_unpacklo_epi8(T, zero); const __m128i T_hi = _mm_unpackhi_epi8(T, zero); const __m128i TL = _mm_loadu_si128((const __m128i*)&upper[i - 1]); const __m128i TL_lo = _mm_unpacklo_epi8(TL, zero); const __m128i TL_hi = _mm_unpackhi_epi8(TL, zero); __m128i diff_lo = _mm_sub_epi16(T_lo, TL_lo); __m128i diff_hi = _mm_sub_epi16(T_hi, TL_hi); DO_PRED12(diff_lo, 0, 0); DO_PRED12(diff_lo, 1, 1); DO_PRED12(diff_hi, 0, 2); DO_PRED12(diff_hi, 1, 3); } if (i != num_pixels) { VP8LPredictorsAdd_C[12](in + i, upper + i, num_pixels - i, out + i); } } #undef DO_PRED12 // Due to averages with integers, values cannot be accumulated in parallel for // predictors 13. GENERATE_PREDICTOR_ADD(Predictor13_SSE2, PredictorAdd13_SSE2) //------------------------------------------------------------------------------ // Subtract-Green Transform static void AddGreenToBlueAndRed(const uint32_t* const src, int num_pixels, uint32_t* dst) { int i; for (i = 0; i + 4 <= num_pixels; i += 4) { const __m128i in = _mm_loadu_si128((const __m128i*)&src[i]); // argb const __m128i A = _mm_srli_epi16(in, 8); // 0 a 0 g const __m128i B = _mm_shufflelo_epi16(A, _MM_SHUFFLE(2, 2, 0, 0)); const __m128i C = _mm_shufflehi_epi16(B, _MM_SHUFFLE(2, 2, 0, 0)); // 0g0g const __m128i out = _mm_add_epi8(in, C); _mm_storeu_si128((__m128i*)&dst[i], out); } // fallthrough and finish off with plain-C if (i != num_pixels) { VP8LAddGreenToBlueAndRed_C(src + i, num_pixels - i, dst + i); } } //------------------------------------------------------------------------------ // Color Transform static void TransformColorInverse(const VP8LMultipliers* const m, const uint32_t* const src, int num_pixels, uint32_t* dst) { // sign-extended multiplying constants, pre-shifted by 5. #define CST(X) (((int16_t)(m->X << 8)) >> 5) // sign-extend const __m128i mults_rb = _mm_set_epi16( CST(green_to_red_), CST(green_to_blue_), CST(green_to_red_), CST(green_to_blue_), CST(green_to_red_), CST(green_to_blue_), CST(green_to_red_), CST(green_to_blue_)); const __m128i mults_b2 = _mm_set_epi16( CST(red_to_blue_), 0, CST(red_to_blue_), 0, CST(red_to_blue_), 0, CST(red_to_blue_), 0); #undef CST const __m128i mask_ag = _mm_set1_epi32(0xff00ff00); // alpha-green masks int i; for (i = 0; i + 4 <= num_pixels; i += 4) { const __m128i in = _mm_loadu_si128((const __m128i*)&src[i]); // argb const __m128i A = _mm_and_si128(in, mask_ag); // a 0 g 0 const __m128i B = _mm_shufflelo_epi16(A, _MM_SHUFFLE(2, 2, 0, 0)); const __m128i C = _mm_shufflehi_epi16(B, _MM_SHUFFLE(2, 2, 0, 0)); // g0g0 const __m128i D = _mm_mulhi_epi16(C, mults_rb); // x dr x db1 const __m128i E = _mm_add_epi8(in, D); // x r' x b' const __m128i F = _mm_slli_epi16(E, 8); // r' 0 b' 0 const __m128i G = _mm_mulhi_epi16(F, mults_b2); // x db2 0 0 const __m128i H = _mm_srli_epi32(G, 8); // 0 x db2 0 const __m128i I = _mm_add_epi8(H, F); // r' x b'' 0 const __m128i J = _mm_srli_epi16(I, 8); // 0 r' 0 b'' const __m128i out = _mm_or_si128(J, A); _mm_storeu_si128((__m128i*)&dst[i], out); } // Fall-back to C-version for left-overs. if (i != num_pixels) { VP8LTransformColorInverse_C(m, src + i, num_pixels - i, dst + i); } } //------------------------------------------------------------------------------ // Color-space conversion functions static void ConvertBGRAToRGB(const uint32_t* src, int num_pixels, uint8_t* dst) { const __m128i* in = (const __m128i*)src; __m128i* out = (__m128i*)dst; while (num_pixels >= 32) { // Load the BGRA buffers. __m128i in0 = _mm_loadu_si128(in + 0); __m128i in1 = _mm_loadu_si128(in + 1); __m128i in2 = _mm_loadu_si128(in + 2); __m128i in3 = _mm_loadu_si128(in + 3); __m128i in4 = _mm_loadu_si128(in + 4); __m128i in5 = _mm_loadu_si128(in + 5); __m128i in6 = _mm_loadu_si128(in + 6); __m128i in7 = _mm_loadu_si128(in + 7); VP8L32bToPlanar(&in0, &in1, &in2, &in3); VP8L32bToPlanar(&in4, &in5, &in6, &in7); // At this points, in1/in5 contains red only, in2/in6 green only ... // Pack the colors in 24b RGB. VP8PlanarTo24b(&in1, &in5, &in2, &in6, &in3, &in7); _mm_storeu_si128(out + 0, in1); _mm_storeu_si128(out + 1, in5); _mm_storeu_si128(out + 2, in2); _mm_storeu_si128(out + 3, in6); _mm_storeu_si128(out + 4, in3); _mm_storeu_si128(out + 5, in7); in += 8; out += 6; num_pixels -= 32; } // left-overs if (num_pixels > 0) { VP8LConvertBGRAToRGB_C((const uint32_t*)in, num_pixels, (uint8_t*)out); } } static void ConvertBGRAToRGBA(const uint32_t* src, int num_pixels, uint8_t* dst) { const __m128i* in = (const __m128i*)src; __m128i* out = (__m128i*)dst; while (num_pixels >= 8) { const __m128i bgra0 = _mm_loadu_si128(in++); // bgra0|bgra1|bgra2|bgra3 const __m128i bgra4 = _mm_loadu_si128(in++); // bgra4|bgra5|bgra6|bgra7 const __m128i v0l = _mm_unpacklo_epi8(bgra0, bgra4); // b0b4g0g4r0r4a0a4... const __m128i v0h = _mm_unpackhi_epi8(bgra0, bgra4); // b2b6g2g6r2r6a2a6... const __m128i v1l = _mm_unpacklo_epi8(v0l, v0h); // b0b2b4b6g0g2g4g6... const __m128i v1h = _mm_unpackhi_epi8(v0l, v0h); // b1b3b5b7g1g3g5g7... const __m128i v2l = _mm_unpacklo_epi8(v1l, v1h); // b0...b7 | g0...g7 const __m128i v2h = _mm_unpackhi_epi8(v1l, v1h); // r0...r7 | a0...a7 const __m128i ga0 = _mm_unpackhi_epi64(v2l, v2h); // g0...g7 | a0...a7 const __m128i rb0 = _mm_unpacklo_epi64(v2h, v2l); // r0...r7 | b0...b7 const __m128i rg0 = _mm_unpacklo_epi8(rb0, ga0); // r0g0r1g1 ... r6g6r7g7 const __m128i ba0 = _mm_unpackhi_epi8(rb0, ga0); // b0a0b1a1 ... b6a6b7a7 const __m128i rgba0 = _mm_unpacklo_epi16(rg0, ba0); // rgba0|rgba1... const __m128i rgba4 = _mm_unpackhi_epi16(rg0, ba0); // rgba4|rgba5... _mm_storeu_si128(out++, rgba0); _mm_storeu_si128(out++, rgba4); num_pixels -= 8; } // left-overs if (num_pixels > 0) { VP8LConvertBGRAToRGBA_C((const uint32_t*)in, num_pixels, (uint8_t*)out); } } static void ConvertBGRAToRGBA4444(const uint32_t* src, int num_pixels, uint8_t* dst) { const __m128i mask_0x0f = _mm_set1_epi8(0x0f); const __m128i mask_0xf0 = _mm_set1_epi8(0xf0); const __m128i* in = (const __m128i*)src; __m128i* out = (__m128i*)dst; while (num_pixels >= 8) { const __m128i bgra0 = _mm_loadu_si128(in++); // bgra0|bgra1|bgra2|bgra3 const __m128i bgra4 = _mm_loadu_si128(in++); // bgra4|bgra5|bgra6|bgra7 const __m128i v0l = _mm_unpacklo_epi8(bgra0, bgra4); // b0b4g0g4r0r4a0a4... const __m128i v0h = _mm_unpackhi_epi8(bgra0, bgra4); // b2b6g2g6r2r6a2a6... const __m128i v1l = _mm_unpacklo_epi8(v0l, v0h); // b0b2b4b6g0g2g4g6... const __m128i v1h = _mm_unpackhi_epi8(v0l, v0h); // b1b3b5b7g1g3g5g7... const __m128i v2l = _mm_unpacklo_epi8(v1l, v1h); // b0...b7 | g0...g7 const __m128i v2h = _mm_unpackhi_epi8(v1l, v1h); // r0...r7 | a0...a7 const __m128i ga0 = _mm_unpackhi_epi64(v2l, v2h); // g0...g7 | a0...a7 const __m128i rb0 = _mm_unpacklo_epi64(v2h, v2l); // r0...r7 | b0...b7 const __m128i ga1 = _mm_srli_epi16(ga0, 4); // g0-|g1-|...|a6-|a7- const __m128i rb1 = _mm_and_si128(rb0, mask_0xf0); // -r0|-r1|...|-b6|-a7 const __m128i ga2 = _mm_and_si128(ga1, mask_0x0f); // g0-|g1-|...|a6-|a7- const __m128i rgba0 = _mm_or_si128(ga2, rb1); // rg0..rg7 | ba0..ba7 const __m128i rgba1 = _mm_srli_si128(rgba0, 8); // ba0..ba7 | 0 #ifdef WEBP_SWAP_16BIT_CSP const __m128i rgba = _mm_unpacklo_epi8(rgba1, rgba0); // barg0...barg7 #else const __m128i rgba = _mm_unpacklo_epi8(rgba0, rgba1); // rgba0...rgba7 #endif _mm_storeu_si128(out++, rgba); num_pixels -= 8; } // left-overs if (num_pixels > 0) { VP8LConvertBGRAToRGBA4444_C((const uint32_t*)in, num_pixels, (uint8_t*)out); } } static void ConvertBGRAToRGB565(const uint32_t* src, int num_pixels, uint8_t* dst) { const __m128i mask_0xe0 = _mm_set1_epi8(0xe0); const __m128i mask_0xf8 = _mm_set1_epi8(0xf8); const __m128i mask_0x07 = _mm_set1_epi8(0x07); const __m128i* in = (const __m128i*)src; __m128i* out = (__m128i*)dst; while (num_pixels >= 8) { const __m128i bgra0 = _mm_loadu_si128(in++); // bgra0|bgra1|bgra2|bgra3 const __m128i bgra4 = _mm_loadu_si128(in++); // bgra4|bgra5|bgra6|bgra7 const __m128i v0l = _mm_unpacklo_epi8(bgra0, bgra4); // b0b4g0g4r0r4a0a4... const __m128i v0h = _mm_unpackhi_epi8(bgra0, bgra4); // b2b6g2g6r2r6a2a6... const __m128i v1l = _mm_unpacklo_epi8(v0l, v0h); // b0b2b4b6g0g2g4g6... const __m128i v1h = _mm_unpackhi_epi8(v0l, v0h); // b1b3b5b7g1g3g5g7... const __m128i v2l = _mm_unpacklo_epi8(v1l, v1h); // b0...b7 | g0...g7 const __m128i v2h = _mm_unpackhi_epi8(v1l, v1h); // r0...r7 | a0...a7 const __m128i ga0 = _mm_unpackhi_epi64(v2l, v2h); // g0...g7 | a0...a7 const __m128i rb0 = _mm_unpacklo_epi64(v2h, v2l); // r0...r7 | b0...b7 const __m128i rb1 = _mm_and_si128(rb0, mask_0xf8); // -r0..-r7|-b0..-b7 const __m128i g_lo1 = _mm_srli_epi16(ga0, 5); const __m128i g_lo2 = _mm_and_si128(g_lo1, mask_0x07); // g0-...g7-|xx (3b) const __m128i g_hi1 = _mm_slli_epi16(ga0, 3); const __m128i g_hi2 = _mm_and_si128(g_hi1, mask_0xe0); // -g0...-g7|xx (3b) const __m128i b0 = _mm_srli_si128(rb1, 8); // -b0...-b7|0 const __m128i rg1 = _mm_or_si128(rb1, g_lo2); // gr0...gr7|xx const __m128i b1 = _mm_srli_epi16(b0, 3); const __m128i gb1 = _mm_or_si128(b1, g_hi2); // bg0...bg7|xx #ifdef WEBP_SWAP_16BIT_CSP const __m128i rgba = _mm_unpacklo_epi8(gb1, rg1); // rggb0...rggb7 #else const __m128i rgba = _mm_unpacklo_epi8(rg1, gb1); // bgrb0...bgrb7 #endif _mm_storeu_si128(out++, rgba); num_pixels -= 8; } // left-overs if (num_pixels > 0) { VP8LConvertBGRAToRGB565_C((const uint32_t*)in, num_pixels, (uint8_t*)out); } } static void ConvertBGRAToBGR(const uint32_t* src, int num_pixels, uint8_t* dst) { const __m128i mask_l = _mm_set_epi32(0, 0x00ffffff, 0, 0x00ffffff); const __m128i mask_h = _mm_set_epi32(0x00ffffff, 0, 0x00ffffff, 0); const __m128i* in = (const __m128i*)src; const uint8_t* const end = dst + num_pixels * 3; // the last storel_epi64 below writes 8 bytes starting at offset 18 while (dst + 26 <= end) { const __m128i bgra0 = _mm_loadu_si128(in++); // bgra0|bgra1|bgra2|bgra3 const __m128i bgra4 = _mm_loadu_si128(in++); // bgra4|bgra5|bgra6|bgra7 const __m128i a0l = _mm_and_si128(bgra0, mask_l); // bgr0|0|bgr0|0 const __m128i a4l = _mm_and_si128(bgra4, mask_l); // bgr0|0|bgr0|0 const __m128i a0h = _mm_and_si128(bgra0, mask_h); // 0|bgr0|0|bgr0 const __m128i a4h = _mm_and_si128(bgra4, mask_h); // 0|bgr0|0|bgr0 const __m128i b0h = _mm_srli_epi64(a0h, 8); // 000b|gr00|000b|gr00 const __m128i b4h = _mm_srli_epi64(a4h, 8); // 000b|gr00|000b|gr00 const __m128i c0 = _mm_or_si128(a0l, b0h); // rgbrgb00|rgbrgb00 const __m128i c4 = _mm_or_si128(a4l, b4h); // rgbrgb00|rgbrgb00 const __m128i c2 = _mm_srli_si128(c0, 8); const __m128i c6 = _mm_srli_si128(c4, 8); _mm_storel_epi64((__m128i*)(dst + 0), c0); _mm_storel_epi64((__m128i*)(dst + 6), c2); _mm_storel_epi64((__m128i*)(dst + 12), c4); _mm_storel_epi64((__m128i*)(dst + 18), c6); dst += 24; num_pixels -= 8; } // left-overs if (num_pixels > 0) { VP8LConvertBGRAToBGR_C((const uint32_t*)in, num_pixels, dst); } } //------------------------------------------------------------------------------ // Entry point extern void VP8LDspInitSSE2(void); WEBP_TSAN_IGNORE_FUNCTION void VP8LDspInitSSE2(void) { VP8LPredictors[5] = Predictor5_SSE2; VP8LPredictors[6] = Predictor6_SSE2; VP8LPredictors[7] = Predictor7_SSE2; VP8LPredictors[8] = Predictor8_SSE2; VP8LPredictors[9] = Predictor9_SSE2; VP8LPredictors[10] = Predictor10_SSE2; VP8LPredictors[11] = Predictor11_SSE2; VP8LPredictors[12] = Predictor12_SSE2; VP8LPredictors[13] = Predictor13_SSE2; VP8LPredictorsAdd[0] = PredictorAdd0_SSE2; VP8LPredictorsAdd[1] = PredictorAdd1_SSE2; VP8LPredictorsAdd[2] = PredictorAdd2_SSE2; VP8LPredictorsAdd[3] = PredictorAdd3_SSE2; VP8LPredictorsAdd[4] = PredictorAdd4_SSE2; VP8LPredictorsAdd[5] = PredictorAdd5_SSE2; VP8LPredictorsAdd[6] = PredictorAdd6_SSE2; VP8LPredictorsAdd[7] = PredictorAdd7_SSE2; VP8LPredictorsAdd[8] = PredictorAdd8_SSE2; VP8LPredictorsAdd[9] = PredictorAdd9_SSE2; VP8LPredictorsAdd[10] = PredictorAdd10_SSE2; VP8LPredictorsAdd[11] = PredictorAdd11_SSE2; VP8LPredictorsAdd[12] = PredictorAdd12_SSE2; VP8LPredictorsAdd[13] = PredictorAdd13_SSE2; VP8LAddGreenToBlueAndRed = AddGreenToBlueAndRed; VP8LTransformColorInverse = TransformColorInverse; VP8LConvertBGRAToRGB = ConvertBGRAToRGB; VP8LConvertBGRAToRGBA = ConvertBGRAToRGBA; VP8LConvertBGRAToRGBA4444 = ConvertBGRAToRGBA4444; VP8LConvertBGRAToRGB565 = ConvertBGRAToRGB565; VP8LConvertBGRAToBGR = ConvertBGRAToBGR; } #else // !WEBP_USE_SSE2 WEBP_DSP_INIT_STUB(VP8LDspInitSSE2) #endif // WEBP_USE_SSE2
MrMaidx/godot
thirdparty/libwebp/dsp/lossless_sse2.c
C
mit
29,485
using System; using System.Collections.Concurrent; using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Services; using Umbraco.Web.Security; using Umbraco.Web.WebApi; namespace Umbraco.Web.Mvc { /// <summary> /// A base class for all plugin controllers to inherit from /// </summary> public abstract class PluginController : Controller { /// <summary> /// stores the metadata about plugin controllers /// </summary> private static readonly ConcurrentDictionary<Type, PluginControllerMetadata> MetadataStorage = new ConcurrentDictionary<Type, PluginControllerMetadata>(); private UmbracoHelper _umbracoHelper; /// <summary> /// Default constructor /// </summary> /// <param name="umbracoContext"></param> protected PluginController(UmbracoContext umbracoContext) { if (umbracoContext == null) throw new ArgumentNullException("umbracoContext"); UmbracoContext = umbracoContext; InstanceId = Guid.NewGuid(); } protected PluginController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper) { if (umbracoContext == null) throw new ArgumentNullException("umbracoContext"); if (umbracoHelper == null) throw new ArgumentNullException("umbracoHelper"); UmbracoContext = umbracoContext; InstanceId = Guid.NewGuid(); _umbracoHelper = umbracoHelper; } /// <summary> /// Useful for debugging /// </summary> internal Guid InstanceId { get; private set; } /// <summary> /// Returns the MemberHelper instance /// </summary> public MembershipHelper Members { get { return Umbraco.MembershipHelper; } } /// <summary> /// Returns an UmbracoHelper object /// </summary> public virtual UmbracoHelper Umbraco { get { return _umbracoHelper ?? (_umbracoHelper = new UmbracoHelper(UmbracoContext)); } } /// <summary> /// Returns an ILogger /// </summary> public ILogger Logger { get { return ProfilingLogger.Logger; } } /// <summary> /// Returns a ProfilingLogger /// </summary> public virtual ProfilingLogger ProfilingLogger { get { return UmbracoContext.Application.ProfilingLogger; } } /// <summary> /// Returns the current UmbracoContext /// </summary> public virtual UmbracoContext UmbracoContext { get; private set; } /// <summary> /// Returns the current ApplicationContext /// </summary> public virtual ApplicationContext ApplicationContext { get { return UmbracoContext.Application; } } /// <summary> /// Returns a ServiceContext /// </summary> public ServiceContext Services { get { return ApplicationContext.Services; } } /// <summary> /// Returns a DatabaseContext /// </summary> public DatabaseContext DatabaseContext { get { return ApplicationContext.DatabaseContext; } } /// <summary> /// Returns the metadata for this instance /// </summary> internal PluginControllerMetadata Metadata { get { return GetMetadata(this.GetType()); } } /// <summary> /// Returns the metadata for a PluginController /// </summary> /// <param name="type"></param> /// <returns></returns> internal static PluginControllerMetadata GetMetadata(Type type) { return MetadataStorage.GetOrAdd(type, type1 => { var pluginAttribute = type.GetCustomAttribute<PluginControllerAttribute>(false); //check if any inherited class of this type contains the IsBackOffice attribute var backOfficeAttribute = type.GetCustomAttribute<IsBackOfficeAttribute>(true); var meta = new PluginControllerMetadata() { AreaName = pluginAttribute == null ? null : pluginAttribute.AreaName, ControllerName = ControllerExtensions.GetControllerName(type), ControllerNamespace = type.Namespace, ControllerType = type, IsBackOffice = backOfficeAttribute != null }; MetadataStorage.TryAdd(type, meta); return meta; }); } } }
qizhiyu/Umbraco-CMS
src/Umbraco.Web/Mvc/PluginController.cs
C#
mit
4,947
/* * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ package sun.jvm.hotspot.asm.sparc; import sun.jvm.hotspot.asm.*; public class SPARCV9FMOVccInstruction extends SPARCFPMoveInstruction implements MoveInstruction { final int conditionCode; final int conditionFlag; public SPARCV9FMOVccInstruction(String name, int opf, int conditionCode, int conditionFlag, SPARCFloatRegister rs, SPARCFloatRegister rd) { super(name, opf, rs, rd); this.conditionFlag = conditionFlag; this.conditionCode = conditionCode; } public int getConditionCode() { return conditionCode; } public int getConditionFlag() { return conditionFlag; } public boolean isConditional() { return false; } }
rokn/Count_Words_2015
testing/openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/asm/sparc/SPARCV9FMOVccInstruction.java
Java
mit
1,829
/****************************************************************************** * * Copyright(c) 2007 - 2010 Realtek 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 * * ******************************************************************************/ #define _RECV_OSDEP_C_ #include <drv_conf.h> #include <osdep_service.h> #include <drv_types.h> #include <wifi.h> #include <recv_osdep.h> #include <osdep_intf.h> #include <ethernet.h> #include <linux/if_arp.h> #ifdef CONFIG_USB_HCI #include <usb_ops.h> #endif //init os related resource in struct recv_priv int os_recv_resource_init(struct recv_priv *precvpriv, _adapter *padapter) { int res=_SUCCESS; return res; } //alloc os related resource in union recv_frame int os_recv_resource_alloc(_adapter *padapter, union recv_frame *precvframe) { int res=_SUCCESS; struct recv_priv *precvpriv = &(padapter->recvpriv); precvframe->u.hdr.pkt_newalloc = precvframe->u.hdr.pkt = NULL; return res; } //free os related resource in union recv_frame void os_recv_resource_free(struct recv_priv *precvpriv) { } //alloc os related resource in struct recv_buf #ifdef CONFIG_RTL8712 int os_recvbuf_resource_alloc(_adapter *padapter, struct recv_buf *precvbuf) { int res=_SUCCESS; #ifdef CONFIG_USB_HCI precvbuf->irp_pending = _FALSE; precvbuf->purb = usb_alloc_urb(0, GFP_KERNEL); if(precvbuf->purb == NULL){ res = _FAIL; } precvbuf->pskb = NULL; precvbuf->reuse = _FALSE; precvbuf->pallocated_buf = precvbuf->pbuf = NULL; precvbuf->pdata = precvbuf->phead = precvbuf->ptail = precvbuf->pend = NULL; precvbuf->transfer_len = 0; precvbuf->len = 0; #endif #ifdef CONFIG_SDIO_HCI precvbuf->pskb = NULL; precvbuf->pallocated_buf = precvbuf->pbuf = NULL; precvbuf->pdata = precvbuf->phead = precvbuf->ptail = precvbuf->pend = NULL; precvbuf->len = 0; #endif return res; } //free os related resource in struct recv_buf int os_recvbuf_resource_free(_adapter *padapter, struct recv_buf *precvbuf) { int ret = _SUCCESS; if(precvbuf->pskb) dev_kfree_skb_any(precvbuf->pskb); #ifdef CONFIG_USB_HCI if(precvbuf->purb) { usb_kill_urb(precvbuf->purb); usb_free_urb(precvbuf->purb); } #endif return ret; } #endif void handle_tkip_mic_err(_adapter *padapter,u8 bgroup) { #ifdef CONFIG_IOCTL_CFG80211 enum nl80211_key_type key_type; #endif //CONFIG_IOCTL_CFG80211 union iwreq_data wrqu; struct iw_michaelmicfailure ev; struct mlme_priv* pmlmepriv = &padapter->mlmepriv; _memset( &ev, 0x00, sizeof( ev ) ); #ifdef CONFIG_IOCTL_CFG80211 if ( bgroup ) { key_type |= NL80211_KEYTYPE_GROUP; } else { key_type |= NL80211_KEYTYPE_PAIRWISE; } cfg80211_michael_mic_failure(padapter->pnetdev, (u8 *)&pmlmepriv->assoc_bssid[ 0 ], key_type, -1, NULL, GFP_ATOMIC); #endif if ( bgroup ) { ev.flags |= IW_MICFAILURE_GROUP; } else { ev.flags |= IW_MICFAILURE_PAIRWISE; } ev.src_addr.sa_family = ARPHRD_ETHER; _memcpy( ev.src_addr.sa_data, &pmlmepriv->assoc_bssid[ 0 ], ETH_ALEN ); _memset( &wrqu, 0x00, sizeof( wrqu ) ); wrqu.data.length = sizeof( ev ); wireless_send_event( padapter->pnetdev, IWEVMICHAELMICFAILURE, &wrqu, (char*) &ev ); } void recv_indicatepkt(_adapter *padapter, union recv_frame *precv_frame) { struct recv_priv *precvpriv; _queue *pfree_recv_queue; _pkt *skb; #ifdef CONFIG_RTL8712_TCP_CSUM_OFFLOAD_RX struct rx_pkt_attrib *pattrib = &precv_frame->u.hdr.attrib; #endif _func_enter_; precvpriv = &(padapter->recvpriv); pfree_recv_queue = &(precvpriv->free_recv_queue); skb = precv_frame->u.hdr.pkt; if(skb == NULL) { RT_TRACE(_module_recv_osdep_c_,_drv_err_,("recv_indicatepkt():skb==NULL something wrong!!!!\n")); goto _recv_indicatepkt_drop; } RT_TRACE(_module_recv_osdep_c_,_drv_info_,("recv_indicatepkt():skb != NULL !!!\n")); RT_TRACE(_module_recv_osdep_c_,_drv_info_,("\n recv_indicatepkt():precv_frame->u.hdr.rx_head=%p precv_frame->hdr.rx_data=%p ", precv_frame->u.hdr.rx_head, precv_frame->u.hdr.rx_data)); RT_TRACE(_module_recv_osdep_c_,_drv_info_,("precv_frame->hdr.rx_tail=%p precv_frame->u.hdr.rx_end=%p precv_frame->hdr.len=%d \n", precv_frame->u.hdr.rx_tail, precv_frame->u.hdr.rx_end, precv_frame->u.hdr.len)); skb->data = precv_frame->u.hdr.rx_data; skb->tail = precv_frame->u.hdr.rx_tail; skb->len = precv_frame->u.hdr.len; RT_TRACE(_module_recv_osdep_c_,_drv_info_,("\n skb->head=%p skb->data=%p skb->tail=%p skb->end=%p skb->len=%d\n", skb->head, skb->data, skb->tail, skb->end, skb->len)); #ifdef CONFIG_RTL8712_TCP_CSUM_OFFLOAD_RX if ( (pattrib->tcpchk_valid == 1) && (pattrib->tcp_chkrpt == 1) ) { skb->ip_summed = CHECKSUM_UNNECESSARY; //printk("CHECKSUM_UNNECESSARY \n"); } else { skb->ip_summed = CHECKSUM_NONE; //printk("CHECKSUM_NONE(%d, %d) \n", pattrib->tcpchk_valid, pattrib->tcp_chkrpt); } #else /* !CONFIG_RTL8712_TCP_CSUM_OFFLOAD_RX */ skb->ip_summed = CHECKSUM_NONE; #endif skb->dev = padapter->pnetdev; skb->protocol = eth_type_trans(skb, padapter->pnetdev); netif_rx(skb); precv_frame->u.hdr.pkt = NULL; // pointers to NULL before free_recvframe() free_recvframe(precv_frame, pfree_recv_queue); RT_TRACE(_module_recv_osdep_c_,_drv_info_,("\n recv_indicatepkt :after netif_rx!!!!\n")); _func_exit_; return; _recv_indicatepkt_drop: //enqueue back to free_recv_queue if(precv_frame) free_recvframe(precv_frame, pfree_recv_queue); precvpriv->rx_drop++; _func_exit_; } void os_read_port(_adapter *padapter, struct recv_buf *precvbuf) { struct recv_priv *precvpriv = &padapter->recvpriv; #ifdef CONFIG_USB_HCI precvbuf->ref_cnt--; //free skb in recv_buf dev_kfree_skb_any(precvbuf->pskb); precvbuf->pskb = NULL; precvbuf->reuse = _FALSE; if(precvbuf->irp_pending == _FALSE) { read_port(padapter, precvpriv->ff_hwaddr, 0, (unsigned char *)precvbuf); } #endif #ifdef CONFIG_SDIO_HCI precvbuf->pskb = NULL; #endif } void _reordering_ctrl_timeout_handler (void *FunctionContext) { struct recv_reorder_ctrl *preorder_ctrl = (struct recv_reorder_ctrl *)FunctionContext; reordering_ctrl_timeout_handler(preorder_ctrl); } void init_recv_timer(struct recv_reorder_ctrl *preorder_ctrl) { _adapter *padapter = preorder_ctrl->padapter; _init_timer(&(preorder_ctrl->reordering_ctrl_timer), padapter->pnetdev, _reordering_ctrl_timeout_handler, preorder_ctrl); }
embeddedgeeks/rtl819xsu
os_dep/linux/recv_linux.c
C
gpl-2.0
7,193
;; PowerPC paired single and double hummer description ;; Copyright (C) 2007-2014 Free Software Foundation, Inc. ;; Contributed by David Edelsohn <edelsohn@gnu.org> and Revital Eres ;; <eres@il.ibm.com> ;; This file is part of GCC. ;; GCC 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. ;; GCC 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 COPYING3. If not see ;; <http://www.gnu.org/licenses/>. (define_c_enum "unspec" [UNSPEC_INTERHI_V2SF UNSPEC_INTERLO_V2SF UNSPEC_EXTEVEN_V2SF UNSPEC_EXTODD_V2SF ]) (define_insn "paired_negv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (neg:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_neg %0,%1" [(set_attr "type" "fp")]) (define_insn "sqrtv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (sqrt:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_rsqrte %0,%1" [(set_attr "type" "fp")]) (define_insn "paired_absv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (abs:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_abs %0,%1" [(set_attr "type" "fp")]) (define_insn "nabsv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (neg:V2SF (abs:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f"))))] "TARGET_PAIRED_FLOAT" "ps_nabs %0,%1" [(set_attr "type" "fp")]) (define_insn "paired_addv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (plus:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "%f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_add %0,%1,%2" [(set_attr "type" "fp")]) (define_insn "paired_subv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (minus:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_sub %0,%1,%2" [(set_attr "type" "fp")]) (define_insn "paired_mulv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (mult:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "%f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_mul %0,%1,%2" [(set_attr "type" "fp")]) (define_insn "resv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (unspec:V2SF [(match_operand:V2SF 1 "gpc_reg_operand" "f")] UNSPEC_FRES))] "TARGET_PAIRED_FLOAT && flag_finite_math_only" "ps_res %0,%1" [(set_attr "type" "fp")]) (define_insn "paired_divv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (div:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_div %0,%1,%2" [(set_attr "type" "sdiv")]) (define_insn "paired_madds0" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (fma:SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 3 "gpc_reg_operand" "f") (parallel [(const_int 0)]))) (fma:SF (vec_select:SF (match_dup 1) (parallel [(const_int 1)])) (vec_select:SF (match_dup 2) (parallel [(const_int 0)])) (vec_select:SF (match_dup 3) (parallel [(const_int 1)])))))] "TARGET_PAIRED_FLOAT" "ps_madds0 %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "paired_madds1" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (fma:SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 1)])) (vec_select:SF (match_operand:V2SF 3 "gpc_reg_operand" "f") (parallel [(const_int 0)]))) (fma:SF (vec_select:SF (match_dup 1) (parallel [(const_int 1)])) (vec_select:SF (match_dup 2) (parallel [(const_int 1)])) (vec_select:SF (match_dup 3) (parallel [(const_int 1)])))))] "TARGET_PAIRED_FLOAT" "ps_madds1 %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "*paired_madd" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (fma:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f") (match_operand:V2SF 3 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_madd %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "*paired_msub" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (fma:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f") (neg:V2SF (match_operand:V2SF 3 "gpc_reg_operand" "f"))))] "TARGET_PAIRED_FLOAT" "ps_msub %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "*paired_nmadd" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (neg:V2SF (fma:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f") (match_operand:V2SF 3 "gpc_reg_operand" "f"))))] "TARGET_PAIRED_FLOAT" "ps_nmadd %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "*paired_nmsub" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (neg:V2SF (fma:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f") (neg:V2SF (match_operand:V2SF 3 "gpc_reg_operand" "f")))))] "TARGET_PAIRED_FLOAT" "ps_nmsub %0,%1,%2,%3" [(set_attr "type" "dmul")]) (define_insn "selv2sf4" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (if_then_else:SF (ge (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (match_operand:SF 4 "zero_fp_constant" "F")) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 3 "gpc_reg_operand" "f") (parallel [(const_int 0)]))) (if_then_else:SF (ge (vec_select:SF (match_dup 1) (parallel [(const_int 1)])) (match_dup 4)) (vec_select:SF (match_dup 2) (parallel [(const_int 1)])) (vec_select:SF (match_dup 3) (parallel [(const_int 1)])))))] "TARGET_PAIRED_FLOAT" "ps_sel %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "*movv2sf_paired" [(set (match_operand:V2SF 0 "nonimmediate_operand" "=Z,f,f,Y,r,r,f") (match_operand:V2SF 1 "input_operand" "f,Z,f,r,Y,r,W"))] "TARGET_PAIRED_FLOAT && (register_operand (operands[0], V2SFmode) || register_operand (operands[1], V2SFmode))" { switch (which_alternative) { case 0: return "psq_stx %1,%y0,0,0"; case 1: return "psq_lx %0,%y1,0,0"; case 2: return "ps_mr %0,%1"; case 3: return "#"; case 4: return "#"; case 5: return "#"; case 6: return "#"; default: gcc_unreachable (); } } [(set_attr "type" "fpstore,fpload,fp,*,*,*,*")]) (define_insn "paired_stx" [(set (match_operand:V2SF 0 "memory_operand" "=Z") (match_operand:V2SF 1 "gpc_reg_operand" "f"))] "TARGET_PAIRED_FLOAT" "psq_stx %1,%y0,0,0" [(set_attr "type" "fpstore")]) (define_insn "paired_lx" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (match_operand:V2SF 1 "memory_operand" "Z"))] "TARGET_PAIRED_FLOAT" "psq_lx %0,%y1,0,0" [(set_attr "type" "fpload")]) (define_split [(set (match_operand:V2SF 0 "nonimmediate_operand" "") (match_operand:V2SF 1 "input_operand" ""))] "TARGET_PAIRED_FLOAT && reload_completed && gpr_or_gpr_p (operands[0], operands[1])" [(pc)] { rs6000_split_multireg_move (operands[0], operands[1]); DONE; }) (define_insn "paired_cmpu0" [(set (match_operand:CCFP 0 "cc_reg_operand" "=y") (compare:CCFP (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 0)]))))] "TARGET_PAIRED_FLOAT" "ps_cmpu0 %0,%1,%2" [(set_attr "type" "fpcompare")]) (define_insn "paired_cmpu1" [(set (match_operand:CCFP 0 "cc_reg_operand" "=y") (compare:CCFP (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 1)])) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 1)]))))] "TARGET_PAIRED_FLOAT" "ps_cmpu1 %0,%1,%2" [(set_attr "type" "fpcompare")]) (define_insn "paired_merge00" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_select:V2SF (vec_concat:V4SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")) (parallel [(const_int 0) (const_int 2)])))] "TARGET_PAIRED_FLOAT" "ps_merge00 %0, %1, %2" [(set_attr "type" "fp")]) (define_insn "paired_merge01" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_select:V2SF (vec_concat:V4SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")) (parallel [(const_int 0) (const_int 3)])))] "TARGET_PAIRED_FLOAT" "ps_merge01 %0, %1, %2" [(set_attr "type" "fp")]) (define_insn "paired_merge10" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_select:V2SF (vec_concat:V4SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")) (parallel [(const_int 1) (const_int 2)])))] "TARGET_PAIRED_FLOAT" "ps_merge10 %0, %1, %2" [(set_attr "type" "fp")]) (define_insn "paired_merge11" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_select:V2SF (vec_concat:V4SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")) (parallel [(const_int 1) (const_int 3)])))] "TARGET_PAIRED_FLOAT" "ps_merge11 %0, %1, %2" [(set_attr "type" "fp")]) (define_expand "vec_perm_constv2sf" [(match_operand:V2SF 0 "gpc_reg_operand" "") (match_operand:V2SF 1 "gpc_reg_operand" "") (match_operand:V2SF 2 "gpc_reg_operand" "") (match_operand:V2SI 3 "" "")] "TARGET_PAIRED_FLOAT" { if (rs6000_expand_vec_perm_const (operands)) DONE; else FAIL; }) (define_insn "paired_sum0" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (plus:SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 1)]))) (vec_select:SF (match_operand:V2SF 3 "gpc_reg_operand" "f") (parallel [(const_int 1)]))))] "TARGET_PAIRED_FLOAT" "ps_sum0 %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "paired_sum1" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (vec_select:SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (parallel [(const_int 1)])) (plus:SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])) (vec_select:SF (match_operand:V2SF 3 "gpc_reg_operand" "f") (parallel [(const_int 1)])))))] "TARGET_PAIRED_FLOAT" "ps_sum1 %0,%1,%2,%3" [(set_attr "type" "fp")]) (define_insn "paired_muls0" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (mult:V2SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (vec_duplicate:V2SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 0)])))))] "TARGET_PAIRED_FLOAT" "ps_muls0 %0, %1, %2" [(set_attr "type" "fp")]) (define_insn "paired_muls1" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (mult:V2SF (match_operand:V2SF 2 "gpc_reg_operand" "f") (vec_duplicate:V2SF (vec_select:SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (parallel [(const_int 1)])))))] "TARGET_PAIRED_FLOAT" "ps_muls1 %0, %1, %2" [(set_attr "type" "fp")]) (define_expand "vec_initv2sf" [(match_operand:V2SF 0 "gpc_reg_operand" "=f") (match_operand 1 "" "")] "TARGET_PAIRED_FLOAT" { paired_expand_vector_init (operands[0], operands[1]); DONE; }) (define_insn "*vconcatsf" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (vec_concat:V2SF (match_operand:SF 1 "gpc_reg_operand" "f") (match_operand:SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" "ps_merge00 %0, %1, %2" [(set_attr "type" "fp")]) (define_expand "sminv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (smin:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" { rtx tmp = gen_reg_rtx (V2SFmode); emit_insn (gen_subv2sf3 (tmp, operands[1], operands[2])); emit_insn (gen_selv2sf4 (operands[0], tmp, operands[2], operands[1], CONST0_RTX (SFmode))); DONE; }) (define_expand "smaxv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (smax:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT" { rtx tmp = gen_reg_rtx (V2SFmode); emit_insn (gen_subv2sf3 (tmp, operands[1], operands[2])); emit_insn (gen_selv2sf4 (operands[0], tmp, operands[1], operands[2], CONST0_RTX (SFmode))); DONE; }) (define_expand "reduc_smax_v2sf" [(match_operand:V2SF 0 "gpc_reg_operand" "=f") (match_operand:V2SF 1 "gpc_reg_operand" "f")] "TARGET_PAIRED_FLOAT" { rtx tmp_swap = gen_reg_rtx (V2SFmode); rtx tmp = gen_reg_rtx (V2SFmode); emit_insn (gen_paired_merge10 (tmp_swap, operands[1], operands[1])); emit_insn (gen_subv2sf3 (tmp, operands[1], tmp_swap)); emit_insn (gen_selv2sf4 (operands[0], tmp, operands[1], tmp_swap, CONST0_RTX (SFmode))); DONE; }) (define_expand "reduc_smin_v2sf" [(match_operand:V2SF 0 "gpc_reg_operand" "=f") (match_operand:V2SF 1 "gpc_reg_operand" "f")] "TARGET_PAIRED_FLOAT" { rtx tmp_swap = gen_reg_rtx (V2SFmode); rtx tmp = gen_reg_rtx (V2SFmode); emit_insn (gen_paired_merge10 (tmp_swap, operands[1], operands[1])); emit_insn (gen_subv2sf3 (tmp, operands[1], tmp_swap)); emit_insn (gen_selv2sf4 (operands[0], tmp, tmp_swap, operands[1], CONST0_RTX (SFmode))); DONE; }) (define_expand "reduc_splus_v2sf" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (match_operand:V2SF 1 "gpc_reg_operand" "f"))] "TARGET_PAIRED_FLOAT" " { emit_insn (gen_paired_sum1 (operands[0], operands[1], operands[1], operands[1])); DONE; }") (define_expand "movmisalignv2sf" [(set (match_operand:V2SF 0 "nonimmediate_operand" "") (match_operand:V2SF 1 "any_operand" ""))] "TARGET_PAIRED_FLOAT" { paired_expand_vector_move (operands); DONE; }) (define_expand "vcondv2sfv2sf" [(set (match_operand:V2SF 0 "gpc_reg_operand" "=f") (if_then_else:V2SF (match_operator 3 "gpc_reg_operand" [(match_operand:V2SF 4 "gpc_reg_operand" "f") (match_operand:V2SF 5 "gpc_reg_operand" "f")]) (match_operand:V2SF 1 "gpc_reg_operand" "f") (match_operand:V2SF 2 "gpc_reg_operand" "f")))] "TARGET_PAIRED_FLOAT && flag_unsafe_math_optimizations" { if (paired_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; })
periclesroalves/gcc-conair
gcc/config/rs6000/paired.md
Markdown
gpl-2.0
16,016
// { dg-require-c-std "" } // Copyright (C) 2011-2014 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. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <complex> #include <limits> #include <testsuite_hooks.h> template<typename T> void do_test01() { bool test __attribute__((unused)) = true; if (std::numeric_limits<T>::has_quiet_NaN) { std::complex<T> c1(T(0), std::numeric_limits<T>::quiet_NaN()); VERIFY( c1.real() == T(0) ); VERIFY( std::isnan(c1.imag()) ); std::complex<T> c2(std::numeric_limits<T>::quiet_NaN(), T(0)); VERIFY( std::isnan(c2.real()) ); VERIFY( c2.imag() == T(0) ); std::complex<T> c3(std::numeric_limits<T>::quiet_NaN(), std::numeric_limits<T>::quiet_NaN()); VERIFY( std::isnan(c3.real()) ); VERIFY( std::isnan(c3.imag()) ); } } // libstdc++/48760 void test01() { do_test01<float>(); do_test01<double>(); do_test01<long double>(); } int main() { test01(); return 0; }
xinchoubiology/gcc
libstdc++-v3/testsuite/26_numerics/complex/cons/48760.cc
C++
gpl-2.0
1,595
// 2003-10-14 Paolo Carlini <pcarlini@unitus.it> // Copyright (C) 2003-2014 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. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 25.2.8 [lib.alg.unique] Unique #include <list> #include <algorithm> #include <functional> #include <testsuite_hooks.h> const int T1[] = {1, 4, 4, 6, 1, 2, 2, 3, 1, 6, 6, 6, 5, 7, 5, 4, 4}; const int T2[] = {1, 1, 1, 2, 2, 1, 1, 7, 6, 6, 7, 8, 8, 8, 8, 9, 9}; const int N = sizeof(T1) / sizeof(int); const int A1[] = {1, 4, 6, 1, 2, 3, 1, 6, 5, 7, 5, 4}; const int A2[] = {1, 4, 4, 6, 6, 6, 6, 7}; const int A3[] = {1, 1, 1}; const int B1[] = {1, 2, 1, 7, 6, 7, 8, 9}; const int B2[] = {1, 1, 1, 2, 2, 7, 7, 8, 8, 8, 8, 9, 9}; const int B3[] = {9, 9, 8, 8, 8, 8, 7, 6, 6, 1, 1, 1, 1, 1}; void test01() { bool test __attribute__((unused)) = true; using namespace std; list<int>::iterator pos; list<int> coll(T1, T1 + N); pos = unique(coll.begin(), coll.end()); VERIFY( equal(coll.begin(), pos, A1) ); list<int> coll2(T2, T2 + N); pos = unique(coll2.begin(), coll2.end()); VERIFY( equal(coll2.begin(), pos, B1) ); } void test02() { bool test __attribute__((unused)) = true; using namespace std; list<int>::iterator pos; list<int> coll(T1, T1 + N); pos = unique(coll.begin(), coll.end(), greater<int>()); VERIFY( equal(coll.begin(), pos, A2) ); list<int> coll2(T2, T2 + N); pos = unique(coll2.begin(), coll2.end(), greater<int>()); VERIFY( equal(coll2.begin(), pos, B2) ); } void test03() { bool test __attribute__((unused)) = true; using namespace std; list<int>::iterator pos; list<int> coll(T1, T1 + N); pos = unique(coll.begin(), coll.end(), less<int>()); VERIFY( equal(coll.begin(), pos, A3) ); list<int> coll2(T2, T2 + N); reverse(coll2.begin(), coll2.end()); pos = unique(coll2.begin(), coll2.end(), less<int>()); VERIFY( equal(coll2.begin(), pos, B3) ); } int main() { test01(); test02(); test03(); return 0; }
xinchoubiology/gcc
libstdc++-v3/testsuite/25_algorithms/unique/2.cc
C++
gpl-2.0
2,615
<?php /** * @version $Id: AbstractRokMenuFormatter.php 4585 2012-10-27 01:44:54Z btowles $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ require_once(dirname(__FILE__) . '/RokMenuFormatter.php'); /** * */ abstract class AbstractRokMenuFormatter implements RokMenuFormatter { protected $active_branch = array(); protected $args = array(); protected $current_node = 0; /** * @param $args * @return void */ public function __construct(&$args) { $this->args =& $args; } /** * @param $current_node * @return void */ public function setCurrentNodeId($current_node) { $this->current_node = $current_node; } /** * @param $active_branch * @return void */ public function setActiveBranch(array $active_branch) { $this->active_branch = $active_branch; } /** * @param $menu * @return void */ public function format_tree(&$menu) { if (!empty($menu) && $menu !== false) { $this->_default_format_menu($menu); $this->format_menu($menu); $nodeIterator = new RecursiveIteratorIterator($menu, RecursiveIteratorIterator::SELF_FIRST); foreach ($nodeIterator as $node) { $this->_format_subnodes($node); } } } /** * @param $node * @return void */ protected function _format_subnodes(&$node) { if ($node->getId() == $this->current_node) { $node->setCssId('current'); } if (array_key_exists($node->getId(), $this->active_branch)) { $node->addListItemClass('active'); } $this->format_subnode($node); } /** * @param $menu * @return void */ protected function _default_format_menu(&$menu) { // Limit the levels of the tree is called for By limitLevels $start = $this->args['startLevel']; $end = $this->args['endLevel']; if ($this->args['limit_levels']) { //Limit to the active path if the start is more the level 0 if ($start > 0) { $found = false; // get active path and find the start level that matches if (count($this->active_branch)) { foreach ($this->active_branch as $active_child) { if ($active_child->getLevel() == $start - 1) { $menu->resetTop($active_child->getId()); $found = true; break; } } } if (!$found) { $menu->setChildren(array()); } } //remove lower then the defined end level $menu->removeLevel($end); } $always_show_menu = false; if (!array_key_exists('showAllChildren', $this->args) && $start==0) { $always_show_menu = true; } elseif (array_key_exists('showAllChildren', $this->args)) { $always_show_menu = $this->args['showAllChildren']; } if (!$always_show_menu) { if ($menu->hasChildren()) { if (count($this->active_branch) == 0 || empty($this->active_branch)) { $menu->removeLevel($start); } else { $active = array_keys($this->active_branch); foreach ($menu->getChildren() as $toplevel) { if (array_key_exists($toplevel->getId(), $this->active_branch) !== false) { end($active); $menu->removeIfNotInTree($active, current($active)); } else { if (count($this->active_branch) > 0) $menu->removeLevelFromNonActive($this->active_branch, end($this->active_branch)->getLevel()); } } } } } } /** * @param $menu * @return void */ public function format_menu(&$menu) { } }
pdonaire1/gisaga
tmp/install_544db754ed102/mod_roknavmenu/lib/librokmenu/AbstractRokMenuFormatter.php
PHP
gpl-2.0
4,658
/* * Copyright (c) 2006, 2007 QLogic Corporation. All rights reserved. * Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/list.h> #include <linux/rcupdate.h> #include "ipath_verbs.h" /* * Global table of GID to attached QPs. * The table is global to all ipath devices since a send from one QP/device * needs to be locally routed to any locally attached QPs on the same * or different device. */ static struct rb_root mcast_tree; static DEFINE_SPINLOCK(mcast_lock); /** * ipath_mcast_qp_alloc - alloc a struct to link a QP to mcast GID struct * @qp: the QP to link */ static struct ipath_mcast_qp *ipath_mcast_qp_alloc(struct ipath_qp *qp) { struct ipath_mcast_qp *mqp; mqp = kmalloc(sizeof *mqp, GFP_KERNEL); if (!mqp) goto bail; mqp->qp = qp; atomic_inc(&qp->refcount); bail: return mqp; } static void ipath_mcast_qp_free(struct ipath_mcast_qp *mqp) { struct ipath_qp *qp = mqp->qp; /* Notify ipath_destroy_qp() if it is waiting. */ if (atomic_dec_and_test(&qp->refcount)) wake_up(&qp->wait); kfree(mqp); } /** * ipath_mcast_alloc - allocate the multicast GID structure * @mgid: the multicast GID * * A list of QPs will be attached to this structure. */ static struct ipath_mcast *ipath_mcast_alloc(union ib_gid *mgid) { struct ipath_mcast *mcast; mcast = kmalloc(sizeof *mcast, GFP_KERNEL); if (!mcast) goto bail; mcast->mgid = *mgid; INIT_LIST_HEAD(&mcast->qp_list); init_waitqueue_head(&mcast->wait); atomic_set(&mcast->refcount, 0); mcast->n_attached = 0; bail: return mcast; } static void ipath_mcast_free(struct ipath_mcast *mcast) { struct ipath_mcast_qp *p, *tmp; list_for_each_entry_safe(p, tmp, &mcast->qp_list, list) ipath_mcast_qp_free(p); kfree(mcast); } /** * ipath_mcast_find - search the global table for the given multicast GID * @mgid: the multicast GID to search for * * Returns NULL if not found. * * The caller is responsible for decrementing the reference count if found. */ struct ipath_mcast *ipath_mcast_find(union ib_gid *mgid) { struct rb_node *n; unsigned long flags; struct ipath_mcast *mcast; spin_lock_irqsave(&mcast_lock, flags); n = mcast_tree.rb_node; while (n) { int ret; mcast = rb_entry(n, struct ipath_mcast, rb_node); ret = memcmp(mgid->raw, mcast->mgid.raw, sizeof(union ib_gid)); if (ret < 0) n = n->rb_left; else if (ret > 0) n = n->rb_right; else { atomic_inc(&mcast->refcount); spin_unlock_irqrestore(&mcast_lock, flags); goto bail; } } spin_unlock_irqrestore(&mcast_lock, flags); mcast = NULL; bail: return mcast; } /** * ipath_mcast_add - insert mcast GID into table and attach QP struct * @mcast: the mcast GID table * @mqp: the QP to attach * * Return zero if both were added. Return EEXIST if the GID was already in * the table but the QP was added. Return ESRCH if the QP was already * attached and neither structure was added. */ static int ipath_mcast_add(struct ipath_ibdev *dev, struct ipath_mcast *mcast, struct ipath_mcast_qp *mqp) { struct rb_node **n = &mcast_tree.rb_node; struct rb_node *pn = NULL; int ret; spin_lock_irq(&mcast_lock); while (*n) { struct ipath_mcast *tmcast; struct ipath_mcast_qp *p; pn = *n; tmcast = rb_entry(pn, struct ipath_mcast, rb_node); ret = memcmp(mcast->mgid.raw, tmcast->mgid.raw, sizeof(union ib_gid)); if (ret < 0) { n = &pn->rb_left; continue; } if (ret > 0) { n = &pn->rb_right; continue; } /* Search the QP list to see if this is already there. */ list_for_each_entry_rcu(p, &tmcast->qp_list, list) { if (p->qp == mqp->qp) { ret = ESRCH; goto bail; } } if (tmcast->n_attached == ib_ipath_max_mcast_qp_attached) { ret = ENOMEM; goto bail; } tmcast->n_attached++; list_add_tail_rcu(&mqp->list, &tmcast->qp_list); ret = EEXIST; goto bail; } spin_lock(&dev->n_mcast_grps_lock); if (dev->n_mcast_grps_allocated == ib_ipath_max_mcast_grps) { spin_unlock(&dev->n_mcast_grps_lock); ret = ENOMEM; goto bail; } dev->n_mcast_grps_allocated++; spin_unlock(&dev->n_mcast_grps_lock); mcast->n_attached++; list_add_tail_rcu(&mqp->list, &mcast->qp_list); atomic_inc(&mcast->refcount); rb_link_node(&mcast->rb_node, pn, n); rb_insert_color(&mcast->rb_node, &mcast_tree); ret = 0; bail: spin_unlock_irq(&mcast_lock); return ret; } int ipath_multicast_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid) { struct ipath_qp *qp = to_iqp(ibqp); struct ipath_ibdev *dev = to_idev(ibqp->device); struct ipath_mcast *mcast; struct ipath_mcast_qp *mqp; int ret; /* * Allocate data structures since its better to do this outside of * spin locks and it will most likely be needed. */ mcast = ipath_mcast_alloc(gid); if (mcast == NULL) { ret = -ENOMEM; goto bail; } mqp = ipath_mcast_qp_alloc(qp); if (mqp == NULL) { ipath_mcast_free(mcast); ret = -ENOMEM; goto bail; } switch (ipath_mcast_add(dev, mcast, mqp)) { case ESRCH: /* Neither was used: can't attach the same QP twice. */ ipath_mcast_qp_free(mqp); ipath_mcast_free(mcast); ret = -EINVAL; goto bail; case EEXIST: /* The mcast wasn't used */ ipath_mcast_free(mcast); break; case ENOMEM: /* Exceeded the maximum number of mcast groups. */ ipath_mcast_qp_free(mqp); ipath_mcast_free(mcast); ret = -ENOMEM; goto bail; default: break; } ret = 0; bail: return ret; } int ipath_multicast_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid) { struct ipath_qp *qp = to_iqp(ibqp); struct ipath_ibdev *dev = to_idev(ibqp->device); struct ipath_mcast *mcast = NULL; struct ipath_mcast_qp *p, *tmp; struct rb_node *n; int last = 0; int ret; spin_lock_irq(&mcast_lock); /* Find the GID in the mcast table. */ n = mcast_tree.rb_node; while (1) { if (n == NULL) { spin_unlock_irq(&mcast_lock); ret = -EINVAL; goto bail; } mcast = rb_entry(n, struct ipath_mcast, rb_node); ret = memcmp(gid->raw, mcast->mgid.raw, sizeof(union ib_gid)); if (ret < 0) n = n->rb_left; else if (ret > 0) n = n->rb_right; else break; } /* Search the QP list. */ list_for_each_entry_safe(p, tmp, &mcast->qp_list, list) { if (p->qp != qp) continue; /* * We found it, so remove it, but don't poison the forward * link until we are sure there are no list walkers. */ list_del_rcu(&p->list); mcast->n_attached--; /* If this was the last attached QP, remove the GID too. */ if (list_empty(&mcast->qp_list)) { rb_erase(&mcast->rb_node, &mcast_tree); last = 1; } break; } spin_unlock_irq(&mcast_lock); if (p) { /* * Wait for any list walkers to finish before freeing the * list element. */ wait_event(mcast->wait, atomic_read(&mcast->refcount) <= 1); ipath_mcast_qp_free(p); } if (last) { atomic_dec(&mcast->refcount); wait_event(mcast->wait, !atomic_read(&mcast->refcount)); ipath_mcast_free(mcast); spin_lock_irq(&dev->n_mcast_grps_lock); dev->n_mcast_grps_allocated--; spin_unlock_irq(&dev->n_mcast_grps_lock); } ret = 0; bail: return ret; } int ipath_mcast_tree_empty(void) { return mcast_tree.rb_node == NULL; }
kidmaple/CoolWall
linux-2.6.x/drivers/infiniband/hw/ipath/ipath_verbs_mcast.c
C
gpl-2.0
8,559
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com */ #include "tomcrypt.h" /** @file der_length_bit_string.c ASN.1 DER, get length of BIT STRING, Tom St Denis */ #ifdef LTC_DER /** Gets length of DER encoding of BIT STRING @param nbits The number of bits in the string to encode @param outlen [out] The length of the DER encoding for the given string @return CRYPT_OK if successful */ int der_length_bit_string(unsigned long nbits, unsigned long *outlen) { unsigned long nbytes; LTC_ARGCHK(outlen != NULL); /* get the number of the bytes */ nbytes = (nbits >> 3) + ((nbits & 7) ? 1 : 0) + 1; if (nbytes < 128) { /* 03 LL PP DD DD DD ... */ *outlen = 2 + nbytes; } else if (nbytes < 256) { /* 03 81 LL PP DD DD DD ... */ *outlen = 3 + nbytes; } else if (nbytes < 65536) { /* 03 82 LL LL PP DD DD DD ... */ *outlen = 4 + nbytes; } else { return CRYPT_INVALID_ARG; } return CRYPT_OK; } #endif /* $Source: /cvs/libtom/libtomcrypt/src/pk/asn1/der/bit/der_length_bit_string.c,v $ */ /* $Revision: 1.2 $ */ /* $Date: 2006/03/31 14:15:35 $ */
rhuitl/uClinux
user/dropbear/libtomcrypt/src/pk/asn1/der/bit/der_length_bit_string.c
C
gpl-2.0
1,416
/**************************************************************************** **************************************************************************** *** *** This header was automatically generated from a Linux kernel header *** of the same name, to make information necessary for userspace to *** call into the kernel available to libc. It contains only constants, *** structures, and macros generated from the original header, and thus, *** contains no copyrightable information. *** *** To edit the content of this header, modify the corresponding *** source file (e.g. under external/kernel-headers/original/) then *** run bionic/libc/kernel/tools/update_all.py *** *** Any manual change here will be lost the next time this script will *** be run. You've been warned! *** **************************************************************************** ****************************************************************************/ #ifndef _ASM_RESOURCE_H #define _ASM_RESOURCE_H #define RLIMIT_NOFILE 5 #define RLIMIT_AS 6 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ #define RLIMIT_RSS 7 #define RLIMIT_NPROC 8 #define RLIMIT_MEMLOCK 9 #ifndef __mips64 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ #define RLIM_INFINITY 0x7fffffffUL #endif #include <asm-generic/resource.h> #endif /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
s20121035/rk3288_android5.1_repo
bionic/libc/kernel/uapi/asm-mips/asm/resource.h
C
gpl-3.0
1,461
<!doctype html> <html> <head> <title>Name test case 601</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "foo" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "foo" ] ], "IAccessible2" : [ [ "property", "accName", "is", "foo" ] ], "UIA" : [ [ "property", "Name", "is", "foo" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 601" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name test case 601.</p> <div id="test" role="button">foo</div> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
UK992/servo
tests/wpt/web-platform-tests/accname/name_test_case_601-manual.html
HTML
mpl-2.0
1,661
# frozen_string_literal: true class StatusFinder attr_reader :url def initialize(url) @url = url end def status verify_action! raise ActiveRecord::RecordNotFound unless TagManager.instance.local_url?(url) case recognized_params[:controller] when 'statuses' Status.find(recognized_params[:id]) else raise ActiveRecord::RecordNotFound end end private def recognized_params Rails.application.routes.recognize_path(url) end def verify_action! unless recognized_params[:action] == 'show' raise ActiveRecord::RecordNotFound end end end
tootsuite/mastodon
app/lib/status_finder.rb
Ruby
agpl-3.0
616
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaiproject.importer.impl; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.sakaiproject.importer.api.ImportDataSource; import org.sakaiproject.importer.api.ImportFileParser; import org.sakaiproject.importer.impl.importables.Assessment; import org.sakaiproject.importer.impl.importables.HtmlDocument; @Slf4j public class CommonCartridgeTest { private static ImportFileParser parser = null; private InputStream archiveStream = null; @Before public void setUp() { try { parser = new CommonCartridgeFileParser(); FileInputStream archiveStream = new FileInputStream(new File("psychology.zip")); } catch (IOException e) { log.error(e.getMessage(), e); } } @Ignore @Test public void testIsValidArchive() { Assert.assertTrue(parser.isValidArchive(archiveStream)); } @Ignore @Test public void testCanGetQti() { ImportDataSource ids = parser.parse(archiveStream, "psychology"); Collection importables = ids.getItemsForCategories(ids.getItemCategories()); int numberOfAssessments = 0; int numberOfWebContent = 0; for (Iterator i = importables.iterator();i.hasNext();) { Object x = i.next(); if(x instanceof Assessment) { numberOfAssessments++; } else if(x instanceof HtmlDocument) { numberOfWebContent++; } } log.debug("{} top-level items", ids.getItemCategories().size()); log.debug("{} importables", importables.size()); log.debug("{} assessments", numberOfAssessments); log.debug("{} webcontent", numberOfWebContent); Assert.assertTrue("Why no assessments?", numberOfAssessments > 0); } }
OpenCollabZA/sakai
common/import-parsers/common-cartridge/src/test/java/org/sakaiproject/importer/impl/CommonCartridgeTest.java
Java
apache-2.0
2,737
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- namespace Behavior; /** * 系统行为扩展:模板内容输出替换 */ class ContentReplaceBehavior { // 行为扩展的执行入口必须是run public function run(&$content){ $content = $this->templateContentReplace($content); } /** * 模板内容替换 * @access protected * @param string $content 模板内容 * @return string */ protected function templateContentReplace($content) { // 系统默认的特殊变量替换 $replace = array( '__ROOT__' => __ROOT__, // 当前网站地址 '__APP__' => __APP__, // 当前应用地址 '__MODULE__' => __MODULE__, '__ACTION__' => __ACTION__, // 当前操作地址 '__SELF__' => htmlentities(__SELF__), // 当前页面地址 '__CONTROLLER__'=> __CONTROLLER__, '__URL__' => __CONTROLLER__, '__PUBLIC__' => __ROOT__.'/Public',// 站点公共目录 ); // 允许用户自定义模板的字符串替换 if(is_array(C('TMPL_PARSE_STRING')) ) $replace = array_merge($replace,C('TMPL_PARSE_STRING')); $content = str_replace(array_keys($replace),array_values($replace),$content); return $content; } }
wangzhanjian/php_weiguanjia
weiguanjia/ThinkPHP/Library/Behavior/ContentReplaceBehavior.class.php
PHP
apache-2.0
1,974
cask 'xscreensaver' do version '5.35' sha256 '6ad392df82005b7a6915ebe18eb340e2fc8e1e1dc7d8e0e8a2822be1377f23b7' url "https://www.jwz.org/xscreensaver/xscreensaver-#{version}.dmg" name 'XScreenSaver' homepage 'https://www.jwz.org/xscreensaver/' license :bsd screen_saver 'Screen Savers/Abstractile.saver' screen_saver 'Screen Savers/Anemone.saver' screen_saver 'Screen Savers/Anemotaxis.saver' screen_saver 'Screen Savers/AntInspect.saver' screen_saver 'Screen Savers/AntMaze.saver' screen_saver 'Screen Savers/AntSpotlight.saver' screen_saver 'Screen Savers/Apollonian.saver' screen_saver 'Screen Savers/Apple2.app' screen_saver 'Screen Savers/Apple2.saver' screen_saver 'Screen Savers/Atlantis.saver' screen_saver 'Screen Savers/Attraction.saver' screen_saver 'Screen Savers/Atunnel.saver' screen_saver 'Screen Savers/Barcode.saver' screen_saver 'Screen Savers/BinaryRing.saver' screen_saver 'Screen Savers/Blaster.saver' screen_saver 'Screen Savers/BlinkBox.saver' screen_saver 'Screen Savers/BlitSpin.saver' screen_saver 'Screen Savers/BlockTube.saver' screen_saver 'Screen Savers/Boing.saver' screen_saver 'Screen Savers/Bouboule.saver' screen_saver 'Screen Savers/BouncingCow.saver' screen_saver 'Screen Savers/Boxed.saver' screen_saver 'Screen Savers/BoxFit.saver' screen_saver 'Screen Savers/Braid.saver' screen_saver 'Screen Savers/BSOD.saver' screen_saver 'Screen Savers/Bubble3D.saver' screen_saver 'Screen Savers/Bumps.saver' screen_saver 'Screen Savers/Cage.saver' screen_saver 'Screen Savers/Carousel.saver' screen_saver 'Screen Savers/CCurve.saver' screen_saver 'Screen Savers/Celtic.saver' screen_saver 'Screen Savers/Circuit.saver' screen_saver 'Screen Savers/Cityflow.saver' screen_saver 'Screen Savers/CloudLife.saver' screen_saver 'Screen Savers/CompanionCube.saver' screen_saver 'Screen Savers/Compass.saver' screen_saver 'Screen Savers/Coral.saver' screen_saver 'Screen Savers/Crackberg.saver' screen_saver 'Screen Savers/Crystal.saver' screen_saver 'Screen Savers/Cube21.saver' screen_saver 'Screen Savers/Cubenetic.saver' screen_saver 'Screen Savers/CubeStorm.saver' screen_saver 'Screen Savers/CubicGrid.saver' screen_saver 'Screen Savers/CWaves.saver' screen_saver 'Screen Savers/Cynosure.saver' screen_saver 'Screen Savers/DaliClock.saver' screen_saver 'Screen Savers/DangerBall.saver' screen_saver 'Screen Savers/DecayScreen.saver' screen_saver 'Screen Savers/Deco.saver' screen_saver 'Screen Savers/Deluxe.saver' screen_saver 'Screen Savers/Demon.saver' screen_saver 'Screen Savers/Discrete.saver' screen_saver 'Screen Savers/Distort.saver' screen_saver 'Screen Savers/DNAlogo.saver' screen_saver 'Screen Savers/Drift.saver' screen_saver 'Screen Savers/DymaxionMap.saver' screen_saver 'Screen Savers/Endgame.saver' screen_saver 'Screen Savers/EnergyStream.saver' screen_saver 'Screen Savers/Engine.saver' screen_saver 'Screen Savers/Epicycle.saver' screen_saver 'Screen Savers/Eruption.saver' screen_saver 'Screen Savers/Euler2D.saver' screen_saver 'Screen Savers/Extrusion.saver' screen_saver 'Screen Savers/FadePlot.saver' screen_saver 'Screen Savers/Fiberlamp.saver' screen_saver 'Screen Savers/Fireworkx.saver' screen_saver 'Screen Savers/Flame.saver' screen_saver 'Screen Savers/FlipFlop.saver' screen_saver 'Screen Savers/FlipScreen3D.saver' screen_saver 'Screen Savers/FlipText.saver' screen_saver 'Screen Savers/Flow.saver' screen_saver 'Screen Savers/FluidBalls.saver' screen_saver 'Screen Savers/FlyingToasters.saver' screen_saver 'Screen Savers/FontGlide.saver' screen_saver 'Screen Savers/FuzzyFlakes.saver' screen_saver 'Screen Savers/Galaxy.saver' screen_saver 'Screen Savers/Gears.saver' screen_saver 'Screen Savers/Geodesic.saver' screen_saver 'Screen Savers/GeodesicGears.saver' screen_saver 'Screen Savers/GFlux.saver' screen_saver 'Screen Savers/GLBlur.saver' screen_saver 'Screen Savers/GLCells.saver' screen_saver 'Screen Savers/Gleidescope.saver' screen_saver 'Screen Savers/GLHanoi.saver' screen_saver 'Screen Savers/GLKnots.saver' screen_saver 'Screen Savers/GLMatrix.saver' screen_saver 'Screen Savers/GLPlanet.saver' screen_saver 'Screen Savers/GLSchool.saver' screen_saver 'Screen Savers/GLSlideshow.saver' screen_saver 'Screen Savers/GLSnake.saver' screen_saver 'Screen Savers/GLText.saver' screen_saver 'Screen Savers/Goop.saver' screen_saver 'Screen Savers/Grav.saver' screen_saver 'Screen Savers/Greynetic.saver' screen_saver 'Screen Savers/Halftone.saver' screen_saver 'Screen Savers/Halo.saver' screen_saver 'Screen Savers/Helix.saver' screen_saver 'Screen Savers/Hexadrop.saver' screen_saver 'Screen Savers/Hilbert.saver' screen_saver 'Screen Savers/Hopalong.saver' screen_saver 'Screen Savers/Hydrostat.saver' screen_saver 'Screen Savers/Hypertorus.saver' screen_saver 'Screen Savers/Hypnowheel.saver' screen_saver 'Screen Savers/IFS.saver' screen_saver 'Screen Savers/IMSMap.saver' screen_saver 'Screen Savers/Interaggregate.saver' screen_saver 'Screen Savers/Interference.saver' screen_saver 'Screen Savers/Intermomentary.saver' screen_saver 'Screen Savers/JigglyPuff.saver' screen_saver 'Screen Savers/Jigsaw.saver' screen_saver 'Screen Savers/Juggler3D.saver' screen_saver 'Screen Savers/Julia.saver' screen_saver 'Screen Savers/Kaleidescope.saver' screen_saver 'Screen Savers/Kaleidocycle.saver' screen_saver 'Screen Savers/Klein.saver' screen_saver 'Screen Savers/Kumppa.saver' screen_saver 'Screen Savers/Lament.saver' screen_saver 'Screen Savers/Lavalite.saver' screen_saver 'Screen Savers/LCDscrub.saver' screen_saver 'Screen Savers/Lockward.saver' screen_saver 'Screen Savers/Loop.saver' screen_saver 'Screen Savers/m6502.saver' screen_saver 'Screen Savers/Maze.saver' screen_saver 'Screen Savers/MemScroller.saver' screen_saver 'Screen Savers/Menger.saver' screen_saver 'Screen Savers/MetaBalls.saver' screen_saver 'Screen Savers/MirrorBlob.saver' screen_saver 'Screen Savers/Moebius.saver' screen_saver 'Screen Savers/MoebiusGears.saver' screen_saver 'Screen Savers/Moire.saver' screen_saver 'Screen Savers/Moire2.saver' screen_saver 'Screen Savers/Molecule.saver' screen_saver 'Screen Savers/Morph3D.saver' screen_saver 'Screen Savers/Mountain.saver' screen_saver 'Screen Savers/Munch.saver' screen_saver 'Screen Savers/NerveRot.saver' screen_saver 'Screen Savers/Noof.saver' screen_saver 'Screen Savers/NoseGuy.saver' screen_saver 'Screen Savers/Pacman.saver' screen_saver 'Screen Savers/Pedal.saver' screen_saver 'Screen Savers/Penetrate.saver' screen_saver 'Screen Savers/Penrose.saver' screen_saver 'Screen Savers/Petri.saver' screen_saver 'Screen Savers/Phosphor.app' screen_saver 'Screen Savers/Phosphor.saver' screen_saver 'Screen Savers/Photopile.saver' screen_saver 'Screen Savers/Piecewise.saver' screen_saver 'Screen Savers/Pinion.saver' screen_saver 'Screen Savers/Pipes.saver' screen_saver 'Screen Savers/Polyhedra.saver' screen_saver 'Screen Savers/Polyominoes.saver' screen_saver 'Screen Savers/Polytopes.saver' screen_saver 'Screen Savers/Pong.saver' screen_saver 'Screen Savers/PopSquares.saver' screen_saver 'Screen Savers/ProjectivePlane.saver' screen_saver 'Screen Savers/Providence.saver' screen_saver 'Screen Savers/Pulsar.saver' screen_saver 'Screen Savers/Pyro.saver' screen_saver 'Screen Savers/Qix.saver' screen_saver 'Screen Savers/QuasiCrystal.saver' screen_saver 'Screen Savers/Queens.saver' screen_saver 'Screen Savers/RaverHoop.saver' screen_saver 'Screen Savers/RDbomb.saver' screen_saver 'Screen Savers/Ripples.saver' screen_saver 'Screen Savers/Rocks.saver' screen_saver 'Screen Savers/RomanBoy.saver' screen_saver 'Screen Savers/Rorschach.saver' screen_saver 'Screen Savers/RotZoomer.saver' screen_saver 'Screen Savers/Rubik.saver' screen_saver 'Screen Savers/RubikBlocks.saver' screen_saver 'Screen Savers/SBalls.saver' screen_saver 'Screen Savers/ShadeBobs.saver' screen_saver 'Screen Savers/Sierpinski.saver' screen_saver 'Screen Savers/Sierpinski3D.saver' screen_saver 'Screen Savers/SkyTentacles.saver' screen_saver 'Screen Savers/SlideScreen.saver' screen_saver 'Screen Savers/Slip.saver' screen_saver 'Screen Savers/Sonar.saver' screen_saver 'Screen Savers/SpeedMine.saver' screen_saver 'Screen Savers/Spheremonics.saver' screen_saver 'Screen Savers/SplitFlap.saver' screen_saver 'Screen Savers/Spotlight.saver' screen_saver 'Screen Savers/Sproingies.saver' screen_saver 'Screen Savers/Squiral.saver' screen_saver 'Screen Savers/Stairs.saver' screen_saver 'Screen Savers/Starfish.saver' screen_saver 'Screen Savers/StarWars.saver' screen_saver 'Screen Savers/StonerView.saver' screen_saver 'Screen Savers/Strange.saver' screen_saver 'Screen Savers/Substrate.saver' screen_saver 'Screen Savers/Superquadrics.saver' screen_saver 'Screen Savers/Surfaces.saver' screen_saver 'Screen Savers/Swirl.saver' screen_saver 'Screen Savers/Tangram.saver' screen_saver 'Screen Savers/Tessellimage.saver' screen_saver 'Screen Savers/Thornbird.saver' screen_saver 'Screen Savers/TimeTunnel.saver' screen_saver 'Screen Savers/TopBlock.saver' screen_saver 'Screen Savers/Triangle.saver' screen_saver 'Screen Savers/TronBit.saver' screen_saver 'Screen Savers/Truchet.saver' screen_saver 'Screen Savers/Twang.saver' screen_saver 'Screen Savers/Unicrud.saver' screen_saver 'Screen Savers/UnknownPleasures.saver' screen_saver 'Screen Savers/Vermiculate.saver' screen_saver 'Screen Savers/Voronoi.saver' screen_saver 'Screen Savers/Wander.saver' screen_saver 'Screen Savers/WebCollage.saver' screen_saver 'Screen Savers/WhirlWindWarp.saver' screen_saver 'Screen Savers/WindupRobot.saver' screen_saver 'Screen Savers/Wormhole.saver' screen_saver 'Screen Savers/XAnalogTV.saver' screen_saver 'Screen Savers/XFlame.saver' screen_saver 'Screen Savers/XJack.saver' screen_saver 'Screen Savers/XLyap.saver' screen_saver 'Screen Savers/XMatrix.saver' screen_saver 'Screen Savers/XRaySwarm.saver' screen_saver 'Screen Savers/XSpirograph.saver' screen_saver 'Screen Savers/Zoom.saver' end
asbachb/homebrew-cask
Casks/xscreensaver.rb
Ruby
bsd-2-clause
10,327
#!/bin/bash test_info() { cat <<EOF Verify that a mounted NFS share is still operational after failover. We mount an NFS share from a node, write a file via NFS and then confirm that we can correctly read the file after a failover. Prerequisites: * An active CTDB cluster with at least 2 nodes with public addresses. * Test must be run on a real or virtual cluster rather than against local daemons. * Test must not be run from a cluster node. Steps: 1. Verify that the cluster is healthy. 2. Select a public address and its corresponding node. 3. Select the 1st NFS share exported on the node. 4. Mount the selected NFS share. 5. Create a file in the NFS mount and calculate its checksum. 6. Kill CTDB on the selected node. 7. Read the file and calculate its checksum. 8. Compare the checksums. Expected results: * When a node is disabled the public address fails over and it is possible to correctly read a file over NFS. The checksums should be the same before and after. EOF } . "${TEST_SCRIPTS_DIR}/integration.bash" set -e ctdb_test_init "$@" ctdb_test_check_real_cluster cluster_is_healthy # Reset configuration ctdb_restart_when_done nfs_test_setup echo "Create file containing random data..." dd if=/dev/urandom of=$nfs_local_file bs=1k count=1 original_sum=$(sum $nfs_local_file) [ $? -eq 0 ] gratarp_sniff_start echo "Killing node $test_node" try_command_on_node $test_node $CTDB getpid pid=${out#*:} # We need to be nasty to make that the node being failed out doesn't # get a chance to send any tickles or doing anything else clever. IPs # also need to be dropped because we're simulating a dead node rather # than a CTDB failure. To properly handle a CTDB failure we would # need a watchdog to drop the IPs when CTDB disappears. try_command_on_node -v $test_node "kill -9 $pid ; $CTDB_TEST_WRAPPER drop_ips ${test_node_ips}" wait_until_node_has_status $test_node disconnected gratarp_sniff_wait_show new_sum=$(sum $nfs_local_file) [ $? -eq 0 ] if [ "$original_md5" = "$new_md5" ] ; then echo "GOOD: file contents unchanged after failover" else echo "BAD: file contents are different after failover" testfailures=1 fi
SVoxel/R7800
git_home/samba.git/ctdb/tests/complex/45_failover_nfs_kill.sh
Shell
gpl-2.0
2,179
/* SPDX-License-Identifier: MIT */ /* * Copyright © 2019 Intel Corporation */ #ifndef __I915_GEM_REGION_H__ #define __I915_GEM_REGION_H__ #include <linux/types.h> struct intel_memory_region; struct drm_i915_gem_object; struct sg_table; void i915_gem_object_init_memory_region(struct drm_i915_gem_object *obj, struct intel_memory_region *mem); void i915_gem_object_release_memory_region(struct drm_i915_gem_object *obj); struct drm_i915_gem_object * i915_gem_object_create_region(struct intel_memory_region *mem, resource_size_t size, resource_size_t page_size, unsigned int flags); #endif
tprrt/linux-stable
drivers/gpu/drm/i915/gem/i915_gem_region.h
C
gpl-2.0
630
/* Copyright (c) 2008-2010, Code Aurora Forum. 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 of Code Aurora Forum, Inc. 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * 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. * */ #ifndef MSM_FB_PANEL_H #define MSM_FB_PANEL_H #include "msm_fb_def.h" struct msm_fb_data_type; typedef void (*msm_fb_vsync_handler_type) (void *arg); /* panel id type */ typedef struct panel_id_s { uint16 id; uint16 type; } panel_id_type; /* panel type list */ #define NO_PANEL 0xffff /* No Panel */ #define MDDI_PANEL 1 /* MDDI */ #define EBI2_PANEL 2 /* EBI2 */ #define LCDC_PANEL 3 /* internal LCDC type */ #define EXT_MDDI_PANEL 4 /* Ext.MDDI */ #define TV_PANEL 5 /* TV */ #define HDMI_PANEL 6 /* HDMI TV */ #define DTV_PANEL 7 /* DTV */ #define MIPI_VIDEO_PANEL 8 /* MIPI */ #define MIPI_CMD_PANEL 9 /* MIPI */ /* panel class */ typedef enum { DISPLAY_LCD = 0, /* lcd = ebi2/mddi */ DISPLAY_LCDC, /* lcdc */ DISPLAY_TV, /* TV Out */ DISPLAY_EXT_MDDI, /* External MDDI */ } DISP_TARGET; /* panel device locaiton */ typedef enum { DISPLAY_1 = 0, /* attached as first device */ DISPLAY_2, /* attached on second device */ MAX_PHYS_TARGET_NUM, } DISP_TARGET_PHYS; /* panel info type */ struct lcd_panel_info { __u32 vsync_enable; __u32 refx100; __u32 v_back_porch; __u32 v_front_porch; __u32 v_pulse_width; __u32 hw_vsync_mode; __u32 vsync_notifier_period; __u32 rev; }; struct lcdc_panel_info { __u32 h_back_porch; __u32 h_front_porch; __u32 h_pulse_width; __u32 v_back_porch; __u32 v_front_porch; __u32 v_pulse_width; __u32 border_clr; __u32 underflow_clr; __u32 hsync_skew; }; struct mddi_panel_info { __u32 vdopkt; }; /* DSI PHY configuration */ struct mipi_dsi_phy_ctrl { uint32 regulator[4]; uint32 timing[12]; uint32 ctrl[4]; uint32 strength[4]; uint32 pll[21]; }; struct mipi_panel_info { char mode; /* video/cmd */ char interleave_mode; char crc_check; char ecc_check; char dst_format; /* shared by video and command */ char data_lane0; char data_lane1; char data_lane2; char data_lane3; char dlane_swap; /* data lane swap */ char rgb_swap; char b_sel; char g_sel; char r_sel; char rx_eot_ignore; char tx_eot_append; char t_clk_post; /* 0xc0, DSI_CLKOUT_TIMING_CTRL */ char t_clk_pre; /* 0xc0, DSI_CLKOUT_TIMING_CTRL */ char vc; /* virtual channel */ struct mipi_dsi_phy_ctrl *dsi_phy_db; /* video mode */ char pulse_mode_hsa_he; char hfp_power_stop; char hbp_power_stop; char hsa_power_stop; char eof_bllp_power_stop; char bllp_power_stop; char traffic_mode; /* command mode */ char interleave_max; char insert_dcs_cmd; char wr_mem_continue; char wr_mem_start; char te_sel; char stream; /* 0 or 1 */ char mdp_trigger; char dma_trigger; }; struct msm_panel_info { __u32 xres; __u32 yres; __u32 bpp; __u32 mode2_xres; __u32 mode2_yres; __u32 mode2_bpp; __u32 type; __u32 wait_cycle; DISP_TARGET_PHYS pdest; __u32 bl_max; __u32 bl_min; __u32 fb_num; __u32 clk_rate; __u32 clk_min; __u32 clk_max; __u32 frame_count; union { struct mddi_panel_info mddi; }; union { struct lcd_panel_info lcd; struct lcdc_panel_info lcdc; }; struct mipi_panel_info mipi; }; #define MSM_FB_SINGLE_MODE_PANEL(pinfo) \ do { \ (pinfo)->mode2_xres = 0; \ (pinfo)->mode2_yres = 0; \ (pinfo)->mode2_bpp = 0; \ } while (0) struct msm_fb_panel_data { struct msm_panel_info panel_info; void (*set_rect) (int x, int y, int xres, int yres); void (*set_vsync_notifier) (msm_fb_vsync_handler_type, void *arg); void (*set_backlight) (struct msm_fb_data_type *); void (*display_on) (struct msm_fb_data_type *); /* function entry chain */ int (*on) (struct platform_device *pdev); int (*off) (struct platform_device *pdev); void (*bklswitch) (struct msm_fb_data_type *, bool on); void (*bklctrl) (bool on); void (*panel_type_detect) (void); struct platform_device *next; int (*clk_func) (int enable); }; /*=========================================================================== FUNCTIONS PROTOTYPES ============================================================================*/ struct platform_device *msm_fb_device_alloc(struct msm_fb_panel_data *pdata, u32 type, u32 id); int panel_next_on(struct platform_device *pdev); int panel_next_off(struct platform_device *pdev); int lcdc_device_register(struct msm_panel_info *pinfo); int mddi_toshiba_device_register(struct msm_panel_info *pinfo, u32 channel, u32 panel); #endif /* MSM_FB_PANEL_H */
mwalt2/shooter-2.6.35_mr-kernel
drivers/video/msm_8x60/msm_fb_panel.h
C
gpl-2.0
5,894
// VirtualDub - Video processing and capture application // System library component // Copyright (C) 1998-2004 Avery Lee, All Rights Reserved. // // Beginning with 1.6.0, the VirtualDub system library is licensed // differently than the remainder of VirtualDub. This particular file is // thus licensed as follows (the "zlib" license): // // 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. #include "stdafx.h" #include <math.h> #include <vd2/system/math.h> #include <vd2/system/int128.h> int VDRoundToInt(double x) { return (int)floor(x + 0.5); } long VDRoundToLong(double x) { return (long)floor(x + 0.5); } sint32 VDRoundToInt32(double x) { return (sint32)floor(x + 0.5); } sint64 VDRoundToInt64(double x) { return (sint64)floor(x + 0.5); } #if defined(VD_CPU_X86) && defined(VD_COMPILER_MSVC) sint64 __declspec(naked) __stdcall VDFractionScale64(uint64 a, uint32 b, uint32 c, uint32& remainder) { __asm { push edi push ebx mov edi, [esp+12+8] ;edi = b mov eax, [esp+4+8] ;eax = a[lo] mul edi ;edx:eax = a[lo]*b mov ecx, eax ;ecx = (a*b)[lo] mov eax, [esp+8+8] ;eax = a[hi] mov ebx, edx ;ebx = (a*b)[mid] mul edi ;edx:eax = a[hi]*b add eax, ebx mov ebx, [esp+16+8] ;ebx = c adc edx, 0 div ebx ;eax = (a*b)/c [hi], edx = (a[hi]*b)%c mov edi, eax ;edi = (a[hi]*b)/c mov eax, ecx ;eax = (a*b)[lo] mov ecx, [esp+20+8] div ebx ;eax = (a*b)/c [lo], edx = (a*b)%c mov [ecx], edx mov edx, edi pop ebx pop edi ret 20 } } uint64 __declspec(naked) __stdcall VDUMulDiv64x32(uint64 a, uint32 b, uint32 c) { __asm { mov eax, [esp+4] ;eax = a0 mul dword ptr [esp+12] ;edx:eax = a0*b mov dword ptr [esp+4], eax ;tmp = a0*b[0:31] mov ecx, edx ;ecx = a0*b[32:63] mov eax, [esp+8] ;eax = a1 mul dword ptr [esp+12] ;edx:eax = a1*b add eax, ecx ;edx:eax += a0*b[32:95] adc edx, 0 ;(cont.) cmp edx, [esp+16] ;test if a*b[64:95] >= c; equiv to a*b >= (c<<64) jae invalid ;abort if so (overflow) div dword ptr [esp+16] ;edx,eax = ((a*b)[32:95]/c, (a*b)[32:95]%c) mov ecx, eax mov eax, [esp+4] div dword ptr [esp+16] mov edx, ecx ret 16 invalid: mov eax, -1 ;return FFFFFFFFFFFFFFFF mov edx, -1 ret 16 } } #elif !defined(VD_CPU_AMD64) sint64 VDFractionScale64(uint64 a, uint32 b, uint32 c, uint32& remainder) { uint32 a0 = (uint32)a; uint32 a1 = (uint32)(a >> 32); uint64 m0 = (uint64)a0*b; uint64 m1 = (uint64)a1*b; // collect all multiplier terms uint32 s0 = (uint32)m0; uint32 s1a = (uint32)(m0 >> 32); uint32 s1b = (uint32)m1; uint32 s2 = (uint32)(m1 >> 32); // form 96-bit intermediate product uint32 acc0 = s0; uint32 acc1 = s1a + s1b; uint32 acc2 = s2 + (acc1 < s1b); // check for overflow (or divide by zero) if (acc2 >= c) return 0xFFFFFFFFFFFFFFFFULL; // do divide uint64 div1 = ((uint64)acc2 << 32) + acc1; uint64 q1 = div1 / c; uint64 div0 = ((div1 % c) << 32) + acc0; uint32 q0 = (uint32)(div0 / c); remainder = (uint32)(div0 % c); return (q1 << 32) + q0; } uint64 VDUMulDiv64x32(uint64 a, uint32 b, uint32 c) { uint32 r; return VDFractionScale64(a, b, c, r); } #endif sint64 VDMulDiv64(sint64 a, sint64 b, sint64 c) { bool flip = false; if (a < 0) { a = -a; flip = true; } if (b < 0) { b = -b; flip = !flip; } if (c < 0) { c = -c; flip = !flip; } uint64 rem; uint64 v = VDUDiv128x64To64(VDUMul64x64To128((uint64)a, (uint64)b), (uint64)c, rem); if ((rem+rem) >= (uint64)c) ++v; return flip ? -(sint64)v : (sint64)v; } bool VDVerifyFiniteFloats(const float *p0, uint32 n) { const uint32 *p = (const uint32 *)p0; while(n--) { uint32 v = *p++; // 00000000 zero // 00000001-007FFFFF denormal // 00800000-7F7FFFFF finite // 7F800000 infinity // 7F800001-7FBFFFFF SNaN // 7FC00000-7FFFFFFF QNaN if ((v & 0x7FFFFFFF) >= 0x7F800000) return false; } return true; }
zengweitotty/mpc-hc
src/thirdparty/VirtualDub/system/source/math.cpp
C++
gpl-3.0
5,024
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Global readPyrolysisTimeControls Description \*---------------------------------------------------------------------------*/ scalar maxDi = pyrolysis.maxDiff(); // ************************************************************************* //
morgoth541/of_realFluid
applications/solvers/combustion/fireFoam/readPyrolysisTimeControls.H
C++
gpl-3.0
1,322
/** * Classes that ensure web requests are received over required transport channels. * <p> * Most commonly used to enforce that requests are submitted over HTTP or HTTPS. */ package org.springframework.security.web.access.channel;
panchenko/spring-security
web/src/main/java/org/springframework/security/web/access/channel/package-info.java
Java
apache-2.0
237
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Apress.Recipes.WebApi.Areas.HelpPage.ModelDescriptions; using Apress.Recipes.WebApi.Areas.HelpPage.Models; namespace Apress.Recipes.WebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
filipw/apress-recipes-webapi
Chapter 12/10-1/Apress.Recipes.WebApi/Apress.Recipes.WebApi/Areas/HelpPage/HelpPageConfigurationExtensions.cs
C#
apache-2.0
22,777
//this file is autogenerated using stringify.bat (premake --stringify) in the build folder of this project static const char* integrateKernelCL= \ "/*\n" "Copyright (c) 2013 Advanced Micro Devices, Inc. \n" "This software is provided 'as-is', without any express or implied warranty.\n" "In no event will the authors be held liable for any damages arising from the use of this software.\n" "Permission is granted to anyone to use this software for any purpose, \n" "including commercial applications, and to alter it and redistribute it freely, \n" "subject to the following restrictions:\n" "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.\n" "2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n" "3. This notice may not be removed or altered from any source distribution.\n" "*/\n" "//Originally written by Erwin Coumans\n" "#ifndef B3_RIGIDBODY_DATA_H\n" "#define B3_RIGIDBODY_DATA_H\n" "#ifndef B3_FLOAT4_H\n" "#define B3_FLOAT4_H\n" "#ifndef B3_PLATFORM_DEFINITIONS_H\n" "#define B3_PLATFORM_DEFINITIONS_H\n" "struct MyTest\n" "{\n" " int bla;\n" "};\n" "#ifdef __cplusplus\n" "#else\n" "//keep B3_LARGE_FLOAT*B3_LARGE_FLOAT < FLT_MAX\n" "#define B3_LARGE_FLOAT 1e18f\n" "#define B3_INFINITY 1e18f\n" "#define b3Assert(a)\n" "#define b3ConstArray(a) __global const a*\n" "#define b3AtomicInc atomic_inc\n" "#define b3AtomicAdd atomic_add\n" "#define b3Fabs fabs\n" "#define b3Sqrt native_sqrt\n" "#define b3Sin native_sin\n" "#define b3Cos native_cos\n" "#endif\n" "#endif\n" "#ifdef __cplusplus\n" "#else\n" " typedef float4 b3Float4;\n" " #define b3Float4ConstArg const b3Float4\n" " #define b3MakeFloat4 (float4)\n" " float b3Dot3F4(b3Float4ConstArg v0,b3Float4ConstArg v1)\n" " {\n" " float4 a1 = b3MakeFloat4(v0.xyz,0.f);\n" " float4 b1 = b3MakeFloat4(v1.xyz,0.f);\n" " return dot(a1, b1);\n" " }\n" " b3Float4 b3Cross3(b3Float4ConstArg v0,b3Float4ConstArg v1)\n" " {\n" " float4 a1 = b3MakeFloat4(v0.xyz,0.f);\n" " float4 b1 = b3MakeFloat4(v1.xyz,0.f);\n" " return cross(a1, b1);\n" " }\n" " #define b3MinFloat4 min\n" " #define b3MaxFloat4 max\n" " #define b3Normalized(a) normalize(a)\n" "#endif \n" " \n" "inline bool b3IsAlmostZero(b3Float4ConstArg v)\n" "{\n" " if(b3Fabs(v.x)>1e-6 || b3Fabs(v.y)>1e-6 || b3Fabs(v.z)>1e-6) \n" " return false;\n" " return true;\n" "}\n" "inline int b3MaxDot( b3Float4ConstArg vec, __global const b3Float4* vecArray, int vecLen, float* dotOut )\n" "{\n" " float maxDot = -B3_INFINITY;\n" " int i = 0;\n" " int ptIndex = -1;\n" " for( i = 0; i < vecLen; i++ )\n" " {\n" " float dot = b3Dot3F4(vecArray[i],vec);\n" " \n" " if( dot > maxDot )\n" " {\n" " maxDot = dot;\n" " ptIndex = i;\n" " }\n" " }\n" " b3Assert(ptIndex>=0);\n" " if (ptIndex<0)\n" " {\n" " ptIndex = 0;\n" " }\n" " *dotOut = maxDot;\n" " return ptIndex;\n" "}\n" "#endif //B3_FLOAT4_H\n" "#ifndef B3_QUAT_H\n" "#define B3_QUAT_H\n" "#ifndef B3_PLATFORM_DEFINITIONS_H\n" "#ifdef __cplusplus\n" "#else\n" "#endif\n" "#endif\n" "#ifndef B3_FLOAT4_H\n" "#ifdef __cplusplus\n" "#else\n" "#endif \n" "#endif //B3_FLOAT4_H\n" "#ifdef __cplusplus\n" "#else\n" " typedef float4 b3Quat;\n" " #define b3QuatConstArg const b3Quat\n" " \n" " \n" "inline float4 b3FastNormalize4(float4 v)\n" "{\n" " v = (float4)(v.xyz,0.f);\n" " return fast_normalize(v);\n" "}\n" " \n" "inline b3Quat b3QuatMul(b3Quat a, b3Quat b);\n" "inline b3Quat b3QuatNormalized(b3QuatConstArg in);\n" "inline b3Quat b3QuatRotate(b3QuatConstArg q, b3QuatConstArg vec);\n" "inline b3Quat b3QuatInvert(b3QuatConstArg q);\n" "inline b3Quat b3QuatInverse(b3QuatConstArg q);\n" "inline b3Quat b3QuatMul(b3QuatConstArg a, b3QuatConstArg b)\n" "{\n" " b3Quat ans;\n" " ans = b3Cross3( a, b );\n" " ans += a.w*b+b.w*a;\n" "// ans.w = a.w*b.w - (a.x*b.x+a.y*b.y+a.z*b.z);\n" " ans.w = a.w*b.w - b3Dot3F4(a, b);\n" " return ans;\n" "}\n" "inline b3Quat b3QuatNormalized(b3QuatConstArg in)\n" "{\n" " b3Quat q;\n" " q=in;\n" " //return b3FastNormalize4(in);\n" " float len = native_sqrt(dot(q, q));\n" " if(len > 0.f)\n" " {\n" " q *= 1.f / len;\n" " }\n" " else\n" " {\n" " q.x = q.y = q.z = 0.f;\n" " q.w = 1.f;\n" " }\n" " return q;\n" "}\n" "inline float4 b3QuatRotate(b3QuatConstArg q, b3QuatConstArg vec)\n" "{\n" " b3Quat qInv = b3QuatInvert( q );\n" " float4 vcpy = vec;\n" " vcpy.w = 0.f;\n" " float4 out = b3QuatMul(b3QuatMul(q,vcpy),qInv);\n" " return out;\n" "}\n" "inline b3Quat b3QuatInverse(b3QuatConstArg q)\n" "{\n" " return (b3Quat)(-q.xyz, q.w);\n" "}\n" "inline b3Quat b3QuatInvert(b3QuatConstArg q)\n" "{\n" " return (b3Quat)(-q.xyz, q.w);\n" "}\n" "inline float4 b3QuatInvRotate(b3QuatConstArg q, b3QuatConstArg vec)\n" "{\n" " return b3QuatRotate( b3QuatInvert( q ), vec );\n" "}\n" "inline b3Float4 b3TransformPoint(b3Float4ConstArg point, b3Float4ConstArg translation, b3QuatConstArg orientation)\n" "{\n" " return b3QuatRotate( orientation, point ) + (translation);\n" "}\n" " \n" "#endif \n" "#endif //B3_QUAT_H\n" "#ifndef B3_MAT3x3_H\n" "#define B3_MAT3x3_H\n" "#ifndef B3_QUAT_H\n" "#ifdef __cplusplus\n" "#else\n" "#endif \n" "#endif //B3_QUAT_H\n" "#ifdef __cplusplus\n" "#else\n" "typedef struct\n" "{\n" " b3Float4 m_row[3];\n" "}b3Mat3x3;\n" "#define b3Mat3x3ConstArg const b3Mat3x3\n" "#define b3GetRow(m,row) (m.m_row[row])\n" "inline b3Mat3x3 b3QuatGetRotationMatrix(b3Quat quat)\n" "{\n" " b3Float4 quat2 = (b3Float4)(quat.x*quat.x, quat.y*quat.y, quat.z*quat.z, 0.f);\n" " b3Mat3x3 out;\n" " out.m_row[0].x=1-2*quat2.y-2*quat2.z;\n" " out.m_row[0].y=2*quat.x*quat.y-2*quat.w*quat.z;\n" " out.m_row[0].z=2*quat.x*quat.z+2*quat.w*quat.y;\n" " out.m_row[0].w = 0.f;\n" " out.m_row[1].x=2*quat.x*quat.y+2*quat.w*quat.z;\n" " out.m_row[1].y=1-2*quat2.x-2*quat2.z;\n" " out.m_row[1].z=2*quat.y*quat.z-2*quat.w*quat.x;\n" " out.m_row[1].w = 0.f;\n" " out.m_row[2].x=2*quat.x*quat.z-2*quat.w*quat.y;\n" " out.m_row[2].y=2*quat.y*quat.z+2*quat.w*quat.x;\n" " out.m_row[2].z=1-2*quat2.x-2*quat2.y;\n" " out.m_row[2].w = 0.f;\n" " return out;\n" "}\n" "inline b3Mat3x3 b3AbsoluteMat3x3(b3Mat3x3ConstArg matIn)\n" "{\n" " b3Mat3x3 out;\n" " out.m_row[0] = fabs(matIn.m_row[0]);\n" " out.m_row[1] = fabs(matIn.m_row[1]);\n" " out.m_row[2] = fabs(matIn.m_row[2]);\n" " return out;\n" "}\n" "__inline\n" "b3Mat3x3 mtZero();\n" "__inline\n" "b3Mat3x3 mtIdentity();\n" "__inline\n" "b3Mat3x3 mtTranspose(b3Mat3x3 m);\n" "__inline\n" "b3Mat3x3 mtMul(b3Mat3x3 a, b3Mat3x3 b);\n" "__inline\n" "b3Float4 mtMul1(b3Mat3x3 a, b3Float4 b);\n" "__inline\n" "b3Float4 mtMul3(b3Float4 a, b3Mat3x3 b);\n" "__inline\n" "b3Mat3x3 mtZero()\n" "{\n" " b3Mat3x3 m;\n" " m.m_row[0] = (b3Float4)(0.f);\n" " m.m_row[1] = (b3Float4)(0.f);\n" " m.m_row[2] = (b3Float4)(0.f);\n" " return m;\n" "}\n" "__inline\n" "b3Mat3x3 mtIdentity()\n" "{\n" " b3Mat3x3 m;\n" " m.m_row[0] = (b3Float4)(1,0,0,0);\n" " m.m_row[1] = (b3Float4)(0,1,0,0);\n" " m.m_row[2] = (b3Float4)(0,0,1,0);\n" " return m;\n" "}\n" "__inline\n" "b3Mat3x3 mtTranspose(b3Mat3x3 m)\n" "{\n" " b3Mat3x3 out;\n" " out.m_row[0] = (b3Float4)(m.m_row[0].x, m.m_row[1].x, m.m_row[2].x, 0.f);\n" " out.m_row[1] = (b3Float4)(m.m_row[0].y, m.m_row[1].y, m.m_row[2].y, 0.f);\n" " out.m_row[2] = (b3Float4)(m.m_row[0].z, m.m_row[1].z, m.m_row[2].z, 0.f);\n" " return out;\n" "}\n" "__inline\n" "b3Mat3x3 mtMul(b3Mat3x3 a, b3Mat3x3 b)\n" "{\n" " b3Mat3x3 transB;\n" " transB = mtTranspose( b );\n" " b3Mat3x3 ans;\n" " // why this doesn't run when 0ing in the for{}\n" " a.m_row[0].w = 0.f;\n" " a.m_row[1].w = 0.f;\n" " a.m_row[2].w = 0.f;\n" " for(int i=0; i<3; i++)\n" " {\n" "// a.m_row[i].w = 0.f;\n" " ans.m_row[i].x = b3Dot3F4(a.m_row[i],transB.m_row[0]);\n" " ans.m_row[i].y = b3Dot3F4(a.m_row[i],transB.m_row[1]);\n" " ans.m_row[i].z = b3Dot3F4(a.m_row[i],transB.m_row[2]);\n" " ans.m_row[i].w = 0.f;\n" " }\n" " return ans;\n" "}\n" "__inline\n" "b3Float4 mtMul1(b3Mat3x3 a, b3Float4 b)\n" "{\n" " b3Float4 ans;\n" " ans.x = b3Dot3F4( a.m_row[0], b );\n" " ans.y = b3Dot3F4( a.m_row[1], b );\n" " ans.z = b3Dot3F4( a.m_row[2], b );\n" " ans.w = 0.f;\n" " return ans;\n" "}\n" "__inline\n" "b3Float4 mtMul3(b3Float4 a, b3Mat3x3 b)\n" "{\n" " b3Float4 colx = b3MakeFloat4(b.m_row[0].x, b.m_row[1].x, b.m_row[2].x, 0);\n" " b3Float4 coly = b3MakeFloat4(b.m_row[0].y, b.m_row[1].y, b.m_row[2].y, 0);\n" " b3Float4 colz = b3MakeFloat4(b.m_row[0].z, b.m_row[1].z, b.m_row[2].z, 0);\n" " b3Float4 ans;\n" " ans.x = b3Dot3F4( a, colx );\n" " ans.y = b3Dot3F4( a, coly );\n" " ans.z = b3Dot3F4( a, colz );\n" " return ans;\n" "}\n" "#endif\n" "#endif //B3_MAT3x3_H\n" "typedef struct b3RigidBodyData b3RigidBodyData_t;\n" "struct b3RigidBodyData\n" "{\n" " b3Float4 m_pos;\n" " b3Quat m_quat;\n" " b3Float4 m_linVel;\n" " b3Float4 m_angVel;\n" " int m_collidableIdx;\n" " float m_invMass;\n" " float m_restituitionCoeff;\n" " float m_frictionCoeff;\n" "};\n" "typedef struct b3InertiaData b3InertiaData_t;\n" "struct b3InertiaData\n" "{\n" " b3Mat3x3 m_invInertiaWorld;\n" " b3Mat3x3 m_initInvInertia;\n" "};\n" "#endif //B3_RIGIDBODY_DATA_H\n" " \n" "#ifndef B3_RIGIDBODY_DATA_H\n" "#endif //B3_RIGIDBODY_DATA_H\n" " \n" "inline void integrateSingleTransform( __global b3RigidBodyData_t* bodies,int nodeID, float timeStep, float angularDamping, b3Float4ConstArg gravityAcceleration)\n" "{\n" " \n" " if (bodies[nodeID].m_invMass != 0.f)\n" " {\n" " float BT_GPU_ANGULAR_MOTION_THRESHOLD = (0.25f * 3.14159254f);\n" " //angular velocity\n" " {\n" " b3Float4 axis;\n" " //add some hardcoded angular damping\n" " bodies[nodeID].m_angVel.x *= angularDamping;\n" " bodies[nodeID].m_angVel.y *= angularDamping;\n" " bodies[nodeID].m_angVel.z *= angularDamping;\n" " \n" " b3Float4 angvel = bodies[nodeID].m_angVel;\n" " float fAngle = b3Sqrt(b3Dot3F4(angvel, angvel));\n" " \n" " //limit the angular motion\n" " if(fAngle*timeStep > BT_GPU_ANGULAR_MOTION_THRESHOLD)\n" " {\n" " fAngle = BT_GPU_ANGULAR_MOTION_THRESHOLD / timeStep;\n" " }\n" " if(fAngle < 0.001f)\n" " {\n" " // use Taylor's expansions of sync function\n" " axis = angvel * (0.5f*timeStep-(timeStep*timeStep*timeStep)*0.020833333333f * fAngle * fAngle);\n" " }\n" " else\n" " {\n" " // sync(fAngle) = sin(c*fAngle)/t\n" " axis = angvel * ( b3Sin(0.5f * fAngle * timeStep) / fAngle);\n" " }\n" " \n" " b3Quat dorn;\n" " dorn.x = axis.x;\n" " dorn.y = axis.y;\n" " dorn.z = axis.z;\n" " dorn.w = b3Cos(fAngle * timeStep * 0.5f);\n" " b3Quat orn0 = bodies[nodeID].m_quat;\n" " b3Quat predictedOrn = b3QuatMul(dorn, orn0);\n" " predictedOrn = b3QuatNormalized(predictedOrn);\n" " bodies[nodeID].m_quat=predictedOrn;\n" " }\n" " //linear velocity \n" " bodies[nodeID].m_pos += bodies[nodeID].m_linVel * timeStep;\n" " \n" " //apply gravity\n" " bodies[nodeID].m_linVel += gravityAcceleration * timeStep;\n" " \n" " }\n" " \n" "}\n" "inline void b3IntegrateTransform( __global b3RigidBodyData_t* body, float timeStep, float angularDamping, b3Float4ConstArg gravityAcceleration)\n" "{\n" " float BT_GPU_ANGULAR_MOTION_THRESHOLD = (0.25f * 3.14159254f);\n" " \n" " if( (body->m_invMass != 0.f))\n" " {\n" " //angular velocity\n" " {\n" " b3Float4 axis;\n" " //add some hardcoded angular damping\n" " body->m_angVel.x *= angularDamping;\n" " body->m_angVel.y *= angularDamping;\n" " body->m_angVel.z *= angularDamping;\n" " \n" " b3Float4 angvel = body->m_angVel;\n" " float fAngle = b3Sqrt(b3Dot3F4(angvel, angvel));\n" " //limit the angular motion\n" " if(fAngle*timeStep > BT_GPU_ANGULAR_MOTION_THRESHOLD)\n" " {\n" " fAngle = BT_GPU_ANGULAR_MOTION_THRESHOLD / timeStep;\n" " }\n" " if(fAngle < 0.001f)\n" " {\n" " // use Taylor's expansions of sync function\n" " axis = angvel * (0.5f*timeStep-(timeStep*timeStep*timeStep)*0.020833333333f * fAngle * fAngle);\n" " }\n" " else\n" " {\n" " // sync(fAngle) = sin(c*fAngle)/t\n" " axis = angvel * ( b3Sin(0.5f * fAngle * timeStep) / fAngle);\n" " }\n" " b3Quat dorn;\n" " dorn.x = axis.x;\n" " dorn.y = axis.y;\n" " dorn.z = axis.z;\n" " dorn.w = b3Cos(fAngle * timeStep * 0.5f);\n" " b3Quat orn0 = body->m_quat;\n" " b3Quat predictedOrn = b3QuatMul(dorn, orn0);\n" " predictedOrn = b3QuatNormalized(predictedOrn);\n" " body->m_quat=predictedOrn;\n" " }\n" " //apply gravity\n" " body->m_linVel += gravityAcceleration * timeStep;\n" " //linear velocity \n" " body->m_pos += body->m_linVel * timeStep;\n" " \n" " }\n" " \n" "}\n" "__kernel void \n" " integrateTransformsKernel( __global b3RigidBodyData_t* bodies,const int numNodes, float timeStep, float angularDamping, float4 gravityAcceleration)\n" "{\n" " int nodeID = get_global_id(0);\n" " \n" " if( nodeID < numNodes)\n" " {\n" " integrateSingleTransform(bodies,nodeID, timeStep, angularDamping,gravityAcceleration);\n" " }\n" "}\n" ;
Naftoreiclag/VS7C
thirdparty/bullet3-2.83.4/include/Bullet3OpenCL/RigidBody/kernels/integrateKernel.h
C
apache-2.0
13,183
/* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * 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. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.d_modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="d_modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('d_modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('d_modal-open') }) }(window.jQuery);
johannnallathamby/product-is
modules/jaggery-apps/user-dashboard/dashboard/js/d_modal.js
JavaScript
apache-2.0
7,003
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <memory> // template <class X> class auto_ptr; // void reset(X* p=0) throw(); #include <memory> #include <cassert> #include "../A.h" void test() { { A* p = new A(1); std::auto_ptr<A> ap(p); ap.reset(); assert(ap.get() == 0); assert(A::count == 0); } assert(A::count == 0); { A* p = new A(1); std::auto_ptr<A> ap(p); ap.reset(p); assert(ap.get() == p); assert(A::count == 1); } assert(A::count == 0); { A* p = new A(1); std::auto_ptr<A> ap(p); A* p2 = new A(2); ap.reset(p2); assert(ap.get() == p2); assert(A::count == 1); } assert(A::count == 0); } int main() { test(); }
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/depr/depr.auto.ptr/auto.ptr/auto.ptr.members/reset.pass.cpp
C++
bsd-3-clause
1,042
/** * Defines Percent Chart Series. */ /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { Series, SeriesDataItem, ISeriesProperties, ISeriesDataFields, ISeriesAdapters, ISeriesEvents } from "./Series"; import { ISpriteEvents, AMEvent } from "../../core/Sprite"; import { Sprite } from "../../core/Sprite"; import { Label } from "../../core/elements/Label"; import { Tick } from "../elements/Tick"; import { ListTemplate } from "../../core/utils/List"; import { Container } from "../../core/Container"; import { Animation } from "../../core/utils/Animation"; import { LegendDataItem, LegendSettings } from "../../charts/Legend"; import { ColorSet } from "../../core/utils/ColorSet"; import { PatternSet } from "../../core/utils/PatternSet"; import { PercentChart } from "../types/PercentChart"; import * as $type from "../../core/utils/Type"; /** * ============================================================================ * DATA ITEM * ============================================================================ * @hidden */ /** * Defines a [[DataItem]] for [[PercentSeries]]. * * @see {@link DataItem} */ export declare class PercentSeriesDataItem extends SeriesDataItem { /** * A type of slice used for this series. */ _slice: Sprite; /** * A reference to a slice label element. * * @ignore Exclude from docs */ _label: Label; /** * A reference to a slice tick element. * @ignore Exclude from docs */ _tick: Tick; /** * A reference to a corresponding legend data item. */ protected _legendDataItem: LegendDataItem; /** * Custom settings for the legend item. * Not used, only added to sattisfy LegendDataItem * * @ignore */ legendSettings: LegendSettings; /** * Defines a type of [[Component]] this data item is used for. */ _component: PercentSeries; /** * Constructor */ constructor(); /** * Adds an `id` attribute the the slice element and returns its id. * * @ignore Exclude from docs */ uidAttr(): string; /** * Hide the data item (and corresponding visual elements). * * @param duration Duration (ms) * @param delay Delay hiding (ms) * @param toValue Target value for animation * @param fields Fields to animate while hiding */ hide(duration?: number, delay?: number, toValue?: number, fields?: string[]): $type.Optional<Animation>; /** * Sets visibility of the Data Item. * * @param value Data Item */ setVisibility(value: boolean, noChangeValues?: boolean): void; /** * Show hidden data item (and corresponding visual elements). * * @param duration Duration (ms) * @param delay Delay hiding (ms) * @param fields Fields to animate while hiding */ show(duration?: number, delay?: number, fields?: string[]): $type.Optional<Animation>; /** * Category. * * @param value Category */ /** * @return Category */ category: string; /** * Creates a marker used in the legend for this slice. * * @ignore Exclude from docs * @param marker Marker container */ createLegendMarker(marker: Container): void; /** * A legend's data item, that corresponds to this data item. * * @param value Legend data item */ /** * @return Legend data item */ legendDataItem: LegendDataItem; /** * A Tick element, related to this data item. (slice) * * @readonly * @return Tick element */ readonly tick: this["_tick"]; /** * A Label element, related to this data item. (slice) * * @readonly * @return Label element */ readonly label: this["_label"]; /** * An element, related to this data item. (slice) * * @readonly * @return Slice element */ readonly slice: this["_slice"]; /** * Should dataItem (slice) be hidden in legend? * * @param value Visible in legend? */ /** * @return Disabled in legend? */ hiddenInLegend: boolean; } /** * ============================================================================ * REQUISITES * ============================================================================ * @hidden */ /** * Defines data fields for [[PercentSeries]]. */ export interface IPercentSeriesDataFields extends ISeriesDataFields { /** * Name of the field in data that holds category. */ category?: string; /** * Name of the field in data that holds boolean flag if item should be * hidden in legend. */ hiddenInLegend?: string; } /** * Defines properties for [[PercentSeries]]. */ export interface IPercentSeriesProperties extends ISeriesProperties { /** * A color set to be used for slices. * * For each new subsequent slice, the chart will assign the next color in * this set. */ colors?: ColorSet; /** * Pattern set to apply to fills. * * @since 4.7.5 */ patterns?: PatternSet; /** * Align labels into nice vertical columns? * * @default true */ alignLabels?: boolean; /** * If set to `true` the chart will not show slices with zero values. * * @default false * @since 4.7.9 */ ignoreZeroValues?: boolean; } /** * Defines events for [[PercentSeries]]. */ export interface IPercentSeriesEvents extends ISeriesEvents { } /** * Defines adapters for [[PercentSeries]]. * * @see {@link Adapter} */ export interface IPercentSeriesAdapters extends ISeriesAdapters, IPercentSeriesProperties { } /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * Defines [[PercentSeries]] which is a base class for [[PieSeries]], * [[FunnelSeries]], and [[PyramidSeries]]. * * @see {@link IPercentSeriesEvents} for a list of available Events * @see {@link IPercentSeriesAdapters} for a list of available Adapters */ export declare class PercentSeries extends Series { /** * Defines type of the slice elements for the series. */ _slice: Sprite; /** * Defines type of the tick elements for the series. */ _tick: Tick; /** * Defines type of the label elements for the series. */ _label: Label; /** * A reference to chart this series is for. * * @ignore Exclude from docs */ _chart: PercentChart; /** * Defines the type of data fields used for the series. */ _dataFields: IPercentSeriesDataFields; /** * Defines available properties. */ _properties: IPercentSeriesProperties; /** * Defines available adapters. */ _adapter: IPercentSeriesAdapters; /** * Defines available events. */ _events: IPercentSeriesEvents; /** * Defines the type of data item. */ _dataItem: PercentSeriesDataItem; /** * Container slice elements are put in. */ slicesContainer: Container; /** * Container tick elements are put in. */ ticksContainer: Container; /** * Container label elements are put in. */ labelsContainer: Container; /** * List of slice elements. */ protected _slices: ListTemplate<this["_slice"]>; /** * List of tick elements. */ protected _ticks: ListTemplate<this["_tick"]>; /** * List of label elements. */ protected _labels: ListTemplate<this["_label"]>; /** * Constructor */ constructor(); /** * Creates a slice element. * * @return Slice */ protected createSlice(): this["_slice"]; /** * Creates a tick element. * * @return Tick */ protected createTick(): this["_tick"]; /** * Sreates label element. * * @return label */ protected createLabel(): this["_label"]; /** * A list of slice elements for the series. * * Use its `template` to configure look and behavior of the slices. E.g.: * * ```TypeScript * series.slices.template.stroke = am4core.color("#fff"); * series.slices.template.strokeWidth = 2; * ``` * ```JavaScript * series.slices.template.stroke = am4core.color("#fff"); * series.slices.template.strokeWidth = 2; * ``` * ```JSON * { * // ... * "series": [{ * // ... * "slices": { * "stroke": "#fff", * "strokeWidth": 2 * } * }] * } * ``` * * @see {@link https://www.amcharts.com/docs/v4/concepts/list-templates/} for more information about list templates * @return Slices */ readonly slices: ListTemplate<this["_slice"]>; /** * A list of tick elements for the series. Ticks connect slice to its label. * * Use its `template` to configure look and behavior of the ticks. E.g.: * * ```TypeScript * series.ticks.template.strokeWidth = 2; * ``` * ```JavaScript * series.ticks.template.strokeWidth = 2; * ``` * ```JSON * { * // ... * "series": [{ * // ... * "ticks": { * "strokeWidth": 2 * } * }] * } * ``` * * @see {@link https://www.amcharts.com/docs/v4/concepts/list-templates/} for more information about list templates * @return Ticks */ readonly ticks: ListTemplate<this["_tick"]>; /** * A list of slice label elements for the series. * * Use its `template` to configure look and behavior of the labels. E.g.: * * ```TypeScript * series.labels.template.fill = am4core.color("#c00"); * series.labels.template.fontSize = 20; * ``` * ```JavaScript * series.labels.template.fill = am4core.color("#c00"); * series.labels.template.fontSize = 20; * ``` * ```JSON * { * // ... * "series": [{ * // ... * "labels": { * "stroke": "#c00", * "fontSize": 20 * } * }] * } * ``` * * @see {@link https://www.amcharts.com/docs/v4/concepts/list-templates/} for more information about list templates * @return Labels */ readonly labels: ListTemplate<this["_label"]>; /** * Returns a new/empty DataItem of the type appropriate for this object. * * @see {@link DataItem} * @return Data Item */ protected createDataItem(): this["_dataItem"]; /** * Creates and returns a new slice element. * * @param sliceType Type of the slice element * @return Slice */ protected initSlice(slice: this["_slice"]): void; protected initLabel(label: this["_label"]): void; protected initTick(label: this["_tick"]): void; /** * Validates (processes) data items. * * @ignore Exclude from docs */ validateDataItems(): void; /** * Validates data item's element, effectively redrawing it. * * @ignore Exclude from docs * @param dataItem Data item */ validateDataElement(dataItem: this["_dataItem"]): void; /** * Validates (processes) data. * * @ignore Exclude from docs */ validateData(): void; /** * Arranges slice labels according to position settings. * * @ignore Exclude from docs * @param dataItems Data items */ protected arrangeLabels(dataItems: this["_dataItem"][]): void; protected arrangeLabels2(dataItems: this["_dataItem"][]): void; /** * Returns the next label according to `index`. * * @param index Current index * @param dataItems Data items * @return Label element */ protected getNextLabel(index: number, dataItems: this["_dataItem"][]): this["_label"]; /** * A color set to be used for slices. * * For each new subsequent slice, the chart will assign the next color in * this set. * * @param value Color set */ /** * @return Color set */ colors: ColorSet; /** * A [[PatternSet]] to use when creating patterned fills for slices. * * @since 4.7.5 * @param value Pattern set */ /** * @return Pattern set */ patterns: PatternSet; /** * Binds related legend data item's visual settings to this series' visual * settings. * * @ignore Exclude from docs * @param marker Container * @param dataItem Data item */ createLegendMarker(marker: Container, dataItem?: this["_dataItem"]): void; /** * Repositions bullets when slice's size changes. * * @ignore Exclude from docs * @param event Event */ protected handleSliceScale(event: AMEvent<this["_slice"], ISpriteEvents>["propertychanged"]): void; /** * Repositions bullet and labels when slice moves. * * @ignore Exclude from docs * @param event Event */ protected handleSliceMove(event: AMEvent<this["_slice"], ISpriteEvents>["propertychanged"]): void; /** * Copies all properties from another instance of [[PercentSeries]]. * * @param source Source series */ copyFrom(source: this): void; /** * Align labels into nice vertical columns? * * This will ensure that labels never overlap with each other. * * Arranging labels into columns makes them more readble, and better user * experience. * * If set to `false` labels will be positioned at `label.radius` distance, * and may, in some cases, overlap. * * @default true * @param value Align labels? */ /** * @return Align labels? */ alignLabels: boolean; /** * @ignore */ protected setAlignLabels(value: boolean): void; /** * If set to `true` the chart will not show slices with zero values. * * @default false * @since 4.7.9 * @param value Ignore zero values */ /** * @return Ignore zero values */ ignoreZeroValues: boolean; /** * Updates corresponding legend data item with current values. * * @ignore Exclude from docs * @param dataItem Data item */ updateLegendValue(dataItem?: this["_dataItem"]): void; }
cdnjs/cdnjs
ajax/libs/amcharts4/4.9.37/.internal/charts/series/PercentSeries.d.ts
TypeScript
mit
15,218
/* * Copyright 2008 Jerome Glisse. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: * Jerome Glisse <glisse@freedesktop.org> */ #include <linux/list_sort.h> #include <linux/pagemap.h> #include <drm/drmP.h> #include <drm/amdgpu_drm.h> #include "amdgpu.h" #include "amdgpu_trace.h" int amdgpu_cs_get_ring(struct amdgpu_device *adev, u32 ip_type, u32 ip_instance, u32 ring, struct amdgpu_ring **out_ring) { /* Right now all IPs have only one instance - multiple rings. */ if (ip_instance != 0) { DRM_ERROR("invalid ip instance: %d\n", ip_instance); return -EINVAL; } switch (ip_type) { default: DRM_ERROR("unknown ip type: %d\n", ip_type); return -EINVAL; case AMDGPU_HW_IP_GFX: if (ring < adev->gfx.num_gfx_rings) { *out_ring = &adev->gfx.gfx_ring[ring]; } else { DRM_ERROR("only %d gfx rings are supported now\n", adev->gfx.num_gfx_rings); return -EINVAL; } break; case AMDGPU_HW_IP_COMPUTE: if (ring < adev->gfx.num_compute_rings) { *out_ring = &adev->gfx.compute_ring[ring]; } else { DRM_ERROR("only %d compute rings are supported now\n", adev->gfx.num_compute_rings); return -EINVAL; } break; case AMDGPU_HW_IP_DMA: if (ring < adev->sdma.num_instances) { *out_ring = &adev->sdma.instance[ring].ring; } else { DRM_ERROR("only %d SDMA rings are supported\n", adev->sdma.num_instances); return -EINVAL; } break; case AMDGPU_HW_IP_UVD: *out_ring = &adev->uvd.ring; break; case AMDGPU_HW_IP_VCE: if (ring < 2){ *out_ring = &adev->vce.ring[ring]; } else { DRM_ERROR("only two VCE rings are supported\n"); return -EINVAL; } break; } return 0; } static int amdgpu_cs_user_fence_chunk(struct amdgpu_cs_parser *p, struct amdgpu_user_fence *uf, struct drm_amdgpu_cs_chunk_fence *fence_data) { struct drm_gem_object *gobj; uint32_t handle; handle = fence_data->handle; gobj = drm_gem_object_lookup(p->adev->ddev, p->filp, fence_data->handle); if (gobj == NULL) return -EINVAL; uf->bo = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj)); uf->offset = fence_data->offset; if (amdgpu_ttm_tt_get_usermm(uf->bo->tbo.ttm)) { drm_gem_object_unreference_unlocked(gobj); return -EINVAL; } p->uf_entry.robj = amdgpu_bo_ref(uf->bo); p->uf_entry.priority = 0; p->uf_entry.tv.bo = &p->uf_entry.robj->tbo; p->uf_entry.tv.shared = true; p->uf_entry.user_pages = NULL; drm_gem_object_unreference_unlocked(gobj); return 0; } int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, void *data) { struct amdgpu_fpriv *fpriv = p->filp->driver_priv; union drm_amdgpu_cs *cs = data; uint64_t *chunk_array_user; uint64_t *chunk_array; struct amdgpu_user_fence uf = {}; unsigned size, num_ibs = 0; int i; int ret; if (cs->in.num_chunks == 0) return 0; chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL); if (!chunk_array) return -ENOMEM; p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id); if (!p->ctx) { ret = -EINVAL; goto free_chunk; } /* get chunks */ chunk_array_user = (uint64_t __user *)(unsigned long)(cs->in.chunks); if (copy_from_user(chunk_array, chunk_array_user, sizeof(uint64_t)*cs->in.num_chunks)) { ret = -EFAULT; goto put_ctx; } p->nchunks = cs->in.num_chunks; p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk), GFP_KERNEL); if (!p->chunks) { ret = -ENOMEM; goto put_ctx; } for (i = 0; i < p->nchunks; i++) { struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL; struct drm_amdgpu_cs_chunk user_chunk; uint32_t __user *cdata; chunk_ptr = (void __user *)(unsigned long)chunk_array[i]; if (copy_from_user(&user_chunk, chunk_ptr, sizeof(struct drm_amdgpu_cs_chunk))) { ret = -EFAULT; i--; goto free_partial_kdata; } p->chunks[i].chunk_id = user_chunk.chunk_id; p->chunks[i].length_dw = user_chunk.length_dw; size = p->chunks[i].length_dw; cdata = (void __user *)(unsigned long)user_chunk.chunk_data; p->chunks[i].kdata = drm_malloc_ab(size, sizeof(uint32_t)); if (p->chunks[i].kdata == NULL) { ret = -ENOMEM; i--; goto free_partial_kdata; } size *= sizeof(uint32_t); if (copy_from_user(p->chunks[i].kdata, cdata, size)) { ret = -EFAULT; goto free_partial_kdata; } switch (p->chunks[i].chunk_id) { case AMDGPU_CHUNK_ID_IB: ++num_ibs; break; case AMDGPU_CHUNK_ID_FENCE: size = sizeof(struct drm_amdgpu_cs_chunk_fence); if (p->chunks[i].length_dw * sizeof(uint32_t) < size) { ret = -EINVAL; goto free_partial_kdata; } ret = amdgpu_cs_user_fence_chunk(p, &uf, (void *)p->chunks[i].kdata); if (ret) goto free_partial_kdata; break; case AMDGPU_CHUNK_ID_DEPENDENCIES: break; default: ret = -EINVAL; goto free_partial_kdata; } } ret = amdgpu_job_alloc(p->adev, num_ibs, &p->job); if (ret) goto free_all_kdata; p->job->uf = uf; kfree(chunk_array); return 0; free_all_kdata: i = p->nchunks - 1; free_partial_kdata: for (; i >= 0; i--) drm_free_large(p->chunks[i].kdata); kfree(p->chunks); put_ctx: amdgpu_ctx_put(p->ctx); free_chunk: kfree(chunk_array); return ret; } /* Returns how many bytes TTM can move per IB. */ static u64 amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev) { u64 real_vram_size = adev->mc.real_vram_size; u64 vram_usage = atomic64_read(&adev->vram_usage); /* This function is based on the current VRAM usage. * * - If all of VRAM is free, allow relocating the number of bytes that * is equal to 1/4 of the size of VRAM for this IB. * - If more than one half of VRAM is occupied, only allow relocating * 1 MB of data for this IB. * * - From 0 to one half of used VRAM, the threshold decreases * linearly. * __________________ * 1/4 of -|\ | * VRAM | \ | * | \ | * | \ | * | \ | * | \ | * | \ | * | \________|1 MB * |----------------| * VRAM 0 % 100 % * used used * * Note: It's a threshold, not a limit. The threshold must be crossed * for buffer relocations to stop, so any buffer of an arbitrary size * can be moved as long as the threshold isn't crossed before * the relocation takes place. We don't want to disable buffer * relocations completely. * * The idea is that buffers should be placed in VRAM at creation time * and TTM should only do a minimum number of relocations during * command submission. In practice, you need to submit at least * a dozen IBs to move all buffers to VRAM if they are in GTT. * * Also, things can get pretty crazy under memory pressure and actual * VRAM usage can change a lot, so playing safe even at 50% does * consistently increase performance. */ u64 half_vram = real_vram_size >> 1; u64 half_free_vram = vram_usage >= half_vram ? 0 : half_vram - vram_usage; u64 bytes_moved_threshold = half_free_vram >> 1; return max(bytes_moved_threshold, 1024*1024ull); } int amdgpu_cs_list_validate(struct amdgpu_cs_parser *p, struct list_head *validated) { struct amdgpu_bo_list_entry *lobj; u64 initial_bytes_moved; int r; list_for_each_entry(lobj, validated, tv.head) { struct amdgpu_bo *bo = lobj->robj; bool binding_userptr = false; struct mm_struct *usermm; uint32_t domain; usermm = amdgpu_ttm_tt_get_usermm(bo->tbo.ttm); if (usermm && usermm != current->mm) return -EPERM; /* Check if we have user pages and nobody bound the BO already */ if (lobj->user_pages && bo->tbo.ttm->state != tt_bound) { size_t size = sizeof(struct page *); size *= bo->tbo.ttm->num_pages; memcpy(bo->tbo.ttm->pages, lobj->user_pages, size); binding_userptr = true; } if (bo->pin_count) continue; /* Avoid moving this one if we have moved too many buffers * for this IB already. * * Note that this allows moving at least one buffer of * any size, because it doesn't take the current "bo" * into account. We don't want to disallow buffer moves * completely. */ if (p->bytes_moved <= p->bytes_moved_threshold) domain = bo->prefered_domains; else domain = bo->allowed_domains; retry: amdgpu_ttm_placement_from_domain(bo, domain); initial_bytes_moved = atomic64_read(&bo->adev->num_bytes_moved); r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false); p->bytes_moved += atomic64_read(&bo->adev->num_bytes_moved) - initial_bytes_moved; if (unlikely(r)) { if (r != -ERESTARTSYS && domain != bo->allowed_domains) { domain = bo->allowed_domains; goto retry; } return r; } if (binding_userptr) { drm_free_large(lobj->user_pages); lobj->user_pages = NULL; } } return 0; } static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p, union drm_amdgpu_cs *cs) { struct amdgpu_fpriv *fpriv = p->filp->driver_priv; struct amdgpu_bo_list_entry *e; struct list_head duplicates; bool need_mmap_lock = false; unsigned i, tries = 10; int r; INIT_LIST_HEAD(&p->validated); p->bo_list = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle); if (p->bo_list) { need_mmap_lock = p->bo_list->first_userptr != p->bo_list->num_entries; amdgpu_bo_list_get_list(p->bo_list, &p->validated); } INIT_LIST_HEAD(&duplicates); amdgpu_vm_get_pd_bo(&fpriv->vm, &p->validated, &p->vm_pd); if (p->job->uf.bo) list_add(&p->uf_entry.tv.head, &p->validated); if (need_mmap_lock) down_read(&current->mm->mmap_sem); while (1) { struct list_head need_pages; unsigned i; r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true, &duplicates); if (unlikely(r != 0)) goto error_free_pages; /* Without a BO list we don't have userptr BOs */ if (!p->bo_list) break; INIT_LIST_HEAD(&need_pages); for (i = p->bo_list->first_userptr; i < p->bo_list->num_entries; ++i) { e = &p->bo_list->array[i]; if (amdgpu_ttm_tt_userptr_invalidated(e->robj->tbo.ttm, &e->user_invalidated) && e->user_pages) { /* We acquired a page array, but somebody * invalidated it. Free it an try again */ release_pages(e->user_pages, e->robj->tbo.ttm->num_pages, false); drm_free_large(e->user_pages); e->user_pages = NULL; } if (e->robj->tbo.ttm->state != tt_bound && !e->user_pages) { list_del(&e->tv.head); list_add(&e->tv.head, &need_pages); amdgpu_bo_unreserve(e->robj); } } if (list_empty(&need_pages)) break; /* Unreserve everything again. */ ttm_eu_backoff_reservation(&p->ticket, &p->validated); /* We tried to often, just abort */ if (!--tries) { r = -EDEADLK; goto error_free_pages; } /* Fill the page arrays for all useptrs. */ list_for_each_entry(e, &need_pages, tv.head) { struct ttm_tt *ttm = e->robj->tbo.ttm; e->user_pages = drm_calloc_large(ttm->num_pages, sizeof(struct page*)); if (!e->user_pages) { r = -ENOMEM; goto error_free_pages; } r = amdgpu_ttm_tt_get_user_pages(ttm, e->user_pages); if (r) { drm_free_large(e->user_pages); e->user_pages = NULL; goto error_free_pages; } } /* And try again. */ list_splice(&need_pages, &p->validated); } amdgpu_vm_get_pt_bos(&fpriv->vm, &duplicates); p->bytes_moved_threshold = amdgpu_cs_get_threshold_for_moves(p->adev); p->bytes_moved = 0; r = amdgpu_cs_list_validate(p, &duplicates); if (r) goto error_validate; r = amdgpu_cs_list_validate(p, &p->validated); if (r) goto error_validate; if (p->bo_list) { struct amdgpu_vm *vm = &fpriv->vm; unsigned i; for (i = 0; i < p->bo_list->num_entries; i++) { struct amdgpu_bo *bo = p->bo_list->array[i].robj; p->bo_list->array[i].bo_va = amdgpu_vm_bo_find(vm, bo); } } error_validate: if (r) { amdgpu_vm_move_pt_bos_in_lru(p->adev, &fpriv->vm); ttm_eu_backoff_reservation(&p->ticket, &p->validated); } error_free_pages: if (need_mmap_lock) up_read(&current->mm->mmap_sem); if (p->bo_list) { for (i = p->bo_list->first_userptr; i < p->bo_list->num_entries; ++i) { e = &p->bo_list->array[i]; if (!e->user_pages) continue; release_pages(e->user_pages, e->robj->tbo.ttm->num_pages, false); drm_free_large(e->user_pages); } } return r; } static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p) { struct amdgpu_bo_list_entry *e; int r; list_for_each_entry(e, &p->validated, tv.head) { struct reservation_object *resv = e->robj->tbo.resv; r = amdgpu_sync_resv(p->adev, &p->job->sync, resv, p->filp); if (r) return r; } return 0; } static int cmp_size_smaller_first(void *priv, struct list_head *a, struct list_head *b) { struct amdgpu_bo_list_entry *la = list_entry(a, struct amdgpu_bo_list_entry, tv.head); struct amdgpu_bo_list_entry *lb = list_entry(b, struct amdgpu_bo_list_entry, tv.head); /* Sort A before B if A is smaller. */ return (int)la->robj->tbo.num_pages - (int)lb->robj->tbo.num_pages; } /** * cs_parser_fini() - clean parser states * @parser: parser structure holding parsing context. * @error: error number * * If error is set than unvalidate buffer, otherwise just free memory * used by parsing context. **/ static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error, bool backoff) { struct amdgpu_fpriv *fpriv = parser->filp->driver_priv; unsigned i; if (!error) { amdgpu_vm_move_pt_bos_in_lru(parser->adev, &fpriv->vm); /* Sort the buffer list from the smallest to largest buffer, * which affects the order of buffers in the LRU list. * This assures that the smallest buffers are added first * to the LRU list, so they are likely to be later evicted * first, instead of large buffers whose eviction is more * expensive. * * This slightly lowers the number of bytes moved by TTM * per frame under memory pressure. */ list_sort(NULL, &parser->validated, cmp_size_smaller_first); ttm_eu_fence_buffer_objects(&parser->ticket, &parser->validated, parser->fence); } else if (backoff) { ttm_eu_backoff_reservation(&parser->ticket, &parser->validated); } fence_put(parser->fence); if (parser->ctx) amdgpu_ctx_put(parser->ctx); if (parser->bo_list) amdgpu_bo_list_put(parser->bo_list); for (i = 0; i < parser->nchunks; i++) drm_free_large(parser->chunks[i].kdata); kfree(parser->chunks); if (parser->job) amdgpu_job_free(parser->job); amdgpu_bo_unref(&parser->uf_entry.robj); } static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p, struct amdgpu_vm *vm) { struct amdgpu_device *adev = p->adev; struct amdgpu_bo_va *bo_va; struct amdgpu_bo *bo; int i, r; r = amdgpu_vm_update_page_directory(adev, vm); if (r) return r; r = amdgpu_sync_fence(adev, &p->job->sync, vm->page_directory_fence); if (r) return r; r = amdgpu_vm_clear_freed(adev, vm); if (r) return r; if (p->bo_list) { for (i = 0; i < p->bo_list->num_entries; i++) { struct fence *f; /* ignore duplicates */ bo = p->bo_list->array[i].robj; if (!bo) continue; bo_va = p->bo_list->array[i].bo_va; if (bo_va == NULL) continue; r = amdgpu_vm_bo_update(adev, bo_va, &bo->tbo.mem); if (r) return r; f = bo_va->last_pt_update; r = amdgpu_sync_fence(adev, &p->job->sync, f); if (r) return r; } } r = amdgpu_vm_clear_invalids(adev, vm, &p->job->sync); if (amdgpu_vm_debug && p->bo_list) { /* Invalidate all BOs to test for userspace bugs */ for (i = 0; i < p->bo_list->num_entries; i++) { /* ignore duplicates */ bo = p->bo_list->array[i].robj; if (!bo) continue; amdgpu_vm_bo_invalidate(adev, bo); } } return r; } static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev, struct amdgpu_cs_parser *p) { struct amdgpu_fpriv *fpriv = p->filp->driver_priv; struct amdgpu_vm *vm = &fpriv->vm; struct amdgpu_ring *ring = p->job->ring; int i, r; /* Only for UVD/VCE VM emulation */ if (ring->funcs->parse_cs) { for (i = 0; i < p->job->num_ibs; i++) { r = amdgpu_ring_parse_cs(ring, p, i); if (r) return r; } } r = amdgpu_bo_vm_update_pte(p, vm); if (!r) amdgpu_cs_sync_rings(p); return r; } static int amdgpu_cs_handle_lockup(struct amdgpu_device *adev, int r) { if (r == -EDEADLK) { r = amdgpu_gpu_reset(adev); if (!r) r = -EAGAIN; } return r; } static int amdgpu_cs_ib_fill(struct amdgpu_device *adev, struct amdgpu_cs_parser *parser) { struct amdgpu_fpriv *fpriv = parser->filp->driver_priv; struct amdgpu_vm *vm = &fpriv->vm; int i, j; int r; for (i = 0, j = 0; i < parser->nchunks && j < parser->job->num_ibs; i++) { struct amdgpu_cs_chunk *chunk; struct amdgpu_ib *ib; struct drm_amdgpu_cs_chunk_ib *chunk_ib; struct amdgpu_ring *ring; chunk = &parser->chunks[i]; ib = &parser->job->ibs[j]; chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata; if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB) continue; r = amdgpu_cs_get_ring(adev, chunk_ib->ip_type, chunk_ib->ip_instance, chunk_ib->ring, &ring); if (r) return r; if (parser->job->ring && parser->job->ring != ring) return -EINVAL; parser->job->ring = ring; if (ring->funcs->parse_cs) { struct amdgpu_bo_va_mapping *m; struct amdgpu_bo *aobj = NULL; uint64_t offset; uint8_t *kptr; m = amdgpu_cs_find_mapping(parser, chunk_ib->va_start, &aobj); if (!aobj) { DRM_ERROR("IB va_start is invalid\n"); return -EINVAL; } if ((chunk_ib->va_start + chunk_ib->ib_bytes) > (m->it.last + 1) * AMDGPU_GPU_PAGE_SIZE) { DRM_ERROR("IB va_start+ib_bytes is invalid\n"); return -EINVAL; } /* the IB should be reserved at this point */ r = amdgpu_bo_kmap(aobj, (void **)&kptr); if (r) { return r; } offset = ((uint64_t)m->it.start) * AMDGPU_GPU_PAGE_SIZE; kptr += chunk_ib->va_start - offset; r = amdgpu_ib_get(adev, NULL, chunk_ib->ib_bytes, ib); if (r) { DRM_ERROR("Failed to get ib !\n"); return r; } memcpy(ib->ptr, kptr, chunk_ib->ib_bytes); amdgpu_bo_kunmap(aobj); } else { r = amdgpu_ib_get(adev, vm, 0, ib); if (r) { DRM_ERROR("Failed to get ib !\n"); return r; } ib->gpu_addr = chunk_ib->va_start; } ib->length_dw = chunk_ib->ib_bytes / 4; ib->flags = chunk_ib->flags; ib->ctx = parser->ctx; j++; } /* add GDS resources to first IB */ if (parser->bo_list) { struct amdgpu_bo *gds = parser->bo_list->gds_obj; struct amdgpu_bo *gws = parser->bo_list->gws_obj; struct amdgpu_bo *oa = parser->bo_list->oa_obj; struct amdgpu_ib *ib = &parser->job->ibs[0]; if (gds) { ib->gds_base = amdgpu_bo_gpu_offset(gds); ib->gds_size = amdgpu_bo_size(gds); } if (gws) { ib->gws_base = amdgpu_bo_gpu_offset(gws); ib->gws_size = amdgpu_bo_size(gws); } if (oa) { ib->oa_base = amdgpu_bo_gpu_offset(oa); ib->oa_size = amdgpu_bo_size(oa); } } /* wrap the last IB with user fence */ if (parser->job->uf.bo) { struct amdgpu_ib *ib = &parser->job->ibs[parser->job->num_ibs - 1]; /* UVD & VCE fw doesn't support user fences */ if (parser->job->ring->type == AMDGPU_RING_TYPE_UVD || parser->job->ring->type == AMDGPU_RING_TYPE_VCE) return -EINVAL; ib->user = &parser->job->uf; } return 0; } static int amdgpu_cs_dependencies(struct amdgpu_device *adev, struct amdgpu_cs_parser *p) { struct amdgpu_fpriv *fpriv = p->filp->driver_priv; int i, j, r; for (i = 0; i < p->nchunks; ++i) { struct drm_amdgpu_cs_chunk_dep *deps; struct amdgpu_cs_chunk *chunk; unsigned num_deps; chunk = &p->chunks[i]; if (chunk->chunk_id != AMDGPU_CHUNK_ID_DEPENDENCIES) continue; deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata; num_deps = chunk->length_dw * 4 / sizeof(struct drm_amdgpu_cs_chunk_dep); for (j = 0; j < num_deps; ++j) { struct amdgpu_ring *ring; struct amdgpu_ctx *ctx; struct fence *fence; r = amdgpu_cs_get_ring(adev, deps[j].ip_type, deps[j].ip_instance, deps[j].ring, &ring); if (r) return r; ctx = amdgpu_ctx_get(fpriv, deps[j].ctx_id); if (ctx == NULL) return -EINVAL; fence = amdgpu_ctx_get_fence(ctx, ring, deps[j].handle); if (IS_ERR(fence)) { r = PTR_ERR(fence); amdgpu_ctx_put(ctx); return r; } else if (fence) { r = amdgpu_sync_fence(adev, &p->job->sync, fence); fence_put(fence); amdgpu_ctx_put(ctx); if (r) return r; } } } return 0; } static int amdgpu_cs_submit(struct amdgpu_cs_parser *p, union drm_amdgpu_cs *cs) { struct amdgpu_ring *ring = p->job->ring; struct amd_sched_fence *fence; struct amdgpu_job *job; job = p->job; p->job = NULL; job->base.sched = &ring->sched; job->base.s_entity = &p->ctx->rings[ring->idx].entity; job->owner = p->filp; fence = amd_sched_fence_create(job->base.s_entity, p->filp); if (!fence) { amdgpu_job_free(job); return -ENOMEM; } job->base.s_fence = fence; p->fence = fence_get(&fence->base); cs->out.handle = amdgpu_ctx_add_fence(p->ctx, ring, &fence->base); job->ibs[job->num_ibs - 1].sequence = cs->out.handle; trace_amdgpu_cs_ioctl(job); amd_sched_entity_push_job(&job->base); return 0; } int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp) { struct amdgpu_device *adev = dev->dev_private; union drm_amdgpu_cs *cs = data; struct amdgpu_cs_parser parser = {}; bool reserved_buffers = false; int i, r; if (!adev->accel_working) return -EBUSY; parser.adev = adev; parser.filp = filp; r = amdgpu_cs_parser_init(&parser, data); if (r) { DRM_ERROR("Failed to initialize parser !\n"); amdgpu_cs_parser_fini(&parser, r, false); r = amdgpu_cs_handle_lockup(adev, r); return r; } r = amdgpu_cs_parser_bos(&parser, data); if (r == -ENOMEM) DRM_ERROR("Not enough memory for command submission!\n"); else if (r && r != -ERESTARTSYS) DRM_ERROR("Failed to process the buffer list %d!\n", r); else if (!r) { reserved_buffers = true; r = amdgpu_cs_ib_fill(adev, &parser); } if (!r) { r = amdgpu_cs_dependencies(adev, &parser); if (r) DRM_ERROR("Failed in the dependencies handling %d!\n", r); } if (r) goto out; for (i = 0; i < parser.job->num_ibs; i++) trace_amdgpu_cs(&parser, i); r = amdgpu_cs_ib_vm_chunk(adev, &parser); if (r) goto out; r = amdgpu_cs_submit(&parser, cs); out: amdgpu_cs_parser_fini(&parser, r, reserved_buffers); r = amdgpu_cs_handle_lockup(adev, r); return r; } /** * amdgpu_cs_wait_ioctl - wait for a command submission to finish * * @dev: drm device * @data: data from userspace * @filp: file private * * Wait for the command submission identified by handle to finish. */ int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *filp) { union drm_amdgpu_wait_cs *wait = data; struct amdgpu_device *adev = dev->dev_private; unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout); struct amdgpu_ring *ring = NULL; struct amdgpu_ctx *ctx; struct fence *fence; long r; r = amdgpu_cs_get_ring(adev, wait->in.ip_type, wait->in.ip_instance, wait->in.ring, &ring); if (r) return r; ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id); if (ctx == NULL) return -EINVAL; fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle); if (IS_ERR(fence)) r = PTR_ERR(fence); else if (fence) { r = fence_wait_timeout(fence, true, timeout); fence_put(fence); } else r = 1; amdgpu_ctx_put(ctx); if (r < 0) return r; memset(wait, 0, sizeof(*wait)); wait->out.status = (r == 0); return 0; } /** * amdgpu_cs_find_bo_va - find bo_va for VM address * * @parser: command submission parser context * @addr: VM address * @bo: resulting BO of the mapping found * * Search the buffer objects in the command submission context for a certain * virtual memory address. Returns allocation structure when found, NULL * otherwise. */ struct amdgpu_bo_va_mapping * amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser, uint64_t addr, struct amdgpu_bo **bo) { struct amdgpu_bo_va_mapping *mapping; unsigned i; if (!parser->bo_list) return NULL; addr /= AMDGPU_GPU_PAGE_SIZE; for (i = 0; i < parser->bo_list->num_entries; i++) { struct amdgpu_bo_list_entry *lobj; lobj = &parser->bo_list->array[i]; if (!lobj->bo_va) continue; list_for_each_entry(mapping, &lobj->bo_va->valids, list) { if (mapping->it.start > addr || addr > mapping->it.last) continue; *bo = lobj->bo_va->bo; return mapping; } list_for_each_entry(mapping, &lobj->bo_va->invalids, list) { if (mapping->it.start > addr || addr > mapping->it.last) continue; *bo = lobj->bo_va->bo; return mapping; } } return NULL; }
cneira/ebpf-backports
linux-3.10.0-514.21.1.el7.x86_64/drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c
C
gpl-2.0
26,057
/** * \file radeon_drv.c * ATI Radeon driver * * \author Gareth Hughes <gareth@valinux.com> */ /* * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <drm/drmP.h> #include <drm/radeon_drm.h> #include "radeon_drv.h" #include <drm/drm_pciids.h> #include <linux/console.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/vga_switcheroo.h> #include "drm_crtc_helper.h" /* * KMS wrapper. * - 2.0.0 - initial interface * - 2.1.0 - add square tiling interface * - 2.2.0 - add r6xx/r7xx const buffer support * - 2.3.0 - add MSPOS + 3D texture + r500 VAP regs * - 2.4.0 - add crtc id query * - 2.5.0 - add get accel 2 to work around ddx breakage for evergreen * - 2.6.0 - add tiling config query (r6xx+), add initial HiZ support (r300->r500) * 2.7.0 - fixups for r600 2D tiling support. (no external ABI change), add eg dyn gpr regs * 2.8.0 - pageflip support, r500 US_FORMAT regs. r500 ARGB2101010 colorbuf, r300->r500 CMASK, clock crystal query * 2.9.0 - r600 tiling (s3tc,rgtc) working, SET_PREDICATION packet 3 on r600 + eg, backend query * 2.10.0 - fusion 2D tiling * 2.11.0 - backend map, initial compute support for the CS checker * 2.12.0 - RADEON_CS_KEEP_TILING_FLAGS * 2.13.0 - virtual memory support, streamout * 2.14.0 - add evergreen tiling informations * 2.15.0 - add max_pipes query * 2.16.0 - fix evergreen 2D tiled surface calculation * 2.17.0 - add STRMOUT_BASE_UPDATE for r7xx * 2.18.0 - r600-eg: allow "invalid" DB formats * 2.19.0 - r600-eg: MSAA textures * 2.20.0 - r600-si: RADEON_INFO_TIMESTAMP query * 2.21.0 - r600-r700: FMASK and CMASK * 2.22.0 - r600 only: RESOLVE_BOX allowed * 2.23.0 - allow STRMOUT_BASE_UPDATE on RS780 and RS880 * 2.24.0 - eg only: allow MIP_ADDRESS=0 for MSAA textures * 2.25.0 - eg+: new info request for num SE and num SH * 2.26.0 - r600-eg: fix htile size computation * 2.27.0 - r600-SI: Add CS ioctl support for async DMA * 2.28.0 - r600-eg: Add MEM_WRITE packet support * 2.29.0 - R500 FP16 color clear registers * 2.30.0 - fix for FMASK texturing * 2.31.0 - Add fastfb support for rs690 * 2.32.0 - new info request for rings working * 2.33.0 - Add SI tiling mode array query * 2.34.0 - Add CIK tiling mode array query * 2.35.0 - Add CIK macrotile mode array query * 2.36.0 - Fix CIK DCE tiling setup * 2.37.0 - allow GS ring setup on r6xx/r7xx */ #define KMS_DRIVER_MAJOR 2 #define KMS_DRIVER_MINOR 37 #define KMS_DRIVER_PATCHLEVEL 0 int radeon_driver_load_kms(struct drm_device *dev, unsigned long flags); int radeon_driver_unload_kms(struct drm_device *dev); void radeon_driver_lastclose_kms(struct drm_device *dev); int radeon_driver_open_kms(struct drm_device *dev, struct drm_file *file_priv); void radeon_driver_postclose_kms(struct drm_device *dev, struct drm_file *file_priv); void radeon_driver_preclose_kms(struct drm_device *dev, struct drm_file *file_priv); int radeon_suspend_kms(struct drm_device *dev, bool suspend, bool fbcon); int radeon_resume_kms(struct drm_device *dev, bool resume, bool fbcon); u32 radeon_get_vblank_counter_kms(struct drm_device *dev, int crtc); int radeon_enable_vblank_kms(struct drm_device *dev, int crtc); void radeon_disable_vblank_kms(struct drm_device *dev, int crtc); int radeon_get_vblank_timestamp_kms(struct drm_device *dev, int crtc, int *max_error, struct timeval *vblank_time, unsigned flags); void radeon_driver_irq_preinstall_kms(struct drm_device *dev); int radeon_driver_irq_postinstall_kms(struct drm_device *dev); void radeon_driver_irq_uninstall_kms(struct drm_device *dev); irqreturn_t radeon_driver_irq_handler_kms(int irq, void *arg); void radeon_gem_object_free(struct drm_gem_object *obj); int radeon_gem_object_open(struct drm_gem_object *obj, struct drm_file *file_priv); void radeon_gem_object_close(struct drm_gem_object *obj, struct drm_file *file_priv); extern int radeon_get_crtc_scanoutpos(struct drm_device *dev, int crtc, unsigned int flags, int *vpos, int *hpos, ktime_t *stime, ktime_t *etime); extern const struct drm_ioctl_desc radeon_ioctls_kms[]; extern int radeon_max_kms_ioctl; int radeon_mmap(struct file *filp, struct vm_area_struct *vma); int radeon_mode_dumb_mmap(struct drm_file *filp, struct drm_device *dev, uint32_t handle, uint64_t *offset_p); int radeon_mode_dumb_create(struct drm_file *file_priv, struct drm_device *dev, struct drm_mode_create_dumb *args); struct sg_table *radeon_gem_prime_get_sg_table(struct drm_gem_object *obj); struct drm_gem_object *radeon_gem_prime_import_sg_table(struct drm_device *dev, size_t size, struct sg_table *sg); int radeon_gem_prime_pin(struct drm_gem_object *obj); void radeon_gem_prime_unpin(struct drm_gem_object *obj); void *radeon_gem_prime_vmap(struct drm_gem_object *obj); void radeon_gem_prime_vunmap(struct drm_gem_object *obj, void *vaddr); extern long radeon_kms_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); #if defined(CONFIG_DEBUG_FS) int radeon_debugfs_init(struct drm_minor *minor); void radeon_debugfs_cleanup(struct drm_minor *minor); #endif /* atpx handler */ #if defined(CONFIG_VGA_SWITCHEROO) void radeon_register_atpx_handler(void); void radeon_unregister_atpx_handler(void); bool radeon_is_px(void); #else static inline void radeon_register_atpx_handler(void) {} static inline void radeon_unregister_atpx_handler(void) {} static inline bool radeon_is_px(void) { return false; } #endif int radeon_no_wb; int radeon_modeset = -1; int radeon_dynclks = -1; int radeon_r4xx_atom = 0; int radeon_agpmode = 0; int radeon_vram_limit = 0; int radeon_gart_size = -1; /* auto */ int radeon_benchmarking = 0; int radeon_testing = 0; int radeon_connector_table = 0; int radeon_tv = 1; int radeon_audio = -1; int radeon_disp_priority = 0; int radeon_hw_i2c = 0; int radeon_pcie_gen2 = -1; int radeon_msi = -1; int radeon_lockup_timeout = 10000; int radeon_fastfb = 0; int radeon_dpm = -1; int radeon_aspm = -1; int radeon_runtime_pm = -1; int radeon_hard_reset = 0; MODULE_PARM_DESC(no_wb, "Disable AGP writeback for scratch registers"); module_param_named(no_wb, radeon_no_wb, int, 0444); MODULE_PARM_DESC(modeset, "Disable/Enable modesetting"); module_param_named(modeset, radeon_modeset, int, 0400); MODULE_PARM_DESC(dynclks, "Disable/Enable dynamic clocks"); module_param_named(dynclks, radeon_dynclks, int, 0444); MODULE_PARM_DESC(r4xx_atom, "Enable ATOMBIOS modesetting for R4xx"); module_param_named(r4xx_atom, radeon_r4xx_atom, int, 0444); MODULE_PARM_DESC(vramlimit, "Restrict VRAM for testing"); module_param_named(vramlimit, radeon_vram_limit, int, 0600); MODULE_PARM_DESC(agpmode, "AGP Mode (-1 == PCI)"); module_param_named(agpmode, radeon_agpmode, int, 0444); MODULE_PARM_DESC(gartsize, "Size of PCIE/IGP gart to setup in megabytes (32, 64, etc., -1 = auto)"); module_param_named(gartsize, radeon_gart_size, int, 0600); MODULE_PARM_DESC(benchmark, "Run benchmark"); module_param_named(benchmark, radeon_benchmarking, int, 0444); MODULE_PARM_DESC(test, "Run tests"); module_param_named(test, radeon_testing, int, 0444); MODULE_PARM_DESC(connector_table, "Force connector table"); module_param_named(connector_table, radeon_connector_table, int, 0444); MODULE_PARM_DESC(tv, "TV enable (0 = disable)"); module_param_named(tv, radeon_tv, int, 0444); MODULE_PARM_DESC(audio, "Audio enable (-1 = auto, 0 = disable, 1 = enable)"); module_param_named(audio, radeon_audio, int, 0444); MODULE_PARM_DESC(disp_priority, "Display Priority (0 = auto, 1 = normal, 2 = high)"); module_param_named(disp_priority, radeon_disp_priority, int, 0444); MODULE_PARM_DESC(hw_i2c, "hw i2c engine enable (0 = disable)"); module_param_named(hw_i2c, radeon_hw_i2c, int, 0444); MODULE_PARM_DESC(pcie_gen2, "PCIE Gen2 mode (-1 = auto, 0 = disable, 1 = enable)"); module_param_named(pcie_gen2, radeon_pcie_gen2, int, 0444); MODULE_PARM_DESC(msi, "MSI support (1 = enable, 0 = disable, -1 = auto)"); module_param_named(msi, radeon_msi, int, 0444); MODULE_PARM_DESC(lockup_timeout, "GPU lockup timeout in ms (defaul 10000 = 10 seconds, 0 = disable)"); module_param_named(lockup_timeout, radeon_lockup_timeout, int, 0444); MODULE_PARM_DESC(fastfb, "Direct FB access for IGP chips (0 = disable, 1 = enable)"); module_param_named(fastfb, radeon_fastfb, int, 0444); MODULE_PARM_DESC(dpm, "DPM support (1 = enable, 0 = disable, -1 = auto)"); module_param_named(dpm, radeon_dpm, int, 0444); MODULE_PARM_DESC(aspm, "ASPM support (1 = enable, 0 = disable, -1 = auto)"); module_param_named(aspm, radeon_aspm, int, 0444); MODULE_PARM_DESC(runpm, "PX runtime pm (1 = force enable, 0 = disable, -1 = PX only default)"); module_param_named(runpm, radeon_runtime_pm, int, 0444); MODULE_PARM_DESC(hard_reset, "PCI config reset (1 = force enable, 0 = disable (default))"); module_param_named(hard_reset, radeon_hard_reset, int, 0444); static struct pci_device_id pciidlist[] = { radeon_PCI_IDS }; MODULE_DEVICE_TABLE(pci, pciidlist); #ifdef CONFIG_DRM_RADEON_UMS static int radeon_suspend(struct drm_device *dev, pm_message_t state) { drm_radeon_private_t *dev_priv = dev->dev_private; if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600) return 0; /* Disable *all* interrupts */ if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) RADEON_WRITE(R500_DxMODE_INT_MASK, 0); RADEON_WRITE(RADEON_GEN_INT_CNTL, 0); return 0; } static int radeon_resume(struct drm_device *dev) { drm_radeon_private_t *dev_priv = dev->dev_private; if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600) return 0; /* Restore interrupt registers */ if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) RADEON_WRITE(R500_DxMODE_INT_MASK, dev_priv->r500_disp_irq_reg); RADEON_WRITE(RADEON_GEN_INT_CNTL, dev_priv->irq_enable_reg); return 0; } static const struct file_operations radeon_driver_old_fops = { .owner = THIS_MODULE, .open = drm_open, .release = drm_release, .unlocked_ioctl = drm_ioctl, .mmap = drm_mmap, .poll = drm_poll, .read = drm_read, #ifdef CONFIG_COMPAT .compat_ioctl = radeon_compat_ioctl, #endif .llseek = noop_llseek, }; static struct drm_driver driver_old = { .driver_features = DRIVER_USE_AGP | DRIVER_PCI_DMA | DRIVER_SG | DRIVER_HAVE_IRQ | DRIVER_HAVE_DMA | DRIVER_IRQ_SHARED, .dev_priv_size = sizeof(drm_radeon_buf_priv_t), .load = radeon_driver_load, .firstopen = radeon_driver_firstopen, .open = radeon_driver_open, .preclose = radeon_driver_preclose, .postclose = radeon_driver_postclose, .lastclose = radeon_driver_lastclose, .unload = radeon_driver_unload, .suspend = radeon_suspend, .resume = radeon_resume, .get_vblank_counter = radeon_get_vblank_counter, .enable_vblank = radeon_enable_vblank, .disable_vblank = radeon_disable_vblank, .master_create = radeon_master_create, .master_destroy = radeon_master_destroy, .irq_preinstall = radeon_driver_irq_preinstall, .irq_postinstall = radeon_driver_irq_postinstall, .irq_uninstall = radeon_driver_irq_uninstall, .irq_handler = radeon_driver_irq_handler, .ioctls = radeon_ioctls, .dma_ioctl = radeon_cp_buffers, .fops = &radeon_driver_old_fops, .name = DRIVER_NAME, .desc = DRIVER_DESC, .date = DRIVER_DATE, .major = DRIVER_MAJOR, .minor = DRIVER_MINOR, .patchlevel = DRIVER_PATCHLEVEL, }; #endif static struct drm_driver kms_driver; static int radeon_kick_out_firmware_fb(struct pci_dev *pdev) { struct apertures_struct *ap; bool primary = false; ap = alloc_apertures(1); if (!ap) return -ENOMEM; ap->ranges[0].base = pci_resource_start(pdev, 0); ap->ranges[0].size = pci_resource_len(pdev, 0); #ifdef CONFIG_X86 primary = pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW; #endif remove_conflicting_framebuffers(ap, "radeondrmfb", primary); kfree(ap); return 0; } static int radeon_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { int ret; /* Get rid of things like offb */ ret = radeon_kick_out_firmware_fb(pdev); if (ret) return ret; return drm_get_pci_dev(pdev, ent, &kms_driver); } static void radeon_pci_remove(struct pci_dev *pdev) { struct drm_device *dev = pci_get_drvdata(pdev); drm_put_dev(dev); } static int radeon_pmops_suspend(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); return radeon_suspend_kms(drm_dev, true, true); } static int radeon_pmops_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); return radeon_resume_kms(drm_dev, true, true); } static int radeon_pmops_freeze(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); return radeon_suspend_kms(drm_dev, false, true); } static int radeon_pmops_thaw(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); return radeon_resume_kms(drm_dev, false, true); } static int radeon_pmops_runtime_suspend(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); int ret; if (radeon_runtime_pm == 0) return -EINVAL; if (radeon_runtime_pm == -1 && !radeon_is_px()) return -EINVAL; drm_dev->switch_power_state = DRM_SWITCH_POWER_CHANGING; drm_kms_helper_poll_disable(drm_dev); vga_switcheroo_set_dynamic_switch(pdev, VGA_SWITCHEROO_OFF); ret = radeon_suspend_kms(drm_dev, false, false); pci_save_state(pdev); pci_disable_device(pdev); pci_set_power_state(pdev, PCI_D3cold); drm_dev->switch_power_state = DRM_SWITCH_POWER_DYNAMIC_OFF; return 0; } static int radeon_pmops_runtime_resume(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); int ret; if (radeon_runtime_pm == 0) return -EINVAL; if (radeon_runtime_pm == -1 && !radeon_is_px()) return -EINVAL; drm_dev->switch_power_state = DRM_SWITCH_POWER_CHANGING; pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); ret = pci_enable_device(pdev); if (ret) return ret; pci_set_master(pdev); ret = radeon_resume_kms(drm_dev, false, false); drm_kms_helper_poll_enable(drm_dev); vga_switcheroo_set_dynamic_switch(pdev, VGA_SWITCHEROO_ON); drm_dev->switch_power_state = DRM_SWITCH_POWER_ON; return 0; } static int radeon_pmops_runtime_idle(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); struct drm_device *drm_dev = pci_get_drvdata(pdev); struct drm_crtc *crtc; if (radeon_runtime_pm == 0) return -EBUSY; /* are we PX enabled? */ if (radeon_runtime_pm == -1 && !radeon_is_px()) { DRM_DEBUG_DRIVER("failing to power off - not px\n"); return -EBUSY; } list_for_each_entry(crtc, &drm_dev->mode_config.crtc_list, head) { if (crtc->enabled) { DRM_DEBUG_DRIVER("failing to power off - crtc active\n"); return -EBUSY; } } pm_runtime_mark_last_busy(dev); pm_runtime_autosuspend(dev); /* we don't want the main rpm_idle to call suspend - we want to autosuspend */ return 1; } long radeon_drm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct drm_file *file_priv = filp->private_data; struct drm_device *dev; long ret; dev = file_priv->minor->dev; ret = pm_runtime_get_sync(dev->dev); if (ret < 0) return ret; ret = drm_ioctl(filp, cmd, arg); pm_runtime_mark_last_busy(dev->dev); pm_runtime_put_autosuspend(dev->dev); return ret; } static const struct dev_pm_ops radeon_pm_ops = { .suspend = radeon_pmops_suspend, .resume = radeon_pmops_resume, .freeze = radeon_pmops_freeze, .thaw = radeon_pmops_thaw, .poweroff = radeon_pmops_freeze, .restore = radeon_pmops_resume, .runtime_suspend = radeon_pmops_runtime_suspend, .runtime_resume = radeon_pmops_runtime_resume, .runtime_idle = radeon_pmops_runtime_idle, }; static const struct file_operations radeon_driver_kms_fops = { .owner = THIS_MODULE, .open = drm_open, .release = drm_release, .unlocked_ioctl = radeon_drm_ioctl, .mmap = radeon_mmap, .poll = drm_poll, .read = drm_read, #ifdef CONFIG_COMPAT .compat_ioctl = radeon_kms_compat_ioctl, #endif }; static struct drm_driver kms_driver = { .driver_features = DRIVER_USE_AGP | DRIVER_HAVE_IRQ | DRIVER_IRQ_SHARED | DRIVER_GEM | DRIVER_PRIME | DRIVER_RENDER, .dev_priv_size = 0, .load = radeon_driver_load_kms, .open = radeon_driver_open_kms, .preclose = radeon_driver_preclose_kms, .postclose = radeon_driver_postclose_kms, .lastclose = radeon_driver_lastclose_kms, .unload = radeon_driver_unload_kms, .get_vblank_counter = radeon_get_vblank_counter_kms, .enable_vblank = radeon_enable_vblank_kms, .disable_vblank = radeon_disable_vblank_kms, .get_vblank_timestamp = radeon_get_vblank_timestamp_kms, .get_scanout_position = radeon_get_crtc_scanoutpos, #if defined(CONFIG_DEBUG_FS) .debugfs_init = radeon_debugfs_init, .debugfs_cleanup = radeon_debugfs_cleanup, #endif .irq_preinstall = radeon_driver_irq_preinstall_kms, .irq_postinstall = radeon_driver_irq_postinstall_kms, .irq_uninstall = radeon_driver_irq_uninstall_kms, .irq_handler = radeon_driver_irq_handler_kms, .ioctls = radeon_ioctls_kms, .gem_free_object = radeon_gem_object_free, .gem_open_object = radeon_gem_object_open, .gem_close_object = radeon_gem_object_close, .dumb_create = radeon_mode_dumb_create, .dumb_map_offset = radeon_mode_dumb_mmap, .dumb_destroy = drm_gem_dumb_destroy, .fops = &radeon_driver_kms_fops, .prime_handle_to_fd = drm_gem_prime_handle_to_fd, .prime_fd_to_handle = drm_gem_prime_fd_to_handle, .gem_prime_export = drm_gem_prime_export, .gem_prime_import = drm_gem_prime_import, .gem_prime_pin = radeon_gem_prime_pin, .gem_prime_unpin = radeon_gem_prime_unpin, .gem_prime_get_sg_table = radeon_gem_prime_get_sg_table, .gem_prime_import_sg_table = radeon_gem_prime_import_sg_table, .gem_prime_vmap = radeon_gem_prime_vmap, .gem_prime_vunmap = radeon_gem_prime_vunmap, .name = DRIVER_NAME, .desc = DRIVER_DESC, .date = DRIVER_DATE, .major = KMS_DRIVER_MAJOR, .minor = KMS_DRIVER_MINOR, .patchlevel = KMS_DRIVER_PATCHLEVEL, }; static struct drm_driver *driver; static struct pci_driver *pdriver; #ifdef CONFIG_DRM_RADEON_UMS static struct pci_driver radeon_pci_driver = { .name = DRIVER_NAME, .id_table = pciidlist, }; #endif static struct pci_driver radeon_kms_pci_driver = { .name = DRIVER_NAME, .id_table = pciidlist, .probe = radeon_pci_probe, .remove = radeon_pci_remove, .driver.pm = &radeon_pm_ops, }; static int __init radeon_init(void) { #ifdef CONFIG_VGA_CONSOLE if (vgacon_text_force() && radeon_modeset == -1) { DRM_INFO("VGACON disable radeon kernel modesetting.\n"); radeon_modeset = 0; } #endif /* set to modesetting by default if not nomodeset */ if (radeon_modeset == -1) radeon_modeset = 1; if (radeon_modeset == 1) { DRM_INFO("radeon kernel modesetting enabled.\n"); driver = &kms_driver; pdriver = &radeon_kms_pci_driver; driver->driver_features |= DRIVER_MODESET; driver->num_ioctls = radeon_max_kms_ioctl; radeon_register_atpx_handler(); } else { #ifdef CONFIG_DRM_RADEON_UMS DRM_INFO("radeon userspace modesetting enabled.\n"); driver = &driver_old; pdriver = &radeon_pci_driver; driver->driver_features &= ~DRIVER_MODESET; driver->num_ioctls = radeon_max_ioctl; #else DRM_ERROR("No UMS support in radeon module!\n"); return -EINVAL; #endif } /* let modprobe override vga console setting */ return drm_pci_init(driver, pdriver); } static void __exit radeon_exit(void) { drm_pci_exit(driver, pdriver); radeon_unregister_atpx_handler(); } module_init(radeon_init); module_exit(radeon_exit); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL and additional rights");
makarandk/linux
drivers/gpu/drm/radeon/radeon_drv.c
C
gpl-2.0
21,025
// SPDX-License-Identifier: GPL-2.0-only /* * kretprobe_example.c * * Here's a sample kernel module showing the use of return probes to * report the return value and total time taken for probed function * to run. * * usage: insmod kretprobe_example.ko func=<func_name> * * If no func_name is specified, _do_fork is instrumented * * For more information on theory of operation of kretprobes, see * Documentation/kprobes.txt * * Build and insert the kernel module as done in the kprobe example. * You will see the trace data in /var/log/messages and on the console * whenever the probed function returns. (Some messages may be suppressed * if syslogd is configured to eliminate duplicate messages.) */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/kprobes.h> #include <linux/ktime.h> #include <linux/limits.h> #include <linux/sched.h> static char func_name[NAME_MAX] = "_do_fork"; module_param_string(func, func_name, NAME_MAX, S_IRUGO); MODULE_PARM_DESC(func, "Function to kretprobe; this module will report the" " function's execution time"); /* per-instance private data */ struct my_data { ktime_t entry_stamp; }; /* Here we use the entry_hanlder to timestamp function entry */ static int entry_handler(struct kretprobe_instance *ri, struct pt_regs *regs) { struct my_data *data; if (!current->mm) return 1; /* Skip kernel threads */ data = (struct my_data *)ri->data; data->entry_stamp = ktime_get(); return 0; } NOKPROBE_SYMBOL(entry_handler); /* * Return-probe handler: Log the return value and duration. Duration may turn * out to be zero consistently, depending upon the granularity of time * accounting on the platform. */ static int ret_handler(struct kretprobe_instance *ri, struct pt_regs *regs) { unsigned long retval = regs_return_value(regs); struct my_data *data = (struct my_data *)ri->data; s64 delta; ktime_t now; now = ktime_get(); delta = ktime_to_ns(ktime_sub(now, data->entry_stamp)); pr_info("%s returned %lu and took %lld ns to execute\n", func_name, retval, (long long)delta); return 0; } NOKPROBE_SYMBOL(ret_handler); static struct kretprobe my_kretprobe = { .handler = ret_handler, .entry_handler = entry_handler, .data_size = sizeof(struct my_data), /* Probe up to 20 instances concurrently. */ .maxactive = 20, }; static int __init kretprobe_init(void) { int ret; my_kretprobe.kp.symbol_name = func_name; ret = register_kretprobe(&my_kretprobe); if (ret < 0) { pr_err("register_kretprobe failed, returned %d\n", ret); return -1; } pr_info("Planted return probe at %s: %p\n", my_kretprobe.kp.symbol_name, my_kretprobe.kp.addr); return 0; } static void __exit kretprobe_exit(void) { unregister_kretprobe(&my_kretprobe); pr_info("kretprobe at %p unregistered\n", my_kretprobe.kp.addr); /* nmissed > 0 suggests that maxactive was set too low. */ pr_info("Missed probing %d instances of %s\n", my_kretprobe.nmissed, my_kretprobe.kp.symbol_name); } module_init(kretprobe_init) module_exit(kretprobe_exit) MODULE_LICENSE("GPL");
skalk/linux
samples/kprobes/kretprobe_example.c
C
gpl-2.0
3,060
using System; namespace Server.Items { [Flipable(0xC17, 0xC18)] public class BrokenCoveredChairComponent : AddonComponent { public BrokenCoveredChairComponent() : base(0xC17) { } public BrokenCoveredChairComponent(Serial serial) : base(serial) { } public override int LabelNumber { get { return 1076257; } }// Broken Covered Chair public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } public class BrokenCoveredChairAddon : BaseAddon { [Constructable] public BrokenCoveredChairAddon() : base() { this.AddComponent(new BrokenCoveredChairComponent(), 0, 0, 0); } public BrokenCoveredChairAddon(Serial serial) : base(serial) { } public override BaseAddonDeed Deed { get { return new BrokenCoveredChairDeed(); } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } public class BrokenCoveredChairDeed : BaseAddonDeed { [Constructable] public BrokenCoveredChairDeed() : base() { this.LootType = LootType.Blessed; } public BrokenCoveredChairDeed(Serial serial) : base(serial) { } public override BaseAddon Addon { get { return new BrokenCoveredChairAddon(); } } public override int LabelNumber { get { return 1076257; } }// Broken Covered Chair public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } }
GenerationOfWorlds/GOW
Scripts/Systems/Items/Management/Anniversy_Collections/Broken Furniture Collection/BrokenCoveredChair.cs
C#
gpl-3.0
2,676
<?php class ControllerFeedGoogleBase extends Controller { public function index() { if ($this->config->get('google_base_status')) { $output = '<?xml version="1.0" encoding="UTF-8" ?>'; $output .= '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">'; $output .= '<channel>'; $output .= '<title>' . $this->config->get('config_name') . '</title>'; $output .= '<description>' . $this->config->get('config_meta_description') . '</description>'; $output .= '<link>' . HTTP_SERVER . '</link>'; $this->load->model('feed/google_base'); $this->load->model('catalog/category'); $this->load->model('catalog/product'); $this->load->model('tool/image'); $product_data = array(); $google_base_categories = $this->model_feed_google_base->getCategories(); foreach ($google_base_categories as $google_base_category) { $filter_data = array( 'filter_category_id' => $google_base_category['category_id'], 'filter_filter' => false ); $products = $this->model_catalog_product->getProducts($filter_data); foreach ($products as $product) { if (!in_array($product['product_id'], $product_data) && $product['description']) { $output .= '<item>'; $output .= '<title><![CDATA[' . $product['name'] . ']]></title>'; $output .= '<link>' . $this->url->link('product/product', 'product_id=' . $product['product_id']) . '</link>'; $output .= '<description><![CDATA[' . $product['description'] . ']]></description>'; $output .= '<g:brand><![CDATA[' . html_entity_decode($product['manufacturer'], ENT_QUOTES, 'UTF-8') . ']]></g:brand>'; $output .= '<g:condition>new</g:condition>'; $output .= '<g:id>' . $product['product_id'] . '</g:id>'; if ($product['image']) { $output .= '<g:image_link>' . $this->model_tool_image->resize($product['image'], 500, 500) . '</g:image_link>'; } else { $output .= '<g:image_link></g:image_link>'; } $output .= '<g:model_number>' . $product['model'] . '</g:model_number>'; if ($product['mpn']) { $output .= '<g:mpn><![CDATA[' . $product['mpn'] . ']]></g:mpn>' ; } else { $output .= '<g:identifier_exists>false</g:identifier_exists>'; } if ($product['upc']) { $output .= '<g:upc>' . $product['upc'] . '</g:upc>'; } if ($product['ean']) { $output .= '<g:ean>' . $product['ean'] . '</g:ean>'; } $currencies = array( 'USD', 'EUR', 'GBP' ); if (in_array($this->currency->getCode(), $currencies)) { $currency_code = $this->currency->getCode(); $currency_value = $this->currency->getValue(); } else { $currency_code = 'USD'; $currency_value = $this->currency->getValue('USD'); } if ((float)$product['special']) { $output .= '<g:price>' . $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id']), $currency_code, $currency_value, false) . '</g:price>'; } else { $output .= '<g:price>' . $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id']), $currency_code, $currency_value, false) . '</g:price>'; } $output .= '<g:google_product_category>' . $google_base_category['google_base_category_id'] . '</g:google_product_category>'; $categories = $this->model_catalog_product->getCategories($product['product_id']); foreach ($categories as $category) { $path = $this->getPath($category['category_id']); if ($path) { $string = ''; foreach (explode('_', $path) as $path_id) { $category_info = $this->model_catalog_category->getCategory($path_id); if ($category_info) { if (!$string) { $string = $category_info['name']; } else { $string .= ' &gt; ' . $category_info['name']; } } } $output .= '<g:product_type><![CDATA[' . $string . ']]></g:product_type>'; } } $output .= '<g:quantity>' . $product['quantity'] . '</g:quantity>'; $output .= '<g:weight>' . $this->weight->format($product['weight'], $product['weight_class_id']) . '</g:weight>'; $output .= '<g:availability><![CDATA[' . ($product['quantity'] ? 'in stock' : 'out of stock') . ']]></g:availability>'; $output .= '</item>'; } } } $output .= '</channel>'; $output .= '</rss>'; $this->response->addHeader('Content-Type: application/rss+xml'); $this->response->setOutput($output); } } protected function getPath($parent_id, $current_path = '') { $category_info = $this->model_catalog_category->getCategory($parent_id); if ($category_info) { if (!$current_path) { $new_path = $category_info['category_id']; } else { $new_path = $category_info['category_id'] . '_' . $current_path; } $path = $this->getPath($category_info['parent_id'], $new_path); if ($path) { return $path; } else { return $new_path; } } } }
zhoujiafei/opencart
upload/catalog/controller/feed/google_base.php
PHP
gpl-3.0
5,046
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.remoting; /** * CloseListeners can be registered with a {@link org.apache.activemq.artemis.spi.core.protocol.RemotingConnection} to get notified when the connection is closed. * <p> * {@link org.apache.activemq.artemis.spi.core.protocol.RemotingConnection#addCloseListener(CloseListener)} */ public interface CloseListener { /** * called when the connection is closed */ void connectionClosed(); }
lburgazzoli/apache-activemq-artemis
artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/CloseListener.java
Java
apache-2.0
1,259
/* * LZO 1x decompression * Copyright (c) 2006 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "common.h" //! avoid e.g. MPlayers fast_memcpy, it slows things down here #undef memcpy #include <string.h> #include "lzo.h" //! define if we may write up to 12 bytes beyond the output buffer #define OUTBUF_PADDED 1 //! define if we may read up to 8 bytes beyond the input buffer #define INBUF_PADDED 1 typedef struct LZOContext { uint8_t *in, *in_end; uint8_t *out_start, *out, *out_end; int error; } LZOContext; /** * \brief read one byte from input buffer, avoiding overrun * \return byte read */ static inline int get_byte(LZOContext *c) { if (c->in < c->in_end) return *c->in++; c->error |= LZO_INPUT_DEPLETED; return 1; } #ifdef INBUF_PADDED #define GETB(c) (*(c).in++) #else #define GETB(c) get_byte(&(c)) #endif /** * \brief decode a length value in the coding used by lzo * \param x previous byte value * \param mask bits used from x * \return decoded length value */ static inline int get_len(LZOContext *c, int x, int mask) { int cnt = x & mask; if (!cnt) { while (!(x = get_byte(c))) cnt += 255; cnt += mask + x; } return cnt; } //#define UNALIGNED_LOADSTORE #define BUILTIN_MEMCPY #ifdef UNALIGNED_LOADSTORE #define COPY2(d, s) *(uint16_t *)(d) = *(uint16_t *)(s); #define COPY4(d, s) *(uint32_t *)(d) = *(uint32_t *)(s); #elif defined(BUILTIN_MEMCPY) #define COPY2(d, s) memcpy(d, s, 2); #define COPY4(d, s) memcpy(d, s, 4); #else #define COPY2(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1]; #define COPY4(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1]; (d)[2] = (s)[2]; (d)[3] = (s)[3]; #endif /** * \brief copy bytes from input to output buffer with checking * \param cnt number of bytes to copy, must be >= 0 */ static inline void copy(LZOContext *c, int cnt) { register uint8_t *src = c->in; register uint8_t *dst = c->out; if (cnt > c->in_end - src) { cnt = FFMAX(c->in_end - src, 0); c->error |= LZO_INPUT_DEPLETED; } if (cnt > c->out_end - dst) { cnt = FFMAX(c->out_end - dst, 0); c->error |= LZO_OUTPUT_FULL; } #if defined(INBUF_PADDED) && defined(OUTBUF_PADDED) COPY4(dst, src); src += 4; dst += 4; cnt -= 4; if (cnt > 0) #endif memcpy(dst, src, cnt); c->in = src + cnt; c->out = dst + cnt; } /** * \brief copy previously decoded bytes to current position * \param back how many bytes back we start * \param cnt number of bytes to copy, must be >= 0 * * cnt > back is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of back. */ static inline void copy_backptr(LZOContext *c, int back, int cnt) { register uint8_t *src = &c->out[-back]; register uint8_t *dst = c->out; if (src < c->out_start || src > dst) { c->error |= LZO_INVALID_BACKPTR; return; } if (cnt > c->out_end - dst) { cnt = FFMAX(c->out_end - dst, 0); c->error |= LZO_OUTPUT_FULL; } if (back == 1) { memset(dst, *src, cnt); dst += cnt; } else { #ifdef OUTBUF_PADDED COPY2(dst, src); COPY2(dst + 2, src + 2); src += 4; dst += 4; cnt -= 4; if (cnt > 0) { COPY2(dst, src); COPY2(dst + 2, src + 2); COPY2(dst + 4, src + 4); COPY2(dst + 6, src + 6); src += 8; dst += 8; cnt -= 8; } #endif if (cnt > 0) { int blocklen = back; while (cnt > blocklen) { memcpy(dst, src, blocklen); dst += blocklen; cnt -= blocklen; blocklen <<= 1; } memcpy(dst, src, cnt); } dst += cnt; } c->out = dst; } /** * \brief decode LZO 1x compressed data * \param out output buffer * \param outlen size of output buffer, number of bytes left are returned here * \param in input buffer * \param inlen size of input buffer, number of bytes left are returned here * \return 0 on success, otherwise error flags, see lzo.h * * make sure all buffers are appropriately padded, in must provide * LZO_INPUT_PADDING, out must provide LZO_OUTPUT_PADDING additional bytes */ int lzo1x_decode(void *out, int *outlen, void *in, int *inlen) { int state= 0; int x; LZOContext c; c.in = in; c.in_end = (uint8_t *)in + *inlen; c.out = c.out_start = out; c.out_end = (uint8_t *)out + * outlen; c.error = 0; x = GETB(c); if (x > 17) { copy(&c, x - 17); x = GETB(c); if (x < 16) c.error |= LZO_ERROR; } if (c.in > c.in_end) c.error |= LZO_INPUT_DEPLETED; while (!c.error) { int cnt, back; if (x > 15) { if (x > 63) { cnt = (x >> 5) - 1; back = (GETB(c) << 3) + ((x >> 2) & 7) + 1; } else if (x > 31) { cnt = get_len(&c, x, 31); x = GETB(c); back = (GETB(c) << 6) + (x >> 2) + 1; } else { cnt = get_len(&c, x, 7); back = (1 << 14) + ((x & 8) << 11); x = GETB(c); back += (GETB(c) << 6) + (x >> 2); if (back == (1 << 14)) { if (cnt != 1) c.error |= LZO_ERROR; break; } } } else if(!state){ cnt = get_len(&c, x, 15); copy(&c, cnt + 3); x = GETB(c); if (x > 15) continue; cnt = 1; back = (1 << 11) + (GETB(c) << 2) + (x >> 2) + 1; } else { cnt = 0; back = (GETB(c) << 2) + (x >> 2) + 1; } copy_backptr(&c, back, cnt + 2); state= cnt = x & 3; copy(&c, cnt); x = GETB(c); } *inlen = c.in_end - c.in; if (c.in > c.in_end) *inlen = 0; *outlen = c.out_end - c.out; return c.error; } #ifdef TEST #include <stdio.h> #include <lzo/lzo1x.h> #include "log.h" #define MAXSZ (10*1024*1024) int main(int argc, char *argv[]) { FILE *in = fopen(argv[1], "rb"); uint8_t *orig = av_malloc(MAXSZ + 16); uint8_t *comp = av_malloc(2*MAXSZ + 16); uint8_t *decomp = av_malloc(MAXSZ + 16); size_t s = fread(orig, 1, MAXSZ, in); lzo_uint clen = 0; long tmp[LZO1X_MEM_COMPRESS]; int inlen, outlen; int i; av_log_level = AV_LOG_DEBUG; lzo1x_999_compress(orig, s, comp, &clen, tmp); for (i = 0; i < 300; i++) { START_TIMER inlen = clen; outlen = MAXSZ; #ifdef LIBLZO if (lzo1x_decompress_safe(comp, inlen, decomp, &outlen, NULL)) #elif defined(LIBLZO_UNSAFE) if (lzo1x_decompress(comp, inlen, decomp, &outlen, NULL)) #else if (lzo1x_decode(decomp, &outlen, comp, &inlen)) #endif av_log(NULL, AV_LOG_ERROR, "decompression error\n"); STOP_TIMER("lzod") } if (memcmp(orig, decomp, s)) av_log(NULL, AV_LOG_ERROR, "decompression incorrect\n"); else av_log(NULL, AV_LOG_ERROR, "decompression ok\n"); return 0; } #endif
JREkiwi/sagetv
third_party/mplayer/libavutil/lzo.c
C
apache-2.0
8,004
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class SingleTests : EnumerableBasedTests { [Fact] public void Empty() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single()); } [Fact] public void SingleElement() { int[] source = { 4 }; Assert.Equal(4, source.AsQueryable().Single()); } [Fact] public void ManyElement() { int[] source = { 4, 4, 4, 4, 4 }; Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single()); } [Fact] public void EmptySourceWithPredicate() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single(i => i % 2 == 0)); } [Fact] public void ManyElementsPredicateFalseForAll() { int[] source = { 3, 1, 7, 9, 13, 19 }; Assert.Throws<InvalidOperationException>(() => source.AsQueryable().Single(i => i % 2 == 0)); } [Fact] public void ManyElementsPredicateTrueForLast() { int[] source = { 3, 1, 7, 9, 13, 19, 20 }; Assert.Equal(20, source.AsQueryable().Single(i => i % 2 == 0)); } [Theory] [InlineData(1, 100)] [InlineData(42, 100)] public void FindSingleMatch(int target, int range) { Assert.Equal(target, Enumerable.Range(0, range).AsQueryable().Single(i => i == target)); } [Fact] public void ThrowsOnNullSource() { IQueryable<int> source = null; Assert.Throws<ArgumentNullException>("source", () => source.Single()); Assert.Throws<ArgumentNullException>("source", () => source.Single(i => i % 2 == 0)); } [Fact] public void ThrowsOnNullPredicate() { int[] source = { }; Expression<Func<int, bool>> nullPredicate = null; Assert.Throws<ArgumentNullException>("predicate", () => source.AsQueryable().Single(nullPredicate)); } [Fact] public void Single1() { var val = (new int[] { 2 }).AsQueryable().Single(); Assert.Equal(2, val); } [Fact] public void Single2() { var val = (new int[] { 2 }).AsQueryable().Single(n => n > 1); Assert.Equal(2, val); } } }
iamjasonp/corefx
src/System.Linq.Queryable/tests/SingleTests.cs
C#
mit
2,798
namespace Nancy.Tests.Unit.Conventions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nancy.Conventions; using Xunit; using System.Globalization; public class DefaultCultureConventionsFixture { private readonly NancyConventions conventions; private readonly DefaultCultureConventions cultureConventions; public DefaultCultureConventionsFixture() { this.conventions = new NancyConventions(); this.cultureConventions = new DefaultCultureConventions(); } [Fact] public void Should_not_be_valid_when_view_culture_conventions_is_null() { // Given this.conventions.CultureConventions = null; // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item1.ShouldBeFalse(); } [Fact] public void Should_return_correct_error_message_when_not_valid_because_culture_conventions_is_null() { // Given this.conventions.CultureConventions = null; // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item2.ShouldEqual("The culture conventions cannot be null."); } [Fact] public void Should_not_be_valid_when_culture_conventions_is_empty() { // Given this.conventions.CultureConventions = new List<Func<NancyContext, CultureInfo>>(); // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item1.ShouldBeFalse(); } [Fact] public void Should_return_correct_error_message_when_not_valid_because_culture_conventions_is_empty() { // Given this.conventions.CultureConventions = new List<Func<NancyContext, CultureInfo>>(); // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item2.ShouldEqual("The culture conventions cannot be empty."); } [Fact] public void Should_be_valid_when_culture_conventions_is_not_empty() { // Given this.conventions.CultureConventions = new List<Func<NancyContext, CultureInfo>> { (ctx) => { return new CultureInfo("en-GB"); } }; // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item1.ShouldBeTrue(); } [Fact] public void Should_return_empty_error_message_when_valid() { // Given this.conventions.CultureConventions = new List<Func<NancyContext, CultureInfo>> { (ctx) => { return new CultureInfo("en-GB"); } }; // When var result = this.cultureConventions.Validate(this.conventions); // Then result.Item2.ShouldBeEmpty(); } [Fact] public void Should_add_conventions_when_initialised() { // Given, When this.cultureConventions.Initialise(this.conventions); // Then this.conventions.CultureConventions.Count.ShouldBeGreaterThan(0); } } }
AlexPuiu/Nancy
src/Nancy.Tests/Unit/Conventions/DefaultCultureConventionsFixture.cs
C#
mit
3,757
namespace Nancy.ViewEngines.DotLiquid.Tests.Functional { using Testing; using Xunit; public class PartialRenderingFixture { private readonly Browser browser; public PartialRenderingFixture() { var bootstrapper = new ConfigurableBootstrapper(with => { with.Module<PartialRenderingModule>(); with.RootPathProvider<RootPathProvider>(); }); this.browser = new Browser(bootstrapper); } [Fact] public void Should_render_view_with_unquoted_partial() { // Given // When var result = this.browser.Get("/unquotedpartial"); // Then Assert.Equal(result.StatusCode, HttpStatusCode.OK); Assert.Equal(result.Body.AsString(), "This content is from the partial"); } [Fact] public void Should_render_view_with_singlequoted_partial() { // Given // When var result = this.browser.Get("/singlequotedpartial"); // Then Assert.Equal(result.StatusCode, HttpStatusCode.OK); Assert.Equal(result.Body.AsString(), "This content is from the partial"); } [Fact] public void Should_render_view_with_doublequoted_partial() { // Given // When var result = this.browser.Get("/doublequotedpartial"); // Then Assert.Equal(result.StatusCode, HttpStatusCode.OK); Assert.Equal(result.Body.AsString(), "This content is from the partial"); } } public class PartialRenderingModule : NancyModule { public PartialRenderingModule() { Get["/unquotedpartial"] = _ => View["unquotedpartial"]; Get["/doublequotedpartial"] = _ => View["doublequotedpartial"]; Get["/singlequotedpartial"] = _ => View["singlequotedpartial"]; } } }
AlexPuiu/Nancy
src/Nancy.ViewEngines.DotLiquid.Tests/Functional/PartialRenderingFixture.cs
C#
mit
2,078
/* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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; version 2 of the License. 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 */ package com.mysql.jdbc.util; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.TimeUtil; /** * Dumps the timezone of the MySQL server represented by the JDBC url given on the commandline (or localhost/test if none provided). */ public class TimezoneDump { private static final String DEFAULT_URL = "jdbc:mysql:///test"; /** * Constructor for TimezoneDump. */ public TimezoneDump() { super(); } /** * Entry point for program when called from the command line. * * @param args * command-line args. Arg 1 is JDBC URL. * @throws Exception * if any errors occur */ public static void main(String[] args) throws Exception { String jdbcUrl = DEFAULT_URL; if ((args.length == 1) && (args[0] != null)) { jdbcUrl = args[0]; } Class.forName("com.mysql.jdbc.Driver").newInstance(); ResultSet rs = null; try { rs = DriverManager.getConnection(jdbcUrl).createStatement().executeQuery("SHOW VARIABLES LIKE 'timezone'"); while (rs.next()) { String timezoneFromServer = rs.getString(2); System.out.println("MySQL timezone name: " + timezoneFromServer); String canonicalTimezone = TimeUtil.getCanonicalTimezone(timezoneFromServer, null); System.out.println("Java timezone name: " + canonicalTimezone); } } finally { if (rs != null) { rs.close(); } } } }
seanbright/mysql-connector-j
src/com/mysql/jdbc/util/TimezoneDump.java
Java
gpl-2.0
2,696
<ul class="UIAPIPlugin-toc"> <li><a href="#overview">Overview</a></li> <li><a href="#options">Options</a></li> <li><a href="#events">Events</a></li> <li><a href="#methods">Methods</a></li> <li><a href="#theming">Theming</a></li> </ul> <div class="UIAPIPlugin"> <h1>jQuery UI Autocomplete</h1> <div id="overview"> <h2 class="top-header">Overview</h2> <div id="overview-main"> <p>Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.</p> <p>By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.</p> <p>This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.</p> <p>You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.</p> <p>Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:</p> <ul> <li>an Array with local data</li> <li>a String, specifying a URL</li> <li>a Callback</li> </ul> <p>The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.</p> <p>When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.</p> <p>The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:</p> <ul> <li>A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".</li> <li>A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).</li> </ul> <p>The demos all focus on different variations of the source-option - look for the one that matches your use case, and take a look at the code.</p> </div> <div id="overview-dependencies"> <h3>Dependencies</h3> <ul> <li>UI Core</li> <li>UI Widget</li> <li>UI Position</li> </ul> </div> <div id="overview-example"> <h3>Example</h3> <div id="overview-example" class="example"> <ul><li><a href="#demo"><span>Demo</span></a></li><li><a href="#source"><span>View Source</span></a></li></ul> <p><div id="demo" class="tabs-container" rel="300"> A simple jQuery UI Autocomplete.<br /> </p> <pre>$(&quot;input#autocomplete&quot;).autocomplete({ source: [&quot;c++&quot;, &quot;java&quot;, &quot;php&quot;, &quot;coldfusion&quot;, &quot;javascript&quot;, &quot;asp&quot;, &quot;ruby&quot;] }); </pre> <p></div><div id="source" class="tabs-container"> </p> <pre>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&gt; &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { $(&quot;input#autocomplete&quot;).autocomplete({ source: [&quot;c++&quot;, &quot;java&quot;, &quot;php&quot;, &quot;coldfusion&quot;, &quot;javascript&quot;, &quot;asp&quot;, &quot;ruby&quot;] }); }); &lt;/script&gt; &lt;/head&gt; &lt;body style="font-size:62.5%;"&gt; &lt;input id=&quot;autocomplete&quot; /&gt; &lt;/body&gt; &lt;/html&gt; </pre> <p></div> </p><p></div> </div> </div> <div id="options"> <h2 class="top-header">Options</h2> <ul class="options-list"> <li class="option" id="option-disabled"> <div class="option-header"> <h3 class="option-name"><a href="#option-disabled">disabled</a></h3> <dl> <dt class="option-type-label">Type:</dt> <dd class="option-type">Boolean</dd> <dt class="option-default-label">Default:</dt> <dd class="option-default">false</dd> </dl> </div> <div class="option-description"> <p>Disables (true) or enables (false) the autocomplete. Can be set when initialising (first creating) the autocomplete.</p> </div> <div class="option-examples"> <h4>Code examples</h4> <dl class="option-examples-list"> <dt> Initialize a autocomplete with the <code>disabled</code> option specified. </dt> <dd> <pre><code>$( ".selector" ).autocomplete({ disabled: true });</code></pre> </dd> <dt> Get or set the <code>disabled</code> option, after init. </dt> <dd> <pre><code>//getter var disabled = $( ".selector" ).autocomplete( "option", "disabled" ); //setter $( ".selector" ).autocomplete( "option", "disabled", true );</code></pre> </dd> </dl> </div> </li> <li class="option" id="option-delay"> <div class="option-header"> <h3 class="option-name"><a href="#option-delay">delay</a></h3> <dl> <dt class="option-type-label">Type:</dt> <dd class="option-type">Integer</dd> <dt class="option-default-label">Default:</dt> <dd class="option-default">300</dd> </dl> </div> <div class="option-description"> <p>The delay in milliseconds the Autocomplete waits after a keystroke to activate itself. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.</p> </div> <div class="option-examples"> <h4>Code examples</h4> <dl class="option-examples-list"> <dt> Initialize a autocomplete with the <code>delay</code> option specified. </dt> <dd> <pre><code>$( ".selector" ).autocomplete({ delay: 0 });</code></pre> </dd> <dt> Get or set the <code>delay</code> option, after init. </dt> <dd> <pre><code>//getter var delay = $( ".selector" ).autocomplete( "option", "delay" ); //setter $( ".selector" ).autocomplete( "option", "delay", 0 );</code></pre> </dd> </dl> </div> </li> <li class="option" id="option-minLength"> <div class="option-header"> <h3 class="option-name"><a href="#option-minLength">minLength</a></h3> <dl> <dt class="option-type-label">Type:</dt> <dd class="option-type">Integer</dd> <dt class="option-default-label">Default:</dt> <dd class="option-default">1</dd> </dl> </div> <div class="option-description"> <p>The minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. Should be increased when there are a lot of items, where a single character would match a few thousand items.</p> </div> <div class="option-examples"> <h4>Code examples</h4> <dl class="option-examples-list"> <dt> Initialize a autocomplete with the <code>minLength</code> option specified. </dt> <dd> <pre><code>$( ".selector" ).autocomplete({ minLength: 0 });</code></pre> </dd> <dt> Get or set the <code>minLength</code> option, after init. </dt> <dd> <pre><code>//getter var minLength = $( ".selector" ).autocomplete( "option", "minLength" ); //setter $( ".selector" ).autocomplete( "option", "minLength", 0 );</code></pre> </dd> </dl> </div> </li> <li class="option" id="option-source"> <div class="option-header"> <h3 class="option-name"><a href="#option-source">source</a></h3> <dl> <dt class="option-type-label">Type:</dt> <dd class="option-type">String, Array, Callback</dd> <dt class="option-default-label">Default:</dt> <dd class="option-default">none, must be specified</dd> </dl> </div> <div class="option-description"> <p>Defines the data to use, must be specified. See Overview section for more details, and look at the various demos. </p> </div> <div class="option-examples"> <h4>Code examples</h4> <dl class="option-examples-list"> <dt> Initialize a autocomplete with the <code>source</code> option specified. </dt> <dd> <pre><code>$( ".selector" ).autocomplete({ source: [&quot;c++&quot;, &quot;java&quot;, &quot;php&quot;, &quot;coldfusion&quot;, &quot;javascript&quot;, &quot;asp&quot;, &quot;ruby&quot;] });</code></pre> </dd> <dt> Get or set the <code>source</code> option, after init. </dt> <dd> <pre><code>//getter var source = $( ".selector" ).autocomplete( "option", "source" ); //setter $( ".selector" ).autocomplete( "option", "source", [&quot;c++&quot;, &quot;java&quot;, &quot;php&quot;, &quot;coldfusion&quot;, &quot;javascript&quot;, &quot;asp&quot;, &quot;ruby&quot;] );</code></pre> </dd> </dl> </div> </li> </ul> </div> <div id="events"> <h2 class="top-header">Events</h2> <ul class="events-list"> <li class="event" id="event-search"> <div class="event-header"> <h3 class="event-name"><a href="#event-search">search</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompletesearch</dd> </dl> </div> <div class="event-description"> <p>Before a request (source-option) is started, after minLength and delay are met. Can be canceled (return false), then no request will be started and no items suggested.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>search</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ search: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>search</code> event by type: <code>autocompletesearch</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompletesearch&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> <li class="event" id="event-open"> <div class="event-header"> <h3 class="event-name"><a href="#event-open">open</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompleteopen</dd> </dl> </div> <div class="event-description"> <p>Triggered when the suggestion menu is opened.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>open</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ open: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>open</code> event by type: <code>autocompleteopen</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompleteopen&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> <li class="event" id="event-focus"> <div class="event-header"> <h3 class="event-name"><a href="#event-focus">focus</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompletefocus</dd> </dl> </div> <div class="event-description"> <p>Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>focus</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ focus: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>focus</code> event by type: <code>autocompletefocus</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompletefocus&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> <li class="event" id="event-select"> <div class="event-header"> <h3 class="event-name"><a href="#event-select">select</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompleteselect</dd> </dl> </div> <div class="event-description"> <p>Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>select</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ select: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>select</code> event by type: <code>autocompleteselect</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompleteselect&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> <li class="event" id="event-close"> <div class="event-header"> <h3 class="event-name"><a href="#event-close">close</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompleteclose</dd> </dl> </div> <div class="event-description"> <p>When the list is hidden - doesn't have to occur together with a change.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>close</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ close: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>close</code> event by type: <code>autocompleteclose</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompleteclose&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> <li class="event" id="event-change"> <div class="event-header"> <h3 class="event-name"><a href="#event-change">change</a></h3> <dl> <dt class="event-type-label">Type:</dt> <dd class="event-type">autocompletechange</dd> </dl> </div> <div class="event-description"> <p>After an item was selected; ui.item refers to the selected item. Always triggered after the close event.</p> </div> <div class="event-examples"> <h4>Code examples</h4> <dl class="event-examples-list"> <dt> Supply a callback function to handle the <code>change</code> event as an init option. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).autocomplete({ change: function(event, ui) { ... } });</code></pre> </dd> <dt> Bind to the <code>change</code> event by type: <code>autocompletechange</code>. </dt> <dd> <pre><code>$( &quot;.selector&quot; ).bind( &quot;autocompletechange&quot;, function(event, ui) { ... });</code></pre> </dd> </dl> </div> </li> </ul> </div> <div id="methods"> <h2 class="top-header">Methods</h2> <ul class="methods-list"> <li class="method" id="method-destroy"> <div class="method-header"> <h3 class="method-name"><a href="#method-destroy">destroy</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "destroy" )</dd> </dl> </div> <div class="method-description"> <p>Remove the autocomplete functionality completely. This will return the element back to its pre-init state.</p> </div> </li> <li class="method" id="method-disable"> <div class="method-header"> <h3 class="method-name"><a href="#method-disable">disable</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "disable" )</dd> </dl> </div> <div class="method-description"> <p>Disable the autocomplete.</p> </div> </li> <li class="method" id="method-enable"> <div class="method-header"> <h3 class="method-name"><a href="#method-enable">enable</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "enable" )</dd> </dl> </div> <div class="method-description"> <p>Enable the autocomplete.</p> </div> </li> <li class="method" id="method-option"> <div class="method-header"> <h3 class="method-name"><a href="#method-option">option</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "option" , optionName , <span class="optional">[</span>value<span class="optional">] </span> )</dd> </dl> </div> <div class="method-description"> <p>Get or set any autocomplete option. If no value is specified, will act as a getter.</p> </div> </li> <li class="method" id="method-option"> <div class="method-header"> <h3 class="method-name"><a href="#method-option">option</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "option" , options )</dd> </dl> </div> <div class="method-description"> <p>Set multiple autocomplete options at once by providing an options object.</p> </div> </li> <li class="method" id="method-widget"> <div class="method-header"> <h3 class="method-name"><a href="#method-widget">widget</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "widget" )</dd> </dl> </div> <div class="method-description"> <p>Returns the .ui-autocomplete element.</p> </div> </li> <li class="method" id="method-search"> <div class="method-header"> <h3 class="method-name"><a href="#method-search">search</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "search" , <span class="optional">[</span>value<span class="optional">] </span> )</dd> </dl> </div> <div class="method-description"> <p>Triggers a search event, which, when data is available, then will display the suggestions; can be used by a selectbox-like button to open the suggestions when clicked. If no value argument is specified, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.</p> </div> </li> <li class="method" id="method-close"> <div class="method-header"> <h3 class="method-name"><a href="#method-close">close</a></h3> <dl> <dt class="method-signature-label">Signature:</dt> <dd class="method-signature">.autocomplete( "close" )</dd> </dl> </div> <div class="method-description"> <p>Close the Autocomplete menu. Useful in combination with the search method, to close the open menu.</p> </div> </li> </ul> </div> <div id="theming"> <h2 class="top-header">Theming</h2> <p>The jQuery UI Autocomplete plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain. </p> <p>If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.autocomplete.css stylesheet that can be modified. These classes are highlighed in bold below. </p> <h3>Sample markup with jQuery UI CSS Framework classes</h3> &lt;input class=&quot;ui-autocomplete-input&quot;/&gt;<br /> &lt;ul class=&quot;ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all&quot;&gt;<br /> &nbsp;&nbsp;&lt;li class=&quot;ui-menu-item&quot;&gt;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&lt;a class=&quot;ui-corner-all&quot;&gt;item 1&lt;/a&gt;<br /> &nbsp;&nbsp;&lt;/li&gt;<br /> &nbsp;&nbsp;&lt;li class=&quot;ui-menu-item&quot;&gt;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&lt;a class=&quot;ui-corner-all&quot;&gt;item 2&lt;/a&gt;<br /> &nbsp;&nbsp;&lt;/li&gt;<br /> &nbsp;&nbsp;&lt;li class=&quot;ui-menu-item&quot;&gt;<br /> &nbsp;&nbsp;&nbsp;&nbsp;&lt;a class=&quot;ui-corner-all&quot;&gt;item 3&lt;/a&gt;<br /> &nbsp;&nbsp;&lt;/li&gt;<br /> &lt;/ul&gt; <p class="theme-note"> <strong> Note: This is a sample of markup generated by the autocomplete plugin, not markup you should use to create a autocomplete. The only markup needed for that is &lt;input/&gt;. </strong> </p> </div> </div> </p><!-- Pre-expand include size: 29839 bytes Post-expand include size: 47753 bytes Template argument size: 26499 bytes Maximum: 2097152 bytes --> <!-- Saved in parser cache with key jqdocs_docs:pcache:idhash:3766-1!1!0!!en!2 and timestamp 20100421092026 -->
patdunlavey/williamstownbeat
sites/all/modules/jquery_ui/jquery.ui/docs/autocomplete.html
HTML
gpl-2.0
22,151
/* * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright 2012, 2013 SAP AG. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef CPU_PPC_VM_DEPCHECKER_PPC_HPP #define CPU_PPC_VM_DEPCHECKER_PPC_HPP // Nothing to do on ppc64 #endif // CPU_PPC_VM_DEPCHECKER_PPC_HPP
mur47x111/JDK8-concurrent-tagging
src/cpu/ppc/vm/depChecker_ppc.hpp
C++
gpl-2.0
1,258
/* Copyright (c) 2013 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <BridgeClient.h> BridgeClient::BridgeClient(int _h, BridgeClass &_b) : bridge(_b), handle(_h), opened(true), buffered(0) { } BridgeClient::BridgeClient(BridgeClass &_b) : bridge(_b), handle(0), opened(false), buffered(0) { } BridgeClient::~BridgeClient() { } BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { opened = _x.opened; handle = _x.handle; return *this; } void BridgeClient::stop() { if (opened) { uint8_t cmd[] = {'j', handle}; bridge.transfer(cmd, 2); } opened = false; buffered = 0; readPos = 0; } void BridgeClient::doBuffer() { // If there are already char in buffer exit if (buffered > 0) return; // Try to buffer up to 32 characters readPos = 0; uint8_t cmd[] = {'K', handle, sizeof(buffer)}; buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); } int BridgeClient::available() { // Look if there is new data available doBuffer(); return buffered; } int BridgeClient::read() { doBuffer(); if (buffered == 0) return -1; // no chars available else { buffered--; return buffer[readPos++]; } } int BridgeClient::read(uint8_t *buff, size_t size) { int readed = 0; do { if (buffered == 0) { doBuffer(); if (buffered == 0) return readed; } buff[readed++] = buffer[readPos++]; buffered--; } while (readed < size); return readed; } int BridgeClient::peek() { doBuffer(); if (buffered == 0) return -1; // no chars available else return buffer[readPos]; } size_t BridgeClient::write(uint8_t c) { if (!opened) return 0; uint8_t cmd[] = {'l', handle, c}; bridge.transfer(cmd, 3); return 1; } size_t BridgeClient::write(const uint8_t *buf, size_t size) { if (!opened) return 0; uint8_t cmd[] = {'l', handle}; bridge.transfer(cmd, 2, buf, size, NULL, 0); return size; } void BridgeClient::flush() { } uint8_t BridgeClient::connected() { if (!opened) return false; // Client is "connected" if it has unread bytes if (available()) return true; uint8_t cmd[] = {'L', handle}; uint8_t res[1]; bridge.transfer(cmd, 2, res, 1); return (res[0] == 1); } int BridgeClient::connect(IPAddress ip, uint16_t port) { String address; address.reserve(18); address += ip[0]; address += '.'; address += ip[1]; address += '.'; address += ip[2]; address += '.'; address += ip[3]; return connect(address.c_str(), port); } int BridgeClient::connect(const char *host, uint16_t port) { uint8_t tmp[] = { 'C', (port >> 8) & 0xFF, port & 0xFF }; uint8_t res[1]; int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); if (l == 0) return 0; handle = res[0]; // wait for connection uint8_t tmp2[] = { 'c', handle }; uint8_t res2[1]; while (true) { bridge.transfer(tmp2, 2, res2, 1); if (res2[0] == 0) break; delay(1); } opened = true; // check for successful connection if (connected()) return 1; stop(); handle = 0; return 0; }
snargledorf/Arduino
libraries/Bridge/src/BridgeClient.cpp
C++
lgpl-2.1
3,823
package org.andengine.util.adt.trie; import android.util.SparseArray; /** * (c) Zynga 2012 * * @author Nicolas Gramlich <ngramlich@zynga.com> * @since 12:25:47 - 30.01.2012 */ public class Trie implements ITrie { // =========================================================== // Constants // =========================================================== private static final int CHILDREN_SIZE_DEFAULT = 'Z' - 'A' + 1; // =========================================================== // Fields // =========================================================== private final TrieNode mRoot = new TrieNode(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void add(final CharSequence pCharSequence) { this.mRoot.add(pCharSequence); } @Override public void add(final CharSequence pCharSequence, final int pStart, final int pEnd) { this.mRoot.add(pCharSequence, pStart, pEnd); } @Override public boolean contains(final CharSequence pCharSequence) { return this.mRoot.contains(pCharSequence); } @Override public boolean contains(final CharSequence pCharSequence, final int pStart, final int pEnd) { return this.mRoot.contains(pCharSequence, pStart, pEnd); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class TrieNode implements ITrie { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private SparseArray<TrieNode> mChildren; private boolean mWordEndFlag; // =========================================================== // Constructors // =========================================================== public TrieNode() { this(false); } public TrieNode(final boolean pWordEndFlag) { this.mWordEndFlag = pWordEndFlag; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public void add(final CharSequence pCharSequence) { final int length = pCharSequence.length(); if(length == 0) { return; } this.add(pCharSequence, 0, length); } @Override public void add(final CharSequence pCharSequence, final int pStart, final int pEnd) { if(this.mChildren == null) { this.mChildren = new SparseArray<Trie.TrieNode>(Trie.CHILDREN_SIZE_DEFAULT); } final char character = pCharSequence.charAt(pStart); TrieNode child = this.mChildren.get(character); if(child == null) { child = new TrieNode(); this.mChildren.put(character, child); } if(pStart < pEnd - 1) { child.add(pCharSequence, pStart + 1, pEnd); } else { child.mWordEndFlag = true; } } @Override public boolean contains(final CharSequence pCharSequence) { final int length = pCharSequence.length(); if(length == 0) { throw new IllegalArgumentException(); } return this.contains(pCharSequence, 0, length); } @Override public boolean contains(final CharSequence pCharSequence, final int pStart, final int pEnd) { if(this.mChildren == null) { return false; } final char character = pCharSequence.charAt(pStart); final TrieNode child = this.mChildren.get(character); if(child == null) { return false; } else { if(pStart < pEnd - 1) { return child.contains(pCharSequence, pStart + 1, pEnd); } else { return child.mWordEndFlag; } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
zcwk/AndEngine
src/org/andengine/util/adt/trie/Trie.java
Java
apache-2.0
4,735
'use strict'; var pathFn = require('path'); var Promise = require('bluebird'); var fs = require('hexo-fs'); function getExtname(str) { if (typeof str !== 'string') return ''; var extname = pathFn.extname(str); return extname[0] === '.' ? extname.slice(1) : extname; } function Render(ctx) { this.context = ctx; this.renderer = ctx.extend.renderer; } Render.prototype.isRenderable = function(path) { return this.renderer.isRenderable(path); }; Render.prototype.isRenderableSync = function(path) { return this.renderer.isRenderableSync(path); }; Render.prototype.getOutput = function(path) { return this.renderer.getOutput(path); }; Render.prototype.getRenderer = function(ext, sync) { return this.renderer.get(ext, sync); }; Render.prototype.getRendererSync = function(ext) { return this.getRenderer(ext, true); }; Render.prototype.render = function(data, options, callback) { if (!callback && typeof options === 'function') { callback = options; options = {}; } var ctx = this.context; var self = this; var ext = ''; return new Promise(function(resolve, reject) { if (!data) return reject(new TypeError('No input file or string!')); if (data.text != null) return resolve(data.text); if (!data.path) return reject(new TypeError('No input file or string!')); fs.readFile(data.path).then(resolve, reject); }).then(function(text) { data.text = text; ext = data.engine || getExtname(data.path); if (!ext || !self.isRenderable(ext)) return text; var renderer = self.getRenderer(ext); return renderer.call(ctx, data, options); }).then(function(result) { result = toString(result, data); if (data.onRenderEnd) { return data.onRenderEnd(result); } return result; }).then(function(result) { var output = self.getOutput(ext) || ext; return ctx.execFilter('after_render:' + output, result, { context: ctx, args: [data] }); }).asCallback(callback); }; Render.prototype.renderSync = function(data, options) { if (!data) throw new TypeError('No input file or string!'); options = options || {}; var ctx = this.context; if (data.text == null) { if (!data.path) throw new TypeError('No input file or string!'); data.text = fs.readFileSync(data.path); } if (data.text == null) throw new TypeError('No input file or string!'); var ext = data.engine || getExtname(data.path); var result; if (ext && this.isRenderableSync(ext)) { var renderer = this.getRendererSync(ext); result = renderer.call(ctx, data, options); } else { result = data.text; } var output = this.getOutput(ext) || ext; result = toString(result, data); if (data.onRenderEnd) { result = data.onRenderEnd(result); } return ctx.execFilterSync('after_render:' + output, result, { context: ctx, args: [data] }); }; function toString(result, options) { if (!options.hasOwnProperty('toString') || typeof result === 'string') return result; if (typeof options.toString === 'function') { return options.toString(result); } else if (typeof result === 'object') { return JSON.stringify(result); } else if (result.toString) { return result.toString(); } return result; } module.exports = Render;
rocknamx8/rocknamx8.github.io
node_modules/hexo/lib/hexo/render.js
JavaScript
apache-2.0
3,280
/* * The Clear BSD License * Copyright (c) 2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided * that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. * 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 HOLDER 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. */ #ifndef _FSL_PINT_H_ #define _FSL_PINT_H_ #include "fsl_common.h" /*! * @addtogroup pint_driver * @{ */ /*! @file */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @name Driver version */ /*@{*/ #define FSL_PINT_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0 */ /*@}*/ /* Number of interrupt line supported by PINT */ #define PINT_PIN_INT_COUNT 8U /* Number of input sources supported by PINT */ #define PINT_INPUT_COUNT 8U /* PININT Bit slice source register bits */ #define PININT_BITSLICE_SRC_START 8U #define PININT_BITSLICE_SRC_MASK 7U /* PININT Bit slice configuration register bits */ #define PININT_BITSLICE_CFG_START 8U #define PININT_BITSLICE_CFG_MASK 7U #define PININT_BITSLICE_ENDP_MASK 7U #define PINT_PIN_INT_LEVEL 0x10U #define PINT_PIN_INT_EDGE 0x00U #define PINT_PIN_INT_FALL_OR_HIGH_LEVEL 0x02U #define PINT_PIN_INT_RISE 0x01U #define PINT_PIN_RISE_EDGE (PINT_PIN_INT_EDGE | PINT_PIN_INT_RISE) #define PINT_PIN_FALL_EDGE (PINT_PIN_INT_EDGE | PINT_PIN_INT_FALL_OR_HIGH_LEVEL) #define PINT_PIN_BOTH_EDGE (PINT_PIN_INT_EDGE | PINT_PIN_INT_RISE | PINT_PIN_INT_FALL_OR_HIGH_LEVEL) #define PINT_PIN_LOW_LEVEL (PINT_PIN_INT_LEVEL) #define PINT_PIN_HIGH_LEVEL (PINT_PIN_INT_LEVEL | PINT_PIN_INT_FALL_OR_HIGH_LEVEL) /*! @brief PINT Pin Interrupt enable type */ typedef enum _pint_pin_enable { kPINT_PinIntEnableNone = 0U, /*!< Do not generate Pin Interrupt */ kPINT_PinIntEnableRiseEdge = PINT_PIN_RISE_EDGE, /*!< Generate Pin Interrupt on rising edge */ kPINT_PinIntEnableFallEdge = PINT_PIN_FALL_EDGE, /*!< Generate Pin Interrupt on falling edge */ kPINT_PinIntEnableBothEdges = PINT_PIN_BOTH_EDGE, /*!< Generate Pin Interrupt on both edges */ kPINT_PinIntEnableLowLevel = PINT_PIN_LOW_LEVEL, /*!< Generate Pin Interrupt on low level */ kPINT_PinIntEnableHighLevel = PINT_PIN_HIGH_LEVEL /*!< Generate Pin Interrupt on high level */ } pint_pin_enable_t; /*! @brief PINT Pin Interrupt type */ typedef enum _pint_int { kPINT_PinInt0 = 0U, /*!< Pin Interrupt 0 */ #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 1U) kPINT_PinInt1 = 1U, /*!< Pin Interrupt 1 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 2U) kPINT_PinInt2 = 2U, /*!< Pin Interrupt 2 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 3U) kPINT_PinInt3 = 3U, /*!< Pin Interrupt 3 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 4U) kPINT_PinInt4 = 4U, /*!< Pin Interrupt 4 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 5U) kPINT_PinInt5 = 5U, /*!< Pin Interrupt 5 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 6U) kPINT_PinInt6 = 6U, /*!< Pin Interrupt 6 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 7U) kPINT_PinInt7 = 7U, /*!< Pin Interrupt 7 */ #endif } pint_pin_int_t; /*! @brief PINT Pattern Match bit slice input source type */ typedef enum _pint_pmatch_input_src { kPINT_PatternMatchInp0Src = 0U, /*!< Input source 0 */ kPINT_PatternMatchInp1Src = 1U, /*!< Input source 1 */ kPINT_PatternMatchInp2Src = 2U, /*!< Input source 2 */ kPINT_PatternMatchInp3Src = 3U, /*!< Input source 3 */ kPINT_PatternMatchInp4Src = 4U, /*!< Input source 4 */ kPINT_PatternMatchInp5Src = 5U, /*!< Input source 5 */ kPINT_PatternMatchInp6Src = 6U, /*!< Input source 6 */ kPINT_PatternMatchInp7Src = 7U, /*!< Input source 7 */ } pint_pmatch_input_src_t; /*! @brief PINT Pattern Match bit slice type */ typedef enum _pint_pmatch_bslice { kPINT_PatternMatchBSlice0 = 0U, /*!< Bit slice 0 */ #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 1U) kPINT_PatternMatchBSlice1 = 1U, /*!< Bit slice 1 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 2U) kPINT_PatternMatchBSlice2 = 2U, /*!< Bit slice 2 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 3U) kPINT_PatternMatchBSlice3 = 3U, /*!< Bit slice 3 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 4U) kPINT_PatternMatchBSlice4 = 4U, /*!< Bit slice 4 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 5U) kPINT_PatternMatchBSlice5 = 5U, /*!< Bit slice 5 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 6U) kPINT_PatternMatchBSlice6 = 6U, /*!< Bit slice 6 */ #endif #if (FSL_FEATURE_PINT_NUMBER_OF_CONNECTED_OUTPUTS > 7U) kPINT_PatternMatchBSlice7 = 7U, /*!< Bit slice 7 */ #endif } pint_pmatch_bslice_t; /*! @brief PINT Pattern Match configuration type */ typedef enum _pint_pmatch_bslice_cfg { kPINT_PatternMatchAlways = 0U, /*!< Always Contributes to product term match */ kPINT_PatternMatchStickyRise = 1U, /*!< Sticky Rising edge */ kPINT_PatternMatchStickyFall = 2U, /*!< Sticky Falling edge */ kPINT_PatternMatchStickyBothEdges = 3U, /*!< Sticky Rising or Falling edge */ kPINT_PatternMatchHigh = 4U, /*!< High level */ kPINT_PatternMatchLow = 5U, /*!< Low level */ kPINT_PatternMatchNever = 6U, /*!< Never contributes to product term match */ kPINT_PatternMatchBothEdges = 7U, /*!< Either rising or falling edge */ } pint_pmatch_bslice_cfg_t; /*! @brief PINT Callback function. */ typedef void (*pint_cb_t)(pint_pin_int_t pintr, uint32_t pmatch_status); typedef struct _pint_pmatch_cfg { pint_pmatch_input_src_t bs_src; pint_pmatch_bslice_cfg_t bs_cfg; bool end_point; pint_cb_t callback; } pint_pmatch_cfg_t; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @brief Initialize PINT peripheral. * This function initializes the PINT peripheral and enables the clock. * * @param base Base address of the PINT peripheral. * * @retval None. */ void PINT_Init(PINT_Type *base); /*! * @brief Configure PINT peripheral pin interrupt. * This function configures a given pin interrupt. * * @param base Base address of the PINT peripheral. * @param intr Pin interrupt. * @param enable Selects detection logic. * @param callback Callback. * * @retval None. */ void PINT_PinInterruptConfig(PINT_Type *base, pint_pin_int_t intr, pint_pin_enable_t enable, pint_cb_t callback); /*! * @brief Get PINT peripheral pin interrupt configuration. * This function returns the configuration of a given pin interrupt. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * @param enable Pointer to store the detection logic. * @param callback Callback. * * @retval None. */ void PINT_PinInterruptGetConfig(PINT_Type *base, pint_pin_int_t pintr, pint_pin_enable_t *enable, pint_cb_t *callback); /*! * @brief Clear Selected pin interrupt status. * This function clears the selected pin interrupt status. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval None. */ static inline void PINT_PinInterruptClrStatus(PINT_Type *base, pint_pin_int_t pintr) { base->IST = (1U << pintr); } /*! * @brief Get Selected pin interrupt status. * This function returns the selected pin interrupt status. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval status = 0 No pin interrupt request. = 1 Selected Pin interrupt request active. */ static inline uint32_t PINT_PinInterruptGetStatus(PINT_Type *base, pint_pin_int_t pintr) { return ((base->IST & (1U << pintr)) ? 1U : 0U); } /*! * @brief Clear all pin interrupts status. * This function clears the status of all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PinInterruptClrStatusAll(PINT_Type *base) { base->IST = PINT_IST_PSTAT_MASK; } /*! * @brief Get all pin interrupts status. * This function returns the status of all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval status Each bit position indicates the status of corresponding pin interrupt. * = 0 No pin interrupt request. = 1 Pin interrupt request active. */ static inline uint32_t PINT_PinInterruptGetStatusAll(PINT_Type *base) { return (base->IST); } /*! * @brief Clear Selected pin interrupt fall flag. * This function clears the selected pin interrupt fall flag. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval None. */ static inline void PINT_PinInterruptClrFallFlag(PINT_Type *base, pint_pin_int_t pintr) { base->FALL = (1U << pintr); } /*! * @brief Get selected pin interrupt fall flag. * This function returns the selected pin interrupt fall flag. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval flag = 0 Falling edge has not been detected. = 1 Falling edge has been detected. */ static inline uint32_t PINT_PinInterruptGetFallFlag(PINT_Type *base, pint_pin_int_t pintr) { return ((base->FALL & (1U << pintr)) ? 1U : 0U); } /*! * @brief Clear all pin interrupt fall flags. * This function clears the fall flag for all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PinInterruptClrFallFlagAll(PINT_Type *base) { base->FALL = PINT_FALL_FDET_MASK; } /*! * @brief Get all pin interrupt fall flags. * This function returns the fall flag of all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval flags Each bit position indicates the falling edge detection of the corresponding pin interrupt. * 0 Falling edge has not been detected. = 1 Falling edge has been detected. */ static inline uint32_t PINT_PinInterruptGetFallFlagAll(PINT_Type *base) { return (base->FALL); } /*! * @brief Clear Selected pin interrupt rise flag. * This function clears the selected pin interrupt rise flag. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval None. */ static inline void PINT_PinInterruptClrRiseFlag(PINT_Type *base, pint_pin_int_t pintr) { base->RISE = (1U << pintr); } /*! * @brief Get selected pin interrupt rise flag. * This function returns the selected pin interrupt rise flag. * * @param base Base address of the PINT peripheral. * @param pintr Pin interrupt. * * @retval flag = 0 Rising edge has not been detected. = 1 Rising edge has been detected. */ static inline uint32_t PINT_PinInterruptGetRiseFlag(PINT_Type *base, pint_pin_int_t pintr) { return ((base->RISE & (1U << pintr)) ? 1U : 0U); } /*! * @brief Clear all pin interrupt rise flags. * This function clears the rise flag for all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PinInterruptClrRiseFlagAll(PINT_Type *base) { base->RISE = PINT_RISE_RDET_MASK; } /*! * @brief Get all pin interrupt rise flags. * This function returns the rise flag of all pin interrupts. * * @param base Base address of the PINT peripheral. * * @retval flags Each bit position indicates the rising edge detection of the corresponding pin interrupt. * 0 Rising edge has not been detected. = 1 Rising edge has been detected. */ static inline uint32_t PINT_PinInterruptGetRiseFlagAll(PINT_Type *base) { return (base->RISE); } /*! * @brief Configure PINT pattern match. * This function configures a given pattern match bit slice. * * @param base Base address of the PINT peripheral. * @param bslice Pattern match bit slice number. * @param cfg Pointer to bit slice configuration. * * @retval None. */ void PINT_PatternMatchConfig(PINT_Type *base, pint_pmatch_bslice_t bslice, pint_pmatch_cfg_t *cfg); /*! * @brief Get PINT pattern match configuration. * This function returns the configuration of a given pattern match bit slice. * * @param base Base address of the PINT peripheral. * @param bslice Pattern match bit slice number. * @param cfg Pointer to bit slice configuration. * * @retval None. */ void PINT_PatternMatchGetConfig(PINT_Type *base, pint_pmatch_bslice_t bslice, pint_pmatch_cfg_t *cfg); /*! * @brief Get pattern match bit slice status. * This function returns the status of selected bit slice. * * @param base Base address of the PINT peripheral. * @param bslice Pattern match bit slice number. * * @retval status = 0 Match has not been detected. = 1 Match has been detected. */ static inline uint32_t PINT_PatternMatchGetStatus(PINT_Type *base, pint_pmatch_bslice_t bslice) { return ((base->PMCTRL >> PINT_PMCTRL_PMAT_SHIFT) & (0x1U << bslice)) >> bslice; } /*! * @brief Get status of all pattern match bit slices. * This function returns the status of all bit slices. * * @param base Base address of the PINT peripheral. * * @retval status Each bit position indicates the match status of corresponding bit slice. * = 0 Match has not been detected. = 1 Match has been detected. */ static inline uint32_t PINT_PatternMatchGetStatusAll(PINT_Type *base) { return base->PMCTRL >> PINT_PMCTRL_PMAT_SHIFT; } /*! * @brief Reset pattern match detection logic. * This function resets the pattern match detection logic if any of the product term is matching. * * @param base Base address of the PINT peripheral. * * @retval pmstatus Each bit position indicates the match status of corresponding bit slice. * = 0 Match was detected. = 1 Match was not detected. */ uint32_t PINT_PatternMatchResetDetectLogic(PINT_Type *base); /*! * @brief Enable pattern match function. * This function enables the pattern match function. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PatternMatchEnable(PINT_Type *base) { base->PMCTRL = (base->PMCTRL & PINT_PMCTRL_ENA_RXEV_MASK) | PINT_PMCTRL_SEL_PMATCH_MASK; } /*! * @brief Disable pattern match function. * This function disables the pattern match function. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PatternMatchDisable(PINT_Type *base) { base->PMCTRL = (base->PMCTRL & PINT_PMCTRL_ENA_RXEV_MASK) & ~PINT_PMCTRL_SEL_PMATCH_MASK; } /*! * @brief Enable RXEV output. * This function enables the pattern match RXEV output. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PatternMatchEnableRXEV(PINT_Type *base) { base->PMCTRL = (base->PMCTRL & PINT_PMCTRL_SEL_PMATCH_MASK) | PINT_PMCTRL_ENA_RXEV_MASK; } /*! * @brief Disable RXEV output. * This function disables the pattern match RXEV output. * * @param base Base address of the PINT peripheral. * * @retval None. */ static inline void PINT_PatternMatchDisableRXEV(PINT_Type *base) { base->PMCTRL = (base->PMCTRL & PINT_PMCTRL_SEL_PMATCH_MASK) & ~PINT_PMCTRL_ENA_RXEV_MASK; } /*! * @brief Enable callback. * This function enables the interrupt for the selected PINT peripheral. Although the pin(s) are monitored * as soon as they are enabled, the callback function is not enabled until this function is called. * * @param base Base address of the PINT peripheral. * * @retval None. */ void PINT_EnableCallback(PINT_Type *base); /*! * @brief Disable callback. * This function disables the interrupt for the selected PINT peripheral. Although the pins are still * being monitored but the callback function is not called. * * @param base Base address of the peripheral. * * @retval None. */ void PINT_DisableCallback(PINT_Type *base); /*! * @brief Deinitialize PINT peripheral. * This function disables the PINT clock. * * @param base Base address of the PINT peripheral. * * @retval None. */ void PINT_Deinit(PINT_Type *base); #ifdef __cplusplus } #endif /*@}*/ #endif /* _FSL_PINT_H_ */
mbedmicro/mbed
targets/TARGET_NXP/TARGET_MCUXpresso_MCUS/TARGET_MCU_LPC546XX/drivers/fsl_pint.h
C
apache-2.0
17,768
<!doctype html> <html> <head> <meta charset=utf-8> <title>Encrypted Media Extensions: Check encryptionScheme with DRM</title> <link rel="help" href="https://w3c.github.io/encrypted-media/"> <!-- Web Platform Test Harness scripts --> <script src=/resources/testharness.js></script> <script src=/resources/testharnessreport.js></script> <!-- Helper scripts for Encrypted Media Extensions tests --> <script src=/encrypted-media/util/utils.js></script> <script src=/encrypted-media/util/utf8.js></script> <!-- Content metadata --> <!--<script src=/encrypted-media/content/content-metadata.js></script>--> <!-- The script for this specific test --> <script src=/encrypted-media/scripts/check-encryption-scheme.js></script> </head> <body> <div id='log'></div> <script> var config = { keysystem: getSupportedKeySystem() } runTest(config); </script> </body> </html>
chromium/chromium
third_party/blink/web_tests/external/wpt/encrypted-media/drm-check-encryption-scheme.https.html
HTML
bsd-3-clause
955
/* 'src_ipsec_pgpIPsec.c' Obfuscated by COBF (Version 1.06 2006-01-07 by BB) at Mon Dec 22 18:00:49 2014 */ #include"cobf.h" #ifdef _WIN32 #if defined( UNDER_CE) && defined( bb334) || ! defined( bb341) #define bb357 1 #define bb356 1 #else #define bb335 bb350 #define bb358 1 #define bb348 1 #endif #define bb360 1 #include"uncobf.h" #include<ndis.h> #include"cobf.h" #ifdef UNDER_CE #include"uncobf.h" #include<ndiswan.h> #include"cobf.h" #endif #include"uncobf.h" #include<stdio.h> #include<basetsd.h> #include"cobf.h" bba bbt bbl bbf, *bb3;bba bbt bbe bbo, *bb80;bba bb137 bb125, *bb351; bba bbt bbl bb41, *bb73;bba bbt bb137 bbk, *bb59;bba bbe bbu, *bb134; bba bbh bbf*bb79; #ifdef bb307 bba bbd bb61, *bb124; #endif #else #include"uncobf.h" #include<linux/module.h> #include<linux/ctype.h> #include<linux/time.h> #include<linux/slab.h> #include"cobf.h" #ifndef bb118 #define bb118 #ifdef _WIN32 #include"uncobf.h" #include<wtypes.h> #include"cobf.h" #else #ifdef bb121 #include"uncobf.h" #include<linux/types.h> #include"cobf.h" #else #include"uncobf.h" #include<stddef.h> #include<sys/types.h> #include"cobf.h" #endif #endif #ifdef _WIN32 #ifdef _MSC_VER bba bb117 bb224; #endif #else bba bbe bbu, *bb134, *bb216; #define bb200 1 #define bb202 0 bba bb261 bb249, *bb205, *bb252;bba bbe bb278, *bb255, *bb227;bba bbt bbo, *bb80, *bb215;bba bb8 bb266, *bb221;bba bbt bb8 bb226, *bb230; bba bb8 bb119, *bb212;bba bbt bb8 bb63, *bb237;bba bb63 bb228, *bb251 ;bba bb63 bb259, *bb220;bba bb119 bb117, *bb217;bba bb244 bb289;bba bb210 bb125;bba bb262 bb85;bba bb112 bb116;bba bb112 bb235; #ifdef bb234 bba bb233 bb41, *bb73;bba bb287 bbk, *bb59;bba bb209 bbd, *bb31;bba bb222 bb57, *bb120; #else bba bb231 bb41, *bb73;bba bb253 bbk, *bb59;bba bb245 bbd, *bb31;bba bb229 bb57, *bb120; #endif bba bb41 bbf, *bb3, *bb263;bba bbk bb206, *bb225, *bb286;bba bbk bb282 , *bb246, *bb284;bba bbd bb61, *bb124, *bb269;bba bb85 bb38, *bb241, * bb223;bba bbd bb239, *bb265, *bb243;bba bb116 bb272, *bb213, *bb281; bba bb57 bb270, *bb240, *bb208; #define bb143 bbb bba bbb*bb247, *bb81;bba bbh bbb*bb271;bba bbl bb218;bba bbl*bb207; bba bbh bbl*bb62; #if defined( bb121) bba bbe bb115; #endif bba bb115 bb19;bba bb19*bb273;bba bbh bb19*bb186; #if defined( bb268) || defined( bb248) bba bb19 bb37;bba bb19 bb111; #else bba bbl bb37;bba bbt bbl bb111; #endif bba bbh bb37*bb279;bba bb37*bb277;bba bb61 bb211, *bb219;bba bbb* bb107;bba bb107*bb257; #define bb250( bb36) bbj bb36##__ { bbe bb267; }; bba bbj bb36##__ * \ bb36 bba bbj{bb38 bb190,bb260,bb214,bb285;}bb232, *bb238, *bb283;bba bbj{ bb38 bb10,bb177;}bb254, *bb280, *bb242;bba bbj{bb38 bb264,bb275;} bb274, *bb288, *bb276; #endif bba bbh bbf*bb79; #endif bba bbf bb103; #define IN #define OUT #ifdef _DEBUG #define bb147( bbc) bb27( bbc) #else #define bb147( bbc) ( bbb)( bbc) #endif bba bbe bb160, *bb172; #define bb293 0 #define bb313 1 #define bb297 2 #define bb325 3 #define bb354 4 bba bbe bb361;bba bbb*bb123; #endif #ifdef _WIN32 #ifndef UNDER_CE #define bb32 bb346 #define bb43 bb347 bba bbt bb8 bb32;bba bb8 bb43; #endif #else #endif #ifdef _WIN32 bbb*bb127(bb32 bb48);bbb bb108(bbb* );bbb*bb138(bb32 bb158,bb32 bb48); #else #define bb127( bbc) bb146(1, bbc, bb141) #define bb108( bbc) bb340( bbc) #define bb138( bbc, bbp) bb146( bbc, bbp, bb141) #endif #ifdef _WIN32 #define bb27( bbc) bb339( bbc) #else #ifdef _DEBUG bbe bb145(bbh bbl*bb98,bbh bbl*bb26,bbt bb258); #define bb27( bbc) ( bbb)(( bbc) || ( bb145(# bbc, __FILE__, __LINE__ \ ))) #else #define bb27( bbc) (( bbb)0) #endif #endif bb43 bb301(bb43*bb319); #ifndef _WIN32 bbe bb331(bbh bbl*bbg);bbe bb320(bbh bbl*bb20,...); #endif #ifdef _WIN32 bba bb355 bb95; #define bb142( bbc) bb353( bbc) #define bb144( bbc) bb336( bbc) #define bb135( bbc) bb359( bbc) #define bb133( bbc) bb342( bbc) #else bba bb343 bb95; #define bb142( bbc) ( bbb)( * bbc = bb337( bbc)) #define bb144( bbc) (( bbb)0) #define bb135( bbc) bb352( bbc) #define bb133( bbc) bb344( bbc) #endif #ifdef UNDER_CE #define bb1970 64 #endif #define bb977 bb56(0x0800) #define bb1131 bb56(0x0806) #define bb958 bb56(0x01f4) #define bb975 bb56(0x1194) #define bb1160 bb56(0x4000) #define bb1134 bb56(0x2000) #define bb1146 bb56(0x1FFF) #define bb1088( bb10) (( bb10) & bb56(0x2000 | 0x1FFF)) #define bb1061( bb10) ((( bb197( bb10)) & 0x1FFF) << 3) #define bb1013( bb10) ((( bb10) & bb56(0x1FFF)) == 0) #define bb513( bb10) (( bb10) & bb56(0x2000)) #define bb1069( bb10) (!( bb513( bb10))) #pragma pack(push, 1) bba bbj{bbf bb376[6 ];bbf bb1044[6 ];bbk bb383;}bb374, *bb389;bba bbj{ bbf bb460[6 ];bbk bb383;}bb1117, *bb1126;bba bbj{bbf bb994:4 ;bbf bb1121 :4 ;bbf bb1085;bbk bb381;bbk bb909;bbk bb603;bbf bb1038;bbf bb291;bbk bb634;bbd bb312;bbd bb256;}bb330, *bb324;bba bbj{bbk bb1071;bbk bb1078 ;bbf bb1073;bbf bb1080;bbk bb1096;bbf bb1093[6 ];bbd bb1075;bbf bb1070 [6 ];bbd bb1098;}bb1090, *bb1115; #pragma pack(pop) bba bbj{bbk bb290;bbk bb439;bbk bb1043;bbk bb326;}bb431, *bb362;bba bbj{bbk bb290;bbk bb621;bbd bb565;bbd bb948;bbf bb97;bbf bb171;bbk bb159;bbk bb326;bbk bb1042;}bb508, *bb317;bba bbj{bbf bb1113;bbf bb1103;bbf bb1092;bbf bb1109;bbd bb1097;bbk bb1107;bbk bb387;bbd bb1127;bbd bb1116;bbd bb1100;bbd bb1095;bbf bb1114[16 ];bbf bb1084[64 ] ;bbf bb26[128 ];bbf bb1128[64 ];}bb1083, *bb1079;bba bbj{bbd bb312;bbd bb256;bbf bb934;bbf bb291;bbk bb937;}bb627, *bb589; #if defined( _WIN32) #define bb56( bbc) (((( bbc) & 0XFF00) >> 8) | ((( bbc) & 0X00FF) << \ 8)) #define bb197( bbc) ( bb56( bbc)) #define bb457( bbc) (((( bbc) & 0XFF000000) >> 24) | ((( bbc) & \ 0X00FF0000) >> 8) | ((( bbc) & 0X0000FF00) << 8) | ((( bbc) & \ 0X000000FF) << 24)) #define bb514( bbc) ( bb457( bbc)) #endif bbk bb942(bbh bbb*bb304);bbk bb660(bbh bbb*bb528,bbe bb22);bba bb85 bb7;bb13{bb101=0 ,bb372=-12000 ,bb365=-11999 ,bb392=-11998 ,bb689=-11997 , bb727=-11996 ,bb767=-11995 ,bb911=-11994 ,bb793=-11992 ,bb804=-11991 , bb896=-11990 ,bb761=-11989 ,bb825=-11988 ,bb657=-11987 ,bb685=-11986 , bb902=-11985 ,bb885=-11984 ,bb644=-11983 ,bb665=-11982 ,bb796=-11981 , bb910=-11980 ,bb737=-11979 ,bb858=-11978 ,bb862=-11977 ,bb610=-11976 , bb870=-11975 ,bb678=-11960 ,bb930=-11959 ,bb912=-11500 ,bb748=-11499 , bb868=-11498 ,bb808=-11497 ,bb709=-11496 ,bb770=-11495 ,bb802=-11494 , bb783=-11493 ,bb882=-11492 ,bb893=-11491 ,bb779=-11490 ,bb866=-11489 , bb692=-11488 ,bb859=-11487 ,bb884=-11486 ,bb645=-11485 ,bb656=-11484 , bb713=-11483 ,bb845=-11482 ,bb690=-11481 ,bb717=-11480 ,bb712=-11479 , bb720=-11478 ,bb735=-11477 ,bb853=-11476 ,bb843=-11475 ,bb873=-11474 , bb835=-11473 ,bb874=-11472 ,bb806=-11460 ,bb854=-11450 ,bb738=-11449 , bb722=-11448 ,bb747=-11447 ,bb871=-11446 ,bb676=-11445 ,bb723=-11444 , bb819=-11443 ,bb721=-11440 ,bb817=-11439 ,bb842=-11438 ,bb803=-11437 , bb691=-11436 ,bb684=-11435 ,bb903=-11420 ,bb548=-11419 ,bb588=-11418 , bb700=-11417 ,bb914=-11416 ,bb680=-11415 ,bb805=-11414 ,bb742=-11413 , bb888=-11412 ,bb865=-11411 ,bb693=-11410 ,bb927=-11409 ,bb905=-11408 , bb714=-11407 ,bb739=-11406 ,bb900=-11405 ,bb894=-11404 ,bb683=-11403 , bb766=-11402 ,bb774=-11401 ,bb773=-11400 ,bb890=-11399 ,bb716=-11398 , bb771=-11397 ,bb699=-11396 ,bb799=-11395 ,bb758=-11394 ,bb919=-11393 , bb834=-11392 ,bb920=-11391 ,bb895=-11390 ,bb741=-11389 ,bb667=-11388 , bb876=-11387 ,bb908=-11386 ,bb759=-11385 ,bb883=-11384 ,bb904=-11383 , bb846=-11382 ,bb658=-11381 ,bb838=-11380 ,bb790=-11379 ,bb928=-11378 , bb762=-11377 ,bb831=-11376 ,bb801=-11375 ,bb849=-11374 ,bb855=-11373 , bb702=-11372 ,bb906=-11371 ,bb653=-11370 ,bb784=-11369 ,bb867=-11368 , bb768=-11367 ,bb812=-11366 ,bb679=-11365 ,bb869=-11364 ,bb659=-11363 , bb401=-11350 ,bb892=bb401,bb729=-11349 ,bb701=-11348 ,bb787=-11347 ,bb740 =-11346 ,bb837=-11345 ,bb705=-11344 ,bb852=-11343 ,bb840=-11342 ,bb731=- 11341 ,bb734=-11340 ,bb907=-11339 ,bb406=-11338 ,bb821=-11337 ,bb688=bb406 ,bb822=-11330 ,bb844=-11329 ,bb832=-11328 ,bb776=-11327 ,bb733=-11326 , bb661=-11325 ,bb918=-11324 ,bb725=-11320 ,bb931=-11319 ,bb763=-11318 , bb788=-11317 ,bb652=-11316 ,bb922=-11315 ,bb792=-11314 ,bb769=-11313 , bb782=-11312 ,bb789=-11300 ,bb778=-11299 ,bb807=-11298 ,bb719=-11297 , bb743=-11296 ,bb673=-11295 ,bb861=-11294 ,bb646=-11293 ,bb797=-11292 , bb901=-11291 ,bb857=-11290 ,bb649=-11289 ,bb785=-11288 ,bb879=-11287 , bb824=-11286 ,bb647=-11285 ,bb851=-11284 ,bb764=-11283 ,bb750=-11282 , bb695=-11281 ,bb833=-11280 ,bb829=-11279 ,bb751=-11250 ,bb798=-11249 , bb899=-11248 ,bb755=-11247 ,bb791=-11246 ,bb711=-11245 ,bb823=-11244 , bb715=-11243 ,bb925=-11242 ,bb860=-11240 ,bb662=-11239 ,bb745=-11238 , bb795=-11237 ,bb863=-11150 ,bb728=-11100 ,bb756=-11099 ,bb781=-11098 , bb726=-11097 ,bb730=-11096 ,bb800=-11095 ,bb923=-11094 ,bb875=-11093 , bb827=-11092 ,bb698=-11091 ,bb655=-11090 ,bb706=-11089 ,bb651=-11088 , bb926=-11087 ,bb878=-11086 ,bb836=-11085 ,bb696=-11050 ,bb753=-11049 , bb708=-10999 ,bb809=-10998 ,bb677=-10997 ,bb718=-10996 ,bb666=-10995 , bb697=-10994 ,bb710=-10993 ,bb650=-10992 ,bb777=-10991 ,bb668=-10990 , bb786=-10989 ,bb913=-10988 ,bb841=-10979 ,bb664=-10978 ,bb932=-10977 , bb887=-10976 ,bb760=-10975 ,bb724=-10974 ,};bba bbj bb469{bb3 bb76;bbd bb129;bbd bb183;bbj bb469*bb99;}bby;bb7 bb489(bby*bb839,bbd bb933,bby *bb847,bbd bb877,bbd bb558);bb7 bb551(bby*bbi,bbd bb97,bbh bbb*bb98, bbd bb48);bb7 bb597(bby*bbi,bbd bb97,bbb*bb132,bbd bb48);bbu bb813( bby*bbi,bbd bb97,bbh bbb*bb98,bbd bb48);bb7 bb614(bby*bb88,bbf bb104, bby*bb60);bb7 bb654(bby*bb88,bbu bb179,bbf*bb419);bb7 bb982(bby*bb60, bbf*bb399);bb7 bb962(bbh bbf*bb399,bby*bb60);bb7 bb564(bby*bb53,bbf bb104,bbd*bb968);bb7 bb946(bby*bb88,bbf bb104,bbf bb419,bby*bb60);bbd bb536(bby*bb53);bbk bb554(bby*bb53);bbb bb549(bbk bb152,bby*bb53);bbb bb556(bby*bb53);bbb bb1009(bby*bb53,bbd*bb29);bbb bb1035(bby*bb53,bbd *bb29);bbb bb1060(bby*bb53,bbd bb29);bbb bb954(bby*bb53,bbd bb29); bbb bb1016(bby*bb53);bbu bb1051(bbf*bb53);bba bbj bb1025*bb1023;bba bbj bb1027*bb1064;bba bbj bb1026*bb1059;bba bbj bb1067*bb1048;bba bbj bb1049*bb1033;bba bbj bb1024*bb1063;bba bb13{bb579=0 ,bb607=1 ,bb609=2 , bb814=3 ,bb612=4 ,bb601=5 ,bb586=6 ,bb593=7 ,bb604=9 ,}bb438;bba bb13{bb630 =0 ,bb1028,bb623,bb1046,bb955,bb941,bb947,bb936,bb949,bb945,bb940,} bb537; #pragma pack(push, 8) #ifdef _MSC_VER #pragma warning (disable:4200) #endif bba bbf bb180[4 ];bba bb13{bb1665=0 ,bb1489=1 ,}bb1412;bba bb13{bb1548=0 ,bb1740=1 ,bb1683=2 ,bb1454=3 ,bb1421=4 ,bb1516=5 ,bb1652=6 ,bb1539=7 , bb1627=8 ,bb1542=9 ,bb1690=10 ,bb1530=11 ,bb1512=12 ,bb1579=13 ,bb1732=14 , bb1446=15 ,bb1476=16 ,bb1422=17 ,bb1622=18 ,bb1702=19 ,bb1660=20 ,bb1520=21 ,bb1528=22 ,bb1496=23 ,bb1625=24 ,bb1620=25 ,bb1472=26 ,bb1555=27 ,bb1750= 28 ,bb1601=29 ,bb1704=30 ,bb1649=16300 ,bb1628=16301 ,bb1745=16384 ,bb1562= 24576 ,bb1482=24577 ,bb1460=24578 ,bb1501=34793 ,bb1758=40500 ,}bb780;bba bb13{bb1484=0 ,bb1547=1 ,bb1477=2 ,bb1447=3 ,bb1718=4 ,bb1413=5 ,bb1498=6 , bb1497=7 ,bb1554=8 ,bb1423=9 ,bb1462=21 ,bb1513=22 ,bb1537=23 ,bb1464=24 , bb1566=25 ,bb1529=26 ,bb1485=27 ,bb1756=28 ,bb1495=29 ,bb1509=80 ,}bb828; bba bb13{bb1653=0 ,bb1712=1 ,bb1709=2 ,bb1506=3 ,bb1541=4 ,}bb1643;bba bb13 {bb1703=0 ,bb1378=1 ,bb1203=2 ,bb1258=3 ,bb1402=4 ,bb1106=61440 ,bb1397= 61441 ,bb1153=61443 ,bb1341=61444 ,}bb498;bba bb13{bb1719=0 ,bb1518=1 , bb1584=2 ,}bb1697;bba bb13{bb1415=0 ,bb1744,bb1453,bb1473,bb1588,bb1519 ,bb1654,bb1488,bb1626,bb1511,bb1414,bb1716,}bb736;bba bb13{bb1465=0 , bb1403=2 ,bb1366=3 ,bb1593=4 ,bb1361=9 ,bb1339=12 ,bb1400=13 ,bb1357=14 , bb1388=249 ,}bb929;bba bb13{bb1398=0 ,bb1342=1 ,bb1404=2 ,bb1445=3 ,bb1646 =4 ,bb1396=5 ,bb1381=12 ,bb1360=13 ,bb1355=14 ,bb1407=61440 ,}bb501;bba bb13 {bb1334=1 ,bb1347=2 ,bb1351=3 ,bb1564=4 ,bb1624=5 ,bb1468=6 ,bb1450=7 , bb1491=8 ,bb1471=9 ,bb1563=10 ,bb1345=11 ,bb413=12 ,bb1335=13 ,bb405=240 , bb1385=(128 <<16 )|bb405,bb1382=(192 <<16 )|bb405,bb1373=(256 <<16 )|bb405, bb1344=(128 <<16 )|bb413,bb1337=(192 <<16 )|bb413,bb1371=(256 <<16 )|bb413, }bb921;bba bb13{bb1336=0 ,bb1525=1 ,bb1405=2 ,bb1368=3 ,bb1480=4 ,}bb643; bba bb13{bb1458=0 ,bb1597=1 ,bb1225=2 ,bb639=3 ,bb1280=4 ,}bb732;bba bb13{ bb1599=0 ,bb1551=1 ,bb1425=2 ,bb1684=5 ,bb1725=7 ,}bb492;bba bb13{bb1448=0 ,bb1538=1 ,bb1623=2 ,bb1726=3 ,bb1494=4 ,bb1700=5 ,bb1657=6 ,bb409=7 ,bb1570 =65001 ,bb403=240 ,bb1508=(128 <<16 )|bb403,bb1526=(192 <<16 )|bb403,bb1533 =(256 <<16 )|bb403,bb1569=(128 <<16 )|bb409,bb1581=(192 <<16 )|bb409,bb1634 =(256 <<16 )|bb409,}bb818;bba bb13{bb1738=0 ,bb1478=1 ,bb1676=2 ,bb1596=3 , bb1493=4 ,bb1550=5 ,bb1589=6 ,bb1662=65001 ,}bb674;bba bb13{bb1642=0 , bb1549=1 ,bb1675=2 ,bb1576=3 ,bb1671=4 ,bb1633=5 ,bb1578=64221 ,bb1638= 64222 ,bb1674=64223 ,bb1688=64224 ,bb1730=65001 ,bb1699=65002 ,bb1573= 65003 ,bb1461=65004 ,bb1741=65005 ,bb1510=65006 ,bb1534=65007 ,bb1500= 65008 ,bb1723=65009 ,bb1499=65010 ,}bb703;bba bb13{bb1710=0 ,bb1439=1 , bb1455=2 ,}bb682;bba bb13{bb1434=0 ,bb1751=1 ,bb1502=2 ,bb1701=3 ,}bb815; bba bb13{bb1613=0 ,bb1444=1 ,bb1457=2 ,bb1666=3 ,bb1619=4 ,bb1659=5 ,bb1515 =21 ,bb1592=6 ,bb1636=7 ,bb1558=8 ,bb1752=1000 ,}bb507;bba bb13{bb1435=0 , bb1606=1 ,bb1681=2 ,}bb746;bba bb13{bb1682=0 ,bb1426=1 ,bb1731=2 ,bb1459=3 ,bb1492=4 ,}bb694;bba bb13{bb1557=0 ,bb1689=1 ,bb1717=1001 ,bb1733=1002 ,} bb648;bba bb13{bb1583=0 ,bb1130=1 ,bb1108=2 ,bb1105=3 ,bb1169=4 ,bb1180=5 , bb1178=6 ,bb1713=100 ,bb1602=101 ,}bb504;bba bbj bb400{bb921 bb298;bb501 bb617;bb498 bb45;}bb400;bba bbj bb402{bb929 bb1384;bb501 bb617;bb498 bb45;}bb402;bba bbj bb408{bb643 bb1040;}bb408;bba bbj bb506{bb703 bb1647;bb674 bb428;bb818 bb298;bbu bb1507;bb492 bb663;}bb506;bba bbj bb497{bbu bb638;bb400 bb316;bbu bb675;bb402 bb582;bbu bb810;bb408 bb632;bb492 bb663;}bb497;bba bbj bb470{bb180 bb984;bb180 bb1241;bb732 bb104;bb329{bbj{bb402 bb47;bbf bb581[64 ];bbf bb583[64 ];}bb582;bbj{ bb400 bb47;bbf bb1249[32 ];bbf bb1263[32 ];bbf bb581[64 ];bbf bb583[64 ]; bbf bb1232[16 ];}bb316;bbj{bb408 bb47;}bb632;}bb299;}bb470;bba bbj{bbd bb889,bb620;bbf bb1173:1 ;bbf bb1208:1 ;bbf bb104;bbk bb455;}bb188;bba bbj bb525{bbd bb11;bb188 bbc[64 *2 ];}bb525; #ifdef UNDER_CE bba bb43 bb394; #else bba bb85 bb394; #endif bba bbj bb174{bbj bb174*bb1487, *bb1760;bbd bb29;bbd bb1151;bb188 bb939[64 ];bb504 bb523;bbd bb1394;bbk bb1104;bbd bb574;bbd bb880;bbd bb820;bbf bb499;bbf bb1375;bbf bb1142;bbd bb1068;bbd bb1759;bb394 bb600;bbk bb1295;bb470 bb417[3 ];bb394 bb1590;bbf bb1527[40 ];bbd bb613 ;bbd bb1600;}bb174; #ifdef CONFIG_COMPAT #include"uncobf.h" #include<linux/compat.h> #include"cobf.h" #define bb1369 ( bb12( bbj bb174 * ) * 2 - bb12( bb500) * 2) #endif bba bbj bb404{bbj bb404*bb1739;bb188 bb493;}bb404;bba bbj bb757{bbu bb496;bbu bb499;bbd bb29;bbd bb613;bbf bb1535;bbk bb1615;bbf*bb1565; bbd bb1443;bbf*bb1522;bbd bb1735;bbf*bb1754;bbd bb1433;bbu bb1663;bbu bb1595;bb404*bb132;bbu bb1544;bb694 bb1545;bbd bb1614;bb682 bb1727; bb504 bb523;bbk bb1747;bbd bb1553;bb648 bb1424;bbd bb1667;bbd bb1673; bb736 bb1440;bbf*bb1427;bbd bb1430;bb507 bb924;bbd bb1670;bbd bb1641; bbd bb1428;bbd bb1721;bbd bb1517;bb506*bb1552;bbd bb1481;bb497*bb1531 ;bbd bb1420;bbd bb1556;bbd bb1668;}bb757;bba bbj bb816{bbu bb496;bbd bb29;bb188 bb493;}bb816;bba bbj bb886{bb174*bb323;bbu bb1591;bbf* bb1715;bbd bb1729;}bb886;bba bbj bb707{bbd bb29;bb188 bb493;bbf bb1456 ;bbf bb1469;}bb707;bba bbj bb917{bbu bb496;bbu bb1155;bbd bb29;bbf* bb1644;bbd bb1567;}bb917;bba bbj bb671{bbd bb29;bbk bb1714;bbk bb1748 ;bbd bb152;bbf*bb51;}bb671;bba bbj bb749{bbu bb1609;bbd bb29;bbd bb574 ;bbd bb880;bbd bb820;}bb749;bba bbj bb891{bb780 bb1514;bbd bb29;bb828 bb1362;bbu bb1580;}bb891;bba bbj bb856{bbf bb1505;bbf bb1416;bbf bb1711;bbf bb1608;bbf bb1694;bbf bb1612;bbf bb951;bbf bb1479;bbf bb1749;bbf bb1543;bbf bb1438;bbf bb981;bbf bb991;bbf bb956;bbf bb1692 ;bbf bb987;bbf bb963;bbf bb1762;bbf bb1470;bbf bb529;bbf bb1574;bbf bb1678;bbf bb1559;bbf bb1707;bbf bb1436;bbf bb1452;bbf bb1441;}bb856; bba bbj bb752{bbu bb1677;bbd bb490;bbd bb1705;bb815 bb1449;bbk bb1651 ;bbu bb1536;bbu bb1585;bbu bb1669;bbu bb1474;bbu bb1650;bbu bb1616; bbu bb1417;bbl bb1640[128 ];bbl bb1685[128 ];bbl bb1611[128 ];bbl bb1687 [256 ];bbl bb1655[128 ];bbl bb1467[128 ];bbd bb1610;bbf bb1586[8 ];bbf bb1432[8 ];}bb752;bba bbj bb669{bbd bb29;bbd bb1411;}bb669;bba bbj bb848{bbd bb29;bbu bb499;}bb848;bba bbj bb915{bbu bb1734;bbd bb528; bbd bb1201;}bb915;bba bbj bb765{bbd bb29;bb507 bb924;bb746 bb1621;bbf *bb1572;bbd bb1757;}bb765;bba bb13{bb1419=0 ,bb1577,bb1686,bb1763, bb1635,bb1560,bb1617,bb1418,bb1561,bb1604,bb1546,bb1706,bb1724,bb1672 ,bb1429,bb1607,bb1486,bb1431,bb1639,bb1658,}bb681;bba bbj bb1664 bb672 ;bba bb7( *bb1575)(bb672*bb1753,bbb*bb1720,bb681 bb327,bbb*bb76); #pragma pack(pop) #ifdef _WIN32 #ifdef UNDER_CE #define bb481 bb1722 bb636("1:") #else #define bb481 bb636("\\\\.\\IPSecTL") #endif #else #define bb641 "ipsecdrvtl" #define bb481 "/dev/" bb641 #ifndef bb118 #define bb118 #ifdef _WIN32 #include"uncobf.h" #include<wtypes.h> #include"cobf.h" #else #ifdef bb121 #include"uncobf.h" #include<linux/types.h> #include"cobf.h" #else #include"uncobf.h" #include<stddef.h> #include<sys/types.h> #include"cobf.h" #endif #endif #ifdef _WIN32 #ifdef _MSC_VER bba bb117 bb224; #endif #else bba bbe bbu, *bb134, *bb216; #define bb200 1 #define bb202 0 bba bb261 bb249, *bb205, *bb252;bba bbe bb278, *bb255, *bb227;bba bbt bbo, *bb80, *bb215;bba bb8 bb266, *bb221;bba bbt bb8 bb226, *bb230; bba bb8 bb119, *bb212;bba bbt bb8 bb63, *bb237;bba bb63 bb228, *bb251 ;bba bb63 bb259, *bb220;bba bb119 bb117, *bb217;bba bb244 bb289;bba bb210 bb125;bba bb262 bb85;bba bb112 bb116;bba bb112 bb235; #ifdef bb234 bba bb233 bb41, *bb73;bba bb287 bbk, *bb59;bba bb209 bbd, *bb31;bba bb222 bb57, *bb120; #else bba bb231 bb41, *bb73;bba bb253 bbk, *bb59;bba bb245 bbd, *bb31;bba bb229 bb57, *bb120; #endif bba bb41 bbf, *bb3, *bb263;bba bbk bb206, *bb225, *bb286;bba bbk bb282 , *bb246, *bb284;bba bbd bb61, *bb124, *bb269;bba bb85 bb38, *bb241, * bb223;bba bbd bb239, *bb265, *bb243;bba bb116 bb272, *bb213, *bb281; bba bb57 bb270, *bb240, *bb208; #define bb143 bbb bba bbb*bb247, *bb81;bba bbh bbb*bb271;bba bbl bb218;bba bbl*bb207; bba bbh bbl*bb62; #if defined( bb121) bba bbe bb115; #endif bba bb115 bb19;bba bb19*bb273;bba bbh bb19*bb186; #if defined( bb268) || defined( bb248) bba bb19 bb37;bba bb19 bb111; #else bba bbl bb37;bba bbt bbl bb111; #endif bba bbh bb37*bb279;bba bb37*bb277;bba bb61 bb211, *bb219;bba bbb* bb107;bba bb107*bb257; #define bb250( bb36) bbj bb36##__ { bbe bb267; }; bba bbj bb36##__ * \ bb36 bba bbj{bb38 bb190,bb260,bb214,bb285;}bb232, *bb238, *bb283;bba bbj{ bb38 bb10,bb177;}bb254, *bb280, *bb242;bba bbj{bb38 bb264,bb275;} bb274, *bb288, *bb276; #endif bba bbh bbf*bb79; #endif #include"uncobf.h" #include<linux/ioctl.h> #include"cobf.h" bba bbj{bb3 bb602;bbd bb592;bb3 bb573;bbd bb545;bbd bb371;}bb1195; #ifdef CONFIG_COMPAT #include"uncobf.h" #include<linux/compat.h> #include"cobf.h" bba bbj{bb500 bb602;bbd bb592;bb500 bb573;bbd bb545;bbd bb371;}bb1291 ; #endif #define bb1323 1 #endif #pragma pack(push, 8) bb13{bb1395=3 ,bb1393,bb1392,bb1442,};bba bbj{bbf bb106[4 ];}bb1284;bba bbj{bbf bb106[4 ];}bb1279;bba bbj{bbd bb973;bbd bb29;}bb1313;bba bbj{ bbd bb131;bbf bb1260[8 ];}bb420;bba bb13{bb1254=0 ,bb1276,bb1294,bb1328 ,bb1746}bb1275;bba bbj{bbf bb1157;bbd bb1110;bbf bb1401;}bb503; #pragma pack(pop) #pragma pack(push, 8) bb13{bb1163=-5000 ,bb1143=-4000 ,bb1032=-4999 ,bb1062=-4998 ,bb1050=-4997 ,bb1015=-4996 ,bb1184=-4995 ,bb1120=-4994 ,bb1140=-4993 ,bb1052=-4992 , bb1125=-4991 };bb7 bb1164(bb7 bb1161,bbd bb1152,bbl*bb1136);bba bbj{ bb174 bb181;bbd bb1230;bbd bb1119;bbd bb1406;bbd bb1118;bbd bb1282; bbd bb1321;bbd bb1305;bbd bb1283;bbd bb1290;bbd bb1274;bbd bb1324;bbu bb1256;bb43 bb600,bb1193,bb1207;bbf bb376[6 ];}bb161;bba bbj bb491{bbj bb491*bb99;bbf bb104;bbk bb1319;bbk bb1293;bbk bb1316;bbk bb1317;} bb445;bba bbj bb794{bbj bb794*bb99;bbj bb491*bb1129;bbd bb29;bbf bb376 [6 ];}bb416;bba bb13{bb1179=0 ,bb1598,bb1112,bb1056,bb1047}bb236;bba bbj {bbd bb395;bbd bb371;bbd bb534;bb420*bb944;bb95 bb1014;}bb311;bba bbj {bb503*bb471;bb416*bb1168;bbd bb611;bb445*bb570;bb95 bb622;bbo bb1154 ;bbo bb566;bb161*bb527;bbu bb1309;bbk bb1194;bbk bb1145;bb311 bb1081; }bb35, *bb1630; #pragma pack(pop) bba bbj bb999 bb1409, *bb83;bba bbj bb830{bbj bb830*bb328;bb3 bb484; bbo bb591;bbd bb29;bbk bb455;bbo bb97;bb3 bb318;bbo bb478;bb3 bb569; bbo bb567;bb3 bb1521;bb103 bb1408;bbf bb1346[6 ];bb103 bb1020;bb103 bb1172;bb103 bb541;bb103 bb547;}bb175, *bb91;bba bbj bb670{bbj bb670* bb99;bb175*bb328;bbd bb29;bbk bb557;bbk bb1490;bbo bb1466;bbo bb1605; bbk bb1451;}bb1475, *bb472;bbu bb1310(bb35* *bb1243);bbb bb1327(bb35* bbi);bb236 bb1311(bb35*bb114,bb389 bb465,bb324 bb140,bb362 bb427, bb317 bb201);bb236 bb1289(bb35*bb114,bb389 bb465,bb324 bb140,bb362 bb427,bb317 bb201);bb236 bb1299(bb35*bb114,bb175*bb51,bb83 bb78); bb236 bb1278(bb35*bb114,bb175*bb51,bb83 bb78);bb7 bb1288(bb35*bb114, bb175*bb51,bbd*bb106);bb7 bb1191(bb83 bb78,bb35*bb114,bb175*bb51, bb161*bb323,bbu bb606,bbu bb972);bba bbj bb1942{bb123 bb1965;bb123 bb1974;bb35*bb1005;}bb1091, *bb1943;bbr bb1091 bb976;bbj bb999{bb123 bb1937;bbo bb1945;bbd bb2008;bb91 bb1034;bb91 bb1986;bb91 bb1908;bb91 bb1946;bb91 bb1991;bb472 bb1907;bb472 bb2006;bb472 bb1958;bb95 bb1174 ;bb103 bb1959;bb103 bb2001;bb103 bb1980;bb123 bb2004;bb123 bb1917;}; bbr bb83 bb2011;bbr bb95 bb1968;bbd bb1912(bbb*bb535,bbb*bb1931,bb160 *bb1167);bb160 bb1999(bb123 bb2010,bb123 bb1956,bb81 bb569,bbo bb567 ,bb81 bb1150,bbo bb1139,bbo bb1183); #ifdef UNDER_CE #define bb618 16 #define bb1176 32 #else #define bb618 128 #define bb1176 256 #endif #define bb1144 bb618 *2 #define bb595 ( bb1144 * 2) #define bb1953 bb595 * 2 #define bb1909 bb595 * 2 bbr bbo bb974;bb160 bb1817(bb61 bb986,bbb*bb42,bbo bb1099,bb124 bb1695 );bb143 bb1976(IN bb83 bb78,IN bb123 bb2019,IN bb3 bb569,IN bbo bb567 ,IN bb81 bb1150,IN bbo bb1139,IN bbo bb1183);bb143 bb1960(IN bb83 bb78 );bbd bb1952(bb81 bb535,bb123 bb1971,bb81 bb1964,bbo bb2012,bb81 bb1905,bbo bb1901,bbo bb1990,bb160*bb1167);bbb bb1273(bb83 bb78,bb91* bb560,bb91 bb51);bb91 bb1307(bb83 bb78,bb91*bb560);bbu bb1814(bb83 bb78);bbb bb1833(bb83 bb78);bb91 bb1483(bb172 bb368,bb83 bb78);bb91 bb1874(bb172 bb368,bb83 bb78);bb91 bb1810(bb172 bb368,bb83 bb78); bb143 bb1679(bb83 bb78,bb91 bb51);bb143 bb1839(bb83 bb78,bb91 bb51); bb143 bb1895(bb83 bb78,bb91 bb51);bbb bb1928();bbb bb1930();bbb bb155 (bbh bbl*bb20,...);bbb bb2062(bb186 bbg);bbb bb2096(bbb*bb28,bbo bb11 );bbb bb2103(bbb*bbx,bbo bb5);bbb bb1852(bbb*bbx,bbo bb5);bbb bb1370( bbb*bbx,bbo bb5);bbb bb1951();bbb bb1779();bbb bb2035(bb374*bb1973); bbb bb1594(bb330*bb28);bbb bb1306(bb330*bb754,bb508*bb136);bbb bb1503 (bb330*bb754,bb431*bb1631);bb7 bb2138(bby*bb302,bbd*bb106);bb7 bb2156 (bby*bb88,bbu bb179,bbd bb490,bb438 bb428,bbf*bb580,bbd bb106,bbd bb517,bby*bb60);bb7 bb2128(bby*bb88,bbu bb179,bb438 bb428,bbf*bb580, bbd*bb494,bbd*bb476,bbd*bb568,bby*bb60);bb7 bb2122(bby*bb302,bbd* bb106);bb7 bb2184(bby*bb88,bbu bb179,bbd bb490,bb537 bb298,bbh bbf* bb1349,bbf*bb92,bb438 bb428,bbf*bb580,bbd bb106,bbd bb517,bby*bb60); bb7 bb2108(bby*bb88,bbu bb179,bb537 bb298,bbh bbf*bb1349,bb438 bb428, bbf*bb580,bbd*bb494,bbd*bb476,bbd*bb568,bby*bb60);bb13{bb571=1 ,};bbb* bb518(bbd bb1264,bbd bb387);bb7 bb474(bbb*bb1004);bba bbj bb2049 bb2031, *bb396;bba bb13{bb2058=0 ,bb1790=1 ,bb1807=2 }bb898;bb7 bb1859( bb898 bb1923,bb396*bb369);bb7 bb2002(bb396 bb369,bbf*bb450,bbd bb434, bbf*bb314,bbd bb295,bbd*bb453,bbd*bb310);bb7 bb1996(bb396 bb369,bbf* bb314,bbd bb295,bbd*bb310,bbu*bb1007);bb7 bb2005(bb396 bb369,bbf* bb450,bbd bb434,bbf*bb314,bbd bb295,bbd*bb453,bbd*bb310,bbu*bb997); bb7 bb1869(bb396 bb369);bb7 bb2261(bby*bb88,bbu bb179,bbd bb490,bb898 bb1399,bby*bb60,bbu*bb2155);bb7 bb2167(bby*bb88,bbu bb179,bb898 bb1399 ,bby*bb60);bba bb13{bb423,bb1524,}bb306;bbk bb1235(bb306 bb881,bbh bbf *bb464);bbd bb553(bb306 bb881,bbh bbf*bb464);bbb bb1213(bbk bb158, bb306 bb584,bbf bb452[2 ]);bbb bb1006(bbd bb158,bb306 bb584,bbf bb452[ 4 ]);bbu bb1920(bb311*bbi,bbo bb534);bbb bb2018(bb311*bbi);bbb bb2098( bb311*bbi);bbu bb1828(bb311*bbi,bb420*bb826);bbu bb1984(bb311*bbi, bb420*bb826);bbb bb1988(bb35*bbi,bb180 bb106);bbb bb1919(bb35*bbi, bb180 bb106);bbb bb1864(bb35*bbi,bbd bb29,bbd bb973);bbu bb2207(bby* bb302);bbu bb2266(bby*bb302);bb7 bb2127(bby*bb302,bbd*bb106);bb7 bb2074(bby*bb302,bbd*bb106);bb7 bb2015(bby*bb88,bby*bb60,bbu bb1123, bbk bb2186,bbk bb1857);bb7 bb1911(bby*bb88,bby*bb60,bbu bb1123);bbu bb1918(bbd bb296);bb161*bb1829(bb35*bbi,bbd bb296,bbu bb606);bb161* bb1896(bb35*bbi,bbd bb296,bbd bb106);bb161*bb1972(bb35*bbi,bb180 bb106 );bbb bb1994(bb525*bb42);bb161*bb1989(bb35*bbi,bb174*bb181);bbb bb1935 (bb35*bbi,bb180 bb106);bbb bb1910(bb35*bbi,bb180 bb106);bbb bb2040( bb35*bbi);bbb bb1836(bb35*bbi);bbo bb974;bb7 bb1288(bb35*bb114,bb175* bb51,bbd*bb106){bby bb42;bbd bb1696;bb7 bb18=bb101;bbm(!bb114||!bb51 ||!bb106)bb4 bb372; *bb106=0 ;bbm(bb51->bb478>0 ){bb42.bb76=bb51->bb318 ;bb42.bb129=bb51->bb478;}bb50{bb42.bb76=bb51->bb484;bb42.bb129=bb51-> bb591;}bb42.bb76+=14 ;bb42.bb129-=14 ;bb42.bb183=bb974+20 ;bb42.bb99= bb93;bb2122(&bb42,&bb1696);bbm(!bb1696)bb2138(&bb42,&bb1696);bbm(! bb1696)bb2127(&bb42,&bb1696);bbm(!bb1696){bbm(bb51->bb455==bb114-> bb1145)bb2074(&bb42,&bb1696);}bbm(!bb1696){bbd bb29;bbd bb2284;bb161* bb166;bb2074(&bb42,&bb2284);bb1009(&bb42,&bb29);bb166=bb1896(bb114, bb29,bb2284);bbm(bb166){bbm(bb166->bb181.bb417[0 ].bb104==bb639&&bb166 ->bb181.bb417[0 ].bb299.bb316.bb47.bb45==bb1106&&bb51->bb455==bb56( bb166->bb181.bb1104))bb1696=bb2284;}} *bb106=bb1696;bb4 bb18;}bb7 bb1191(bb83 bb78,bb35*bb114,bb175*bb51,bb161*bb323,bbu bb606,bbu bb972 ){bb470*bb384;bb537 bb1296=bb630;bb438 bb1816=bb579;bb438 bb1767= bb579;bb898 bb1040=bb2058;bbk bb163;bbf*bb2224=bb93;bbf*bb2495=bb93; bbf*bb2262=bb93;bbf*bb2216=bb93;bbd bb2313=0 ;bbd bb2320=0 ;bbd bb490; bbd bb494;bbd bb476;bbd bb568;bbu bb2247;bbu bb2226;bbu bb638=0 ;bbu bb675=0 ;bbu bb810=0 ;bbu bb993;bbu bb2332;bbu bb541;bbu bb2095;bby* bb302=bb93;bby*bb1029=bb93;bby*bb75=bb93;bby*bb49=bb93;bby*bb479=bb93 ;bby bb988[2 ];bby*bb1691;bby*bb1463;bb175*bb305;bb160 bb368;bb7 bb18= bb101;bbm(!bb114||!bb51)bb4 bb372;bb305=bb51;bbm(!bb305->bb1020)bb4 bb372;bbm(bb1235(bb423,&(bb51->bb484[16 ]))>=65515 )bb4 bb1052;bb2095= bb51->bb478>0 ;bb90(bb163=0 ;bb163<2 ;bb163++){bb988[bb163].bb76=bb93; bb988[bb163].bb129=0 ;bb988[bb163].bb183=0 ;bb988[bb163].bb99=bb93;} bb302=(bby* )bb518(bb12(bby),bb571);bbm(!bb302){bb18=bb365;bb96 bb1363 ;}bbm(bb2095){bb302->bb76=(bbf* )bb518(1500 ,0 );bbm(!bb302->bb76){bb18 =bb365;bb96 bb1363;}bb74(bb302->bb76,&bb305->bb318[14 ],bb305->bb478- 14 );bb302->bb129=bb305->bb478-14 ;}bb50{bb302->bb76=&(bb305->bb484[14 ] );bb302->bb129=bb305->bb591-14 ;}bb302->bb183=1500 ;bb302->bb99=bb93; bb1029=(bby* )bb518(bb12(bby),bb571);bbm(!bb1029){bb18=bb365;bb96 bb1363;}bb1029->bb76=&(bb305->bb318[14 ]);bb1029->bb129=0 ;bb1029-> bb183=bb974+20 ;bb1029->bb99=bb93;bb90(bb163=0 ;bb163<2 ;bb163++){bb988[ bb163].bb76=(bbf* )bb518(bb974+20 ,0 );bbm(!bb988[bb163].bb76){bb18= bb365;bb96 bb1363;}bb988[bb163].bb129=0 ;bb988[bb163].bb183=bb974+20 ; bb988[bb163].bb99=bb93;}bb75=bb302;bb49=bb1029;bb1691=&(bb988[0 ]); bb1463=&(bb988[1 ]);bbm(bb2095)bb541=bb305->bb547;bb50 bb541=bb305-> bb541;bb109(bb305->bb328&&((bb18)==bb101)){bbm(!bb541){bb75->bb99=( bby* )bb518(bb12(bby),bb571);bbm(!bb75->bb99){bb18=bb365;bb96 bb1363; }}bb50 bb75->bb99=bb93;bb49->bb99=(bby* )bb518(bb12(bby),bb571);bbm(! bb49->bb99){bb18=bb365;bb96 bb1363;}bb1691->bb99=(bby* )bb518(bb12( bby),bb571);bbm(!bb1691->bb99){bb18=bb365;bb96 bb1363;}bb1691=bb1691 ->bb99;bb1691->bb76=(bbf* )bb518(bb974,0 );bbm(!bb1691->bb76){bb18= bb365;bb96 bb1363;}bb1691->bb129=0 ;bb1691->bb183=bb974;bb1691->bb99= bb93;bb1463->bb99=(bby* )bb518(bb12(bby),bb571);bbm(!bb1463->bb99){ bb18=bb365;bb96 bb1363;}bb1463=bb1463->bb99;bb1463->bb76=(bbf* )bb518 (bb974,0 );bbm(!bb1463->bb76){bb18=bb365;bb96 bb1363;}bb1463->bb129=0 ; bb1463->bb183=bb974;bb1463->bb99=bb93;bbm(((bb18)==bb101)){bb49=bb49 ->bb99;bb305=bb305->bb328;bbm(!bb541){bb75=bb75->bb99;bbm(bb2095){ bb75->bb76=(bbf* )bb518(1500 -14 -20 ,0 );bbm(!bb75->bb76){bb18=bb365; bb96 bb1363;}bb74(bb75->bb76,&bb305->bb318[14 +20 ],bb305->bb478-14 -20 ); bb75->bb129=bb305->bb478-14 -20 ;bb541=bb305->bb547;}bb50{bb75->bb76=&( bb305->bb484[14 +20 ]);bb75->bb129=bb305->bb591-14 -20 ;bb541=bb305-> bb541;}bb75->bb183=1500 -14 -20 ;bb75->bb99=bb93;}bb49->bb76=&(bb305-> bb318[14 +20 ]);bb49->bb129=0 ;bb49->bb183=bb974;bb49->bb99=bb93;}}bb490 =bb972?bb323->bb181.bb29:0 ;bb90(bb163=0 ;bb163<bb323->bb181.bb1295; bb163++){bb384=&bb323->bb181.bb417[bb163];bbm(bb384->bb104==bb1225){ bb338(bb384->bb299.bb582.bb47.bb1384){bb17 bb1403:bb1767=bb607;bb21; bb17 bb1366:bb1767=bb609;bb21;bb17 bb1339:bb1767=bb601;bb21;bb17 bb1400:bb1767=bb586;bb21;bb17 bb1357:bb1767=bb593;bb21;bb17 bb1361: bb1767=bb604;bb21;bb17 bb1388:bb1767=bb612;bb21;bb477:bb18=bb548;}bbm (bb606){bb2216=bb384->bb299.bb582.bb581;bb2320=bb553(bb423,bb384-> bb984);}bb50{bb2216=bb384->bb299.bb582.bb583;bb2320=bb553(bb423,bb384 ->bb1241);}}bb50 bbm(bb384->bb104==bb639){bb338(bb384->bb299.bb316. bb47.bb298){bb17 bb1351:bb1296=bb623;bb21;bb17 bb1334:bb1296=bb623; bb21;bb17 bb1347:bb1296=bb623;bb21;bb17 bb1335:bb1296=bb955;bb21;bb17 bb1385:bb1296=bb949;bb21;bb17 bb1382:bb1296=bb945;bb21;bb17 bb1373: bb1296=bb940;bb21;bb17 bb1344:bb1296=bb941;bb21;bb17 bb1337:bb1296= bb947;bb21;bb17 bb1371:bb1296=bb936;bb21;bb17 bb1345:bb21;bb477:bb18= bb588;}bb338(bb384->bb299.bb316.bb47.bb617){bb17 bb1342:bb1816=bb607; bb21;bb17 bb1404:bb1816=bb609;bb21;bb17 bb1381:bb1816=bb601;bb21;bb17 bb1360:bb1816=bb586;bb21;bb17 bb1355:bb1816=bb593;bb21;bb17 bb1396: bb1816=bb604;bb21;bb17 bb1407:bb1816=bb612;bb21;bb17 bb1398:bb21; bb477:bb18=bb548;}bbm(bb606){bb2224=bb384->bb299.bb316.bb1249;bb2262= bb384->bb299.bb316.bb581;bb2313=bb553(bb423,bb384->bb984);}bb50{ bb2224=bb384->bb299.bb316.bb1263;bb2262=bb384->bb299.bb316.bb583; bb2313=bb553(bb423,bb384->bb1241);bb2495=bb384->bb299.bb316.bb1232;}} bb50 bbm(bb384->bb104==bb1280){bb338(bb384->bb299.bb632.bb47.bb1040){ bb17 bb1405:bb1040=bb1790;bb21;bb17 bb1368:bb1040=bb1807;bb21;bb17 bb1336:bb21;bb477:bb18=bb372;}}}bb338(bb323->bb181.bb417[0 ].bb104){ bb17 bb1225:bb675=1 ;bb21;bb17 bb639:bb638=1 ;bb21;bb17 bb1280:bb810=1 ; bb21;}bb384=&bb323->bb181.bb417[0 ];bb338(bb323->bb181.bb523){bb17 bb1130:bb993=1 ;bb21;bb17 bb1178:bb993=bb384->bb104==bb639&&bb384-> bb299.bb316.bb47.bb45==bb1153;bb21;bb17 bb1180:bb993=bb384->bb104== bb639&&bb384->bb299.bb316.bb47.bb45==bb1258;bb21;bb17 bb1169:bb993= bb384->bb104==bb639&&(bb384->bb299.bb316.bb47.bb45==bb1153||bb384-> bb299.bb316.bb47.bb45==bb1106);bb21;bb17 bb1108:bb17 bb1105:bb993= bb384->bb104==bb639&&bb384->bb299.bb316.bb47.bb45==bb1106;bb21;bb477: bb993=0 ;bb21;}bbm(bb675&&bb993)bb675=0 ;bbm(!bb638&&!bb675)bb810=0 ; bb2247=!bb638&&!bb810&&bb972;bb2226=!bb810&&bb972;bb75=bb302;bbm( bb638&&(bb675||bb810||bb993))bb49=&(bb988[0 ]);bb50 bbm(bb675&&bb810)bb49 =&(bb988[0 ]);bb50 bb49=bb1029;bbm(bb606){bbm(bb993&&((bb18)==bb101)){ bb338(bb323->bb181.bb523){bb17 bb1178:bb17 bb1180:bb18=bb1911(bb75, bb49,0 );bb21;bb17 bb1130:bb17 bb1169:bb18=bb1911(bb75,bb49,1 );bb21; bb17 bb1108:bb17 bb1105:bb18=bb1911(bb75,bb49,0 );bb21;}bb75=bb49;bbm( bb638&&bb810)bb49=&(bb988[1 ]);bb50 bb49=bb1029;}bbm(bb675&&((bb18)== bb101)){bb494=bb323->bb1324;bb476=bb323->bb1290;bb568=bb323->bb1274; bb18=bb2128(bb75,bb2247,bb1767,bb2216,&bb494,&bb476,&bb568,bb49);bbm( ((bb18)==bb101)){bb323->bb1324=bb494;bb323->bb1290=bb476;bb323-> bb1274=bb568;}bb75=bb49;bbm(bb638&&bb810)bb49=&(bb988[1 ]);bb50 bb49= bb1029;}bbm(bb638&&((bb18)==bb101)){bb494=bb323->bb1283;bb476=bb323-> bb1321;bb568=bb323->bb1305;bb18=bb2108(bb75,bb2226,bb1296,bb2224, bb1816,bb2262,&bb494,&bb476,&bb568,bb49);bbm(((bb18)==bb101)){bb323-> bb1283=bb494;bb323->bb1321=bb476;bb323->bb1305=bb568;}bb75=bb49;bb49= bb1029;}bbm(bb810&&((bb18)==bb101)){bb18=bb2167(bb75,bb972,bb1040, bb49);bb109(bb18==bb392){bb305=bb51;bb479=bb1029;bb479->bb129=0 ;bb109 (bb479->bb99){bb305=bb305->bb328;bb479=bb479->bb99;bb479->bb129=0 ;} bb479->bb99=(bby* )bb518(bb12(bby),0 );bbm(bb479->bb99){bb305->bb328= bb1810(&bb368,bb78);bbm(bb305->bb328){bb479->bb99->bb76=&(bb305-> bb328->bb318[14 +20 ]);bb479->bb99->bb129=0 ;bb479->bb99->bb183=bb974; bb479->bb99->bb99=bb93;bb305->bb328->bb328=bb93;}bb50 bb18=bb365;} bb50 bb18=bb365;bbm(bb18==bb392)bb18=bb2167(bb75,bb972,bb1040,bb49);} }}bb50{bbm(bb2095){bb1016(bb75);bb556(bb75);}bbm(bb810&&((bb18)== bb101)){bb18=bb2261(bb75,bb972,bb490,bb1040,bb49,&bb2332);bb75=bb49; bbm(bb638&&(bb675||bb993))bb49=&(bb988[1 ]);bb50 bb49=bb1029;bb2226= bb972&&bb638&&!bb2332;bb2247=bb972&&bb675&&!bb638&&!bb2332;}bbm(bb638 &&((bb18)==bb101)){bb18=bb2184(bb75,bb2226,bb490,bb1296,bb2224,bb2495 ,bb1816,bb2262,bb2313,bb323->bb1119+1 ,bb49);bb75=bb49;bb49=bb1029;} bbm(bb675&&((bb18)==bb101)){bb18=bb2156(bb75,bb2247,bb490,bb1767, bb2216,bb2320,bb323->bb1119+1 ,bb49);}bbm(bb993&&((bb18)==bb101)){ bb338(bb323->bb181.bb523){bb17 bb1178:bb17 bb1180:bb18=bb2015(bb75, bb49,0 ,bb114->bb1145,bb975);bb21;bb17 bb1130:bb17 bb1169:bb18=bb2015( bb75,bb49,1 ,bb114->bb1194,bb958);bb21;bb17 bb1108:bb17 bb1105:bb18= bb2015(bb75,bb49,0 ,bb56(bb323->bb181.bb1104),bb56(bb323->bb181.bb1104 ));bb21;}}}bbm(((bb18)==bb101)){bb51->bb478=bb1029->bb129+14 ;bb51-> bb1172=1 ;bb49=bb1029->bb99;bbm(!bb51->bb328||!bb49){bb51->bb547=1 ; bb305=bb93;}bb50 bbm(bb49->bb129==0 ){bb51->bb547=1 ;bb305=bb93;}bb50{ bb305=bb51->bb328;bb51->bb547=0 ;}bb109(bb305){bb305->bb478=14 +20 +bb49 ->bb129;bb305->bb1172=0 ;bb305->bb547=0 ;bbm(!bb49->bb99){bb305->bb547= 1 ;bb305=bb93;}bb50 bbm(bb49->bb99->bb129==0 ){bb305->bb547=1 ;bb305= bb93;}bb50{bb49=bb49->bb99;bb305=bb305->bb328;}}}bb1363:bb90(bb163=0 ; bb163<2 ;bb163++){bbm(bb988[bb163].bb76)bb474(bb988[bb163].bb76);bb90( bb75=bb988[bb163].bb99;bb75;){bbm(bb75->bb76)bb474(bb75->bb76);bb479= bb75;bb75=bb75->bb99;bb474(bb479);}}bb90(bb75=bb302;bb75;){bbm(bb2095 )bb474(bb75->bb76);bb479=bb75;bb75=bb75->bb99;bb474(bb479);}bb90(bb49 =bb1029;bb49;){bb479=bb49;bb49=bb49->bb99;bb474(bb479);}bbm(((bb18)== bb101)){bbm(bb606)bb323->bb1207=bb301(bb93);bb50 bb323->bb1193=bb301( bb93);}bb4 bb18;}
lyfest/android_kernel_samsung_sltechn
drivers/net/wireless/ipsecdrvtl/bi.c
C
gpl-2.0
34,048
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ return array( 'code' => '44', 'patterns' => array( 'national' => array( 'general' => '/^[135789]\\d{6,9}$/', 'fixed' => '/^1481\\d{6}$/', 'mobile' => '/^7(?:781|839|911)\\d{6}$/', 'pager' => '/^76(?:0[012]|2[356]|4[0134]|5[49]|6[0-369]|77|81|9[39])\\d{6}$/', 'tollfree' => '/^80(?:0(?:1111|\\d{6,7})|8\\d{7})|500\\d{6}$/', 'premium' => '/^(?:87[123]|9(?:[01]\\d|8[0-3]))\\d{7}$/', 'shared' => '/^8(?:4(?:5464\\d|[2-5]\\d{7})|70\\d{7})$/', 'personal' => '/^70\\d{8}$/', 'voip' => '/^56\\d{8}$/', 'uan' => '/^(?:3[0347]|55)\\d{8}$/', 'shortcode' => '/^1(?:0[01]|1(?:1|[68]\\d{3})|23|4(?:1|7\\d)|55|800\\d|95)$/', 'emergency' => '/^112|999$/', ), 'possible' => array( 'general' => '/^\\d{6,10}$/', 'mobile' => '/^\\d{10}$/', 'pager' => '/^\\d{10}$/', 'tollfree' => '/^\\d{7}(?:\\d{2,3})?$/', 'premium' => '/^\\d{10}$/', 'shared' => '/^\\d{7}(?:\\d{3})?$/', 'personal' => '/^\\d{10}$/', 'voip' => '/^\\d{10}$/', 'uan' => '/^\\d{10}$/', 'shortcode' => '/^\\d{3,6}$/', 'emergency' => '/^\\d{3}$/', ), ), );
JorikVartanov/zf2
zf2_project/vendor/zendframework/zendframework/library/Zend/I18n/Validator/PhoneNumber/GG.php
PHP
bsd-3-clause
1,631
/*! * OOjs UI v0.9.3 * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2015 OOjs Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2015-03-19T23:19:18Z */ .oo-ui-icon-table { background-image: /* @embed */ url(themes/mediawiki/images/icons/table.png); } .oo-ui-icon-newline { background-image: /* @embed */ url(themes/mediawiki/images/icons/newline-rtl.png); } .oo-ui-icon-redirect { background-image: /* @embed */ url(themes/mediawiki/images/icons/redirect-rtl.png); } .oo-ui-icon-noWikiText { background-image: /* @embed */ url(themes/mediawiki/images/icons/noWikiText-rtl.png); } .oo-ui-icon-puzzle { background-image: /* @embed */ url(themes/mediawiki/images/icons/puzzle-rtl.png); } .oo-ui-icon-quotes { background-image: /* @embed */ url(themes/mediawiki/images/icons/quotes-rtl.png); } .oo-ui-icon-quotesAdd { background-image: /* @embed */ url(themes/mediawiki/images/icons/quotesAdd-rtl.png); } .oo-ui-icon-templateAdd { background-image: /* @embed */ url(themes/mediawiki/images/icons/templateAdd-rtl.png); } .oo-ui-icon-translation { background-image: /* @embed */ url(themes/mediawiki/images/icons/translation-rtl.png); } .oo-ui-icon-wikiText { background-image: /* @embed */ url(themes/mediawiki/images/icons/wikiText.png); }
brix/cdnjs
ajax/libs/oojs-ui/0.9.3/oojs-ui-mediawiki-icons-editing-advanced.raster.rtl.css
CSS
mit
1,322
/* Copyright (c) 2016 Barrett Adair Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) HEADER GUARDS INTENTIONALLY OMITTED DO NOT INCLUDE THIS HEADER DIRECTLY macros used: BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS - the function-level qualifiers for the current inclusion (combinations of `const` `volatile` `&` `&&`, or nothing) BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE - the transaction_safe specifier for the current include (`transaction_safe` or nothing) BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE - `std::true_type` or `std::false_type`, tied on whether BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE is `transaction_safe` BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER - `transaction_safe` when BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE is enabled, otherwise nothing BOOST_CLBL_TRTS_NOEXCEPT_SPEC - the noexcept specifier for the current include (`noexcept` or nothing) BOOST_CLBL_TRTS_IS_NOEXCEPT - `std::true_type` or `std::false_type`, tied on whether BOOST_CLBL_TRTS_NOEXCEPT_SPEC is `noexcept` BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER - `noexcept` if BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES is defined, otherwise nothing */ template<typename Return, typename... Args> struct function<Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC> : default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS> { static constexpr bool value = true; using traits = function; using return_type = Return; using arg_types = std::tuple<Args...>; using non_invoke_arg_types = arg_types; using type = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using function_type = Return(Args...); using qualified_function_type = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using remove_varargs = type; using add_varargs = Return (Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using is_noexcept = BOOST_CLBL_TRTS_IS_NOEXCEPT; using remove_noexcept = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE; using add_noexcept = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER; using is_transaction_safe = BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE; using remove_transaction_safe = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using add_transaction_safe = Return(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using qualifiers = default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>; template<qualifier_flags Flags> using set_qualifiers = set_function_qualifiers<Flags, is_transaction_safe::value, is_noexcept::value, Return, Args...>; #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS using add_member_lvalue_reference = abominable_functions_not_supported_on_this_compiler; using add_member_rvalue_reference = abominable_functions_not_supported_on_this_compiler; using add_member_const = abominable_functions_not_supported_on_this_compiler; using add_member_volatile = abominable_functions_not_supported_on_this_compiler; using add_member_cv = abominable_functions_not_supported_on_this_compiler; #else using add_member_lvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, lref_>::value>; using add_member_rvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, rref_>::value>; using add_member_const = set_qualifiers<qualifiers::q_flags | const_>; using add_member_volatile = set_qualifiers<qualifiers::q_flags | volatile_>; using add_member_cv = set_qualifiers<qualifiers::q_flags | cv_>; #endif // #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS using remove_member_reference = set_qualifiers<qualifiers::cv_flags>; using remove_member_const = set_qualifiers< qualifiers::ref_flags | remove_const_flag<qualifiers::cv_flags>::value>; using remove_member_volatile = set_qualifiers< qualifiers::ref_flags | remove_volatile_flag<qualifiers::cv_flags>::value>; using remove_member_cv = set_qualifiers<qualifiers::ref_flags>; template<typename U> using apply_member_pointer = add_member_pointer<type, U>; template<typename NewReturn> using apply_return = NewReturn(Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; template<template<class...> class Container> using expand_args = Container<Args...>; using is_member_pointer = std::false_type; }; template<typename Return, typename... Args> struct function<Return (Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC> : default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS> { static constexpr bool value = true; using has_varargs = std::true_type; using traits = function; using return_type = Return; using arg_types = std::tuple<Args...>; using type = Return (Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using function_type = Return(Args..., ...); using qualified_function_type = Return(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using remove_varargs = Return (Args...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using add_varargs = type; using is_noexcept = BOOST_CLBL_TRTS_IS_NOEXCEPT; using remove_noexcept = Return(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE; using add_noexcept = Return(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER; using is_transaction_safe = BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE; using remove_transaction_safe = Return(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using add_transaction_safe = Return(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER BOOST_CLBL_TRTS_NOEXCEPT_SPEC; using qualifiers = default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>; template<qualifier_flags Flags> using set_qualifiers = set_varargs_function_qualifiers<Flags, is_transaction_safe::value, is_noexcept::value, Return, Args...>; #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS using add_member_lvalue_reference = abominable_functions_not_supported_on_this_compiler; using add_member_rvalue_reference = abominable_functions_not_supported_on_this_compiler; using add_member_const = abominable_functions_not_supported_on_this_compiler; using add_member_volatile = abominable_functions_not_supported_on_this_compiler; using add_member_cv = abominable_functions_not_supported_on_this_compiler; #else using add_member_lvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, lref_>::value>; using add_member_rvalue_reference = set_qualifiers< collapse_flags<qualifiers::q_flags, rref_>::value>; using add_member_const = set_qualifiers<qualifiers::q_flags | const_>; using add_member_volatile = set_qualifiers<qualifiers::q_flags | volatile_>; using add_member_cv = set_qualifiers<qualifiers::q_flags | cv_>; #endif // #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS using remove_member_reference = set_qualifiers<qualifiers::cv_flags>; using remove_member_const = set_qualifiers< qualifiers::ref_flags | remove_const_flag<qualifiers::cv_flags>::value>; using remove_member_volatile = set_qualifiers< qualifiers::ref_flags | remove_volatile_flag<qualifiers::cv_flags>::value>; using remove_member_cv = set_qualifiers<qualifiers::ref_flags>; template<typename U> using apply_member_pointer = Return( BOOST_CLBL_TRTS_DEFAULT_VARARGS_CC U::*)(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; template<typename NewReturn> using apply_return = NewReturn(Args..., ...) BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE BOOST_CLBL_TRTS_NOEXCEPT_SPEC; template<template<class...> class Container> using expand_args = Container<Args...>; using is_member_pointer = std::false_type; };
andrewchenshx/vnpy
vnpy/api/xtp/vnxtp/include/boost/callable_traits/detail/unguarded/function_3.hpp
C++
mit
9,508
/* radio */ .jcf-radio { vertical-align: middle; display: inline-block; position: relative; overflow: hidden; cursor: default; background: #fff; border: 1px solid #777; border-radius: 9px; margin: 0 3px 0 0; height: 16px; width: 16px; } .jcf-radio span{ display:none; position:absolute; top:3px; left:3px; right:3px; bottom:3px; background:#777; border-radius:100%; } .jcf-radio input[type="radio"] { position: absolute; height: 100%; width: 100%; border: 0; margin: 0; left: 0; top: 0; } .jcf-radio.jcf-checked span {display:block;} /* checkbox */ .jcf-checkbox { vertical-align: middle; display: inline-block; position: relative; overflow: hidden; cursor: default; background: #fff; border: 1px solid #777; margin: 0 3px 0 0; height: 16px; width: 16px; } .jcf-checkbox span{ position:absolute; display:none; height:4px; width:8px; top:50%; left:50%; margin:-7px 0 0 -6px; border:3px solid #777; border-width:0 0 3px 3px; -moz-transform: rotate(-45deg); -ms-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.7071067811865483, M12=0.7071067811865467, M21=-0.7071067811865467, M22=0.7071067811865483, SizingMethod='auto expand')"; } :root .jcf-checkbox span {margin:-4px 0 0 -5px;} .jcf-checkbox input[type="checkbox"] { position: absolute; width: 100%; height: 100%; border: 0; margin: 0; left: 0; top: 0; } .jcf-checkbox.jcf-checked span{display:block;} /* button */ .jcf-button { display: inline-block; vertical-align: top; position: relative; overflow: hidden; border: 1px solid #777; background: #fff; margin: 0 10px 10px 0; padding: 5px 10px; } .jcf-button .jcf-real-element { position: absolute; min-height: 100%; min-width: 100%; outline: none; opacity: 0; padding: 0; margin: 0; border: 0; bottom: 0; right: 0; left: 0; top: 0; } /* file */ .jcf-file { display: inline-block; white-space: nowrap; position: relative; overflow: hidden; background: #fff; } .jcf-file .jcf-real-element { position: absolute; font-size: 200px; height: 200px; margin: 0; right: 0; top: 0; } .jcf-file .jcf-fake-input { display: inline-block; text-overflow:ellipsis; white-space: nowrap; vertical-align: top; overflow: hidden; border: 1px solid #777; padding: 0 8px; font-size: 13px; line-height: 28px; height: 28px; width: 125px; } .jcf-file .jcf-upload-button { display: inline-block; vertical-align: top; white-space: nowrap; overflow: hidden; border: 1px solid #777; margin: 0 0 0 -1px; padding: 0 10px; line-height: 28px; height: 28px; } /* scrollbars */ .jcf-scrollable-wrapper { box-sizing: content-box; position: relative; } .jcf-scrollbar-vertical { position: absolute; cursor: default; background: #e3e3e3; width: 14px; bottom: 0; right: 0; top: 0; } .jcf-scrollbar-vertical .jcf-scrollbar-dec, .jcf-scrollbar-vertical .jcf-scrollbar-inc { background: #bbb; height: 14px; width: 14px; left: 0; top: 0; } .jcf-scrollbar-vertical .jcf-scrollbar-inc { top: auto; bottom: 0; } .jcf-scrollbar-vertical .jcf-scrollbar-handle { background: #888; height: 1px; width: 14px; } .jcf-scrollbar-horizontal { position: absolute; background: #e3e3e3; right: auto; top: auto; left: 0; bottom: 0; width: 1px; height: 14px; } .jcf-scrollbar-horizontal .jcf-scrollbar-dec, .jcf-scrollbar-horizontal .jcf-scrollbar-inc { display: inline-block; vertical-align: top; overflow: hidden; background: #bbb; height: 14px; width: 14px; } .jcf-scrollbar-horizontal .jcf-scrollbar-inc { left: auto; right: 0; } .jcf-scrollbar-horizontal .jcf-scrollbar-slider { display: inline-block; position: relative; height: 14px; } .jcf-scrollbar-horizontal .jcf-scrollbar-handle { position: absolute; background: #888; height: 14px; } .jcf-scrollbar.jcf-inactive .jcf-scrollbar-handle { visibility: hidden; } .jcf-scrollbar.jcf-inactive .jcf-scrollbar-dec, .jcf-scrollbar.jcf-inactive .jcf-scrollbar-inc { background: #e3e3e3; } /* select */ .jcf-select { display: inline-block; vertical-align: top; position: relative; border: 1px solid #777; background: #fff; margin: 0 0 12px; min-width: 150px; height: 26px; } .jcf-select select { z-index: 1; left: 0; top: 0; } .jcf-select .jcf-select-text { text-overflow:ellipsis; white-space: nowrap; overflow: hidden; cursor: default; display: block; font-size: 13px; line-height: 26px; margin: 0 35px 0 8px; } .jcf-select .jcf-select-opener { position: absolute; text-align: center; background: #aaa; width: 26px; bottom: 0; right: 0; top: 0; } body > .jcf-select-drop { position: absolute; margin: -1px 0 0; z-index: 9999; } body > .jcf-select-drop.jcf-drop-flipped { margin: 1px 0 0; } .jcf-select .jcf-select-drop { position: absolute; margin-top: 0px; z-index: 9999; top: 100%; left: -1px; right: -1px; } .jcf-select .jcf-drop-flipped { bottom: 100%; top: auto; } .jcf-select-drop .jcf-select-drop-content { border: 1px solid #f00; } /* multiple select styles */ .jcf-list-box { overflow: hidden; display: inline-block; border: 1px solid #b8c3c9; min-width: 200px; margin: 0 15px; } /* select options styles */ .jcf-list { display: inline-block; vertical-align: top; position: relative; background: #fff; line-height: 14px; font-size: 12px; width: 100%; } .jcf-list .jcf-list-content { vertical-align: top; display: inline-block; overflow: auto; width: 100%; } .jcf-list ul { list-style: none; padding: 0; margin: 0; } .jcf-list ul li { overflow: hidden; display: block; } .jcf-list .jcf-overflow { overflow: auto; } .jcf-list .jcf-option { white-space: nowrap; overflow: hidden; cursor: default; display: block; padding: 5px 9px; color: #656565; height: 1%; } .jcf-list .jcf-disabled { background: #fff !important; color: #aaa !important; } .jcf-select-drop .jcf-hover, .jcf-list-box .jcf-selected { background: #e6e6e6; color: #000; } .jcf-list .jcf-optgroup-caption { white-space: nowrap; font-weight: bold; display: block; padding: 5px 9px; cursor: default; color: #000; } .jcf-list .jcf-optgroup .jcf-option { padding-left: 30px; } /* other styles */ .jcf-textarea { border: 1px solid #b8c3c9; box-sizing: content-box; display: inline-block; position: relative; } .jcf-textarea .jcf-scrollbar-horizontal { display: none; height: 0; } .jcf-textarea textarea { padding: 8px 10px; border: none; margin: 0; } .jcf-textarea .jcf-resize { position: absolute; text-align: center; cursor: se-resize; background: #e3e3e3; font-weight: bold; line-height: 15px; text-indent: 1px; font-size: 12px; height: 15px; width: 14px; bottom: 0; right: 0; } .jcf-textarea .jcf-resize:before { border: 1px solid #000; border-width: 0 1px 1px 0; display: block; margin: 4px 0 0 3px; width: 6px; height: 6px; content: ''; } /* number input */ .jcf-number { display: inline-block; position: relative; height: 32px; } .jcf-number input {-moz-appearance: textfield;} .jcf-number input::-webkit-inner-spin-button, .jcf-number input::-webkit-outer-spin-button {-webkit-appearance: none;} .jcf-number input { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; border: 1px solid #777; padding: 3px 27px 3px 7px; margin: 0; height: 100%; } .jcf-number .jcf-btn-dec, .jcf-number .jcf-btn-inc { position: absolute; background: #aaa; width: 20px; height: 15px; right: 1px; top: 1px; } .jcf-number .jcf-btn-dec { top: auto; bottom: 1px; } .jcf-number .jcf-btn-dec:hover, .jcf-number .jcf-btn-inc:hover { background: #e6e6e6; } .jcf-number.jcf-disabled .jcf-btn-dec:hover, .jcf-number.jcf-disabled .jcf-btn-inc:hover { background: #aaa; } .jcf-number .jcf-btn-dec:before, .jcf-number .jcf-btn-inc:before { position: absolute; content: ''; width: 0; height: 0; top: 50%; left: 50%; margin: -6px 0 0 -4px; border: 4px solid #aaa; border-color: transparent transparent #000 transparent; } .jcf-number .jcf-btn-dec:before { margin: -1px 0 0 -4px; border-color: #000 transparent transparent transparent; } .jcf-number.jcf-disabled .jcf-btn-dec:before, .jcf-number.jcf-disabled .jcf-btn-inc:before, .jcf-number .jcf-btn-dec.jcf-disabled:before, .jcf-number .jcf-btn-inc.jcf-disabled:before { opacity: 0.3; } .jcf-number.jcf-disabled input { background: #ddd; } /* range input */ .jcf-range { display: inline-block; min-width: 200px; margin: 0 10px; width: 130px; } .jcf-range .jcf-range-track { margin: 0 20px 0 0; position: relative; display: block; } .jcf-range .jcf-range-wrapper { background: #e5e5e5; border-radius: 5px; display: block; margin: 5px 0; height: 10px; } .jcf-range.jcf-vertical { min-width: 0; width: auto; } .jcf-range.jcf-vertical .jcf-range-wrapper { margin: 0; width: 10px; height: auto; padding: 20px 0 0; } .jcf-range.jcf-vertical .jcf-range-track { height: 180px; width: 10px; } .jcf-range.jcf-vertical .jcf-range-handle { left: -5px; top: auto; } .jcf-range .jcf-range-handle { position: absolute; background: #aaa; border-radius: 19px; width: 19px; height: 19px; margin: -4px 0 0; z-index: 1; top: 0; left: 0; } .jcf-range .jcf-range-mark { position: absolute; overflow: hidden; background: #000; width: 1px; height: 3px; top: -7px; margin: 0 0 0 9px; } .jcf-range.jcf-vertical .jcf-range-mark { margin: 0 0 9px; left: 14px; top: auto; width: 3px; height: 1px; } .jcf-range.jcf-focus .jcf-range-handle { border: 1px solid #f00; margin: -5px 0 0 -1px; } .jcf-range.jcf-disabled { background: none !important; opacity: 0.3; } /* common styles */ .jcf-disabled {background: #ddd !important;} .jcf-focus, .jcf-focus * {border-color: #f00 !important;}
sajochiu/cdnjs
ajax/libs/jcf/1.0.0/css/theme-minimal/jcf.css
CSS
mit
9,719
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _BootstrapTable = __webpack_require__(1); var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable); var _TableHeaderColumn = __webpack_require__(41); var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn); if (typeof window !== 'undefined') { window.BootstrapTable = _BootstrapTable2['default']; window.TableHeaderColumn = _TableHeaderColumn2['default']; } exports.BootstrapTable = _BootstrapTable2['default']; exports.TableHeaderColumn = _TableHeaderColumn2['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-alert: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _TableHeader = __webpack_require__(4); var _TableHeader2 = _interopRequireDefault(_TableHeader); var _TableBody = __webpack_require__(8); var _TableBody2 = _interopRequireDefault(_TableBody); var _paginationPaginationList = __webpack_require__(29); var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList); var _toolbarToolBar = __webpack_require__(31); var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar); var _TableFilter = __webpack_require__(32); var _TableFilter2 = _interopRequireDefault(_TableFilter); var _storeTableDataStore = __webpack_require__(33); var _util = __webpack_require__(34); var _util2 = _interopRequireDefault(_util); var _csv_export_util = __webpack_require__(35); var _csv_export_util2 = _interopRequireDefault(_csv_export_util); var _Filter = __webpack_require__(39); var BootstrapTable = (function (_Component) { _inherits(BootstrapTable, _Component); function BootstrapTable(props) { var _this = this; _classCallCheck(this, BootstrapTable); _get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props); this.handleSort = function (order, sortField) { if (_this.props.options.onSortChange) { _this.props.options.onSortChange(sortField, order, _this.props); } var result = _this.store.sort(order, sortField).get(); _this.setState({ data: result }); }; this.handlePaginationData = function (page, sizePerPage) { var onPageChange = _this.props.options.onPageChange; if (onPageChange) { onPageChange(page, sizePerPage); } if (_this.isRemoteDataSource()) { return; } var result = _this.store.page(page, sizePerPage).get(); _this.setState({ data: result, currPage: page, sizePerPage: sizePerPage }); }; this.handleMouseLeave = function () { if (_this.props.options.onMouseLeave) { _this.props.options.onMouseLeave(); } }; this.handleMouseEnter = function () { if (_this.props.options.onMouseEnter) { _this.props.options.onMouseEnter(); } }; this.handleRowMouseOut = function (row, event) { if (_this.props.options.onRowMouseOut) { _this.props.options.onRowMouseOut(row, event); } }; this.handleRowMouseOver = function (row, event) { if (_this.props.options.onRowMouseOver) { _this.props.options.onRowMouseOver(row, event); } }; this.handleRowClick = function (row) { if (_this.props.options.onRowClick) { _this.props.options.onRowClick(row); } }; this.handleSelectAllRow = function (e) { var isSelected = e.currentTarget.checked; var selectedRowKeys = []; var result = true; if (_this.props.selectRow.onSelectAll) { result = _this.props.selectRow.onSelectAll(isSelected, isSelected ? _this.store.get() : []); } if (typeof result === 'undefined' || result !== false) { if (isSelected) { selectedRowKeys = _this.store.getAllRowkey(); } _this.store.setSelectedRowKey(selectedRowKeys); _this.setState({ selectedRowKeys: selectedRowKeys }); } }; this.handleShowOnlySelected = function () { _this.store.ignoreNonSelected(); var result = undefined; if (_this.props.pagination) { result = _this.store.page(1, _this.state.sizePerPage).get(); } else { result = _this.store.get(); } _this.setState({ data: result, currPage: 1 }); }; this.handleSelectRow = function (row, isSelected) { var result = true; var currSelected = _this.store.getSelectedRowKeys(); var rowKey = row[_this.store.getKeyField()]; var selectRow = _this.props.selectRow; if (selectRow.onSelect) { result = selectRow.onSelect(row, isSelected); } if (typeof result === 'undefined' || result !== false) { if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) { currSelected = isSelected ? [rowKey] : []; } else { if (isSelected) { currSelected.push(rowKey); } else { currSelected = currSelected.filter(function (key) { return rowKey !== key; }); } } _this.store.setSelectedRowKey(currSelected); _this.setState({ selectedRowKeys: currSelected }); } }; this.handleAddRow = function (newObj) { try { _this.store.add(newObj); } catch (e) { return e; } _this._handleAfterAddingRow(newObj); }; this.getPageByRowKey = function (rowKey) { var sizePerPage = _this.state.sizePerPage; var currentData = _this.store.getCurrentDisplayData(); var keyField = _this.store.getKeyField(); var result = currentData.findIndex(function (x) { return x[keyField] === rowKey; }); if (result > -1) { return parseInt(result / sizePerPage, 10) + 1; } else { return result; } }; this.handleDropRow = function (rowKeys) { var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys(); // add confirm before the delete action if that option is set. if (dropRowKeys && dropRowKeys.length > 0) { if (_this.props.options.handleConfirmDeleteRow) { _this.props.options.handleConfirmDeleteRow(function () { _this.deleteRow(dropRowKeys); }, dropRowKeys); } else if (confirm('Are you sure want delete?')) { _this.deleteRow(dropRowKeys); } } }; this.handleFilterData = function (filterObj) { _this.store.filter(filterObj); var sortObj = _this.store.getSortInfo(); if (sortObj) { _this.store.sort(sortObj.order, sortObj.sortField); } var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterColumnFilter) { _this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result, currPage: 1 }); }; this.handleExportCSV = function () { var result = _this.store.getDataIgnoringPagination(); var keys = []; _this.props.children.map(function (column) { if (column.props.hidden === false) { keys.push(column.props.dataField); } }); (0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName); }; this.handleSearch = function (searchText) { _this.store.search(searchText); var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterSearch) { _this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result, currPage: 1 }); }; this._scrollHeader = function (e) { _this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft; }; this._adjustTable = function () { _this._adjustHeaderWidth(); _this._adjustHeight(); }; this._adjustHeaderWidth = function () { var header = _this.refs.header.refs.header; var headerContainer = _this.refs.header.refs.container; var tbody = _this.refs.body.refs.tbody; var firstRow = tbody.childNodes[0]; var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth; var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0; if (firstRow && _this.store.getDataNum()) { var cells = firstRow.childNodes; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var computedStyle = getComputedStyle(cell); var width = parseFloat(computedStyle.width.replace('px', '')); if (_this.isIE) { var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', '')); var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', '')); var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', '')); var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', '')); width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth; } var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0; if (width <= 0) { width = 120; cell.width = width + lastPadding + 'px'; } var result = width + lastPadding + 'px'; header.childNodes[i].style.width = result; header.childNodes[i].style.minWidth = result; } } }; this._adjustHeight = function () { if (_this.props.height.indexOf('%') === -1) { _this.refs.body.refs.container.style.height = parseFloat(_this.props.height, 10) - _this.refs.header.refs.container.offsetHeight + 'px'; } }; this.isIE = false; this._attachCellEditFunc(); if (_util2['default'].canUseDOM()) { this.isIE = document.documentMode; } this.store = new _storeTableDataStore.TableDataStore(this.props.data.slice()); this.initTable(this.props); if (this.filter) { this.filter.on('onFilterChange', function (currentFilter) { _this.handleFilterData(currentFilter); }); } if (this.props.selectRow && this.props.selectRow.selected) { var copy = this.props.selectRow.selected.slice(); this.store.setSelectedRowKey(copy); } this.state = { data: this.getTableData(), currPage: this.props.options.page || 1, sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0], selectedRowKeys: this.store.getSelectedRowKeys() }; } _createClass(BootstrapTable, [{ key: 'initTable', value: function initTable(props) { var _this2 = this; var keyField = props.keyField; var isKeyFieldDefined = typeof keyField === 'string' && keyField.length; _react2['default'].Children.forEach(props.children, function (column) { if (column.props.isKey) { if (keyField) { throw 'Error. Multiple key column be detected in TableHeaderColumn.'; } keyField = column.props.dataField; } if (column.props.filter) { // a column contains a filter if (!_this2.filter) { // first time create the filter on the BootstrapTable _this2.filter = new _Filter.Filter(); } // pass the filter to column with filter column.props.filter.emitter = _this2.filter; } }); var colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) { prev[curr.name] = curr; return prev; }, {}); if (!isKeyFieldDefined && !keyField) { throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.'; } this.store.setProps({ isPagination: props.pagination, keyField: keyField, colInfos: colInfos, multiColumnSearch: props.multiColumnSearch, remote: this.isRemoteDataSource() }); } }, { key: 'getTableData', value: function getTableData() { var _props = this.props; var options = _props.options; var pagination = _props.pagination; var result = []; if (options.sortName && options.sortOrder) { this.store.sort(options.sortOrder, options.sortName); } if (pagination) { var page = undefined; var sizePerPage = undefined; if (this.store.isChangedPage()) { sizePerPage = this.state.sizePerPage; page = this.state.currPage; } else { sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0]; page = options.page || 1; } result = this.store.page(page, sizePerPage).get(); } else { result = this.store.get(); } return result; } }, { key: 'getColumnsDescription', value: function getColumnsDescription(_ref) { var children = _ref.children; return _react2['default'].Children.map(children, function (column, i) { return { name: column.props.dataField, align: column.props.dataAlign, sort: column.props.dataSort, format: column.props.dataFormat, formatExtraData: column.props.formatExtraData, filterFormatted: column.props.filterFormatted, editable: column.props.editable, hidden: column.props.hidden, searchable: column.props.searchable, className: column.props.columnClassName, width: column.props.width, text: column.props.children, sortFunc: column.props.sortFunc, sortFuncExtraData: column.props.sortFuncExtraData, index: i }; }); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.initTable(nextProps); var options = nextProps.options; var selectRow = nextProps.selectRow; this.store.setData(nextProps.data.slice()); var page = options.page || this.state.currPage; var sizePerPage = options.sizePerPage || this.state.sizePerPage; // #125 if (!options.page && page >= Math.ceil(nextProps.data.length / sizePerPage)) { page = 1; } var sortInfo = this.store.getSortInfo(); var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined); var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined); if (sortField && sortOrder) this.store.sort(sortOrder, sortField); var data = this.store.page(page, sizePerPage).get(); this.setState({ data: data, currPage: page, sizePerPage: sizePerPage }); if (selectRow && selectRow.selected) { // set default select rows to store. var copy = selectRow.selected.slice(); this.store.setSelectedRowKey(copy); this.setState({ selectedRowKeys: copy }); } } }, { key: 'componentDidMount', value: function componentDidMount() { this._adjustTable(); window.addEventListener('resize', this._adjustTable); this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { window.removeEventListener('resize', this._adjustTable); this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader); if (this.filter) { this.filter.removeAllListeners('onFilterChange'); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this._adjustTable(); this._attachCellEditFunc(); if (this.props.options.afterTableComplete) { this.props.options.afterTableComplete(); } } }, { key: '_attachCellEditFunc', value: function _attachCellEditFunc() { var cellEdit = this.props.cellEdit; if (cellEdit) { this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this); if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) { this.props.selectRow.clickToSelect = false; } } } /** * Returns true if in the current configuration, * the datagrid should load its data remotely. * * @param {Object} [props] Optional. If not given, this.props will be used * @return {Boolean} */ }, { key: 'isRemoteDataSource', value: function isRemoteDataSource(props) { return (props || this.props).remote; } }, { key: 'render', value: function render() { var style = { height: this.props.height, maxHeight: this.props.maxHeight }; var columns = this.getColumnsDescription(this.props); var sortInfo = this.store.getSortInfo(); var pagination = this.renderPagination(); var toolBar = this.renderToolBar(); var tableFilter = this.renderTableFilter(columns); var isSelectAll = this.isSelectAll(); var sortIndicator = this.props.options.sortIndicator; if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true; return _react2['default'].createElement( 'div', { className: 'react-bs-table-container' }, toolBar, _react2['default'].createElement( 'div', { className: 'react-bs-table', ref: 'table', style: style, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2['default'].createElement( _TableHeader2['default'], { ref: 'header', rowSelectType: this.props.selectRow.mode, hideSelectColumn: this.props.selectRow.hideSelectColumn, sortName: sortInfo ? sortInfo.sortField : undefined, sortOrder: sortInfo ? sortInfo.order : undefined, sortIndicator: sortIndicator, onSort: this.handleSort, onSelectAllRow: this.handleSelectAllRow, bordered: this.props.bordered, condensed: this.props.condensed, isFiltered: this.filter ? true : false, isSelectAll: isSelectAll }, this.props.children ), _react2['default'].createElement(_TableBody2['default'], { ref: 'body', style: style, data: this.state.data, columns: columns, trClassName: this.props.trClassName, striped: this.props.striped, bordered: this.props.bordered, hover: this.props.hover, keyField: this.store.getKeyField(), condensed: this.props.condensed, selectRow: this.props.selectRow, cellEdit: this.props.cellEdit, selectedRowKeys: this.state.selectedRowKeys, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, noDataText: this.props.options.noDataText }) ), tableFilter, pagination ); } }, { key: 'isSelectAll', value: function isSelectAll() { var defaultSelectRowKeys = this.store.getSelectedRowKeys(); var allRowKeys = this.store.getAllRowkey(); if (defaultSelectRowKeys.length !== allRowKeys.length) { return defaultSelectRowKeys.length === 0 ? false : 'indeterminate'; } else { if (this.store.isEmpty()) { return false; } return true; } } }, { key: 'cleanSelected', value: function cleanSelected() { this.store.setSelectedRowKey([]); this.setState({ selectedRowKeys: [] }); } }, { key: 'handleEditCell', value: function handleEditCell(newVal, rowIndex, colIndex) { var _props$cellEdit = this.props.cellEdit; var beforeSaveCell = _props$cellEdit.beforeSaveCell; var afterSaveCell = _props$cellEdit.afterSaveCell; var fieldName = undefined; _react2['default'].Children.forEach(this.props.children, function (column, i) { if (i === colIndex) { fieldName = column.props.dataField; return false; } }); if (beforeSaveCell) { var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal); if (!isValid && typeof isValid !== 'undefined') { this.setState({ data: this.store.get() }); return; } } var result = this.store.edit(newVal, rowIndex, fieldName).get(); this.setState({ data: result }); if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } } }, { key: 'handleAddRowAtBegin', value: function handleAddRowAtBegin(newObj) { try { this.store.addAtBegin(newObj); } catch (e) { return e; } this._handleAfterAddingRow(newObj); } }, { key: 'getSizePerPage', value: function getSizePerPage() { return this.state.sizePerPage; } }, { key: 'getCurrentPage', value: function getCurrentPage() { return this.state.currPage; } }, { key: 'deleteRow', value: function deleteRow(dropRowKeys) { var result = undefined; this.store.remove(dropRowKeys); // remove selected Row this.store.setSelectedRowKey([]); // clear selected row key if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); var currPage = this.state.currPage; if (currPage > currLastPage) currPage = currLastPage; result = this.store.page(currPage, sizePerPage).get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys(), currPage: currPage }); } else { result = this.store.get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys() }); } if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } } }, { key: 'renderPagination', value: function renderPagination() { if (this.props.pagination) { var dataSize = undefined; if (this.isRemoteDataSource()) { dataSize = this.props.fetchInfo.dataTotalSize; } else { dataSize = this.store.getDataNum(); } var options = this.props.options; return _react2['default'].createElement( 'div', { className: 'react-bs-table-pagination' }, _react2['default'].createElement(_paginationPaginationList2['default'], { ref: 'pagination', currPage: this.state.currPage, changePage: this.handlePaginationData, sizePerPage: this.state.sizePerPage, sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST, paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE, remote: this.isRemoteDataSource(), dataSize: dataSize, onSizePerPageList: options.onSizePerPageList, prePage: options.prePage || _Const2['default'].PRE_PAGE, nextPage: options.nextPage || _Const2['default'].NEXT_PAGE, firstPage: options.firstPage || _Const2['default'].FIRST_PAGE, lastPage: options.lastPage || _Const2['default'].LAST_PAGE }) ); } return null; } }, { key: 'renderToolBar', value: function renderToolBar() { var _props2 = this.props; var selectRow = _props2.selectRow; var insertRow = _props2.insertRow; var deleteRow = _props2.deleteRow; var search = _props2.search; var children = _props2.children; var enableShowOnlySelected = selectRow && selectRow.showOnlySelected; if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) { var columns = undefined; if (Array.isArray(children)) { columns = children.map(function (column) { var props = column.props; return { name: props.children, field: props.dataField, // when you want same auto generate value and not allow edit, example ID field autoValue: props.autoValue || false, // for create editor, no params for column.editable() indicate that editor for new row editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable, format: props.dataFormat ? function (value) { return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, ''); } : false }; }); } else { columns = [{ name: children.props.children, field: children.props.dataField, editable: children.props.editable }]; } return _react2['default'].createElement( 'div', { className: 'react-bs-table-tool-bar' }, _react2['default'].createElement(_toolbarToolBar2['default'], { clearSearch: this.props.options.clearSearch, searchDelayTime: this.props.options.searchDelayTime, enableInsert: insertRow, enableDelete: deleteRow, enableSearch: search, enableExportCSV: this.props.exportCSV, enableShowOnlySelected: enableShowOnlySelected, columns: columns, searchPlaceholder: this.props.searchPlaceholder, exportCSVText: this.props.options.exportCSVText, ignoreEditable: this.props.options.ignoreEditable, onAddRow: this.handleAddRow, onDropRow: this.handleDropRow, onSearch: this.handleSearch, onExportCSV: this.handleExportCSV, onShowOnlySelected: this.handleShowOnlySelected }) ); } else { return null; } } }, { key: 'renderTableFilter', value: function renderTableFilter(columns) { if (this.props.columnFilter) { return _react2['default'].createElement(_TableFilter2['default'], { columns: columns, rowSelectType: this.props.selectRow.mode, onFilter: this.handleFilterData }); } else { return null; } } }, { key: '_handleAfterAddingRow', value: function _handleAfterAddingRow(newObj) { var result = undefined; if (this.props.pagination) { // if pagination is enabled and insert row be trigger, change to last page var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); result = this.store.page(currLastPage, sizePerPage).get(); this.setState({ data: result, currPage: currLastPage }); } else { result = this.store.get(); this.setState({ data: result }); } if (this.props.options.afterInsertRow) { this.props.options.afterInsertRow(newObj); } } }]); return BootstrapTable; })(_react.Component); BootstrapTable.propTypes = { keyField: _react.PropTypes.string, height: _react.PropTypes.string, maxHeight: _react.PropTypes.string, data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]), remote: _react.PropTypes.bool, // remote data, default is false striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, pagination: _react.PropTypes.bool, searchPlaceholder: _react.PropTypes.string, selectRow: _react.PropTypes.shape({ mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]), bgColor: _react.PropTypes.string, selected: _react.PropTypes.array, onSelect: _react.PropTypes.func, onSelectAll: _react.PropTypes.func, clickToSelect: _react.PropTypes.bool, hideSelectColumn: _react.PropTypes.bool, clickToSelectAndEditCell: _react.PropTypes.bool, showOnlySelected: _react.PropTypes.bool }), cellEdit: _react.PropTypes.shape({ mode: _react.PropTypes.string, blurToSave: _react.PropTypes.bool, beforeSaveCell: _react.PropTypes.func, afterSaveCell: _react.PropTypes.func }), insertRow: _react.PropTypes.bool, deleteRow: _react.PropTypes.bool, search: _react.PropTypes.bool, columnFilter: _react.PropTypes.bool, trClassName: _react.PropTypes.any, options: _react.PropTypes.shape({ clearSearch: _react.PropTypes.bool, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, sortIndicator: _react.PropTypes.bool, afterTableComplete: _react.PropTypes.func, afterDeleteRow: _react.PropTypes.func, afterInsertRow: _react.PropTypes.func, afterSearch: _react.PropTypes.func, afterColumnFilter: _react.PropTypes.func, onRowClick: _react.PropTypes.func, page: _react.PropTypes.number, sizePerPageList: _react.PropTypes.array, sizePerPage: _react.PropTypes.number, paginationSize: _react.PropTypes.number, onSortChange: _react.PropTypes.func, onPageChange: _react.PropTypes.func, onSizePerPageList: _react.PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), handleConfirmDeleteRow: _react.PropTypes.func, prePage: _react.PropTypes.string, nextPage: _react.PropTypes.string, firstPage: _react.PropTypes.string, lastPage: _react.PropTypes.string, searchDelayTime: _react.PropTypes.number, exportCSVText: _react.PropTypes.text, ignoreEditable: _react.PropTypes.bool }), fetchInfo: _react.PropTypes.shape({ dataTotalSize: _react.PropTypes.number }), exportCSV: _react.PropTypes.bool, csvFileName: _react.PropTypes.string }; BootstrapTable.defaultProps = { height: '100%', maxHeight: undefined, striped: false, bordered: true, hover: false, condensed: false, pagination: false, searchPlaceholder: undefined, selectRow: { mode: _Const2['default'].ROW_SELECT_NONE, bgColor: _Const2['default'].ROW_SELECT_BG_COLOR, selected: [], onSelect: undefined, onSelectAll: undefined, clickToSelect: false, hideSelectColumn: false, clickToSelectAndEditCell: false, showOnlySelected: false }, cellEdit: { mode: _Const2['default'].CELL_EDIT_NONE, blurToSave: false, beforeSaveCell: undefined, afterSaveCell: undefined }, insertRow: false, deleteRow: false, search: false, multiColumnSearch: false, columnFilter: false, trClassName: '', options: { clearSearch: false, sortName: undefined, sortOrder: undefined, sortIndicator: true, afterTableComplete: undefined, afterDeleteRow: undefined, afterInsertRow: undefined, afterSearch: undefined, afterColumnFilter: undefined, onRowClick: undefined, onMouseLeave: undefined, onMouseEnter: undefined, onRowMouseOut: undefined, onRowMouseOver: undefined, page: undefined, sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST, sizePerPage: undefined, paginationSize: _Const2['default'].PAGINATION_SIZE, onSizePerPageList: undefined, noDataText: undefined, handleConfirmDeleteRow: undefined, prePage: _Const2['default'].PRE_PAGE, nextPage: _Const2['default'].NEXT_PAGE, firstPage: _Const2['default'].FIRST_PAGE, lastPage: _Const2['default'].LAST_PAGE, searchDelayTime: undefined, exportCSVText: _Const2['default'].EXPORT_CSV_TEXT, ignoreEditable: false }, fetchInfo: { dataTotalSize: 0 }, exportCSV: false, csvFileName: undefined }; exports['default'] = BootstrapTable; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = { SORT_DESC: 'desc', SORT_ASC: 'asc', SIZE_PER_PAGE: 10, NEXT_PAGE: '>', LAST_PAGE: '>>', PRE_PAGE: '<', FIRST_PAGE: '<<', ROW_SELECT_BG_COLOR: '', ROW_SELECT_NONE: 'none', ROW_SELECT_SINGLE: 'radio', ROW_SELECT_MULTI: 'checkbox', CELL_EDIT_NONE: 'none', CELL_EDIT_CLICK: 'click', CELL_EDIT_DBCLICK: 'dbclick', SIZE_PER_PAGE_LIST: [10, 25, 30, 50], PAGINATION_SIZE: 5, NO_DATA_TEXT: 'There is no data to display', SHOW_ONLY_SELECT: 'Show Selected Only', SHOW_ALL: 'Show All', EXPORT_CSV_TEXT: 'Export to CSV', FILTER_DELAY: 500, FILTER_TYPE: { TEXT: 'TextFilter', REGEX: 'RegexFilter', SELECT: 'SelectFilter', NUMBER: 'NumberFilter', DATE: 'DateFilter', CUSTOM: 'CustomFilter' } }; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _SelectRowHeaderColumn = __webpack_require__(7); var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn); var Checkbox = (function (_Component) { _inherits(Checkbox, _Component); function Checkbox() { _classCallCheck(this, Checkbox); _get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments); } _createClass(Checkbox, [{ key: 'componentDidMount', value: function componentDidMount() { this.update(this.props.checked); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { this.update(props.checked); } }, { key: 'update', value: function update(checked) { _reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate'; } }, { key: 'render', value: function render() { return _react2['default'].createElement('input', { className: 'react-bs-select-all', type: 'checkbox', checked: this.props.checked, onChange: this.props.onChange }); } }]); return Checkbox; })(_react.Component); var TableHeader = (function (_Component2) { _inherits(TableHeader, _Component2); function TableHeader() { _classCallCheck(this, TableHeader); _get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments); } _createClass(TableHeader, [{ key: 'render', value: function render() { var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper'); var tableClasses = (0, _classnames2['default'])('table', 'table-hover', { 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed }); var selectRowHeaderCol = null; if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader(); this._attachClearSortCaretFunc(); return _react2['default'].createElement( 'div', { ref: 'container', className: containerClasses }, _react2['default'].createElement( 'table', { className: tableClasses }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { ref: 'header' }, selectRowHeaderCol, this.props.children ) ) ) ); } }, { key: 'renderSelectRowHeader', value: function renderSelectRowHeader() { if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) { return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null); } else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { return _react2['default'].createElement( _SelectRowHeaderColumn2['default'], null, _react2['default'].createElement(Checkbox, { onChange: this.props.onSelectAllRow, checked: this.props.isSelectAll }) ); } else { return null; } } }, { key: '_attachClearSortCaretFunc', value: function _attachClearSortCaretFunc() { var _props = this.props; var sortIndicator = _props.sortIndicator; var children = _props.children; var sortName = _props.sortName; var sortOrder = _props.sortOrder; var onSort = _props.onSort; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var _children$i$props = children[i].props; var dataField = _children$i$props.dataField; var dataSort = _children$i$props.dataSort; var sort = dataSort && dataField === sortName ? sortOrder : undefined; this.props.children[i] = _react2['default'].cloneElement(children[i], { key: i, onSort: onSort, sort: sort, sortIndicator: sortIndicator }); } } else { var _children$props = children.props; var dataField = _children$props.dataField; var dataSort = _children$props.dataSort; var sort = dataSort && dataField === sortName ? sortOrder : undefined; this.props.children = _react2['default'].cloneElement(children, { key: 0, onSort: onSort, sort: sort, sortIndicator: sortIndicator }); } } }]); return TableHeader; })(_react.Component); TableHeader.propTypes = { rowSelectType: _react.PropTypes.string, onSort: _react.PropTypes.func, onSelectAllRow: _react.PropTypes.func, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, hideSelectColumn: _react.PropTypes.bool, bordered: _react.PropTypes.bool, condensed: _react.PropTypes.bool, isFiltered: _react.PropTypes.bool, isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]), sortIndicator: _react.PropTypes.bool }; exports['default'] = TableHeader; module.exports = exports['default']; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var SelectRowHeaderColumn = (function (_Component) { _inherits(SelectRowHeaderColumn, _Component); function SelectRowHeaderColumn() { _classCallCheck(this, SelectRowHeaderColumn); _get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments); } _createClass(SelectRowHeaderColumn, [{ key: 'render', value: function render() { return _react2['default'].createElement( 'th', { style: { textAlign: 'center' } }, this.props.children ); } }]); return SelectRowHeaderColumn; })(_react.Component); SelectRowHeaderColumn.propTypes = { children: _react.PropTypes.node }; exports['default'] = SelectRowHeaderColumn; module.exports = exports['default']; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _TableRow = __webpack_require__(9); var _TableRow2 = _interopRequireDefault(_TableRow); var _TableColumn = __webpack_require__(10); var _TableColumn2 = _interopRequireDefault(_TableColumn); var _TableEditColumn = __webpack_require__(11); var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var isFun = function isFun(obj) { return obj && typeof obj === 'function'; }; var TableBody = (function (_Component) { _inherits(TableBody, _Component); function TableBody(props) { var _this = this; _classCallCheck(this, TableBody); _get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props); this.handleRowMouseOut = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOut(targetRow, event); }; this.handleRowMouseOver = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOver(targetRow, event); }; this.handleRowClick = function (rowIndex) { var selectedRow = undefined; var _props = _this.props; var data = _props.data; var onRowClick = _props.onRowClick; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; } }); onRowClick(selectedRow); }; this.handleSelectRow = function (rowIndex, isSelected) { var selectedRow = undefined; var _props2 = _this.props; var data = _props2.data; var onSelectRow = _props2.onSelectRow; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; return false; } }); onSelectRow(selectedRow, isSelected); }; this.handleSelectRowColumChange = function (e) { if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) { _this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked); } }; this.handleEditCell = function (rowIndex, columnIndex) { _this.editing = true; if (_this._isSelectRowDefined()) { columnIndex--; if (_this.props.selectRow.hideSelectColumn) columnIndex++; } rowIndex--; var stateObj = { currEditCell: { rid: rowIndex, cid: columnIndex } }; if (_this.props.selectRow.clickToSelectAndEditCell && _this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_DBCLICK) { var selected = _this.props.selectedRowKeys.indexOf(_this.props.data[rowIndex][_this.props.keyField]) !== -1; _this.handleSelectRow(rowIndex + 1, !selected); } _this.setState(stateObj); }; this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) { _this.setState({ currEditCell: null }); if (newVal !== null) { _this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex); } }; this.state = { currEditCell: null }; this.editing = false; } _createClass(TableBody, [{ key: 'render', value: function render() { var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-hover': this.props.hover, 'table-condensed': this.props.condensed }); var isSelectRowDefined = this._isSelectRowDefined(); var tableHeader = this.renderTableHeader(isSelectRowDefined); var tableRows = this.props.data.map(function (data, r) { var tableColumns = this.props.columns.map(function (column, i) { var fieldValue = data[column.name]; if (this.editing && column.name !== this.props.keyField && // Key field can't be edit column.editable && // column is editable? default is true, user can set it false this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) { var editable = column.editable; var format = column.format ? function (value) { return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, ''); } : false; if (isFun(column.editable)) { editable = column.editable(fieldValue, data, r, i); } return _react2['default'].createElement( _TableEditColumn2['default'], { completeEdit: this.handleCompleteEditCell, // add by bluespring for column editor customize editable: editable, format: column.format ? format : false, key: i, blurToSave: this.props.cellEdit.blurToSave, rowIndex: r, colIndex: i }, fieldValue ); } else { // add by bluespring for className customize var columnChild = fieldValue; var tdClassName = column.className; if (isFun(column.className)) { tdClassName = column.className(fieldValue, data, r, i); } if (typeof column.format !== 'undefined') { var formattedValue = column.format(fieldValue, data, column.formatExtraData); if (!_react2['default'].isValidElement(formattedValue)) { columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } }); } else { columnChild = formattedValue; } } return _react2['default'].createElement( _TableColumn2['default'], { key: i, dataAlign: column.align, className: tdClassName, cellEdit: this.props.cellEdit, hidden: column.hidden, onEdit: this.handleEditCell, width: column.width }, columnChild ); } }, this); var selected = this.props.selectedRowKeys.indexOf(data[this.props.keyField]) !== -1; var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected) : null; // add by bluespring for className customize var trClassName = this.props.trClassName; if (isFun(this.props.trClassName)) { trClassName = this.props.trClassName(data, r); } return _react2['default'].createElement( _TableRow2['default'], { isSelected: selected, key: r, className: trClassName, selectRow: isSelectRowDefined ? this.props.selectRow : undefined, enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow }, selectRowColumn, tableColumns ); }, this); if (tableRows.length === 0) { tableRows.push(_react2['default'].createElement( _TableRow2['default'], { key: '##table-empty##' }, _react2['default'].createElement( 'td', { colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0), className: 'react-bs-table-no-data' }, this.props.noDataText || _Const2['default'].NO_DATA_TEXT ) )); } this.editing = false; return _react2['default'].createElement( 'div', { ref: 'container', className: 'react-bs-container-body', style: this.props.style }, _react2['default'].createElement( 'table', { className: tableClasses }, tableHeader, _react2['default'].createElement( 'tbody', { ref: 'tbody' }, tableRows ) ) ); } }, { key: 'renderTableHeader', value: function renderTableHeader(isSelectRowDefined) { var selectRowHeader = null; if (isSelectRowDefined) { var style = { width: 30, minWidth: 30 }; if (!this.props.selectRow.hideSelectColumn) { selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 }); } } var theader = this.props.columns.map(function (column, i) { var width = column.width === null ? column.width : parseInt(column.width, 10); var style = { display: column.hidden ? 'none' : null, width: width, minWidth: width /** add min-wdth to fix user assign column width not eq offsetWidth in large column table **/ }; return _react2['default'].createElement('col', { style: style, key: i, className: column.className }); }); return _react2['default'].createElement( 'colgroup', { ref: 'header' }, selectRowHeader, theader ); } }, { key: 'renderSelectRowColumn', value: function renderSelectRowColumn(selected) { if (this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) { return _react2['default'].createElement( _TableColumn2['default'], { dataAlign: 'center' }, _react2['default'].createElement('input', { type: 'radio', checked: selected, onChange: this.handleSelectRowColumChange }) ); } else { return _react2['default'].createElement( _TableColumn2['default'], { dataAlign: 'center' }, _react2['default'].createElement('input', { type: 'checkbox', checked: selected, onChange: this.handleSelectRowColumChange }) ); } } }, { key: '_isSelectRowDefined', value: function _isSelectRowDefined() { return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI; } }]); return TableBody; })(_react.Component); TableBody.propTypes = { data: _react.PropTypes.array, columns: _react.PropTypes.array, striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, keyField: _react.PropTypes.string, selectedRowKeys: _react.PropTypes.array, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), style: _react.PropTypes.object }; exports['default'] = TableBody; module.exports = exports['default']; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var TableRow = (function (_Component) { _inherits(TableRow, _Component); function TableRow(props) { var _this = this; _classCallCheck(this, TableRow); _get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props); this.rowClick = function (e) { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') { (function () { var rowIndex = e.currentTarget.rowIndex + 1; if (_this.props.selectRow) { if (_this.props.selectRow.clickToSelect) { _this.props.onSelectRow(rowIndex, !_this.props.isSelected); } else if (_this.props.selectRow.clickToSelectAndEditCell) { _this.clickNum++; /** if clickToSelectAndEditCell is enabled, * there should be a delay to prevent a selection changed when * user dblick to edit cell on same row but different cell **/ setTimeout(function () { if (_this.clickNum === 1) { _this.props.onSelectRow(rowIndex, !_this.props.isSelected); } _this.clickNum = 0; }, 200); } } if (_this.props.onRowClick) _this.props.onRowClick(rowIndex); })(); } }; this.rowMouseOut = function (e) { if (_this.props.onRowMouseOut) { _this.props.onRowMouseOut(e.currentTarget.rowIndex, e); } }; this.rowMouseOver = function (e) { if (_this.props.onRowMouseOver) { _this.props.onRowMouseOver(e.currentTarget.rowIndex, e); } }; this.clickNum = 0; } _createClass(TableRow, [{ key: 'render', value: function render() { this.clickNum = 0; var trCss = { style: { backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null }, className: (this.props.isSelected && this.props.selectRow.className ? this.props.selectRow.className : '') + (this.props.className || '') }; if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) { return _react2['default'].createElement( 'tr', _extends({}, trCss, { onMouseOver: this.rowMouseOver, onMouseOut: this.rowMouseOut, onClick: this.rowClick }), this.props.children ); } else { return _react2['default'].createElement( 'tr', trCss, this.props.children ); } } }]); return TableRow; })(_react.Component); TableRow.propTypes = { isSelected: _react.PropTypes.bool, enableCellEdit: _react.PropTypes.bool, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func }; TableRow.defaultProps = { onRowClick: undefined }; exports['default'] = TableRow; module.exports = exports['default']; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var TableColumn = (function (_Component) { _inherits(TableColumn, _Component); function TableColumn(props) { var _this = this; _classCallCheck(this, TableColumn); _get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props); this.handleCellEdit = function (e) { if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } _this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex); }; } /* eslint no-unused-vars: [0, { "args": "after-used" }] */ _createClass(TableColumn, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var children = this.props.children; var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString(); if (shouldUpdated) { return shouldUpdated; } if (typeof children === 'object' && children !== null && children.props !== null) { if (children.props.type === 'checkbox' || children.props.type === 'radio') { shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked; } else { shouldUpdated = true; } } else { shouldUpdated = shouldUpdated || children !== nextProps.children; } if (shouldUpdated) { return shouldUpdated; } if (!(this.props.cellEdit && nextProps.cellEdit)) { return false; } else { return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode; } } }, { key: 'render', value: function render() { var tdStyle = { textAlign: this.props.dataAlign, display: this.props.hidden ? 'none' : null }; var opts = {}; if (this.props.cellEdit) { if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) { opts.onClick = this.handleCellEdit; } else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { opts.onDoubleClick = this.handleCellEdit; } } return _react2['default'].createElement( 'td', _extends({ style: tdStyle, className: this.props.className }, opts), this.props.children ); } }]); return TableColumn; })(_react.Component); TableColumn.propTypes = { dataAlign: _react.PropTypes.string, hidden: _react.PropTypes.bool, className: _react.PropTypes.string, children: _react.PropTypes.node }; TableColumn.defaultProps = { dataAlign: 'left', hidden: false, className: '' }; exports['default'] = TableColumn; module.exports = exports['default']; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var TableEditColumn = (function (_Component) { _inherits(TableEditColumn, _Component); function TableEditColumn(props) { var _this = this; _classCallCheck(this, TableEditColumn); _get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props); this.handleKeyPress = function (e) { if (e.keyCode === 13) { // Pressed ENTER var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } else if (e.keyCode === 27) { _this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex); } }; this.handleBlur = function (e) { if (_this.props.blurToSave) { var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } }; this.timeouteClear = 0; this.state = { shakeEditor: false }; } _createClass(TableEditColumn, [{ key: 'validator', value: function validator(value) { var ts = this; if (ts.props.editable.validator) { var valid = ts.props.editable.validator(value); if (!valid) { ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel'); var input = ts.refs.inputRef; // animate input ts.clearTimeout(); ts.setState({ shakeEditor: true }); ts.timeouteClear = setTimeout(function () { ts.setState({ shakeEditor: false }); }, 300); input.focus(); return false; } } return true; } }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear !== 0) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'componentDidMount', value: function componentDidMount() { this.refs.inputRef.focus(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'render', value: function render() { var _props = this.props; var editable = _props.editable; var format = _props.format; var children = _props.children; var shakeEditor = this.state.shakeEditor; var attr = { ref: 'inputRef', onKeyDown: this.handleKeyPress, onBlur: this.handleBlur }; // put placeholder if exist editable.placeholder && (attr.placeholder = editable.placeholder); var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor }); return _react2['default'].createElement( 'td', { ref: 'td', style: { position: 'relative' } }, (0, _Editor2['default'])(editable, attr, format, editorClass, children || ''), _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }) ); } }, { key: '_getCheckBoxValue', value: function _getCheckBoxValue(e) { var value = ''; var values = e.currentTarget.value.split(':'); value = e.currentTarget.checked ? values[0] : values[1]; return value; } }]); return TableEditColumn; })(_react.Component); TableEditColumn.propTypes = { completeEdit: _react.PropTypes.func, rowIndex: _react.PropTypes.number, colIndex: _react.PropTypes.number, blurToSave: _react.PropTypes.bool, editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]), format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), children: _react.PropTypes.node }; exports['default'] = TableEditColumn; module.exports = exports['default']; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) { if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') { // simple declare var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (!editable) { var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, disabled: 'disabled', className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable.type) { // standard declare // put style if exist editable.style && (attr.style = editable.style); // put class if exist attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : ''); if (editable.type === 'select') { // process select input var options = []; var values = editable.options.values; if (Array.isArray(values)) { (function () { // only can use arrray data for options var rowValue = undefined; options = values.map(function (d, i) { rowValue = format ? format(d) : d; return _react2['default'].createElement( 'option', { key: 'option' + i, value: d }, rowValue ); }); })(); } return _react2['default'].createElement( 'select', _extends({}, attr, { defaultValue: defaultValue }), options ); } else if (editable.type === 'textarea') { var _ret2 = (function () { // process textarea input // put other if exist editable.cols && (attr.cols = editable.cols); editable.rows && (attr.rows = editable.rows); var saveBtn = undefined; var keyUpHandler = attr.onKeyDown; if (keyUpHandler) { attr.onKeyDown = function (e) { if (e.keyCode !== 13) { // not Pressed ENTER keyUpHandler(e); } }; saveBtn = _react2['default'].createElement( 'button', { className: 'btn btn-info btn-xs textarea-save-btn', onClick: keyUpHandler }, 'save' ); } return { v: _react2['default'].createElement( 'div', null, _react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })), saveBtn ) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } else if (editable.type === 'checkbox') { var values = 'true:false'; if (editable.options && editable.options.values) { // values = editable.options.values.split(':'); values = editable.options.values; } attr.className = attr.className.replace('form-control', ''); attr.className += ' checkbox pull-right'; var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false; return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox', value: values, defaultChecked: checked })); } else { // process other input type. as password,url,email... return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue })); } } // default return for other case of editable return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', className: (editorClass || '') + ' form-control editor edit-text' })); }; exports['default'] = editor; module.exports = exports['default']; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactToastr = __webpack_require__(14); var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation); var Notification = (function (_Component) { _inherits(Notification, _Component); function Notification() { _classCallCheck(this, Notification); _get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments); } _createClass(Notification, [{ key: 'notice', // allow type is success,info,warning,error value: function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); } }, { key: 'render', value: function render() { return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr', toastMessageFactory: ToastrMessageFactory, id: 'toast-container', className: 'toast-top-right' }); } }]); return Notification; })(_react.Component); exports['default'] = Notification; module.exports = exports['default']; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ToastMessage = exports.ToastContainer = undefined; var _ToastContainer = __webpack_require__(15); var _ToastContainer2 = _interopRequireDefault(_ToastContainer); var _ToastMessage = __webpack_require__(22); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.ToastContainer = _ToastContainer2.default; exports.ToastMessage = _ToastMessage2.default; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _ToastMessage = __webpack_require__(22); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToastContainer = function (_Component) { _inherits(ToastContainer, _Component); function ToastContainer() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, ToastContainer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { toasts: [], toastId: 0, previousMessage: null }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(ToastContainer, [{ key: "error", value: function error(message, title, optionsOverride) { this._notify(this.props.toastType.error, message, title, optionsOverride); } }, { key: "info", value: function info(message, title, optionsOverride) { this._notify(this.props.toastType.info, message, title, optionsOverride); } }, { key: "success", value: function success(message, title, optionsOverride) { this._notify(this.props.toastType.success, message, title, optionsOverride); } }, { key: "warning", value: function warning(message, title, optionsOverride) { this._notify(this.props.toastType.warning, message, title, optionsOverride); } }, { key: "clear", value: function clear() { var _this2 = this; Object.keys(this.refs).forEach(function (key) { _this2.refs[key].hideToast(false); }); } }, { key: "render", value: function render() { var _this3 = this; return _react2.default.createElement( "div", _extends({}, this.props, { "aria-live": "polite", role: "alert" }), this.state.toasts.map(function (toast) { return _this3.props.toastMessageFactory(toast); }) ); } }, { key: "_notify", value: function _notify(type, message, title) { var _this4 = this; var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; if (this.props.preventDuplicates) { if (this.state.previousMessage === message) { return; } } var key = this.state.toastId++; var toastId = key; var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, { $merge: { type: type, title: title, message: message, toastId: toastId, key: key, ref: "toasts__" + key, handleOnClick: function handleOnClick(e) { if ("function" === typeof optionsOverride.handleOnClick) { optionsOverride.handleOnClick(); } return _this4._handle_toast_on_click(e); }, handleRemove: this._handle_toast_remove.bind(this) } }); var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]); var nextState = (0, _reactAddonsUpdate2.default)(this.state, { toasts: toastOperation, previousMessage: { $set: message } }); this.setState(nextState); } }, { key: "_handle_toast_on_click", value: function _handle_toast_on_click(event) { this.props.onClick(event); if (event.defaultPrevented) { return; } event.preventDefault(); event.stopPropagation(); } }, { key: "_handle_toast_remove", value: function _handle_toast_remove(toastId) { var _this5 = this; var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce"); this.state.toasts[operationName](function (found, toast, index) { if (found || toast.toastId !== toastId) { return false; } _this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, { toasts: { $splice: [[index, 1]] } })); return true; }, false); } }]); return ToastContainer; }(_react.Component); ToastContainer.defaultProps = { toastType: { error: "error", info: "info", success: "success", warning: "warning" }, id: "toast-container", toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default), preventDuplicates: false, newestOnTop: true, onClick: function onClick() {} }; exports.default = ToastContainer; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(17); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ /* global hasOwnProperty:true */ 'use strict'; var assign = __webpack_require__(19); var keyOf = __webpack_require__(20); var invariant = __webpack_require__(21); var hasOwnProperty = ({}).hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({ $push: null }); var COMMAND_UNSHIFT = keyOf({ $unshift: null }); var COMMAND_SPLICE = keyOf({ $splice: null }); var COMMAND_SET = keyOf({ $set: null }); var COMMAND_MERGE = keyOf({ $merge: null }); var COMMAND_APPLY = keyOf({ $apply: null }); var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function (command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined; var specValue = spec[command]; !Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined; } function update(value, spec) { !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined; !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined; assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined; !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 18 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 19 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jQuery = exports.animation = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _animationMixin = __webpack_require__(23); var _animationMixin2 = _interopRequireDefault(_animationMixin); var _jQueryMixin = __webpack_require__(28); var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function noop() {} var ToastMessageSpec = { displayName: "ToastMessage", getDefaultProps: function getDefaultProps() { var iconClassNames = { error: "toast-error", info: "toast-info", success: "toast-success", warning: "toast-warning" }; return { className: "toast", iconClassNames: iconClassNames, titleClassName: "toast-title", messageClassName: "toast-message", tapToDismiss: true, closeButton: false }; }, handleOnClick: function handleOnClick(event) { this.props.handleOnClick(event); if (this.props.tapToDismiss) { this.hideToast(true); } }, _handle_close_button_click: function _handle_close_button_click(event) { event.stopPropagation(); this.hideToast(true); }, _handle_remove: function _handle_remove() { this.props.handleRemove(this.props.toastId); }, _render_close_button: function _render_close_button() { return this.props.closeButton ? _react2.default.createElement("button", { className: "toast-close-button", role: "button", onClick: this._handle_close_button_click, dangerouslySetInnerHTML: { __html: "&times;" } }) : false; }, _render_title_element: function _render_title_element() { return this.props.title ? _react2.default.createElement( "div", { className: this.props.titleClassName }, this.props.title ) : false; }, _render_message_element: function _render_message_element() { return this.props.message ? _react2.default.createElement( "div", { className: this.props.messageClassName }, this.props.message ) : false; }, render: function render() { var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type]; return _react2.default.createElement( "div", { className: (0, _classnames2.default)(this.props.className, iconClassName), style: this.props.style, onClick: this.handleOnClick, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, this._render_close_button(), this._render_title_element(), this._render_message_element() ); } }; var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.animation" }, mixins: { $set: [_animationMixin2.default] } })); var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.jQuery" }, mixins: { $set: [_jQueryMixin2.default] } })); /* * assign default noop functions */ ToastMessageSpec.handleMouseEnter = noop; ToastMessageSpec.handleMouseLeave = noop; ToastMessageSpec.hideToast = noop; var ToastMessage = _react2.default.createClass(ToastMessageSpec); ToastMessage.animation = animation; ToastMessage.jQuery = jQuery; exports.default = ToastMessage; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _CSSCore = __webpack_require__(24); var _CSSCore2 = _interopRequireDefault(_CSSCore); var _ReactTransitionEvents = __webpack_require__(26); var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TICK = 17; var toString = Object.prototype.toString; exports.default = { getDefaultProps: function getDefaultProps() { return { transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate) showAnimation: "animated bounceIn", // or other animations from animate.css hideAnimation: "animated bounceOut", timeOut: 5000, extendedTimeOut: 1000 }; }, componentWillMount: function componentWillMount() { this.classNameQueue = []; this.isHiding = false; this.intervalId = null; }, componentDidMount: function componentDidMount() { var _this = this; this._is_mounted = true; this._show(); var node = _reactDom2.default.findDOMNode(this); var onHideComplete = function onHideComplete() { if (_this.isHiding) { _this._set_is_hiding(false); _ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete); _this._handle_remove(); } }; _ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, componentWillUnmount: function componentWillUnmount() { this._is_mounted = false; if (this.intervalId) { clearTimeout(this.intervalId); } }, _set_transition: function _set_transition(hide) { var animationType = hide ? "leave" : "enter"; var node = _reactDom2.default.findDOMNode(this); var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var endListener = function endListener(e) { if (e && e.target !== node) { return; } _CSSCore2.default.removeClass(node, className); _CSSCore2.default.removeClass(node, activeClassName); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); _CSSCore2.default.addClass(node, className); // Need to do this to actually trigger a transition. this._queue_class(activeClassName); }, _clear_transition: function _clear_transition(hide) { var node = _reactDom2.default.findDOMNode(this); var animationType = hide ? "leave" : "enter"; var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; _CSSCore2.default.removeClass(node, className); _CSSCore2.default.removeClass(node, activeClassName); }, _set_animation: function _set_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); var endListener = function endListener(e) { if (e && e.target !== node) { return; } animations.forEach(function (anim) { _CSSCore2.default.removeClass(node, anim); }); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); animations.forEach(function (anim) { _CSSCore2.default.addClass(node, anim); }); }, _get_animation_classes: function _get_animation_classes(hide) { var animations = hide ? this.props.hideAnimation : this.props.showAnimation; if ("[object Array]" === toString.call(animations)) { return animations; } else if ("string" === typeof animations) { return animations.split(" "); } }, _clear_animation: function _clear_animation(hide) { var _this2 = this; var animations = this._get_animation_classes(hide); animations.forEach(function (animation) { _CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation); }); }, _queue_class: function _queue_class(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this._flush_class_name_queue, TICK); } }, _flush_class_name_queue: function _flush_class_name_queue() { if (this._is_mounted) { this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this))); } this.classNameQueue.length = 0; this.timeout = null; }, _show: function _show() { if (this.props.transition) { this._set_transition(); } else if (this.props.showAnimation) { this._set_animation(); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.intervalId); this._set_interval_id(null); if (this.isHiding) { this._set_is_hiding(false); if (this.props.hideAnimation) { this._clear_animation(true); } else if (this.props.transition) { this._clear_transition(true); } } }, handleMouseLeave: function handleMouseLeave() { if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.isHiding || this.intervalId === null && !override) { return; } this._set_is_hiding(true); if (this.props.transition) { this._set_transition(true); } else if (this.props.hideAnimation) { this._set_animation(true); } else { this._handle_remove(); } }, _set_interval_id: function _set_interval_id(intervalId) { this.intervalId = intervalId; }, _set_is_hiding: function _set_is_hiding(isHiding) { this.isHiding = isHiding; } }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSCore * @typechecks */ 'use strict'; var invariant = __webpack_require__(25); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined; if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function (element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to set the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function (element, className) { !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined; if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; } }; module.exports = CSSCore; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(27); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; /***/ }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function call_show_method($node, props) { $node[props.showMethod]({ duration: props.showDuration, easing: props.showEasing }); } exports.default = { getDefaultProps: function getDefaultProps() { return { style: { display: "none" }, // effective $.hide() showMethod: "fadeIn", // slideDown, and show are built into jQuery showDuration: 300, showEasing: "swing", // and linear are built into jQuery hideMethod: "fadeOut", hideDuration: 1000, hideEasing: "swing", // timeOut: 5000, extendedTimeOut: 1000 }; }, getInitialState: function getInitialState() { return { intervalId: null, isHiding: false }; }, componentDidMount: function componentDidMount() { call_show_method(this._get_$_node(), this.props); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.state.intervalId); this._set_interval_id(null); this._set_is_hiding(false); call_show_method(this._get_$_node().stop(true, true), this.props); }, handleMouseLeave: function handleMouseLeave() { if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.state.isHiding || this.state.intervalId === null && !override) { return; } this.setState({ isHiding: true }); this._get_$_node()[this.props.hideMethod]({ duration: this.props.hideDuration, easing: this.props.hideEasing, complete: this._handle_remove }); }, _get_$_node: function _get_$_node() { /* eslint-disable no-undef */ return jQuery(_reactDom2.default.findDOMNode(this)); /* eslint-enable no-undef */ }, _set_interval_id: function _set_interval_id(intervalId) { this.setState({ intervalId: intervalId }); }, _set_is_hiding: function _set_is_hiding(isHiding) { this.setState({ isHiding: isHiding }); } }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _PageButtonJs = __webpack_require__(30); var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var PaginationList = (function (_Component) { _inherits(PaginationList, _Component); function PaginationList() { var _this = this; _classCallCheck(this, PaginationList); _get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments); this.changePage = function (page) { var _props = _this.props; var prePage = _props.prePage; var currPage = _props.currPage; var nextPage = _props.nextPage; var lastPage = _props.lastPage; var firstPage = _props.firstPage; var sizePerPage = _props.sizePerPage; if (page === prePage) { page = currPage - 1 < 1 ? 1 : currPage - 1; } else if (page === nextPage) { page = currPage + 1 > _this.totalPages ? _this.totalPages : currPage + 1; } else if (page === lastPage) { page = _this.totalPages; } else if (page === firstPage) { page = 1; } else { page = parseInt(page, 10); } if (page !== currPage) { _this.props.changePage(page, sizePerPage); } }; this.changeSizePerPage = function (e) { e.preventDefault(); var selectSize = parseInt(e.currentTarget.text, 10); var currPage = _this.props.currPage; if (selectSize !== _this.props.sizePerPage) { _this.totalPages = Math.ceil(_this.props.dataSize / selectSize); if (currPage > _this.totalPages) currPage = _this.totalPages; _this.props.changePage(currPage, selectSize); if (_this.props.onSizePerPageList) { _this.props.onSizePerPageList(selectSize); } } }; } _createClass(PaginationList, [{ key: 'render', value: function render() { var _this2 = this; var _props2 = this.props; var dataSize = _props2.dataSize; var sizePerPage = _props2.sizePerPage; var sizePerPageList = _props2.sizePerPageList; this.totalPages = Math.ceil(dataSize / sizePerPage); var pageBtns = this.makePage(); var pageListStyle = { float: 'right', // override the margin-top defined in .pagination class in bootstrap. marginTop: '0px' }; var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) { return _react2['default'].createElement( 'li', { key: _sizePerPage, role: 'presentation' }, _react2['default'].createElement( 'a', { role: 'menuitem', tabIndex: '-1', href: '#', onClick: _this2.changeSizePerPage }, _sizePerPage ) ); }); return _react2['default'].createElement( 'div', { className: 'row', style: { marginTop: 15 } }, sizePerPageList.length > 1 ? _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'div', { className: 'dropdown' }, _react2['default'].createElement( 'button', { className: 'btn btn-default dropdown-toggle', type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown', 'aria-expanded': 'true' }, sizePerPage, _react2['default'].createElement( 'span', null, ' ', _react2['default'].createElement('span', { className: 'caret' }) ) ), _react2['default'].createElement( 'ul', { className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' }, sizePerPageOptions ) ) ), _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) : _react2['default'].createElement( 'div', { className: 'col-md-12' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ); } }, { key: 'makePage', value: function makePage() { var pages = this.getPages(); return pages.map(function (page) { var isActive = page === this.props.currPage; var disabled = false; var hidden = false; if (this.props.currPage === 1 && (page === this.props.firstPage || page === this.props.prePage)) { disabled = true; hidden = true; } if (this.props.currPage === this.totalPages && (page === this.props.nextPage || page === this.props.lastPage)) { disabled = true; hidden = true; } return _react2['default'].createElement( _PageButtonJs2['default'], { key: page, changePage: this.changePage, active: isActive, disable: disabled, hidden: hidden }, page ); }, this); } }, { key: 'getPages', value: function getPages() { var pages = undefined; var startPage = 1; var endPage = this.totalPages; startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), 1); endPage = startPage + this.props.paginationSize - 1; if (endPage > this.totalPages) { endPage = this.totalPages; startPage = endPage - this.props.paginationSize + 1; } if (startPage !== 1 && this.totalPages > this.props.paginationSize) { pages = [this.props.firstPage, this.props.prePage]; } else if (this.totalPages > 1) { pages = [this.props.prePage]; } else { pages = []; } for (var i = startPage; i <= endPage; i++) { if (i > 0) pages.push(i); } if (endPage !== this.totalPages) { pages.push(this.props.nextPage); pages.push(this.props.lastPage); } else if (this.totalPages > 1) { pages.push(this.props.nextPage); } return pages; } }]); return PaginationList; })(_react.Component); PaginationList.propTypes = { currPage: _react.PropTypes.number, sizePerPage: _react.PropTypes.number, dataSize: _react.PropTypes.number, changePage: _react.PropTypes.func, sizePerPageList: _react.PropTypes.array, paginationSize: _react.PropTypes.number, remote: _react.PropTypes.bool, onSizePerPageList: _react.PropTypes.func, prePage: _react.PropTypes.string }; PaginationList.defaultProps = { sizePerPage: _Const2['default'].SIZE_PER_PAGE }; exports['default'] = PaginationList; module.exports = exports['default']; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var PageButton = (function (_Component) { _inherits(PageButton, _Component); function PageButton(props) { var _this = this; _classCallCheck(this, PageButton); _get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props); this.pageBtnClick = function (e) { e.preventDefault(); _this.props.changePage(e.currentTarget.textContent); }; } _createClass(PageButton, [{ key: 'render', value: function render() { var classes = (0, _classnames2['default'])({ 'active': this.props.active, 'disabled': this.props.disable, 'hidden': this.props.hidden }); return _react2['default'].createElement( 'li', { className: classes }, _react2['default'].createElement( 'a', { href: '#', onClick: this.pageBtnClick }, this.props.children ) ); } }]); return PageButton; })(_react.Component); PageButton.propTypes = { changePage: _react.PropTypes.func, active: _react.PropTypes.bool, disable: _react.PropTypes.bool, hidden: _react.PropTypes.bool, children: _react.PropTypes.node }; exports['default'] = PageButton; module.exports = exports['default']; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var ToolBar = (function (_Component) { _inherits(ToolBar, _Component); _createClass(ToolBar, null, [{ key: 'modalSeq', value: 0, enumerable: true }]); function ToolBar(props) { var _this = this, _arguments2 = arguments; _classCallCheck(this, ToolBar); _get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props); this.handleSaveBtnClick = function () { var newObj = _this.checkAndParseForm(); if (!newObj) { // validate errors return; } var msg = _this.props.onAddRow(newObj); if (msg) { _this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel'); _this.clearTimeout(); // shake form and hack prevent modal hide _this.setState({ shakeEditor: true, validateState: 'this is hack for prevent bootstrap modal hide' }); // clear animate class _this.timeouteClear = setTimeout(function () { _this.setState({ shakeEditor: false }); }, 300); } else { // reset state and hide modal hide _this.setState({ validateState: null, shakeEditor: false }, function () { document.querySelector('.modal-backdrop').click(); document.querySelector('.' + _this.modalClassName).click(); }); // reset form _this.refs.form.reset(); } }; this.handleShowOnlyToggle = function () { _this.setState({ showSelected: !_this.state.showSelected }); _this.props.onShowOnlySelected(); }; this.handleDropRowBtnClick = function () { _this.props.onDropRow(); }; this.handleDebounce = function (func, wait, immediate) { var timeout = undefined; return function () { var later = function later() { timeout = null; if (!immediate) { func.apply(_this, _arguments2); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait || 0); if (callNow) { func.appy(_this, _arguments2); } }; }; this.handleKeyUp = function (event) { event.persist(); _this.debounceCallback(event); }; this.handleExportCSV = function () { _this.props.onExportCSV(); }; this.handleClearBtnClick = function () { _this.refs.seachInput.value = ''; _this.props.onSearch(''); }; this.timeouteClear = 0; this.modalClassName; this.state = { isInsertRowTrigger: true, validateState: null, shakeEditor: false, showSelected: false }; } _createClass(ToolBar, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0; this.debounceCallback = this.handleDebounce(function () { _this2.props.onSearch(_this2.refs.seachInput.value); }, delay); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'checkAndParseForm', value: function checkAndParseForm() { var _this3 = this; var newObj = {}; var validateState = {}; var isValid = true; var tempValue = undefined; var tempMsg = undefined; this.props.columns.forEach(function (column, i) { if (column.autoValue) { // when you want same auto generate value and not allow edit, example ID field var time = new Date().getTime(); tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time; } else { var dom = this.refs[column.field + i]; tempValue = dom.value; if (column.editable && column.editable.type === 'checkbox') { var values = tempValue.split(':'); tempValue = dom.checked ? values[0] : values[1]; } if (column.editable && column.editable.validator) { // process validate tempMsg = column.editable.validator(tempValue); if (tempMsg !== true) { isValid = false; validateState[column.field] = tempMsg; } } } newObj[column.field] = tempValue; }, this); if (isValid) { return newObj; } else { this.clearTimeout(); // show error in form and shake it this.setState({ validateState: validateState, shakeEditor: true }); // notifier error this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel'); // clear animate class this.timeouteClear = setTimeout(function () { _this3.setState({ shakeEditor: false }); }, 300); return null; } } }, { key: 'handleCloseBtn', value: function handleCloseBtn() { this.refs.warning.style.display = 'none'; } }, { key: 'render', value: function render() { this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++; var insertBtn = null; var deleteBtn = null; var exportCSV = null; var showSelectedOnlyBtn = null; if (this.props.enableInsert) { insertBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-info react-bs-table-add-btn', 'data-toggle': 'modal', 'data-target': '.' + this.modalClassName }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }), ' New' ); } if (this.props.enableDelete) { deleteBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-warning react-bs-table-del-btn', 'data-toggle': 'tooltip', 'data-placement': 'right', title: 'Drop selected row', onClick: this.handleDropRowBtnClick }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }), ' Delete' ); } if (this.props.enableShowOnlySelected) { showSelectedOnlyBtn = _react2['default'].createElement( 'button', { type: 'button', onClick: this.handleShowOnlyToggle, className: 'btn btn-primary', 'data-toggle': 'button', 'aria-pressed': 'false' }, this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT ); } if (this.props.enableExportCSV) { exportCSV = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-success', onClick: this.handleExportCSV }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }), this.props.exportCSVText ); } var searchTextInput = this.renderSearchPanel(); var modal = this.props.enableInsert ? this.renderInsertRowModal() : null; return _react2['default'].createElement( 'div', { className: 'row' }, _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' }, _react2['default'].createElement( 'div', { className: 'btn-group btn-group-sm', role: 'group' }, exportCSV, insertBtn, deleteBtn, showSelectedOnlyBtn ) ), _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' }, searchTextInput ), _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }), modal ); } }, { key: 'renderSearchPanel', value: function renderSearchPanel() { if (this.props.enableSearch) { var classNames = 'form-group form-group-sm react-bs-table-search-form'; var clearBtn = null; if (this.props.clearSearch) { clearBtn = _react2['default'].createElement( 'span', { className: 'input-group-btn' }, _react2['default'].createElement( 'button', { className: 'btn btn-default', type: 'button', onClick: this.handleClearBtnClick }, 'Clear' ) ); classNames += ' input-group input-group-sm'; } return _react2['default'].createElement( 'div', { className: classNames }, _react2['default'].createElement('input', { ref: 'seachInput', className: 'form-control', type: 'text', placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search', onKeyUp: this.handleKeyUp }), clearBtn ); } else { return null; } } }, { key: 'renderInsertRowModal', value: function renderInsertRowModal() { var _this4 = this; var validateState = this.state.validateState || {}; var shakeEditor = this.state.shakeEditor; var inputField = this.props.columns.map(function (column, i) { var editable = column.editable; var format = column.format; var field = column.field; var name = column.name; var autoValue = column.autoValue; var attr = { ref: field + i, placeholder: editable.placeholder ? editable.placeholder : name }; if (autoValue) { // when you want same auto generate value // and not allow edit, for example ID field return null; } var error = validateState[field] ? _react2['default'].createElement( 'span', { className: 'help-block bg-danger' }, validateState[field] ) : null; // let editor = Editor(editable,attr,format); // if(editor.props.type && editor.props.type == 'checkbox'){ return _react2['default'].createElement( 'div', { className: 'form-group', key: field }, _react2['default'].createElement( 'label', null, name ), (0, _Editor2['default'])(editable, attr, format, '', undefined, _this4.props.ignoreEditable), error ); }); var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, { // hack prevent bootstrap modal hide by reRender 'in': shakeEditor || this.state.validateState }); var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', { 'animated': shakeEditor, 'shake': shakeEditor }); return _react2['default'].createElement( 'div', { ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' }, _react2['default'].createElement( 'div', { className: dialogClass }, _react2['default'].createElement( 'div', { className: 'modal-content' }, _react2['default'].createElement( 'div', { className: 'modal-header' }, _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '×' ) ), _react2['default'].createElement( 'h4', { className: 'modal-title' }, 'New Record' ) ), _react2['default'].createElement( 'div', { className: 'modal-body' }, _react2['default'].createElement( 'form', { ref: 'form' }, inputField ) ), _react2['default'].createElement( 'div', { className: 'modal-footer' }, _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-default', 'data-dismiss': 'modal' }, 'Close' ), _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-info', onClick: this.handleSaveBtnClick }, 'Save' ) ) ) ) ); } }]); return ToolBar; })(_react.Component); ToolBar.propTypes = { onAddRow: _react.PropTypes.func, onDropRow: _react.PropTypes.func, onShowOnlySelected: _react.PropTypes.func, enableInsert: _react.PropTypes.bool, enableDelete: _react.PropTypes.bool, enableSearch: _react.PropTypes.bool, enableShowOnlySelected: _react.PropTypes.bool, columns: _react.PropTypes.array, searchPlaceholder: _react.PropTypes.string, exportCSVText: _react.PropTypes.string, clearSearch: _react.PropTypes.bool, ignoreEditable: _react.PropTypes.bool }; ToolBar.defaultProps = { enableInsert: false, enableDelete: false, enableSearch: false, enableShowOnlySelected: false, clearSearch: false, ignoreEditable: false }; exports['default'] = ToolBar; module.exports = exports['default']; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var TableFilter = (function (_Component) { _inherits(TableFilter, _Component); function TableFilter(props) { var _this = this; _classCallCheck(this, TableFilter); _get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props); this.handleKeyUp = function (e) { var _e$currentTarget = e.currentTarget; var value = _e$currentTarget.value; var name = _e$currentTarget.name; if (value.trim() === '') { delete _this.filterObj[name]; } else { _this.filterObj[name] = value; } _this.props.onFilter(_this.filterObj); }; this.filterObj = {}; } _createClass(TableFilter, [{ key: 'render', value: function render() { var _props = this.props; var striped = _props.striped; var condensed = _props.condensed; var rowSelectType = _props.rowSelectType; var columns = _props.columns; var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': striped, 'table-condensed': condensed }); var selectRowHeader = null; if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { var style = { width: 35, paddingLeft: 0, paddingRight: 0 }; selectRowHeader = _react2['default'].createElement( 'th', { style: style, key: -1 }, 'Filter' ); } var filterField = columns.map(function (column) { var hidden = column.hidden; var width = column.width; var name = column.name; var thStyle = { display: hidden ? 'none' : null, width: width }; return _react2['default'].createElement( 'th', { key: name, style: thStyle }, _react2['default'].createElement( 'div', { className: 'th-inner table-header-column' }, _react2['default'].createElement('input', { size: '10', type: 'text', placeholder: name, name: name, onKeyUp: this.handleKeyUp }) ) ); }, this); return _react2['default'].createElement( 'table', { className: tableClasses, style: { marginTop: 5 } }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { style: { borderBottomStyle: 'hidden' } }, selectRowHeader, filterField ) ) ); } }]); return TableFilter; })(_react.Component); TableFilter.propTypes = { columns: _react.PropTypes.array, rowSelectType: _react.PropTypes.string, onFilter: _react.PropTypes.func }; exports['default'] = TableFilter; module.exports = exports['default']; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-nested-ternary: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ /* eslint eqeqeq: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); function _sort(arr, sortField, order, sortFunc, sortFuncExtraData) { order = order.toLowerCase(); var isDesc = order === _Const2['default'].SORT_DESC; arr.sort(function (a, b) { if (sortFunc) { return sortFunc(a, b, order, sortField, sortFuncExtraData); } else { if (isDesc) { if (b[sortField] === null) return false; if (a[sortField] === null) return true; if (typeof b[sortField] === 'string') { return b[sortField].localeCompare(a[sortField]); } else { return a[sortField] > b[sortField] ? -1 : a[sortField] < b[sortField] ? 1 : 0; } } else { if (b[sortField] === null) return true; if (a[sortField] === null) return false; if (typeof a[sortField] === 'string') { return a[sortField].localeCompare(b[sortField]); } else { return a[sortField] < b[sortField] ? -1 : a[sortField] > b[sortField] ? 1 : 0; } } } }); return arr; } var TableDataStore = (function () { function TableDataStore(data) { _classCallCheck(this, TableDataStore); this.data = data; this.colInfos = null; this.filteredData = null; this.isOnFilter = false; this.filterObj = null; this.searchText = null; this.sortObj = null; this.pageObj = {}; this.selected = []; this.multiColumnSearch = false; this.showOnlySelected = false; this.remote = false; // remote data } _createClass(TableDataStore, [{ key: 'setProps', value: function setProps(props) { this.keyField = props.keyField; this.enablePagination = props.isPagination; this.colInfos = props.colInfos; this.remote = props.remote; this.multiColumnSearch = props.multiColumnSearch; } }, { key: 'setData', value: function setData(data) { this.data = data; this._refresh(); } }, { key: 'getSortInfo', value: function getSortInfo() { return this.sortObj; } }, { key: 'setSelectedRowKey', value: function setSelectedRowKey(selectedRowKeys) { this.selected = selectedRowKeys; } }, { key: 'getSelectedRowKeys', value: function getSelectedRowKeys() { return this.selected; } }, { key: 'getCurrentDisplayData', value: function getCurrentDisplayData() { if (this.isOnFilter) return this.filteredData;else return this.data; } }, { key: '_refresh', value: function _refresh() { if (this.isOnFilter) { if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } if (this.sortObj) { this.sort(this.sortObj.order, this.sortObj.sortField); } } }, { key: 'ignoreNonSelected', value: function ignoreNonSelected() { var _this = this; this.showOnlySelected = !this.showOnlySelected; if (this.showOnlySelected) { this.isOnFilter = true; this.filteredData = this.data.filter(function (row) { var result = _this.selected.find(function (x) { return row[_this.keyField] === x; }); return typeof result !== 'undefined' ? true : false; }); } else { this.isOnFilter = false; } } }, { key: 'sort', value: function sort(order, sortField) { this.sortObj = { order: order, sortField: sortField }; var currentDisplayData = this.getCurrentDisplayData(); if (!this.colInfos[sortField]) return this; var _colInfos$sortField = this.colInfos[sortField]; var sortFunc = _colInfos$sortField.sortFunc; var sortFuncExtraData = _colInfos$sortField.sortFuncExtraData; currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc, sortFuncExtraData); return this; } }, { key: 'page', value: function page(_page, sizePerPage) { this.pageObj.end = _page * sizePerPage - 1; this.pageObj.start = this.pageObj.end - (sizePerPage - 1); return this; } }, { key: 'edit', value: function edit(newVal, rowIndex, fieldName) { var currentDisplayData = this.getCurrentDisplayData(); var rowKeyCache = undefined; if (!this.enablePagination) { currentDisplayData[rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[rowIndex][this.keyField]; } else { currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField]; } if (this.isOnFilter) { this.data.forEach(function (row) { if (row[this.keyField] === rowKeyCache) { row[fieldName] = newVal; } }, this); if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } return this; } }, { key: 'addAtBegin', value: function addAtBegin(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.unshift(newObj); if (this.isOnFilter) { this.data.unshift(newObj); } this._refresh(); } }, { key: 'add', value: function add(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.push(newObj); if (this.isOnFilter) { this.data.push(newObj); } this._refresh(); } }, { key: 'remove', value: function remove(rowKey) { var _this2 = this; var currentDisplayData = this.getCurrentDisplayData(); var result = currentDisplayData.filter(function (row) { return rowKey.indexOf(row[_this2.keyField]) === -1; }); if (this.isOnFilter) { this.data = this.data.filter(function (row) { return rowKey.indexOf(row[_this2.keyField]) === -1; }); this.filteredData = result; } else { this.data = result; } } }, { key: 'filter', value: function filter(filterObj) { var _this3 = this; if (Object.keys(filterObj).length === 0) { this.filteredData = null; this.isOnFilter = false; this.filterObj = null; if (this.searchText !== null) this.search(this.searchText); } else { this.filterObj = filterObj; this.filteredData = this.data.filter(function (row) { var valid = true; var filterVal = undefined; for (var key in filterObj) { var targetVal = row[key]; switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { filterVal = filterObj[key].value.number; break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; break; } case _Const2['default'].FILTER_TYPE.REGEX: { filterVal = filterObj[key].value; break; } default: { filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; if (filterVal === undefined) { // Support old filter filterVal = filterObj[key].toLowerCase(); } break; } } if (_this3.colInfos[key]) { var _colInfos$key = _this3.colInfos[key]; var format = _colInfos$key.format; var filterFormatted = _colInfos$key.filterFormatted; var formatExtraData = _colInfos$key.formatExtraData; if (filterFormatted && format) { targetVal = format(row[key], row, formatExtraData); } } switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { valid = _this3.filterNumber(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2['default'].FILTER_TYPE.DATE: { valid = _this3.filterDate(targetVal, filterVal); break; } case _Const2['default'].FILTER_TYPE.REGEX: { valid = _this3.filterRegex(targetVal, filterVal); break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { valid = _this3.filterCustom(targetVal, filterVal, filterObj[key].value); break; } default: { valid = _this3.filterText(targetVal, filterVal); break; } } if (!valid) { break; } } return valid; }); this.isOnFilter = true; } } }, { key: 'filterNumber', value: function filterNumber(targetVal, filterVal, comparator) { var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Number comparator provided is not supported'); break; } } return valid; } }, { key: 'filterDate', value: function filterDate(targetVal, filterVal) { if (!targetVal) { return false; } return targetVal.getDate() === filterVal.getDate() && targetVal.getMonth() === filterVal.getMonth() && targetVal.getFullYear() === filterVal.getFullYear(); } }, { key: 'filterRegex', value: function filterRegex(targetVal, filterVal) { try { return new RegExp(filterVal, 'i').test(targetVal); } catch (e) { console.error('Invalid regular expression'); return true; } } }, { key: 'filterCustom', value: function filterCustom(targetVal, filterVal, callbackInfo) { if (callbackInfo !== null && typeof callbackInfo === 'object') { return callbackInfo.callback(targetVal, callbackInfo.callbackParameters); } return this.filterText(targetVal, filterVal); } }, { key: 'filterText', value: function filterText(targetVal, filterVal) { if (targetVal.toString().toLowerCase().indexOf(filterVal) === -1) { return false; } return true; } /* General search function * It will search for the text if the input includes that text; */ }, { key: 'search', value: function search(searchText) { var _this4 = this; if (searchText.trim() === '') { this.filteredData = null; this.isOnFilter = false; this.searchText = null; if (this.filterObj !== null) this.filter(this.filterObj); } else { (function () { _this4.searchText = searchText; var searchTextArray = []; if (_this4.multiColumnSearch) { searchTextArray = searchText.split(' '); } else { searchTextArray.push(searchText); } // Mark following code for fixing #363 // To avoid to search on a data which be searched or filtered // But this solution have a poor performance, because I do a filter again // const source = this.isOnFilter ? this.filteredData : this.data; var source = _this4.filterObj !== null ? _this4.filter(_this4.filterObj) : _this4.data; _this4.filteredData = source.filter(function (row) { var keys = Object.keys(row); var valid = false; // for loops are ugly, but performance matters here. // And you cant break from a forEach. // http://jsperf.com/for-vs-foreach/66 for (var i = 0, keysLength = keys.length; i < keysLength; i++) { var key = keys[i]; if (_this4.colInfos[key] && row[key]) { var _colInfos$key2 = _this4.colInfos[key]; var format = _colInfos$key2.format; var filterFormatted = _colInfos$key2.filterFormatted; var formatExtraData = _colInfos$key2.formatExtraData; var searchable = _colInfos$key2.searchable; var targetVal = row[key]; if (searchable) { if (filterFormatted && format) { targetVal = format(targetVal, row, formatExtraData); } for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) { var filterVal = searchTextArray[j].toLowerCase(); if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) { valid = true; break; } } } } } return valid; }); _this4.isOnFilter = true; })(); } } }, { key: 'getDataIgnoringPagination', value: function getDataIgnoringPagination() { return this.getCurrentDisplayData(); } }, { key: 'get', value: function get() { var _data = this.getCurrentDisplayData(); if (_data.length === 0) return _data; if (this.remote || !this.enablePagination) { return _data; } else { var result = []; for (var i = this.pageObj.start; i <= this.pageObj.end; i++) { result.push(_data[i]); if (i + 1 === _data.length) break; } return result; } } }, { key: 'getKeyField', value: function getKeyField() { return this.keyField; } }, { key: 'getDataNum', value: function getDataNum() { return this.getCurrentDisplayData().length; } }, { key: 'isChangedPage', value: function isChangedPage() { return this.pageObj.start && this.pageObj.end ? true : false; } }, { key: 'isEmpty', value: function isEmpty() { return this.data.length === 0 || this.data === null || this.data === undefined; } }, { key: 'getAllRowkey', value: function getAllRowkey() { var _this5 = this; return this.data.map(function (row) { return row[_this5.keyField]; }); } }]); return TableDataStore; })(); exports.TableDataStore = TableDataStore; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); exports['default'] = { renderReactSortCaret: function renderReactSortCaret(order) { var orderClass = (0, _classnames2['default'])('order', { 'dropup': order === _Const2['default'].SORT_ASC }); return _react2['default'].createElement( 'span', { className: orderClass }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '0px 5px' } }) ); }, getScrollBarWidth: function getScrollBarWidth() { var inner = document.createElement('p'); inner.style.width = '100%'; inner.style.height = '200px'; var outer = document.createElement('div'); outer.style.position = 'absolute'; outer.style.top = '0px'; outer.style.left = '0px'; outer.style.visibility = 'hidden'; outer.style.width = '200px'; outer.style.height = '150px'; outer.style.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 === w2) w2 = outer.clientWidth; document.body.removeChild(outer); return w1 - w2; }, canUseDOM: function canUseDOM() { return typeof window !== 'undefined' && typeof window.document !== 'undefined'; } }; module.exports = exports['default']; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /* eslint block-scoped-var: 0 */ /* eslint vars-on-top: 0 */ /* eslint no-var: 0 */ /* eslint no-unused-vars: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _util = __webpack_require__(34); var _util2 = _interopRequireDefault(_util); if (_util2['default'].canUseDOM()) { var filesaver = __webpack_require__(36); var saveAs = filesaver.saveAs; } function toString(data, keys) { var dataString = ''; if (data.length === 0) return dataString; dataString += keys.join(',') + '\n'; data.map(function (row) { keys.map(function (col, i) { var cell = typeof row[col] !== 'undefined' ? '"' + row[col] + '"' : ''; dataString += cell; if (i + 1 < keys.length) dataString += ','; }); dataString += '\n'; }); return dataString; } var exportCSV = function exportCSV(data, keys, filename) { var dataString = toString(data, keys); if (typeof window !== 'undefined') { saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename || 'spreadsheet.csv'); } }; exports['default'] = exportCSV; module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js * A saveAs() FileSaver implementation. * 1.1.20151003 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ "use strict"; var saveAs = saveAs || (function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document, // only get URL when necessary in case Blob.js hasn't overridden it yet get_URL = function get_URL() { return view.URL || view.webkitURL || view; }, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"), can_use_save_link = ("download" in save_link), click = function click(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); }, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent), webkit_req_fs = view.webkitRequestFileSystem, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem, throw_outside = function throw_outside(ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); }, force_saveable_type = "application/octet-stream", fs_min_size = 0, // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047 // for the reasoning behind the timeout and revocation flow arbitrary_revoke_timeout = 500, // in ms revoke = function revoke(file) { var revoker = function revoker() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; if (view.chrome) { revoker(); } else { setTimeout(revoker, arbitrary_revoke_timeout); } }, dispatch = function dispatch(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } }, auto_bom = function auto_bom(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob(["", blob], { type: blob.type }); } return blob; }, FileSaver = function FileSaver(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var filesaver = this, type = blob.type, blob_changed = false, object_url, target_view, dispatch_all = function dispatch_all() { dispatch(filesaver, "writestart progress write writeend".split(" ")); }, // on any filesys errors revert to saving with object URLs fs_error = function fs_error() { if (target_view && is_safari && typeof FileReader !== "undefined") { // Safari doesn't allow downloading of blob urls var reader = new FileReader(); reader.onloadend = function () { var base64Data = reader.result; target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); filesaver.readyState = filesaver.DONE; dispatch_all(); }; reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; } // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab == undefined && is_safari) { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url; } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); }, abortable = function abortable(func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; }, create_if_not_found = { create: true, exclusive: false }, slice; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); save_link.href = object_url; save_link.download = name; setTimeout(function () { click(save_link); dispatch_all(); revoke(object_url); filesaver.readyState = filesaver.DONE; }); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function save() { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); }, FS_proto = FileSaver.prototype, saveAs = function saveAs(blob, name, no_auto_bom) { return new FileSaver(blob, name, no_auto_bom); }; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function (blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name || "download"); }; } FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; } else if ("function" !== "undefined" && __webpack_require__(37) !== null && __webpack_require__(38) != null) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return saveAs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 37 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 38 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _events = __webpack_require__(40); var Filter = (function (_EventEmitter) { _inherits(Filter, _EventEmitter); function Filter(data) { _classCallCheck(this, Filter); _get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data); this.currentFilter = {}; } _createClass(Filter, [{ key: 'handleFilter', value: function handleFilter(dataField, value, type) { var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM; if (value !== null && typeof value === 'object') { // value of the filter is an object var hasValue = true; for (var prop in value) { if (!value[prop] || value[prop] === '') { hasValue = false; break; } } // if one of the object properties is undefined or empty, we remove the filter if (hasValue) { this.currentFilter[dataField] = { value: value, type: filterType }; } else { delete this.currentFilter[dataField]; } } else if (!value || value.trim() === '') { delete this.currentFilter[dataField]; } else { this.currentFilter[dataField] = { value: value.trim(), type: filterType }; } this.emit('onFilterChange', this.currentFilter); } }]); return Filter; })(_events.EventEmitter); exports.Filter = Filter; /***/ }, /* 40 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* eslint default-case: 0 */ /* eslint guard-for-in: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var _util = __webpack_require__(34); var _util2 = _interopRequireDefault(_util); var _filtersDate = __webpack_require__(42); var _filtersDate2 = _interopRequireDefault(_filtersDate); var _filtersText = __webpack_require__(43); var _filtersText2 = _interopRequireDefault(_filtersText); var _filtersRegex = __webpack_require__(44); var _filtersRegex2 = _interopRequireDefault(_filtersRegex); var _filtersSelect = __webpack_require__(45); var _filtersSelect2 = _interopRequireDefault(_filtersSelect); var _filtersNumber = __webpack_require__(46); var _filtersNumber2 = _interopRequireDefault(_filtersNumber); var TableHeaderColumn = (function (_Component) { _inherits(TableHeaderColumn, _Component); function TableHeaderColumn(props) { var _this = this; _classCallCheck(this, TableHeaderColumn); _get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props); this.handleColumnClick = function () { if (!_this.props.dataSort) return; var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC; _this.props.onSort(order, _this.props.dataField); }; this.handleFilter = this.handleFilter.bind(this); } _createClass(TableHeaderColumn, [{ key: 'handleFilter', value: function handleFilter(value, type) { this.props.filter.emitter.handleFilter(this.props.dataField, value, type); } }, { key: 'getFilters', value: function getFilters() { switch (this.props.filter.type) { case _Const2['default'].FILTER_TYPE.TEXT: { return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.REGEX: { return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.SELECT: { return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.NUMBER: { return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.DATE: { return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.CUSTOM: { return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters); } } } }, { key: 'componentDidMount', value: function componentDidMount() { this.refs['header-col'].setAttribute('data-field', this.props.dataField); } }, { key: 'render', value: function render() { var defaultCaret = undefined; var thStyle = { textAlign: this.props.dataAlign, display: this.props.hidden ? 'none' : null }; if (this.props.sortIndicator) { defaultCaret = !this.props.dataSort ? null : _react2['default'].createElement( 'span', { className: 'order' }, _react2['default'].createElement( 'span', { className: 'dropdown' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } }) ), _react2['default'].createElement( 'span', { className: 'dropup' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } }) ) ); } var sortCaret = this.props.sort ? _util2['default'].renderReactSortCaret(this.props.sort) : defaultCaret; if (this.props.caretRender) { sortCaret = this.props.caretRender(this.props.sort); } var classes = this.props.className + ' ' + (this.props.dataSort ? 'sort-column' : ''); var title = typeof this.props.children === 'string' ? { title: this.props.children } : null; return _react2['default'].createElement( 'th', _extends({ ref: 'header-col', className: classes, style: thStyle, onClick: this.handleColumnClick }, title), this.props.children, sortCaret, _react2['default'].createElement( 'div', { onClick: function (e) { return e.stopPropagation(); } }, this.props.filter ? this.getFilters() : null ) ); } }]); return TableHeaderColumn; })(_react.Component); var filterTypeArray = []; for (var key in _Const2['default'].FILTER_TYPE) { filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]); } TableHeaderColumn.propTypes = { dataField: _react.PropTypes.string, dataAlign: _react.PropTypes.string, dataSort: _react.PropTypes.bool, onSort: _react.PropTypes.func, dataFormat: _react.PropTypes.func, isKey: _react.PropTypes.bool, editable: _react.PropTypes.any, hidden: _react.PropTypes.bool, searchable: _react.PropTypes.bool, className: _react.PropTypes.string, width: _react.PropTypes.string, sortFunc: _react.PropTypes.func, sortFuncExtraData: _react.PropTypes.any, columnClassName: _react.PropTypes.any, filterFormatted: _react.PropTypes.bool, sort: _react.PropTypes.string, caretRender: _react.PropTypes.func, formatExtraData: _react.PropTypes.any, filter: _react.PropTypes.shape({ type: _react.PropTypes.oneOf(filterTypeArray), delay: _react.PropTypes.number, options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter _react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter ]), numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string), emitter: _react.PropTypes.object, placeholder: _react.PropTypes.string, getElement: _react.PropTypes.func, customFilterParameters: _react.PropTypes.object }), sortIndicator: _react.PropTypes.bool }; TableHeaderColumn.defaultProps = { dataAlign: 'left', dataSort: false, dataFormat: undefined, isKey: false, editable: true, onSort: undefined, hidden: false, searchable: true, className: '', width: null, sortFunc: undefined, columnClassName: '', filterFormatted: false, sort: undefined, formatExtraData: undefined, sortFuncExtraData: undefined, filter: undefined, sortIndicator: true }; exports['default'] = TableHeaderColumn; module.exports = exports['default']; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* eslint quotes: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var DateFilter = (function (_Component) { _inherits(DateFilter, _Component); function DateFilter(props) { _classCallCheck(this, DateFilter); _get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); } _createClass(DateFilter, [{ key: 'setDefaultDate', value: function setDefaultDate() { var defaultDate = ''; if (this.props.defaultValue) { // Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD" var defaultValue = new Date(this.props.defaultValue); defaultDate = defaultValue.getFullYear() + '-' + ("0" + (defaultValue.getMonth() + 1)).slice(-2) + '-' + ("0" + defaultValue.getDate()).slice(-2); } return defaultDate; } }, { key: 'filter', value: function filter(event) { var dateValue = event.target.value; if (dateValue) { this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE); } else { this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'componentDidMount', value: function componentDidMount() { var dateValue = this.refs.inputDate.defaultValue; if (dateValue) { this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'render', value: function render() { return _react2['default'].createElement('input', { ref: 'inputDate', className: 'filter date-filter form-control', type: 'date', onChange: this.filter, defaultValue: this.setDefaultDate() }); } }]); return DateFilter; })(_react.Component); DateFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.object, columnName: _react.PropTypes.string }; exports['default'] = DateFilter; module.exports = exports['default']; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var TextFilter = (function (_Component) { _inherits(TextFilter, _Component); function TextFilter(props) { _classCallCheck(this, TextFilter); _get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(TextFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT); }, this.props.delay); } }, { key: 'componentDidMount', value: function componentDidMount() { var defaultValue = this.refs.inputText.defaultValue; if (defaultValue) { this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var placeholder = _props.placeholder; var columnName = _props.columnName; var defaultValue = _props.defaultValue; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return TextFilter; })(_react.Component); TextFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; TextFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = TextFilter; module.exports = exports['default']; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var RegexFilter = (function (_Component) { _inherits(RegexFilter, _Component); function RegexFilter(props) { _classCallCheck(this, RegexFilter); _get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(RegexFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX); }, this.props.delay); } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.inputText.defaultValue; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var defaultValue = _props.defaultValue; var placeholder = _props.placeholder; var columnName = _props.columnName; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter Regex for ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return RegexFilter; })(_react.Component); RegexFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; RegexFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = RegexFilter; module.exports = exports['default']; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var SelectFilter = (function (_Component) { _inherits(SelectFilter, _Component); function SelectFilter(props) { _classCallCheck(this, SelectFilter); _get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue) }; } _createClass(SelectFilter, [{ key: 'filter', value: function filter(event) { var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } }, { key: 'getOptions', value: function getOptions() { var optionTags = []; var _props = this.props; var options = _props.options; var placeholder = _props.placeholder; var columnName = _props.columnName; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, placeholder || 'Select ' + columnName + '...' )); Object.keys(options).map(function (key) { optionTags.push(_react2['default'].createElement( 'option', { key: key, value: key }, options[key] )); }); return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.selectInput.value; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'select', { ref: 'selectInput', className: selectClass, onChange: this.filter, defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' }, this.getOptions() ); } }]); return SelectFilter; })(_react.Component); SelectFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.object.isRequired, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; exports['default'] = SelectFilter; module.exports = exports['default']; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(6); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(3); var _Const2 = _interopRequireDefault(_Const); var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; var NumberFilter = (function (_Component) { _inherits(NumberFilter, _Component); function NumberFilter(props) { _classCallCheck(this, NumberFilter); _get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props); this.numberComparators = this.props.numberComparators || legalComparators; this.timeout = null; this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1 }; this.onChangeNumber = this.onChangeNumber.bind(this); this.onChangeNumberSet = this.onChangeNumberSet.bind(this); this.onChangeComparator = this.onChangeComparator.bind(this); } _createClass(NumberFilter, [{ key: 'onChangeNumber', value: function onChangeNumber(event) { var _this = this; var comparator = this.refs.numberFilterComparator.value; if (comparator === '') { return; } if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); }, this.props.delay); } }, { key: 'onChangeNumberSet', value: function onChangeNumberSet(event) { var comparator = this.refs.numberFilterComparator.value; var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); if (comparator === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var value = this.refs.numberFilter.value; var comparator = event.target.value; if (value === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2['default'].createElement('option', { key: '-1' })); for (var i = 0; i < this.numberComparators.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: this.numberComparators[i] }, this.numberComparators[i] )); } return optionTags; } }, { key: 'getNumberOptions', value: function getNumberOptions() { var optionTags = []; var options = this.props.options; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, this.props.placeholder || 'Select ' + this.props.columnName + '...' )); for (var i = 0; i < options.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: options[i] }, options[i] )); } return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.numberFilterComparator.value; var number = this.refs.numberFilter.value; if (comparator && number) { this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'div', { className: 'filter number-filter' }, _react2['default'].createElement( 'select', { ref: 'numberFilterComparator', className: 'number-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' }, this.getComparatorOptions() ), this.props.options ? _react2['default'].createElement( 'select', { ref: 'numberFilter', className: selectClass, onChange: this.onChangeNumberSet, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }, this.getNumberOptions() ) : _react2['default'].createElement('input', { ref: 'numberFilter', type: 'number', className: 'number-filter-input form-control', placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...', onChange: this.onChangeNumber, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }) ); } }]); return NumberFilter; })(_react.Component); NumberFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.arrayOf(_react.PropTypes.number), defaultValue: _react.PropTypes.shape({ number: _react.PropTypes.number, comparator: _react.PropTypes.oneOf(legalComparators) }), delay: _react.PropTypes.number, /* eslint consistent-return: 0 */ numberComparators: function numberComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators); } } }, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; NumberFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = NumberFilter; module.exports = exports['default']; /***/ } /******/ ]) }); ; //# sourceMappingURL=react-bootstrap-table.js.map
AMoo-Miki/cdnjs
ajax/libs/react-bootstrap-table/2.1.2/react-bootstrap-table.js
JavaScript
mit
249,065
/*************************************************************************/ /* position_3d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifndef POSITION_3D_H #define POSITION_3D_H #include "scene/3d/spatial.h" class Position3D : public Spatial { OBJ_TYPE(Position3D,Spatial); virtual RES _get_gizmo_geometry() const; public: Position3D(); }; #endif // POSITION_3D_H
ricpelo/godot
scene/3d/position_3d.h
C
mit
2,369
/* http://keith-wood.name/datepick.html Urdu localisation for jQuery Datepicker. Mansoor Munib -- mansoormunib@gmail.com <http://www.mansoor.co.nr/mansoor.html> Thanks to Habib Ahmed, ObaidUllah Anwar. */ (function($) { $.datepick.regionalOptions.ur = { monthNames: ['جنوری','فروری','مارچ','اپریل','مئی','جون', 'جولائی','اگست','ستمبر','اکتوبر','نومبر','دسمبر'], monthNamesShort: ['1','2','3','4','5','6', '7','8','9','10','11','12'], dayNames: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'], dayNamesShort: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'], dayNamesMin: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'], dateFormat: 'dd/mm/yyyy', firstDay: 0, renderer: $.datepick.defaultRenderer, prevText: '&#x3c;گذشتہ', prevStatus: 'ماه گذشتہ', prevJumpText: '&#x3c;&#x3c;', prevJumpStatus: 'برس گذشتہ', nextText: 'آئندہ&#x3e;', nextStatus: 'ماه آئندہ', nextJumpText: '&#x3e;&#x3e;', nextJumpStatus: 'برس آئندہ', currentText: 'رواں', currentStatus: 'ماه رواں', todayText: 'آج', todayStatus: 'آج', clearText: 'حذف تاريخ', clearStatus: 'کریں حذف تاریخ', closeText: 'کریں بند', closeStatus: 'کیلئے کرنے بند', yearStatus: 'برس تبدیلی', monthStatus: 'ماه تبدیلی', weekText: 'ہفتہ', weekStatus: 'ہفتہ', dayStatus: 'انتخاب D, M d', defaultStatus: 'کریں منتخب تاريخ', isRTL: true }; $.datepick.setDefaults($.datepick.regionalOptions.ur); })(jQuery);
seogi1004/cdnjs
ajax/libs/datepick/5.1.0/js/jquery.datepick-ur.js
JavaScript
mit
1,696
/*! * Inheritance.js (0.4.3) * * Copyright (c) 2015 Brandon Sara (http://bsara.github.io) * Licensed under the CPOL-1.02 (https://github.com/bsara/inheritance.js/blob/master/LICENSE.md) */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.I = {}; root.I = factory(); } }(this, function() {/** * TODO: Add description * * @param {Object} obj - The object to mix into. * NOTE: `undefined` and `null` are both VALID values for * this parameter. If `obj` is `undefined` or `null`, then * a new object will be created from the `mixins` given. * @param {Array<Object>|Object} mixins - An array of objects whose properties should be mixed * into the given `obj`. * NOTE: The order of objects in this array does matter! * If there are properties present in multiple mixin * objects, then the mixin with the largest index value * overwrite any values set by the lower index valued * mixin objects. * * @returns {Object} The mixed version of `obj`. */ function mix(obj, mixins) { var newObj = (obj || {}); if (!(mixins instanceof Array)) { mixins = [ mixins ]; } for (var i = 0; i < mixins.length; i++) { var mixin = mixins[i]; if (!mixin) { continue; } for (var propName in mixin) { if (mixin.hasOwnProperty(propName)) { newObj[propName] = mixin[propName]; } } } return newObj; }/** * TODO: Add description * * @param {Object} obj - The object to deep mix into. * NOTE: `undefined` and `null` are both VALID values for * this parameter. If `obj` is `undefined` or `null`, then * a new object will be created from the `mixins` given. * @param {Array<Object>|Object} mixins - An array of objects whose properties should be deep * mixed into the given `obj`. * NOTE: The order of objects in this array does matter! * If there are properties present in multiple mixin * objects, then the mixin with the largest index value * overwrite any values set by the lower index valued * mixin objects. * * @returns {Object} The deep mixed version of `obj`. */ function mixDeep(obj, mixins) { var newObj = (obj || {}); if (!(mixins instanceof Array)) { mixins = [ mixins ]; } for (var i = 0; i < mixins.length; i++) { var mixin = mixins[i]; if (!mixin) { continue; } for (var propName in mixin) { if (!mixin.hasOwnProperty(propName)) { continue; } if (typeof mixin[propName] === 'object') { mixDeep(newObj[propName], mixin[propName]); continue; } newObj[propName] = mixin[propName]; } } return newObj; }/** * Creates a new object definition based upon the given `objDefProps` that inherits the * given `parent`. * * @param {Object} parent - The object to be inherited. * @param {Object} [objDefProps] - An object containing all properties to be used in * creating the new object definition that will inherit * the given `parent` object. If this parameter is * `undefined` or `null`, then a new child object * definition is created. * TODO: Add reference to the `objDefProps` spec * * @returns {Object} An object created from the given `objDefProps` that inherits * `parent`. * * @requires makeInheritable, mixDeep */ function inheritance(parent, objDefProps) { parent = (parent || Object); objDefProps = (objDefProps || {}); var objDef; var objCtor = (objDefProps.ctor || function() { return objDef.__super__.constructor.apply(this, arguments); }); var objDefName = objDefProps.__defName; if (typeof objDefName === 'string' && objDefName.trim()) { objDefName = objDefName.trim(); } else if (objCtor.name) { objDefName = objCtor.name; } else { objDefName = undefined; } delete objDefProps.__defName; eval('objDef = function' + (objDefName ? (' ' + objDefName) : '') + '() { return objCtor.apply(this, arguments); };'); objDef.prototype = Object.create(parent.prototype); _addOwnerIfFunction(objDef.prototype, objCtor); Object.defineProperty(objDef.prototype, '__ctor__', { value: objCtor, configurable: false, enumerable: false, writable: false }); makeInheritable(objDef); _setupMixins(objDefProps); _setupStaticProperties(objDef, objDefProps); _setupPrivateProperties(objDef, objDefProps); _setupSuperFunction(objDef); _setupPublicProperties(objDef, objDefProps); Object.defineProperty(objDef, '__super__', { value: parent.prototype, configurable: false, enumerable: false, writable: false }); return objDef; } function _addOwnerIfFunction(owner, obj) { if (typeof obj === 'function') { obj.owner = owner; } return obj; } function _updatePrototypeWithMixDeep(prototype, props, propName) { if (typeof props[propName] === 'object' && typeof props[propName] === typeof prototype[propName] && typeof props[propName].prototype === 'undefined' && typeof prototype[propName].prototype === 'undefined') { mixDeep(prototype[propName], props[propName]); return; } prototype[propName] = _addOwnerIfFunction(prototype, props[propName]); } function _setupMixins(props) { var mixins = props.mixins; if (mixins !== null && mixins instanceof Array) { mixDeep(props, mixins); } } function _setupStaticProperties(def, props) { var propName; var staticProps = props.static; if (typeof staticProps !== 'undefined' && staticProps !== null) { for (propName in staticProps) { if (propName === 'consts' || propName === '__super__') { continue; } def[propName] = _addOwnerIfFunction(def, staticProps[propName]); } var staticConstProps = staticProps.consts; if (typeof staticConstProps !== 'undefined' && staticConstProps !== null) { for (propName in staticConstProps) { Object.defineProperty(def, propName, { value: staticConstProps[propName], configurable: false, enumerable: true, writable: false }); } } } } function _setupPrivateProperties(def, props) { var propName; var privateProps = props.private; if (typeof privateProps !== 'undefined' && privateProps !== null) { for (propName in privateProps) { if (propName === 'constructor' || propName === 'ctor' || propName === 'static' || propName === '_super' || propName === '__ctor__') { continue; } Object.defineProperty(def.prototype, propName, { value: _addOwnerIfFunction(def.prototype, privateProps[propName]), configurable: true, enumerable: false, writable: true }); } var privateStaticProps = privateProps.static; if (typeof privateStaticProps !== 'undefined' && privateStaticProps !== null) { for (propName in privateStaticProps) { Object.defineProperty(def, propName, { value: _addOwnerIfFunction(def, privateStaticProps[propName]), configurable: true, enumerable: false, writable: true }); } } } } function _setupPublicProperties(def, props) { def.prototype.constructor = _addOwnerIfFunction(def.prototype, def); for (var propName in props) { if (propName === 'constructor' || propName === 'ctor' || propName === 'mixins' || propName === 'private' || propName === 'static' || propName === '_super' || propName === '__ctor__') { continue; } _updatePrototypeWithMixDeep(def.prototype, props, propName); } } function _setupSuperFunction(def) { Object.defineProperty(def.prototype, '_super', { configurable: false, enumerable: false, writable: false, value: function() { var caller = arguments.callee.caller; if (!caller) { return; } var callerOwner = caller.owner; var superType = callerOwner.constructor.__super__; if (!superType) { return; } if (caller === callerOwner.constructor || caller === callerOwner.__ctor__) { return superType.constructor.apply(this, arguments); } var callerName = caller.name; if (!callerName) { var propNames = Object.getOwnPropertyNames(callerOwner); for (var i = 0; i < propNames.length; i++) { var propName = propNames[i]; if (callerOwner[propName] === caller) { callerName = propName; break; } } } if (!callerName) { return; } var superFunc = superType[callerName]; if (typeof superFunc !== 'function' || superFunc === null) { return; } return superFunc.apply(this, arguments); } }); }/** * Makes an object inheritable by adding a function called `extend` as a "static" * property of the object. (I.E. Calling this function passing `MyObject` as a * parameter, creates `MyObject.extend`) * * @param {Object} obj - The object to make inheritable. * @param {Boolean} [overwrite] - If `true`, then an existing `extend` property will be * overwritten regardless of it's value. * @param {Boolean} [ignoreOverwriteError] - If `true`, then no error will be thrown if * `obj.extend` already exists and `overwrite` * is not `true`. * * @returns {Object} The modified `obj` given. * * @throws {TypeError} If `obj` is `undefined` or `null`. * @throws {TypeError} If `obj.extend` already exists and `overwrite` is NOT equal `true`. */ function makeInheritable(obj, overwrite, ignoreOverwriteError) { if (typeof obj === 'undefined' || obj === null) { throw new TypeError("`obj` cannot be undefined or null!"); } if (overwrite !== true && typeof obj.extend !== 'undefined' && obj.extend !== null) { if (ignoreOverwriteError === true) { return obj; } throw new TypeError("`obj.extend` already exists! You're seeing this error to prevent the current extend function from being overwritten. See docs for how to override this functionality."); } /** * Creates a new object definition based upon the given `objDefProps` properties and * causes that new object definition to inherit this object. * * @param {Object} objDefProps - An object containing all properties to be used in * creating the new object definition that will inherit * this object. If this parameter is `undefined` or * `null`, then a new child object definition is created. * TODO: Add reference to the `objDefProps` spec * * @returns {Object} An object created from the given `objDefProps` that inherits this * object. * * @throws {TypeError} If the object's definition has been sealed. @see {@link https://github.com/bsara/inheritance.js/blob/master/src/inherit/seal.js} * * @requires inheritance */ Object.defineProperty(obj, 'extend', { value: function(objDefProps) { return inheritance(obj, objDefProps); }, configurable: true, enumerable: false, writable: true }); return obj; }/** * Makes an object sealed by adding a function called `extend` as a "static" property * of the object that throws an error if it is ever called. (I.E. Calling this function * passing `MyObject` as a parameter, creates `MyObject.extend` and `MyObject.sealed`, * where `MyObject.sealed` will always be `true`) * * @param {Object} obj - The object to seal. * @param {Boolean} [overwrite] - If `true`, then an existing `extend` property will be * overwritten regardless of it's value. * @param {Boolean} [ignoreOverwriteError] - If `true`, then no error will be thrown if * `obj.extend` already exists and `overwrite` * is not `true`. * * @returns {Object} The modified `obj` given. * * @throws {TypeError} If `obj` is `undefined` or `null`. * @throws {TypeError} If `obj.extend` already exists and `overwrite` is NOT equal `true`. */ function seal(obj, overwrite, ignoreOverwriteError) { if (typeof obj === 'undefined' || obj === null) { throw new TypeError("`obj` cannot be undefined or null!"); } if (overwrite !== true && typeof obj.extend !== 'undefined' && obj.extend !== null) { if (ignoreOverwriteError === true) { return obj; } throw new TypeError("`obj.extend` already exists! You're seeing this error to prevent the current extend function from being overwritten. See docs for how to override this functionality."); } if (typeof obj.extend !== 'undefined' && obj.extend !== null) { delete obj.extend; } Object.defineProperties(obj, { sealed: { configurable: false, enumerable: false, writable: false, value: true }, extend: { configurable: false, enumerable: false, writable: false, value: function() { throw new TypeError("The object definition you are trying to extend is sealed and cannot be inherited."); } } }); return obj; }/** @namespace */ var ObjectDefinition = { /** * Creates a new object (I.E. "class") that can be inherited. * NOTE: The new object inherits the native JavaScript `Object`. * * @param {Object} objDef - TODO: Add description * * @returns {Object} The newly created, inheritable, object that inherits `Object`. * * @requires inheritance */ create: function(objDef) { return inheritance(Object, objDef); }, /** * Creates a new object (I.E. "class") that CANNOT be inherited. * NOTE: The new object inherits the native JavaScript `Object`. * * @param {Object} objDef - TODO: Add description * * @returns {Object} The newly created, non-inheritable, object that inherits `Object`. * * @requires seal */ createSealed: function(objDef) { return seal(inheritance(Object, objDef), true); } }; seal(ObjectDefinition, true); return { mix: mix, mixDeep: mixDeep, inheritance: inheritance, makeInheritable: makeInheritable, seal: seal, ObjectDefinition: ObjectDefinition }; }));
extend1994/cdnjs
ajax/libs/inheritance-js/0.4.3/modules/inheritance.objectdef.js
JavaScript
mit
15,529
/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ /* The MIT License (MIT) Copyright (c) 2007-2013 Einar Lielmanis and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JS Beautifier --------------- Written by Einar Lielmanis, <einar@jsbeautifier.org> http://jsbeautifier.org/ Originally converted to javascript by Vital, <vital76@gmail.com> "End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com> Parsing improvements for brace-less statements by Liam Newman <bitwiseman@gmail.com> Usage: js_beautify(js_source_text); js_beautify(js_source_text, options); The options are: indent_size (default 4) - indentation size, indent_char (default space) - character to indent with, preserve_newlines (default true) - whether existing line breaks should be preserved, max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk, jslint_happy (default false) - if true, then jslint-stricter mode is enforced. jslint_happy !jslint_happy --------------------------------- function () function() brace_style (default "collapse") - "collapse" | "expand" | "end-expand" put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line. space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)", unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65" wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters. NOTE: This is not a hard limit. Lines will continue until a point where a newline would be preserved if it were present. e.g js_beautify(js_source_text, { 'indent_size': 1, 'indent_char': '\t' }); */ (function() { function js_beautify(js_source_text, options) { "use strict"; var beautifier = new Beautifier(js_source_text, options); return beautifier.beautify(); } function Beautifier(js_source_text, options) { "use strict"; var input, output, token_text, token_type, last_type, last_last_text, indent_string; var flags, previous_flags, flag_store; var whitespace, wordchar, punct, parser_pos, line_starters, digits; var prefix; var input_wanted_newline; var output_wrapped, output_space_before_token; var input_length, n_newlines, whitespace_before_token; var handlers, MODE, opt; var preindent_string = ''; whitespace = "\n\r\t ".split(''); wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split(''); digits = '0123456789'.split(''); punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::'; punct += ' <%= <% %> <?= <? ?>'; // try to be a good boy and try not to break the markup language identifiers punct = punct.split(' '); // words which should always start on new line. line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(','); MODE = { BlockStatement: 'BlockStatement', // 'BLOCK' Statement: 'Statement', // 'STATEMENT' ObjectLiteral: 'ObjectLiteral', // 'OBJECT', ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]', ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)', Conditional: 'Conditional', //'(COND-EXPRESSION)', Expression: 'Expression' //'(EXPRESSION)' }; handlers = { 'TK_START_EXPR': handle_start_expr, 'TK_END_EXPR': handle_end_expr, 'TK_START_BLOCK': handle_start_block, 'TK_END_BLOCK': handle_end_block, 'TK_WORD': handle_word, 'TK_SEMICOLON': handle_semicolon, 'TK_STRING': handle_string, 'TK_EQUALS': handle_equals, 'TK_OPERATOR': handle_operator, 'TK_COMMA': handle_comma, 'TK_BLOCK_COMMENT': handle_block_comment, 'TK_INLINE_COMMENT': handle_inline_comment, 'TK_COMMENT': handle_comment, 'TK_DOT': handle_dot, 'TK_UNKNOWN': handle_unknown }; function create_flags(flags_base, mode) { return { mode: mode, last_text: flags_base ? flags_base.last_text : '', // last token text last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed var_line: false, var_line_tainted: false, var_line_reindented: false, in_html_comment: false, multiline_array: false, if_block: false, do_block: false, do_while: false, in_case_statement: false, // switch(..){ INSIDE HERE } in_case: false, // we're on the exact line with "case 0:" case_body: false, // the indented case-action block indentation_level: (flags_base ? flags_base.indentation_level + ((flags_base.var_line && flags_base.var_line_reindented) ? 1 : 0) : 0), ternary_depth: 0 }; } // Some interpreters have unexpected results with foo = baz || bar; options = options ? options : {}; opt = {}; // compatibility if (options.space_after_anon_function !== undefined && options.jslint_happy === undefined) { options.jslint_happy = options.space_after_anon_function; } if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option opt.brace_style = options.braces_on_own_line ? "expand" : "collapse"; } opt.brace_style = options.brace_style ? options.brace_style : (opt.brace_style ? opt.brace_style : "collapse"); // graceful handling of deprecated option if (opt.brace_style === "expand-strict") { opt.brace_style = "expand"; } opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4; opt.indent_char = options.indent_char ? options.indent_char : ' '; opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines; opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods; opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10); opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren; opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy; opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation; opt.space_before_conditional= (options.space_before_conditional === undefined) ? true : options.space_before_conditional; opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings; opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10); opt.e4x = (options.e4x === undefined) ? false : options.e4x; //---------------------------------- indent_string = ''; while (opt.indent_size > 0) { indent_string += opt.indent_char; opt.indent_size -= 1; } while (js_source_text && (js_source_text.charAt(0) === ' ' || js_source_text.charAt(0) === '\t')) { preindent_string += js_source_text.charAt(0); js_source_text = js_source_text.substring(1); } input = js_source_text; // cache the source's length. input_length = js_source_text.length; last_type = 'TK_START_BLOCK'; // last token type last_last_text = ''; // pre-last token text output = []; output_wrapped = false; output_space_before_token = false; whitespace_before_token = []; // Stack of parsing/formatting states, including MODE. // We tokenize, parse, and output in an almost purely a forward-only stream of token input // and formatted output. This makes the beautifier less accurate than full parsers // but also far more tolerant of syntax errors. // // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type // MODE.BlockStatement on the the stack, even though it could be object literal. If we later // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";", // most full parsers would die, but the beautifier gracefully falls back to // MODE.BlockStatement and continues on. flag_store = []; set_mode(MODE.BlockStatement); parser_pos = 0; this.beautify = function () { /*jshint onevar:true */ var t, i, keep_whitespace, sweet_code; while (true) { t = get_next_token(); token_text = t[0]; token_type = t[1]; if (token_type === 'TK_EOF') { break; } keep_whitespace = opt.keep_array_indentation && is_array(flags.mode); input_wanted_newline = n_newlines > 0; if (keep_whitespace) { for (i = 0; i < n_newlines; i += 1) { print_newline(i > 0); } } else { if (opt.max_preserve_newlines && n_newlines > opt.max_preserve_newlines) { n_newlines = opt.max_preserve_newlines; } if (opt.preserve_newlines) { if (n_newlines > 1) { print_newline(); for (i = 1; i < n_newlines; i += 1) { print_newline(true); } } } } handlers[token_type](); // The cleanest handling of inline comments is to treat them as though they aren't there. // Just continue formatting and the behavior should be logical. // Also ignore unknown tokens. Again, this should result in better behavior. if (token_type !== 'TK_INLINE_COMMENT' && token_type !== 'TK_COMMENT' && token_type !== 'TK_UNKNOWN') { last_last_text = flags.last_text; last_type = token_type; flags.last_text = token_text; } } sweet_code = preindent_string + output.join('').replace(/[\r\n ]+$/, ''); return sweet_code; }; function trim_output(eat_newlines) { eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; while (output.length && (output[output.length - 1] === ' ' || output[output.length - 1] === indent_string || output[output.length - 1] === preindent_string || (eat_newlines && (output[output.length - 1] === '\n' || output[output.length - 1] === '\r')))) { output.pop(); } } function trim(s) { return s.replace(/^\s\s*|\s\s*$/, ''); } // we could use just string.split, but // IE doesn't like returning empty strings function split_newlines(s) { //return s.split(/\x0d\x0a|\x0a/); s = s.replace(/\x0d/g, ''); var out = [], idx = s.indexOf("\n"); while (idx !== -1) { out.push(s.substring(0, idx)); s = s.substring(idx + 1); idx = s.indexOf("\n"); } if (s.length) { out.push(s); } return out; } function just_added_newline() { return output.length && output[output.length - 1] === "\n"; } function just_added_blankline() { return just_added_newline() && output.length - 1 > 0 && output[output.length - 2] === "\n"; } function _last_index_of(arr, find) { var i = arr.length - 1; if (i < 0) { i += arr.length; } if (i > arr.length - 1) { i = arr.length - 1; } for (i++; i-- > 0;) { if (i in arr && arr[i] === find) { return i; } } return -1; } function allow_wrap_or_preserved_newline(force_linewrap) { force_linewrap = (force_linewrap === undefined) ? false : force_linewrap; if (opt.wrap_line_length && !force_linewrap) { var current_line = ''; var proposed_line_length = 0; var start_line = _last_index_of(output, '\n') + 1; // never wrap the first token of a line. if (start_line < output.length) { current_line = output.slice(start_line).join(''); proposed_line_length = current_line.length + token_text.length + (output_space_before_token ? 1 : 0); if (proposed_line_length >= opt.wrap_line_length) { force_linewrap = true; } } } if (((opt.preserve_newlines && input_wanted_newline) || force_linewrap) && !just_added_newline()) { print_newline(false, true); // Expressions and array literals already indent their contents. if(! (is_array(flags.mode) || is_expression(flags.mode))) { output_wrapped = true; } } } function print_newline(force_newline, preserve_statement_flags) { output_wrapped = false; output_space_before_token = false; if (!preserve_statement_flags) { if (flags.last_text !== ';') { while (flags.mode === MODE.Statement && !flags.if_block) { restore_mode(); } } } if (flags.mode === MODE.ArrayLiteral) { flags.multiline_array = true; } if (!output.length) { return; // no newline on start of file } if (force_newline || !just_added_newline()) { output.push("\n"); } } function print_token_line_indentation() { if (just_added_newline()) { if (opt.keep_array_indentation && is_array(flags.mode) && input_wanted_newline) { for (var i = 0; i < whitespace_before_token.length; i += 1) { output.push(whitespace_before_token[i]); } } else { if (preindent_string) { output.push(preindent_string); } print_indent_string(flags.indentation_level); print_indent_string(flags.var_line && flags.var_line_reindented); print_indent_string(output_wrapped); } } } function print_indent_string(level) { if (level === undefined) { level = 1; } else if (typeof level !== 'number') { level = level ? 1 : 0; } // Never indent your first output indent at the start of the file if (flags.last_text !== '') { for (var i = 0; i < level; i += 1) { output.push(indent_string); } } } function print_token_space_before() { if (output_space_before_token && output.length) { var last_output = output[output.length - 1]; if (!just_added_newline() && last_output !== ' ' && last_output !== indent_string) { // prevent occassional duplicate space output.push(' '); } } } function print_token(printable_token) { printable_token = printable_token || token_text; print_token_line_indentation(); output_wrapped = false; print_token_space_before(); output_space_before_token = false; output.push(printable_token); } function indent() { flags.indentation_level += 1; } function set_mode(mode) { if (flags) { flag_store.push(flags); previous_flags = flags; } else { previous_flags = create_flags(null, mode); } flags = create_flags(previous_flags, mode); } function is_array(mode) { return mode === MODE.ArrayLiteral; } function is_expression(mode) { return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]); } function restore_mode() { if (flag_store.length > 0) { previous_flags = flags; flags = flag_store.pop(); } } function start_of_statement() { if ( (flags.last_text === 'do' || (flags.last_text === 'else' && token_text !== 'if') || (last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)))) { allow_wrap_or_preserved_newline(); set_mode(MODE.Statement); indent(); output_wrapped = false; return true; } return false; } function all_lines_start_with(lines, c) { for (var i = 0; i < lines.length; i++) { var line = trim(lines[i]); if (line.charAt(0) !== c) { return false; } } return true; } function is_special_word(word) { return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']); } function in_array(what, arr) { for (var i = 0; i < arr.length; i += 1) { if (arr[i] === what) { return true; } } return false; } function unescape_string(s) { var esc = false, out = '', pos = 0, s_hex = '', escaped = 0, c; while (esc || pos < s.length) { c = s.charAt(pos); pos++; if (esc) { esc = false; if (c === 'x') { // simple hex-escape \x24 s_hex = s.substr(pos, 2); pos += 2; } else if (c === 'u') { // unicode-escape, \u2134 s_hex = s.substr(pos, 4); pos += 4; } else { // some common escape, e.g \n out += '\\' + c; continue; } if (!s_hex.match(/^[0123456789abcdefABCDEF]+$/)) { // some weird escaping, bail out, // leaving whole string intact return s; } escaped = parseInt(s_hex, 16); if (escaped >= 0x00 && escaped < 0x20) { // leave 0x00...0x1f escaped if (c === 'x') { out += '\\x' + s_hex; } else { out += '\\u' + s_hex; } continue; } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) { // single-quote, apostrophe, backslash - escape these out += '\\' + String.fromCharCode(escaped); } else if (c === 'x' && escaped > 0x7e && escaped <= 0xff) { // we bail out on \x7f..\xff, // leaving whole string escaped, // as it's probably completely binary return s; } else { out += String.fromCharCode(escaped); } } else if (c === '\\') { esc = true; } else { out += c; } } return out; } function is_next(find) { var local_pos = parser_pos; var c = input.charAt(local_pos); while (in_array(c, whitespace) && c !== find) { local_pos++; if (local_pos >= input_length) { return false; } c = input.charAt(local_pos); } return c === find; } function get_next_token() { var i, resulting_string; n_newlines = 0; if (parser_pos >= input_length) { return ['', 'TK_EOF']; } input_wanted_newline = false; whitespace_before_token = []; var c = input.charAt(parser_pos); parser_pos += 1; while (in_array(c, whitespace)) { if (c === '\n') { n_newlines += 1; whitespace_before_token = []; } else if (n_newlines) { if (c === indent_string) { whitespace_before_token.push(indent_string); } else if (c !== '\r') { whitespace_before_token.push(' '); } } if (parser_pos >= input_length) { return ['', 'TK_EOF']; } c = input.charAt(parser_pos); parser_pos += 1; } if (in_array(c, wordchar)) { if (parser_pos < input_length) { while (in_array(input.charAt(parser_pos), wordchar)) { c += input.charAt(parser_pos); parser_pos += 1; if (parser_pos === input_length) { break; } } } // small and surprisingly unugly hack for 1E-10 representation if (parser_pos !== input_length && c.match(/^[0-9]+[Ee]$/) && (input.charAt(parser_pos) === '-' || input.charAt(parser_pos) === '+')) { var sign = input.charAt(parser_pos); parser_pos += 1; var t = get_next_token(); c += sign + t[0]; return [c, 'TK_WORD']; } if (c === 'in') { // hack for 'in' operator return [c, 'TK_OPERATOR']; } return [c, 'TK_WORD']; } if (c === '(' || c === '[') { return [c, 'TK_START_EXPR']; } if (c === ')' || c === ']') { return [c, 'TK_END_EXPR']; } if (c === '{') { return [c, 'TK_START_BLOCK']; } if (c === '}') { return [c, 'TK_END_BLOCK']; } if (c === ';') { return [c, 'TK_SEMICOLON']; } if (c === '/') { var comment = ''; // peek for comment /* ... */ var inline_comment = true; if (input.charAt(parser_pos) === '*') { parser_pos += 1; if (parser_pos < input_length) { while (parser_pos < input_length && !(input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/')) { c = input.charAt(parser_pos); comment += c; if (c === "\n" || c === "\r") { inline_comment = false; } parser_pos += 1; if (parser_pos >= input_length) { break; } } } parser_pos += 2; if (inline_comment && n_newlines === 0) { return ['/*' + comment + '*/', 'TK_INLINE_COMMENT']; } else { return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT']; } } // peek for comment // ... if (input.charAt(parser_pos) === '/') { comment = c; while (input.charAt(parser_pos) !== '\r' && input.charAt(parser_pos) !== '\n') { comment += input.charAt(parser_pos); parser_pos += 1; if (parser_pos >= input_length) { break; } } return [comment, 'TK_COMMENT']; } } if (c === "'" || c === '"' || // string ( (c === '/') || // regexp (opt.e4x && c ==="<" && input.slice(parser_pos - 1).match(/^<[a-zA-Z:0-9]+\s*([a-zA-Z:0-9]+="[^"]*"\s*)*\/?\s*>/)) // xml ) && ( // regex and xml can only appear in specific locations during parsing (last_type === 'TK_WORD' && is_special_word (flags.last_text)) || (last_type === 'TK_END_EXPR' && in_array(previous_flags.mode, [MODE.Conditional, MODE.ForInitializer])) || (in_array(last_type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK', 'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA'])) )) { var sep = c, esc = false, has_char_escapes = false; resulting_string = c; if (parser_pos < input_length) { if (sep === '/') { // // handle regexp // var in_char_class = false; while (esc || in_char_class || input.charAt(parser_pos) !== sep) { resulting_string += input.charAt(parser_pos); if (!esc) { esc = input.charAt(parser_pos) === '\\'; if (input.charAt(parser_pos) === '[') { in_char_class = true; } else if (input.charAt(parser_pos) === ']') { in_char_class = false; } } else { esc = false; } parser_pos += 1; if (parser_pos >= input_length) { // incomplete string/rexp when end-of-file reached. // bail out with what had been received so far. return [resulting_string, 'TK_STRING']; } } } else if (opt.e4x && sep === '<') { // // handle e4x xml literals // var xmlRegExp = /<(\/?)([a-zA-Z:0-9]+)\s*([a-zA-Z:0-9]+="[^"]*"\s*)*(\/?)\s*>/g; var xmlStr = input.slice(parser_pos - 1); var match = xmlRegExp.exec(xmlStr); if (match && match.index === 0) { var rootTag = match[2]; var depth = 0; while (match) { var isEndTag = !! match[1]; var tagName = match[2]; var isSingletonTag = !! match[match.length - 1]; if (tagName === rootTag && !isSingletonTag) { if (isEndTag) { --depth; } else { ++depth; } } if (depth <= 0) { break; } match = xmlRegExp.exec(xmlStr); } var xmlLength = match ? match.index + match[0].length : xmlStr.length; parser_pos += xmlLength - 1; return [xmlStr.slice(0, xmlLength), "TK_STRING"]; } } else { // // handle string // while (esc || input.charAt(parser_pos) !== sep) { resulting_string += input.charAt(parser_pos); if (esc) { if (input.charAt(parser_pos) === 'x' || input.charAt(parser_pos) === 'u') { has_char_escapes = true; } esc = false; } else { esc = input.charAt(parser_pos) === '\\'; } parser_pos += 1; if (parser_pos >= input_length) { // incomplete string/rexp when end-of-file reached. // bail out with what had been received so far. return [resulting_string, 'TK_STRING']; } } } } parser_pos += 1; resulting_string += sep; if (has_char_escapes && opt.unescape_strings) { resulting_string = unescape_string(resulting_string); } if (sep === '/') { // regexps may have modifiers /regexp/MOD , so fetch those, too while (parser_pos < input_length && in_array(input.charAt(parser_pos), wordchar)) { resulting_string += input.charAt(parser_pos); parser_pos += 1; } } return [resulting_string, 'TK_STRING']; } if (c === '#') { if (output.length === 0 && input.charAt(parser_pos) === '!') { // shebang resulting_string = c; while (parser_pos < input_length && c !== '\n') { c = input.charAt(parser_pos); resulting_string += c; parser_pos += 1; } return [trim(resulting_string) + '\n', 'TK_UNKNOWN']; } // Spidermonkey-specific sharp variables for circular references // https://developer.mozilla.org/En/Sharp_variables_in_JavaScript // http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935 var sharp = '#'; if (parser_pos < input_length && in_array(input.charAt(parser_pos), digits)) { do { c = input.charAt(parser_pos); sharp += c; parser_pos += 1; } while (parser_pos < input_length && c !== '#' && c !== '='); if (c === '#') { // } else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') { sharp += '[]'; parser_pos += 2; } else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') { sharp += '{}'; parser_pos += 2; } return [sharp, 'TK_WORD']; } } if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') { parser_pos += 3; c = '<!--'; while (input.charAt(parser_pos) !== '\n' && parser_pos < input_length) { c += input.charAt(parser_pos); parser_pos++; } flags.in_html_comment = true; return [c, 'TK_COMMENT']; } if (c === '-' && flags.in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') { flags.in_html_comment = false; parser_pos += 2; return ['-->', 'TK_COMMENT']; } if (c === '.') { return [c, 'TK_DOT']; } if (in_array(c, punct)) { while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) { c += input.charAt(parser_pos); parser_pos += 1; if (parser_pos >= input_length) { break; } } if (c === ',') { return [c, 'TK_COMMA']; } else if (c === '=') { return [c, 'TK_EQUALS']; } else { return [c, 'TK_OPERATOR']; } } return [c, 'TK_UNKNOWN']; } function handle_start_expr() { if (start_of_statement()) { // The conditional starts the statement if appropriate. } if (token_text === '[') { if (last_type === 'TK_WORD' || flags.last_text === ')') { // this is array index specifier, break immediately // a[x], fn()[x] if (in_array (flags.last_text, line_starters)) { output_space_before_token = true; } set_mode(MODE.Expression); print_token(); if (opt.space_in_paren) { output_space_before_token = true; } return; } if (is_array(flags.mode)) { if (flags.last_text === '[' || (flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) { // ], [ goes to new line // }, [ goes to new line if (!opt.keep_array_indentation) { print_newline(); } } } } else { if (flags.last_text === 'for') { set_mode(MODE.ForInitializer); } else if (in_array (flags.last_text, ['if', 'while'])) { set_mode(MODE.Conditional); } else { set_mode(MODE.Expression); } } if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') { print_newline(); } else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') { if (input_wanted_newline) { print_newline(); } // do nothing on (( and )( and ][ and ]( and .( } else if (last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') { output_space_before_token = true; } else if (flags.last_word === 'function' || flags.last_word === 'typeof') { // function() vs function () if (opt.jslint_happy) { output_space_before_token = true; } } else if (in_array (flags.last_text, line_starters) || flags.last_text === 'catch') { if (opt.space_before_conditional) { output_space_before_token = true; } } // Support of this kind of newline preservation. // a = (b && // (c || d)); if (token_text === '(') { if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { if (flags.mode !== MODE.ObjectLiteral) { allow_wrap_or_preserved_newline(); } } } if (token_text === '[') { set_mode(MODE.ArrayLiteral); } print_token(); if (opt.space_in_paren) { output_space_before_token = true; } // In all cases, if we newline while inside an expression it should be indented. indent(); } function handle_end_expr() { // statements inside expressions are not valid syntax, but... // statements must all be closed when their container closes while (flags.mode === MODE.Statement) { restore_mode(); } if (token_text === ']' && is_array(flags.mode) && flags.multiline_array && !opt.keep_array_indentation) { print_newline(); } if (opt.space_in_paren) { output_space_before_token = true; } if (token_text === ']' && opt.keep_array_indentation) { print_token(); restore_mode(); } else { restore_mode(); print_token(); } // do {} while () // no statement required after if (flags.do_while && previous_flags.mode === MODE.Conditional) { previous_flags.mode = MODE.Expression; flags.do_block = false; flags.do_while = false; } } function handle_start_block() { set_mode(MODE.BlockStatement); var empty_braces = is_next('}'); var empty_anonymous_function = empty_braces && flags.last_word === 'function' && last_type === 'TK_END_EXPR'; if (opt.brace_style === "expand") { if (last_type !== 'TK_OPERATOR' && (empty_anonymous_function || last_type === 'TK_EQUALS' || (is_special_word (flags.last_text) && flags.last_text !== 'else'))) { output_space_before_token = true; } else { print_newline(); } } else { // collapse if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') { if (last_type === 'TK_START_BLOCK') { print_newline(); } else { output_space_before_token = true; } } else { // if TK_OPERATOR or TK_START_EXPR if (is_array(previous_flags.mode) && flags.last_text === ',') { if (last_last_text === '}') { // }, { in array context output_space_before_token = true; } else { print_newline(); // [a, b, c, { } } } } print_token(); indent(); } function handle_end_block() { // statements must all be closed when their container closes while (flags.mode === MODE.Statement) { restore_mode(); } restore_mode(); var empty_braces = last_type === 'TK_START_BLOCK'; if (opt.brace_style === "expand") { if (!empty_braces) { print_newline(); } } else { // skip {} if (!empty_braces) { if (is_array(flags.mode) && opt.keep_array_indentation) { // we REALLY need a newline here, but newliner would skip that opt.keep_array_indentation = false; print_newline(); opt.keep_array_indentation = true; } else { print_newline(); } } } print_token(); } function handle_word() { if (start_of_statement()) { // The conditional starts the statement if appropriate. } else if (input_wanted_newline && !is_expression(flags.mode) && (last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) && last_type !== 'TK_EQUALS' && (opt.preserve_newlines || flags.last_text !== 'var')) { print_newline(); } if (flags.do_block && !flags.do_while) { if (token_text === 'while') { // do {} ## while () output_space_before_token = true; print_token(); output_space_before_token = true; flags.do_while = true; return; } else { // do {} should always have while as the next word. // if we don't see the expected while, recover print_newline(); flags.do_block = false; } } // if may be followed by else, or not // Bare/inline ifs are tricky // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e(); if (flags.if_block) { if (token_text !== 'else') { while (flags.mode === MODE.Statement) { restore_mode(); } flags.if_block = false; } } if (token_text === 'function') { if (flags.var_line && last_type !== 'TK_EQUALS') { flags.var_line_reindented = true; } if ((just_added_newline() || flags.last_text === ';' || flags.last_text === '}') && flags.last_text !== '{' && !is_array(flags.mode)) { // make sure there is a nice clean space of at least one blank line // before a new function definition, except in arrays if(!just_added_newline()) { print_newline(true); } if(!just_added_blankline()) { print_newline(true); } } if (last_type === 'TK_WORD') { if (flags.last_text === 'get' || flags.last_text === 'set' || flags.last_text === 'new' || flags.last_text === 'return') { output_space_before_token = true; } else { print_newline(); } } else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') { // foo = function output_space_before_token = true; } else if (is_expression(flags.mode)) { // (function } else { print_newline(); } print_token(); flags.last_word = token_text; return; } if (token_text === 'case' || (token_text === 'default' && flags.in_case_statement)) { print_newline(); if (flags.case_body || opt.jslint_happy) { // switch cases following one another flags.indentation_level--; flags.case_body = false; } print_token(); flags.in_case = true; flags.in_case_statement = true; return; } prefix = 'NONE'; if (last_type === 'TK_END_BLOCK') { if (!in_array(token_text, ['else', 'catch', 'finally'])) { prefix = 'NEWLINE'; } else { if (opt.brace_style === "expand" || opt.brace_style === "end-expand") { prefix = 'NEWLINE'; } else { prefix = 'SPACE'; output_space_before_token = true; } } } else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) { // TODO: Should this be for STATEMENT as well? prefix = 'NEWLINE'; } else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) { prefix = 'SPACE'; } else if (last_type === 'TK_STRING') { prefix = 'NEWLINE'; } else if (last_type === 'TK_WORD') { prefix = 'SPACE'; } else if (last_type === 'TK_START_BLOCK') { prefix = 'NEWLINE'; } else if (last_type === 'TK_END_EXPR') { output_space_before_token = true; prefix = 'NEWLINE'; } if (in_array(token_text, line_starters) && flags.last_text !== ')') { if (flags.last_text === 'else') { prefix = 'SPACE'; } else { prefix = 'NEWLINE'; } } if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { if (flags.mode !== MODE.ObjectLiteral) { allow_wrap_or_preserved_newline(); } } if (in_array(token_text, ['else', 'catch', 'finally'])) { if (last_type !== 'TK_END_BLOCK' || opt.brace_style === "expand" || opt.brace_style === "end-expand") { print_newline(); } else { trim_output(true); // If we trimmed and there's something other than a close block before us // put a newline back in. Handles '} // comment' scenario. if (output[output.length - 1] !== '}') { print_newline(); } output_space_before_token = true; } } else if (prefix === 'NEWLINE') { if (is_special_word (flags.last_text)) { // no newline between 'return nnn' output_space_before_token = true; } else if (last_type !== 'TK_END_EXPR') { if ((last_type !== 'TK_START_EXPR' || token_text !== 'var') && flags.last_text !== ':') { // no need to force newline on 'var': for (var x = 0...) if (token_text === 'if' && flags.last_word === 'else' && flags.last_text !== '{') { // no newline for } else if { output_space_before_token = true; } else { flags.var_line = false; flags.var_line_reindented = false; print_newline(); } } } else if (in_array(token_text, line_starters) && flags.last_text !== ')') { flags.var_line = false; flags.var_line_reindented = false; print_newline(); } } else if (is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') { print_newline(); // }, in lists get a newline treatment } else if (prefix === 'SPACE') { output_space_before_token = true; } print_token(); flags.last_word = token_text; if (token_text === 'var') { flags.var_line = true; flags.var_line_reindented = false; flags.var_line_tainted = false; } if (token_text === 'do') { flags.do_block = true; } if (token_text === 'if') { flags.if_block = true; } } function handle_semicolon() { while (flags.mode === MODE.Statement && !flags.if_block) { restore_mode(); } print_token(); flags.var_line = false; flags.var_line_reindented = false; if (flags.mode === MODE.ObjectLiteral) { // if we're in OBJECT mode and see a semicolon, its invalid syntax // recover back to treating this as a BLOCK flags.mode = MODE.BlockStatement; } } function handle_string() { if (start_of_statement()) { // The conditional starts the statement if appropriate. // One difference - strings want at least a space before output_space_before_token = true; } else if (last_type === 'TK_WORD') { output_space_before_token = true; } else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') { if (flags.mode !== MODE.ObjectLiteral) { allow_wrap_or_preserved_newline(); } } else { print_newline(); } print_token(); } function handle_equals() { if (flags.var_line) { // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done flags.var_line_tainted = true; } output_space_before_token = true; print_token(); output_space_before_token = true; } function handle_comma() { if (flags.var_line) { if (is_expression(flags.mode) || last_type === 'TK_END_BLOCK') { // do not break on comma, for(var a = 1, b = 2) flags.var_line_tainted = false; } if (flags.var_line) { flags.var_line_reindented = true; } print_token(); if (flags.var_line_tainted) { flags.var_line_tainted = false; print_newline(); } else { output_space_before_token = true; } return; } if (last_type === 'TK_END_BLOCK' && flags.mode !== MODE.Expression) { print_token(); if (flags.mode === MODE.ObjectLiteral && flags.last_text === '}') { print_newline(); } else { output_space_before_token = true; } } else { if (flags.mode === MODE.ObjectLiteral) { print_token(); print_newline(); } else { // EXPR or DO_BLOCK print_token(); output_space_before_token = true; } } } function handle_operator() { var space_before = true; var space_after = true; if (is_special_word (flags.last_text)) { // "return" had a special handling in TK_WORD. Now we need to return the favor output_space_before_token = true; print_token(); return; } // hack for actionscript's import .*; if (token_text === '*' && last_type === 'TK_DOT' && !last_last_text.match(/^\d+$/)) { print_token(); return; } if (token_text === ':' && flags.in_case) { flags.case_body = true; indent(); print_token(); print_newline(); flags.in_case = false; return; } if (token_text === '::') { // no spaces around exotic namespacing syntax operator print_token(); return; } // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1 // if there is a newline between -- or ++ and anything else we should preserve it. if (input_wanted_newline && (token_text === '--' || token_text === '++')) { print_newline(); } if (in_array(token_text, ['--', '++', '!']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array (flags.last_text, line_starters) || flags.last_text === ','))) { // unary operators (and binary +/- pretending to be unary) special cases space_before = false; space_after = false; if (flags.last_text === ';' && is_expression(flags.mode)) { // for (;; ++i) // ^^^ space_before = true; } if (last_type === 'TK_WORD' && in_array (flags.last_text, line_starters)) { space_before = true; } if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) { // { foo; --i } // foo(); --bar; print_newline(); } } else if (token_text === ':') { if (flags.ternary_depth === 0) { if (flags.mode === MODE.BlockStatement) { flags.mode = MODE.ObjectLiteral; } space_before = false; } else { flags.ternary_depth -= 1; } } else if (token_text === '?') { flags.ternary_depth += 1; } output_space_before_token = output_space_before_token || space_before; print_token(); output_space_before_token = space_after; } function handle_block_comment() { var lines = split_newlines(token_text); var j; // iterator for this case var javadoc = false; // block comment starts with a new line print_newline(false, true); if (lines.length > 1) { if (all_lines_start_with(lines.slice(1), '*')) { javadoc = true; } } // first line always indented print_token(lines[0]); for (j = 1; j < lines.length; j++) { print_newline(false, true); if (javadoc) { // javadoc: reformat and re-indent print_token(' ' + trim(lines[j])); } else { // normal comments output raw output.push(lines[j]); } } // for comments of more than one line, make sure there's a new line after print_newline(false, true); } function handle_inline_comment() { output_space_before_token = true; print_token(); output_space_before_token = true; } function handle_comment() { if (input_wanted_newline) { print_newline(false, true); } else { trim_output(true); } output_space_before_token = true; print_token(); print_newline(false, true); } function handle_dot() { if (is_special_word (flags.last_text)) { output_space_before_token = true; } else { // allow preserved newlines before dots in general // force newlines on dots after close paren when break_chained - for bar().baz() allow_wrap_or_preserved_newline (flags.last_text === ')' && opt.break_chained_methods); } print_token(); } function handle_unknown() { print_token(); if (token_text[token_text.length - 1] === '\n') { print_newline(); } } } if (typeof define === "function") { // Add support for require.js define(function(require, exports, module) { exports.js_beautify = js_beautify; }); } else if (typeof exports !== "undefined") { // Add support for CommonJS. Just put this file somewhere on your require.paths // and you will be able to `var js_beautify = require("beautify").js_beautify`. exports.js_beautify = js_beautify; } else if (typeof window !== "undefined") { // If we're running a web page and don't have either of the above, add our one global window.js_beautify = js_beautify; } else if (typeof global !== "undefined") { // If we don't even have window, try global. global.js_beautify = js_beautify; } }());
maruilian11/cdnjs
ajax/libs/js-beautify/1.3.3/beautify.js
JavaScript
mit
60,343
(function(L,O){"object"===typeof exports&&"undefined"!==typeof module?O(exports):"function"===typeof define&&define.amd?define(["exports"],O):L.async?O(L.neo_async=L.neo_async||{}):O(L.async=L.async||{})})(this,function(L){function O(a){var c=function(a){var d=J(arguments,1);setTimeout(function(){a.apply(null,d)})};Q="function"===typeof setImmediate?setImmediate:c;"object"===typeof process&&"function"===typeof process.nextTick?(C=/^v0.10/.test(process.version)?Q:process.nextTick,X=/^v0/.test(process.version)? Q:process.nextTick):X=C=Q;!1===a&&(C=function(a){a()})}function E(a){for(var c=-1,b=a.length,d=Array(b);++c<b;)d[c]=a[c];return d}function J(a,c){var b=-1,d=a.length-c;if(0>=d)return[];for(var e=Array(d);++b<d;)e[b]=a[b+c];return e}function M(a){for(var c=D(a),b=c.length,d=-1,e={};++d<b;){var f=c[d];e[f]=a[f]}return e}function ia(a){for(var c=-1,b=a.length,d=[];++c<b;){var e=a[c];e&&(d[d.length]=e)}return d}function Ua(a){for(var c=-1,b=a.length,d=Array(b),e=b;++c<b;)d[--e]=a[c];return d}function Va(a, c){for(var b=-1,d=a.length;++b<d;)if(a[b]===c)return!1;return!0}function R(a,c){for(var b=-1,d=a.length;++b<d;)c(a[b],b);return a}function S(a,c,b){for(var d=-1,e=b.length;++d<e;){var f=b[d];c(a[f],f)}return a}function K(a,c){for(var b=-1;++b<a;)c(b)}function Y(a,c){for(var b=-1,d=a.length,e=Array(d);++b<d;)e[b]=(a[b]||{})[c];return e}function Z(a,c){return a.criteria-c.criteria}function ja(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++d<e;)c(a[d],d,A(b));else for(;++d<e;)c(a[d],A(b))}function ka(a, c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,A(b));else for(;++f<g;)c(a[d[f]],A(b))}function la(a,c,b){a=a[x]();var d=-1,e;if(3===c.length)for(;!1===(e=a.next()).done;)c(e.value,++d,b);else for(;!1===(e=a.next()).done;)c(e.value,b)}function ma(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++d<e;)c(a[d],d,b(d));else for(;++d<e;)c(a[d],b(d))}function $(a,c,b){var d,e=-1,f=a.length;if(3===c.length)for(;++e<f;)d=a[e],c(d,e,b(d));else for(;++e<f;)d=a[e],c(d,b(d))}function aa(a, c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e,b(f));else for(;++g<l;)f=a[d[g]],c(f,b(f))}function ba(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(d));else for(;!1===(d=a.next()).done;)d=d.value,c(d,b(d))}function T(a,c,b){var d,e=-1,f=a.length;if(3===c.length)for(;++e<f;)d=a[e],c(d,e,b(e,d));else for(;++e<f;)d=a[e],c(d,b(e,d))}function na(a,c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e, b(g,f));else for(;++g<l;)f=a[d[g]],c(f,b(g,f))}function oa(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(e,d));else for(;!1===(d=a.next()).done;)d=d.value,c(d,b(++e,d))}function pa(a,c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e,b(e,f));else for(;++g<l;)e=d[g],f=a[e],c(f,b(e,f))}function qa(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(e,d));else for(;!1===(d=a.next()).done;)d= d.value,c(d,b(++e,d))}function A(a){return function(c,b){var d=a;a=z;d(c,b)}}function H(a){return function(c,b){var d=a;a=y;d(c,b)}}function ra(a,c,b,d){var e,f;d?(e=Array,f=E):(e=function(){return{}},f=M);return function(d,l,s){function q(a){return function(d,b){null===a&&z();d?(a=null,s=H(s),s(d,f(k))):(k[a]=b,a=null,++n===h&&s(null,k))}}s=s||y;var h,m,k,n=0;B(d)?(h=d.length,k=e(h),a(d,l,q)):d&&(x&&d[x]?(h=d.size,k=e(h),b(d,l,q)):"object"===typeof d&&(m=D(d),h=m.length,k=e(h),c(d,l,q,m)));h||s(null, e())}}function sa(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&z();c?(a=null,g=H(g),g(c)):(!!e===d&&(h[a]=b),a=null,++m===s&&g(null,ia(h)))}}g=g||y;var s,q,h,m=0;B(e)?(s=e.length,h=Array(s),a(e,f,l)):e&&(x&&e[x]?(s=e.size,h=Array(s),b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,h=Array(s),c(e,f,l,q)));if(!s)return g(null,[])}}function ta(a){return function(c,b,d){function e(){n=c[u];b(n,h)}function f(){n=c[u];b(n,u,h)}function g(){n=p.next().value;b(n,h)}function l(){n= p.next().value;b(n,u,h)}function s(){k=r[u];n=c[k];b(n,h)}function q(){k=r[u];n=c[k];b(n,k,h)}function h(b,c){b?d(b):(!!c===a&&(w[w.length]=n),++u===m?(t=z,d(null,w)):v?C(t):(v=!0,t()),v=!1)}d=A(d||y);var m,k,n,r,p,t,v=!1,u=0,w=[];B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null,[]);t()}}function ua(a){return function(c,b,d,e){function f(){n=I++;n<k&&(p=c[n],d(p,m(p,n)))}function g(){n= I++;n<k&&(p=c[n],d(p,n,m(p,n)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p,I++)))}function s(){!1===(u=v.next()).done&&(p=u.value,d(p,I,m(p,I++)))}function q(){n=I++;n<k&&(p=c[t[n]],d(p,m(p,n)))}function h(){n=I++;n<k&&(r=t[n],p=c[r],d(p,r,m(p,n)))}function m(d,b){return function(c,f){null===b&&z();c?(b=null,w=y,e=H(e),e(c)):(!!f===a&&(G[b]=d),b=null,++E===k?(e=A(e),e(null,ia(G))):F?C(w):(F=!0,w()),F=!1)}}e=e||y;var k,n,r,p,t,v,u,w,G,F=!1,I=0,E=0;B(c)?(k=c.length,w=3===d.length?g:f): c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q));if(!k||isNaN(b)||1>b)return e(null,[]);G=Array(k);K(b>k?k:b,w)}}function U(a,c,b){function d(){c(a[v],q)}function e(){c(a[v],v,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,v,q)}function l(){c(a[k[v]],q)}function s(){m=k[v];c(a[m],m,q)}function q(a,d){a?b(a):++v===h?(p=z,b(null)):!1===d?(p=z,b(null)):t?C(p):(t=!0,p());t=!1}b=A(b||y);var h,m,k,n,r,p,t=!1,v=0;B(a)? (h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null);p()}function V(a,c,b,d){function e(){w<m&&b(a[w++],h)}function f(){k=w++;k<m&&b(a[k],k,h)}function g(){!1===(t=p.next()).done&&b(t.value,h)}function l(){!1===(t=p.next()).done&&b(t.value,w++,h)}function s(){w<m&&b(a[r[w++]],h)}function q(){k=w++;k<m&&(n=r[k],b(a[n],n,h))}function h(a,b){a?(v=y,d=H(d),d(a)):++G===m?(v=z,d=A(d),d(null)): !1===b?(v=y,d=H(d),d(null)):u?C(v):(u=!0,v());u=!1}d=d||y;var m,k,n,r,p,t,v,u=!1,w=0,G=0;if(B(a))m=a.length,v=3===b.length?f:e;else if(a)if(x&&a[x])m=a.size,p=a[x](),v=3===b.length?l:g;else if("object"===typeof a)r=D(a),m=r.length,v=3===b.length?q:s;else return d(null);if(!m||isNaN(c)||1>c)return d(null);K(c>m?m:c,v)}function va(a,c,b){function d(){c(a[u],q)}function e(){c(a[u],u,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,u,q)}function l(){c(a[k[u]],q)}function s(){m=k[u]; c(a[m],m,q)}function q(a,d){a?(t=z,b=A(b),b(a,E(p))):(p[u]=d,++u===h?(t=z,b(null,p),b=z):v?C(t):(v=!0,t()),v=!1)}b=b||y;var h,m,k,n,r,p,t,v=!1,u=0;B(a)?(h=a.length,t=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),t=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,t=3===c.length?s:l));if(!h)return b(null,[]);p=Array(h);t()}function wa(a,c,b,d){return function(e,f,g){function l(a){var b=!1;return function(c,e){b&&z();b=!0;c?(g=H(g),g(c)):!!e===d?(g=H(g),g(null,a)):++h===s&&g(null)}}g=g|| y;var s,q,h=0;B(e)?(s=e.length,a(e,f,l)):e&&(x&&e[x]?(s=e.size,b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,c(e,f,l,q)));s||g(null)}}function xa(a){return function(c,b,d){function e(){n=c[u];b(n,h)}function f(){n=c[u];b(n,u,h)}function g(){n=p.next().value;b(n,h)}function l(){n=p.next().value;b(n,u,h)}function s(){n=c[r[u]];b(n,h)}function q(){k=r[u];n=c[k];b(n,k,h)}function h(b,c){b?d(b):!!c===a?(t=z,d(null,n)):++u===m?(t=z,d(null)):v?C(t):(v=!0,t());v=!1}d=A(d||y);var m,k,n,r,p,t,v=!1,u=0; B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null);t()}}function ya(a){return function(c,b,d,e){function f(){n=F++;n<k&&(p=c[n],d(p,m(p)))}function g(){n=F++;n<k&&(p=c[n],d(p,n,m(p)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p)))}function s(){!1===(u=v.next()).done&&(p=u.value,d(p,F++,m(p)))}function q(){n=F++;n<k&&(p=c[t[n]],d(p,m(p)))}function h(){F<k&&(r=t[F++],p= c[r],d(p,r,m(p)))}function m(b){var d=!1;return function(c,f){d&&z();d=!0;c?(w=y,e=H(e),e(c)):!!f===a?(w=y,e=H(e),e(null,b)):++I===k?e(null):G?C(w):(G=!0,w());G=!1}}e=e||y;var k,n,r,p,t,v,u,w,G=!1,F=0,I=0;B(c)?(k=c.length,w=3===d.length?g:f):c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q));if(!k||isNaN(b)||1>b)return e(null);K(b>k?k:b,w)}}function za(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&z();c? (a=null,g=H(g),g(c,M(m))):(!!e===d&&(m[a]=b),a=null,++h===s&&g(null,m))}}g=g||y;var s,q,h=0,m={};B(e)?(s=e.length,a(e,f,l)):e&&(x&&e[x]?(s=e.size,b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,c(e,f,l,q)));if(!s)return g(null,{})}}function Aa(a){return function(c,b,d){function e(){k=w;n=c[w];b(n,h)}function f(){k=w;n=c[w];b(n,w,h)}function g(){k=w;n=p.next().value;b(n,h)}function l(){k=w;n=p.next().value;b(n,k,h)}function s(){k=r[w];n=c[k];b(n,h)}function q(){k=r[w];n=c[k];b(n,k,h)}function h(b, c){b?d(b,u):(!!c===a&&(u[k]=n),++w===m?(t=z,d(null,u)):v?C(t):(v=!0,t()),v=!1)}d=A(d||y);var m,k,n,r,p,t,v=!1,u={},w=0;B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null,{});t()}}function Ba(a){return function(c,b,d,e){function f(){n=I++;n<k&&(p=c[n],d(p,m(p,n)))}function g(){n=I++;n<k&&(p=c[n],d(p,n,m(p,n)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p,I++)))}function s(){!1=== (u=v.next()).done&&(p=u.value,d(p,I,m(p,I++)))}function q(){I<k&&(r=t[I++],p=c[r],d(p,m(p,r)))}function h(){I<k&&(r=t[I++],p=c[r],d(p,r,m(p,r)))}function m(b,d){return function(c,f){null===d&&z();c?(d=null,w=y,e=H(e),e(c,M(F))):(!!f===a&&(F[d]=b),d=null,++E===k?(w=z,e=A(e),e(null,F)):G?C(w):(G=!0,w()),G=!1)}}e=e||y;var k,n,r,p,t,v,u,w,G=!1,F={},I=0,E=0;B(c)?(k=c.length,w=3===d.length?g:f):c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q)); if(!k||isNaN(b)||1>b)return e(null,{});K(b>k?k:b,w)}}function W(a,c,b,d){function e(d){b(d,a[v],h)}function f(d){b(d,a[v],v,h)}function g(){b(c,r.next().value,h)}function l(){b(c,r.next().value,v,h)}function s(d){b(d,a[n[v]],h)}function q(d){k=n[v];b(d,a[k],k,h)}function h(a,c){a?d(a,c):++v===m?(b=z,d(null,c)):t?C(function(){p(c)}):(t=!0,p(c));t=!1}d=A(d||y);var m,k,n,r,p,t=!1,v=0;B(a)?(m=a.length,p=4===b.length?f:e):a&&(x&&a[x]?(m=a.size,r=a[x](),p=4===b.length?l:g):"object"===typeof a&&(n=D(a), m=n.length,p=4===b.length?q:s));if(!m)return d(null,c);p(c)}function Ca(a,c,b,d){function e(d){b(d,a[--q],s)}function f(d){b(d,a[--q],q,s)}function g(d){b(d,a[k[--q]],s)}function l(d){m=k[--q];b(d,a[m],m,s)}function s(a,b){a?d(a,b):0===q?(t=z,d(null,b)):v?C(function(){t(b)}):(v=!0,t(b));v=!1}d=A(d||y);var q,h,m,k,n,r,p,t,v=!1;if(B(a))q=a.length,t=4===b.length?f:e;else if(a)if(x&&a[x]){q=a.size;p=Array(q);n=a[x]();for(h=-1;!1===(r=n.next()).done;)p[++h]=r.value;a=p;t=4===b.length?f:e}else"object"=== typeof a&&(k=D(a),q=k.length,t=4===b.length?l:g);if(!q)return d(null,c);t(c)}function Da(a,c,b){b=b||y;ca(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Ea(a,c,b){b=b||y;da(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Fa(a,c,b,d){d=d||y;ea(a,c,b,function(a,b){if(a)return d(a);d(null,!!b)})}function Ga(a,c){return B(a)?0===a.length?(c(null),!1):!0:(c(Error("First argument to waterfall must be an array of functions")),!1)}function Ha(a,c){function b(b,h){if(b)s=z,c=A(c),c(b); else if(++d===f){s=z;var m=c;c=z;2===arguments.length?m(b,h):m.apply(null,E(arguments))}else g=a[d],l=arguments,e?C(s):(e=!0,s()),e=!1}c=c||y;if(Ga(a,c)){var d=0,e=!1,f=a.length,g=a[d],l=[],s=function(){switch(g.length){case 0:try{b(null,g())}catch(a){b(a)}break;case 1:return g(b);case 2:return g(l[1],b);case 3:return g(l[1],l[2],b);case 4:return g(l[1],l[2],l[3],b);case 5:return g(l[1],l[2],l[3],l[4],b);default:return l=J(l,1),l[g.length-1]=b,g.apply(null,l)}};s()}}function Ia(){var a=E(arguments); return function(){var c=this,b=E(arguments),d=b[b.length-1];"function"===typeof d?b.pop():d=y;W(a,b,function(a,b,d){a.push(function(a){var b=J(arguments,1);d(a,b)});b.apply(c,a)},function(a,b){b=B(b)?b:[b];b.unshift(a);d.apply(c,b)})}}function Ja(a){return function(c){var b=function(){var b=this,d=E(arguments),g=d.pop()||y;return a(c,function(a,c){a.apply(b,d.concat([c]))},g)};if(1<arguments.length){var d=J(arguments,1);return b.apply(this,d)}return b}}function N(){this.tail=this.head=null;this.length= 0}function fa(a,c,b,d){function e(a){a={data:a,callback:k};n?r._tasks.unshift(a):r._tasks.push(a);C(r.process)}function f(a,b,d){if(null==b)b=y;else if("function"!==typeof b)throw Error("task callback must be a function");r.started=!0;var c=B(a)?a:[a];void 0!==a&&c.length?(n=d,k=b,R(c,e)):r.idle()&&C(r.drain)}function g(a,b){var d=!1;return function(c,e){d&&z();d=!0;h--;for(var f,g=-1,k=m.length,l=-1,s=b.length,n=2<arguments.length,q=n&&E(arguments);++l<s;){for(f=b[l];++g<k;)m[g]===f&&(m.splice(g, 1),g=k,k--);g=-1;n?f.callback.apply(f,q):f.callback(c,e);c&&a.error(c,f.data)}h<=a.concurrency-a.buffer&&a.unsaturated();0===a._tasks.length+h&&a.drain();a.process()}}function l(){for(;!r.paused&&h<r.concurrency&&r._tasks.length;){var a=r._tasks.shift();0===r._tasks.length&&r.empty();h++;m.push(a);h===r.concurrency&&r.saturated();var b=g(r,[a]);c(a.data,b)}}function s(){for(;!r.paused&&h<r.concurrency&&r._tasks.length;){for(var a=r._tasks.splice(r.payload||r._tasks.length),b=-1,d=a.length,e=Array(d);++b< d;)e[b]=a[b].data;0===r._tasks.length&&r.empty();h++;Array.prototype.push.apply(m,a);h===r.concurrency&&r.saturated();a=g(r,a);c(e,a)}}function q(){C(r.process)}if(void 0===b)b=1;else if(isNaN(b)||1>b)throw Error("Concurrency must not be zero");var h=0,m=[],k,n,r={_tasks:new N,concurrency:b,payload:d,saturated:y,unsaturated:y,buffer:b/4,empty:y,drain:y,error:y,started:!1,paused:!1,push:function(a,b){f(a,b)},kill:function(){r.drain=y;r._tasks.empty()},unshift:function(a,b){f(a,b,!0)},process:a?l:s, length:function(){return r._tasks.length},running:function(){return h},workersList:function(){return m},idle:function(){return 0===r.length()+h},pause:function(){r.paused=!0},resume:function(){!1!==r.paused&&(r.paused=!1,K(r.concurrency<r._tasks.length?r.concurrency:r._tasks.length,q))},_worker:c};return r}function Ka(a,c,b){function d(){if(0===q.length&&0===s){if(0!==g)throw Error("async.auto task has cyclic dependencies");return b(null,l)}for(;q.length&&s<c&&b!==y;){s++;var a=q.shift();if(0===a[1])a[0](a[2]); else a[0](l,a[2])}}function e(a){R(h[a]||[],function(a){a()});d()}"function"===typeof c&&(b=c,c=null);var f=D(a),g=f.length,l={};if(0===g)return b(null,l);var s=0,q=[],h={};b=A(b||y);c=c||g;S(a,function(a,d){function c(a,f){null===d&&z();s--;g--;f=2>=arguments.length?f:J(arguments,1);if(a){var h=M(l);h[d]=f;d=null;var m=b;b=y;m(a,h)}else l[d]=f,e(d),d=null}function r(){0===--v&&q.push([p,t,c])}var p,t;if(B(a)){var v=a.length-1;p=a[v];t=v;if(0===v)q.push([p,t,c]);else for(var u=-1;++u<v;){var w=a[u]; if(Va(f,w))throw u="async.auto task `"+w+"` has non-existent dependency in "+a.join(", "),Error(u);var x=h[w];x||(x=h[w]=[]);x.push(r)}}else p=a,t=0,q.push([p,t,c])},f);d()}function Wa(a){a=a.toString().replace(Xa,"");a=(a=a.match(Ya)[2].replace(" ",""))?a.split(Za):[];return a=a.map(function(a){return a.replace($a,"").trim()})}function ga(a,c,b){function d(a,e){if(++q===g||!a||s&&!s(a)){if(2>=arguments.length)return b(a,e);var f=E(arguments);return b.apply(null,f)}c(d)}function e(){c(f)}function f(a, d){if(++q===g||!a||s&&!s(a)){if(2>=arguments.length)return b(a,d);var c=E(arguments);return b.apply(null,c)}setTimeout(e,l(q))}var g,l,s,q=0;if(3>arguments.length&&"function"===typeof a)b=c||y,c=a,a=null,g=5;else switch(b=b||y,typeof a){case "object":"function"===typeof a.errorFilter&&(s=a.errorFilter);var h=a.interval;switch(typeof h){case "function":l=h;break;case "string":case "number":l=(h=+h)?function(){return h}:function(){return 0}}g=+a.times||5;break;case "number":g=a||5;break;case "string":g= +a||5;break;default:throw Error("Invalid arguments for async.retry");}if("function"!==typeof c)throw Error("Invalid arguments for async.retry");l?c(f):c(d)}function La(a){return function(){var c=E(arguments),b=c.pop(),d;try{d=a.apply(this,c)}catch(e){return b(e)}d&&"object"===typeof d&&"function"===typeof d.then?d.then(function(a){b(null,a)},function(a){b(a.message?a:Error(a))}):b(null,d)}}function Ma(a){return function(){function c(a,d){if(a)return b(null,{error:a});2<arguments.length&&(d=J(arguments, 1));b(null,{value:d})}var b;switch(arguments.length){case 1:return b=arguments[0],a(c);case 2:return b=arguments[1],a(arguments[0],c);default:var d=E(arguments),e=d.length-1;b=d[e];d[e]=c;a.apply(this,d)}}}function ha(a){function c(b){if("object"===typeof console)if(b)console.error&&console.error(b);else if(console[a]){var d=J(arguments,1);R(d,function(b){console[a](b)})}}return function(a){var d=J(arguments,1);d.push(c);a.apply(null,d)}}var y=function(){},z=function(){throw Error("Callback was already called."); },B=Array.isArray,D=Object.keys,x="function"===typeof Symbol&&Symbol.iterator,C,X,Q;O();var P=function(a,c,b){return function(d,e,f){function g(a,b){a?(f=H(f),f(a)):++q===l?f(null):!1===b&&(f=H(f),f(null))}f=f||y;var l,s,q=0;B(d)?(l=d.length,a(d,e,g)):d&&(x&&d[x]?(l=d.size,b(d,e,g)):"object"===typeof d&&(s=D(d),l=s.length,c(d,e,g,s)));l||f(null)}}(ja,ka,la),Na=ra(ma,function(a,c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,b(f));else for(;++f<g;)c(a[d[f]],b(f))},function(a, c,b){var d=-1,e=a.size,f=a[x]();if(3===c.length)for(;++d<e;)a=f.next().value,c(a,d,b(d));else for(;++d<e;)c(f.next().value,b(d))},!0),ab=ra(ma,function(a,c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,b(e));else for(;++f<g;)e=d[f],c(a[e],b(e))},function(a,c,b){var d=-1,e=a[x]();if(3===c.length)for(;!1===(a=e.next()).done;)c(a.value,++d,b(d));else for(;!1===(a=e.next()).done;)c(a.value,b(++d))},!1),Oa=sa(T,na,oa,!0),Pa=ta(!0),Qa=ua(!0),bb=sa(T,na,oa,!1),cb=ta(!1),db=ua(!1), ca=wa($,aa,ba,!0),da=xa(!0),ea=ya(!0),Ra=function(a,c,b){var d=wa(a,c,b,!1);return function(a,b,c){c=c||y;d(a,b,function(a,b){if(a)return c(a);c(null,!b)})}}($,aa,ba),Sa=function(){var a=xa(!1);return function(c,b,d){d=d||y;a(c,b,function(a,b){if(a)return d(a);d(null,!b)})}}(),Ta=function(){var a=ya(!1);return function(c,b,d,e){e=e||y;a(c,b,d,function(a,b){if(a)return e(a);e(null,!b)})}}(),eb=za(T,pa,qa,!0),fb=Aa(!0),gb=Ba(!0),hb=za(T,pa,qa,!1),ib=Aa(!1),jb=Ba(!1),kb=function(a,c,b){return function(d, e,f,g){function l(a,b){a?(g=H(g),g(a,B(h)?E(h):M(h))):++m===s?g(null,h):!1===b&&(g=H(g),g(null,B(h)?E(h):M(h)))}3===arguments.length&&(g=f,f=e,e=void 0);g=g||y;var s,q,h,m=0;B(d)?(s=d.length,h=void 0!==e?e:[],a(d,h,f,l)):d&&(x&&d[x]?(s=d.size,h=void 0!==e?e:{},b(d,h,f,l)):"object"===typeof d&&(q=D(d),s=q.length,h=void 0!==e?e:{},c(d,h,f,l,q)));s||g(null,void 0!==e?e:h||{})}}(function(a,c,b,d){var e=-1,f=a.length;if(4===b.length)for(;++e<f;)b(c,a[e],e,A(d));else for(;++e<f;)b(c,a[e],A(d))},function(a, c,b,d,e){var f,g=-1,l=e.length;if(4===b.length)for(;++g<l;)f=e[g],b(c,a[f],f,A(d));else for(;++g<l;)b(c,a[e[g]],A(d))},function(a,c,b,d){var e=-1,f=a[x]();if(4===b.length)for(;!1===(a=f.next()).done;)b(c,a.value,++e,A(d));else for(;!1===(a=f.next()).done;)b(c,a.value,A(d))}),lb=function(a,c,b){return function(d,e,f){function g(a){var b=!1;return function(d,c){b&&z();b=!0;s[q]={value:a,criteria:c};d?(f=H(f),f(d)):++q===l&&(s.sort(Z),f(null,Y(s,"value")))}}f=f||y;var l,s,q=0;if(B(d))l=d.length,s=Array(l), a(d,e,g);else if(d)if(x&&d[x])l=d.size,s=Array(l),b(d,e,g);else if("object"===typeof d){var h=D(d);l=h.length;s=Array(l);c(d,e,g,h)}l||f(null,[])}}($,aa,ba),mb=function(a,c,b){return function(d,e,f){function g(a,b){b&&Array.prototype.push.apply(q,B(b)?b:[b]);a?(f=H(f),f(a,E(q))):++s===l&&f(null,q)}f=f||y;var l,s=0,q=[];if(B(d))l=d.length,a(d,e,g);else if(d)if(x&&d[x])l=d.size,b(d,e,g);else if("object"===typeof d){var h=D(d);l=h.length;c(d,e,g,h)}l||f(null,q)}}(ja,ka,la),nb=function(a,c){return function(b, d){function e(a){return function(b,c){null===a&&z();b?(a=null,d=H(d),d(b,l)):(l[a]=2>=arguments.length?c:J(arguments,1),a=null,++s===f&&d(null,l))}}d=d||y;var f,g,l,s=0;B(b)?(f=b.length,l=Array(f),a(b,e)):b&&"object"===typeof b&&(g=D(b),f=g.length,l={},c(b,e,g));f||d(null,l)}}(function(a,c){for(var b=-1,d=a.length;++b<d;)a[b](c(b))},function(a,c,b){for(var d,e=-1,f=b.length;++e<f;)d=b[e],a[d](c(d))}),ob=Ja(Na),pb=Ja(va),qb=ha("log"),rb=ha("dir"),P={VERSION:"2.0.1",each:P,eachSeries:U,eachLimit:V, forEach:P,forEachSeries:U,forEachLimit:V,eachOf:P,eachOfSeries:U,eachOfLimit:V,forEachOf:P,forEachOfSeries:U,forEachOfLimit:V,map:Na,mapSeries:va,mapLimit:function(a,c,b,d){function e(){k=G++;k<m&&b(a[k],h(k))}function f(){k=G++;k<m&&b(a[k],k,h(k))}function g(){!1===(t=p.next()).done&&b(t.value,h(G++))}function l(){!1===(t=p.next()).done&&b(t.value,G,h(G++))}function s(){k=G++;k<m&&b(a[r[k]],h(k))}function q(){k=G++;k<m&&(n=r[k],b(a[n],n,h(k)))}function h(a){return function(b,c){null===a&&z();b?(a= null,u=y,d=H(d),d(b,E(v))):(v[a]=c,a=null,++A===m?(u=z,d(null,v),d=z):w?C(u):(w=!0,u()),w=!1)}}d=d||y;var m,k,n,r,p,t,v,u,w=!1,G=0,A=0;B(a)?(m=a.length,u=3===b.length?f:e):a&&(x&&a[x]?(m=a.size,p=a[x](),u=3===b.length?l:g):"object"===typeof a&&(r=D(a),m=r.length,u=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,[]);v=Array(m);K(c>m?m:c,u)},mapValues:ab,mapValuesSeries:function(a,c,b){function d(){m=u;c(a[u],q)}function e(){m=u;c(a[u],u,q)}function f(){m=u;r=n.next().value;c(r,q)}function g(){m= u;r=n.next().value;c(r,u,q)}function l(){m=k[u];c(a[m],q)}function s(){m=k[u];c(a[m],m,q)}function q(a,d){a?(p=z,b=A(b),b(a,M(v))):(v[m]=d,++u===h?(p=z,b(null,v),b=z):t?C(p):(t=!0,p()),t=!1)}b=b||y;var h,m,k,n,r,p,t=!1,v={},u=0;B(a)?(h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null,v);p()},mapValuesLimit:function(a,c,b,d){function e(){k=G++;k<m&&b(a[k],h(k))}function f(){k=G++;k<m&&b(a[k], k,h(k))}function g(){!1===(t=p.next()).done&&b(t.value,h(G++))}function l(){!1===(t=p.next()).done&&b(t.value,G,h(G++))}function s(){k=G++;k<m&&(n=r[k],b(a[n],h(n)))}function q(){k=G++;k<m&&(n=r[k],b(a[n],n,h(n)))}function h(a){return function(b,c){null===a&&z();b?(a=null,v=y,d=H(d),d(b,M(w))):(w[a]=c,a=null,++A===m?d(null,w):u?C(v):(u=!0,v()),u=!1)}}d=d||y;var m,k,n,r,p,t,v,u=!1,w={},G=0,A=0;B(a)?(m=a.length,v=3===b.length?f:e):a&&(x&&a[x]?(m=a.size,p=a[x](),v=3===b.length?l:g):"object"===typeof a&& (r=D(a),m=r.length,v=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,w);K(c>m?m:c,v)},filter:Oa,filterSeries:Pa,filterLimit:Qa,select:Oa,selectSeries:Pa,selectLimit:Qa,reject:bb,rejectSeries:cb,rejectLimit:db,detect:ca,detectSeries:da,detectLimit:ea,find:ca,findSeries:da,findLimit:ea,pick:eb,pickSeries:fb,pickLimit:gb,omit:hb,omitSeries:ib,omitLimit:jb,reduce:W,inject:W,foldl:W,reduceRight:Ca,foldr:Ca,transform:kb,transformSeries:function(a,c,b,d){function e(){b(t,a[u],h)}function f(){b(t,a[u], u,h)}function g(){b(t,r.next().value,h)}function l(){b(t,r.next().value,u,h)}function s(){b(t,a[n[u]],h)}function q(){k=n[u];b(t,a[k],k,h)}function h(a,b){a?d(a,t):++u===m?(p=z,d(null,t)):!1===b?(p=z,d(null,t)):v?C(p):(v=!0,p());v=!1}3===arguments.length&&(d=b,b=c,c=void 0);d=A(d||y);var m,k,n,r,p,t,v=!1,u=0;B(a)?(m=a.length,t=void 0!==c?c:[],p=4===b.length?f:e):a&&(x&&a[x]?(m=a.size,r=a[x](),t=void 0!==c?c:{},p=4===b.length?l:g):"object"===typeof a&&(n=D(a),m=n.length,t=void 0!==c?c:{},p=4===b.length? q:s));if(!m)return d(null,void 0!==c?c:t||{});p()},transformLimit:function(a,c,b,d,e){function f(){n=F++;n<k&&d(w,a[n],A(m))}function g(){n=F++;n<k&&d(w,a[n],n,A(m))}function l(){!1===(v=t.next()).done&&d(w,v.value,A(m))}function s(){!1===(v=t.next()).done&&d(w,v.value,F++,A(m))}function q(){n=F++;n<k&&d(w,a[p[n]],A(m))}function h(){n=F++;n<k&&(r=p[n],d(w,a[r],r,A(m)))}function m(a,b){a?(u=y,e(a,B(w)?E(w):M(w)),e=y):++I===k?e(null,w):!1===b?(u=y,e(null,B(w)?E(w):M(w)),e=y):z?C(u):(z=!0,u());z=!1} 4===arguments.length&&(e=d,d=b,b=void 0);e=e||y;var k,n,r,p,t,v,u,w,z=!1,F=0,I=0;B(a)?(k=a.length,w=void 0!==b?b:[],u=4===d.length?g:f):a&&(x&&a[x]?(k=a.size,t=a[x](),w=void 0!==b?b:{},u=4===d.length?s:l):"object"===typeof a&&(p=D(a),k=p.length,w=void 0!==b?b:{},u=4===d.length?h:q));if(!k||isNaN(c)||1>c)return e(null,void 0!==b?b:w||{});K(c>k?k:c,u)},sortBy:lb,sortBySeries:function(a,c,b){function d(){k=a[u];c(k,q)}function e(){k=a[u];c(k,u,q)}function f(){k=r.next().value;c(k,q)}function g(){k=r.next().value; c(k,u,q)}function l(){k=a[n[u]];c(k,q)}function s(){m=n[u];k=a[m];c(k,m,q)}function q(a,d){p[u]={value:k,criteria:d};a?b(a):++u===h?(t=z,p.sort(Z),b(null,Y(p,"value"))):v?C(t):(v=!0,t());v=!1}b=A(b||y);var h,m,k,n,r,p,t,v=!1,u=0;B(a)?(h=a.length,t=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,r=a[x](),t=3===c.length?g:f):"object"===typeof a&&(n=D(a),h=n.length,t=3===c.length?s:l));if(!h)return b(null,[]);p=Array(h);t()},sortByLimit:function(a,c,b,d){function e(){F<m&&(r=a[F++],b(r,h(r)))}function f(){k= F++;k<m&&(r=a[k],b(r,k,h(r)))}function g(){!1===(v=t.next()).done&&(r=v.value,b(r,h(r)))}function l(){!1===(v=t.next()).done&&(r=v.value,b(r,F++,h(r)))}function s(){F<m&&(r=a[p[F++]],b(r,h(r)))}function q(){F<m&&(n=p[F++],r=a[n],b(r,n,h(r)))}function h(a){var b=!1;return function(c,e){b&&z();b=!0;u[E]={value:a,criteria:e};c?(w=y,d(c),d=y):++E===m?(u.sort(Z),d(null,Y(u,"value"))):A?C(w):(A=!0,w());A=!1}}d=d||y;var m,k,n,r,p,t,v,u,w,A=!1,F=0,E=0;B(a)?(m=a.length,w=3===b.length?f:e):a&&(x&&a[x]?(m=a.size, t=a[x](),w=3===b.length?l:g):"object"===typeof a&&(p=D(a),m=p.length,w=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,[]);u=Array(m);K(c>m?m:c,w)},some:Da,someSeries:Ea,someLimit:Fa,any:Da,anySeries:Ea,anyLimit:Fa,every:Ra,everySeries:Sa,everyLimit:Ta,all:Ra,allSeries:Sa,allLimit:Ta,concat:mb,concatSeries:function(a,c,b){function d(){c(a[u],q)}function e(){c(a[u],u,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,u,q)}function l(){c(a[k[u]],q)}function s(){m=k[u];c(a[m], m,q)}function q(a,d){d&&Array.prototype.push.apply(v,B(d)?d:[d]);a?b(a,v):++u===h?(p=z,b(null,v)):t?C(p):(t=!0,p());t=!1}b=A(b||y);var h,m,k,n,r,p,t=!1,v=[],u=0;B(a)?(h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null,v);p()},concatLimit:function(a,c,b,d){function e(){w<k&&b(a[w++],A(h))}function f(){n=w++;n<k&&b(a[n],n,A(h))}function g(){!1===(t=p.next()).done&&b(t.value,A(h))}function l(){!1=== (t=p.next()).done&&b(t.value,w++,A(h))}function s(){w<k&&b(a[F[w++]],A(h))}function q(){w<k&&(r=F[w++],b(a[r],r,A(h)))}function h(a,b){b&&Array.prototype.push.apply(m,B(b)?b:[b]);a?(v=y,d=H(d),d(a,m)):++E===k?(v=z,d=A(d),d(null,m)):u?C(v):(u=!0,v());u=!1}d=d||y;var m=[],k,n,r,p,t,v,u=!1,w=0,E=0;if(B(a))k=a.length,v=3===b.length?f:e;else if(a)if(x&&a[x])k=a.size,p=a[x](),v=3===b.length?l:g;else if("object"===typeof a){var F=D(a);k=F.length;v=3===b.length?q:s}if(!k||isNaN(c)||1>c)return d(null,m);K(c> k?k:c,v)},parallel:nb,series:function(a,c){function b(){g=m;a[m](e)}function d(){g=l[m];a[g](e)}function e(a,b){a?(q=z,c=A(c),c(a,s)):(s[g]=2>=arguments.length?b:J(arguments,1),++m===f?(q=z,c(null,s)):h?C(q):(h=!0,q()),h=!1)}c=c||y;var f,g,l,s,q,h=!1,m=0;if(B(a))f=a.length,s=Array(f),q=b;else if(a&&"object"===typeof a)l=D(a),f=l.length,s={},q=d;else return c(null);if(!f)return c(null,s);q()},parallelLimit:function(a,c,b){function d(){l=n++;if(l<g)a[l](f(l))}function e(){n<g&&(s=q[n++],a[s](f(s)))} function f(a){return function(d,c){null===a&&z();d?(a=null,m=y,b=H(b),b(d,h)):(h[a]=2>=arguments.length?c:J(arguments,1),a=null,++r===g?b(null,h):k?C(m):(k=!0,m()),k=!1)}}b=b||y;var g,l,s,q,h,m,k=!1,n=0,r=0;B(a)?(g=a.length,h=Array(g),m=d):a&&"object"===typeof a&&(q=D(a),g=q.length,h={},m=e);if(!g||isNaN(c)||1>c)return b(null,h);K(c>g?g:c,m)},waterfall:function(a,c){function b(){f=!1;switch(h.length){case 0:case 1:return q(d);case 2:return q(h[1],d);case 3:return q(h[1],h[2],d);case 4:return q(h[1], h[2],h[3],d);case 5:return q(h[1],h[2],h[3],h[4],d);case 6:return q(h[1],h[2],h[3],h[4],h[5],d);default:return h=J(h,1),h.push(d),q.apply(null,h)}}function d(d,k){f&&z();f=!0;d?(e=c,c=z,e(d)):++l===s?(e=c,c=z,2>=arguments.length?e(d,k):e.apply(null,E(arguments))):(h=arguments,q=a[l]||z,g?C(b):(g=!0,b()),g=!1)}c=c||y;if(Ga(a,c)){var e,f,g,l=0,s=a.length,q=a[l],h=[];b()}},angelFall:Ha,angelfall:Ha,whilst:function(a,c,b){function d(){g?C(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c); 2>=arguments.length?a(e)?d():b(null,e):(e=J(arguments,1),a.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||y;var g=!1;a()?d():b(null)},doWhilst:function(a,c,b){function d(){g?C(e):(g=!0,a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?d():b(null,e):(e=J(arguments,1),c.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||y;var g=!1;e()},until:function(a,c,b){function d(){g?C(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length? a(e)?b(null,e):d():(e=J(arguments,1),a.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||y;var g=!1;a()?b(null):d()},doUntil:function(a,c,b){function d(){g?C(e):(g=!0,a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?b(null,e):d():(e=J(arguments,1),c.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||y;var g=!1;e()},during:function(a,c,b){function d(a,d){if(a)return b(a);d?c(e):b(null)}function e(c){if(c)return b(c);a(d)}b=b||y;a(d)},doDuring:function(a, c,b){function d(d,c){if(d)return b(d);c?a(e):b(null)}function e(a,e){if(a)return b(a);switch(arguments.length){case 0:case 1:c(d);break;case 2:c(e,d);break;default:var l=J(arguments,1);l.push(d);c.apply(null,l)}}b=b||y;d(null,!0)},forever:function(a,c){function b(){a(d)}function d(a){if(a){if(c)return c(a);throw a;}e?C(b):(e=!0,b());e=!1}var e=!1;b()},compose:function(){return Ia.apply(null,Ua(arguments))},seq:Ia,applyEach:ob,applyEachSeries:pb,queue:function(a,c){return fa(!0,a,c)},priorityQueue:function(a, c){var b=fa(!0,a,c);b.push=function(a,c,f){b.started=!0;c=c||0;var g=B(a)?a:[a],l=g.length;if(void 0===a||0===l)b.idle()&&C(b.drain);else{f="function"===typeof f?f:y;for(a=b._tasks.head;a&&c>=a.priority;)a=a.next;for(;l--;){var s={data:g[l],priority:c,callback:f};a?b._tasks.insertBefore(a,s):b._tasks.push(s);C(b.process)}}};delete b.unshift;return b},cargo:function(a,c){return fa(!1,a,1,c)},auto:Ka,autoInject:function(a,c,b){var d={};S(a,function(a,b){var c,l=a.length;if(B(a)){if(0===l)throw Error("autoInject task functions require explicit parameters."); c=E(a);l=c.length-1;a=c[l];if(0===l){d[b]=a;return}}else{if(1===l){d[b]=a;return}c=Wa(a);if(0===l&&0===c.length)throw Error("autoInject task functions require explicit parameters.");l=c.length-1}c[l]=function(b,d){switch(l){case 1:a(b[c[0]],d);break;case 2:a(b[c[0]],b[c[1]],d);break;case 3:a(b[c[0]],b[c[1]],b[c[2]],d);break;default:for(var f=-1;++f<l;)c[f]=b[c[f]];c[f]=d;a.apply(null,c)}};d[b]=c},D(a));Ka(d,c,b)},retry:ga,retryable:function(a,c){c||(c=a,a=null);return function(){function b(a){c(a)} function d(a){c(g[0],a)}function e(a){c(g[0],g[1],a)}var f,g=E(arguments),l=g.length-1,s=g[l];switch(c.length){case 1:f=b;break;case 2:f=d;break;case 3:f=e;break;default:f=function(a){g[l]=a;c.apply(null,g)}}a?ga(a,f,s):ga(f,s)}},iterator:function(a){function c(e){var f=function(){b&&a[d[e]||e].apply(null,E(arguments));return f.next()};f.next=function(){return e<b-1?c(e+1):null};return f}var b=0,d=[];B(a)?b=a.length:(d=D(a),b=d.length);return c(0)},times:function(a,c,b){function d(c){return function(d, l){null===c&&z();e[c]=l;c=null;d?(b(d),b=y):0===--a&&b(null,e)}}b=b||y;a=+a;if(isNaN(a)||1>a)return b(null,[]);var e=Array(a);K(a,function(a){c(a,d(a))})},timesSeries:function(a,c,b){function d(){c(l,e)}function e(c,e){f[l]=e;c?(b(c),b=z):++l>=a?(b(null,f),b=z):g?C(d):(g=!0,d());g=!1}b=b||y;a=+a;if(isNaN(a)||1>a)return b(null,[]);var f=Array(a),g=!1,l=0;d()},timesLimit:function(a,c,b,d){function e(){var c=s++;c<a&&b(c,f(c))}function f(b){return function(c,f){null===b&&z();g[b]=f;b=null;c?(d(c),d= y):++q>=a?(d(null,g),d=z):l?C(e):(l=!0,e());l=!1}}d=d||y;a=+a;if(isNaN(a)||1>a||isNaN(c)||1>c)return d(null,[]);var g=Array(a),l=!1,s=0,q=0;K(c>a?a:c,e)},race:function(a,c){c=H(c||y);var b,d,e=-1;if(B(a))for(b=a.length;++e<b;)a[e](c);else if(a&&"object"===typeof a)for(d=D(a),b=d.length;++e<b;)a[d[e]](c);else return c(new TypeError("First argument to race must be a collection of functions"));b||c(null)},apply:function(a){switch(arguments.length){case 0:case 1:return a;case 2:return a.bind(null,arguments[1]); case 3:return a.bind(null,arguments[1],arguments[2]);case 4:return a.bind(null,arguments[1],arguments[2],arguments[3]);case 5:return a.bind(null,arguments[1],arguments[2],arguments[3],arguments[4]);default:var c=arguments.length,b=0,d=Array(c);for(d[b]=null;++b<c;)d[b]=arguments[b];return a.bind.apply(a,d)}},nextTick:X,setImmediate:Q,memoize:function(a,c){c=c||function(a){return a};var b={},d={},e=function(){function e(){var a=E(arguments);b[s]=a;var c=d[s];delete d[s];for(var f=-1,g=c.length;++f< g;)c[f].apply(null,a)}var g=E(arguments),l=g.pop(),s=c.apply(null,g);if(b.hasOwnProperty(s))C(function(){l.apply(null,b[s])});else{if(d.hasOwnProperty(s))return d[s].push(l);d[s]=[l];g.push(e);a.apply(null,g)}};e.memo=b;e.unmemoized=a;return e},unmemoize:function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},ensureAsync:function(a){return function(){var c=E(arguments),b=c.length-1,d=c[b],e=!0;c[b]=function(){var a=E(arguments);e?C(function(){d.apply(null,a)}):d.apply(null,a)}; a.apply(this,c);e=!1}},constant:function(){var a=[null].concat(E(arguments));return function(c){c=arguments[arguments.length-1];c.apply(this,a)}},asyncify:La,wrapSync:La,log:qb,dir:rb,reflect:Ma,reflectAll:function(a){function c(a,b){d[b]=Ma(a)}var b,d,e;B(a)?(b=a.length,d=Array(b),R(a,c)):a&&"object"===typeof a&&(e=D(a),b=e.length,d={},S(a,c,e));return d},timeout:function(a,c,b){function d(){var c=Error('Callback function "'+(a.name||"anonymous")+'" timed out.');c.code="ETIMEDOUT";b&&(c.info=b); l=null;g(c)}function e(){null!==l&&(f(g,E(arguments)),clearTimeout(l))}function f(a,b){switch(b.length){case 0:a();break;case 1:a(b[0]);break;case 2:a(b[0],b[1]);break;default:a.apply(null,b)}}var g,l;return function(){l=setTimeout(d,c);var b=E(arguments),q=b.length-1;g=b[q];b[q]=e;f(a,b)}},createLogger:ha,safe:function(){O();return L},fast:function(){O(!1);return L}};L["default"]=P;S(P,function(a,c){L[c]=a},D(P));N.prototype._removeLink=function(a){(this.head=a.next)?a.next.prev=a.prev:this.tail= a.prev;a.prev=null;a.next=null;this.length--;return a};N.prototype.empty=N;N.prototype._setInitial=function(a){this.length=1;this.head=this.tail=a};N.prototype.insertBefore=function(a,c){c.prev=a.prev;c.next=a;a.prev?a.prev.next=c:this.head=c;a.prev=c;this.length++};N.prototype.unshift=function(a){this.head?this.insertBefore(this.head,a):this._setInitial(a)};N.prototype.push=function(a){var c=this.tail;c?(a.prev=c,a.next=c.next,this.tail=a,c.next=a,this.length++):this._setInitial(a)};N.prototype.shift= function(){return this.head&&this._removeLink(this.head)};N.prototype.splice=function(a){for(var c,b=[];a--&&(c=this.shift());)b.push(c);return b};var Ya=/^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Za=/,/,$a=/(=.+)?(\s*)$/,Xa=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg});
hare1039/cdnjs
ajax/libs/neo-async/2.0.1/async.min.js
JavaScript
mit
35,775
/* * tclInt.h -- * * Declarations of things used internally by the Tcl interpreter. * * Copyright (c) 1987-1993 The Regents of the University of California. * Copyright (c) 1993-1997 Lucent Technologies. * Copyright (c) 1994-1998 Sun Microsystems, Inc. * Copyright (c) 1998-1999 by Scriptics Corporation. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) Id */ #ifndef _TCLINT #define _TCLINT /* * Common include files needed by most of the Tcl source files are * included here, so that system-dependent personalizations for the * include files only have to be made in once place. This results * in a few extra includes, but greater modularity. The order of * the three groups of #includes is important. For example, stdio.h * is needed by tcl.h, and the _ANSI_ARGS_ declaration in tcl.h is * needed by stdlib.h in some configurations. */ #include <stdio.h> #ifndef _TCL #include "tcl.h" #endif #include <ctype.h> #ifdef NO_LIMITS_H # include "../compat/limits.h" #else # include <limits.h> #endif #ifdef NO_STDLIB_H # include "../compat/stdlib.h" #else # include <stdlib.h> #endif #ifdef NO_STRING_H #include "../compat/string.h" #else #include <string.h> #endif #undef TCL_STORAGE_CLASS #ifdef BUILD_tcl # define TCL_STORAGE_CLASS DLLEXPORT #else # ifdef USE_TCL_STUBS # define TCL_STORAGE_CLASS # else # define TCL_STORAGE_CLASS DLLIMPORT # endif #endif /* * The following procedures allow namespaces to be customized to * support special name resolution rules for commands/variables. * */ struct Tcl_ResolvedVarInfo; typedef Tcl_Var (Tcl_ResolveRuntimeVarProc) _ANSI_ARGS_(( Tcl_Interp* interp, struct Tcl_ResolvedVarInfo *vinfoPtr)); typedef void (Tcl_ResolveVarDeleteProc) _ANSI_ARGS_(( struct Tcl_ResolvedVarInfo *vinfoPtr)); /* * The following structure encapsulates the routines needed to resolve a * variable reference at runtime. Any variable specific state will typically * be appended to this structure. */ typedef struct Tcl_ResolvedVarInfo { Tcl_ResolveRuntimeVarProc *fetchProc; Tcl_ResolveVarDeleteProc *deleteProc; } Tcl_ResolvedVarInfo; typedef int (Tcl_ResolveCompiledVarProc) _ANSI_ARGS_(( Tcl_Interp* interp, char* name, int length, Tcl_Namespace *context, Tcl_ResolvedVarInfo **rPtr)); typedef int (Tcl_ResolveVarProc) _ANSI_ARGS_(( Tcl_Interp* interp, char* name, Tcl_Namespace *context, int flags, Tcl_Var *rPtr)); typedef int (Tcl_ResolveCmdProc) _ANSI_ARGS_((Tcl_Interp* interp, char* name, Tcl_Namespace *context, int flags, Tcl_Command *rPtr)); typedef struct Tcl_ResolverInfo { Tcl_ResolveCmdProc *cmdResProc; /* Procedure handling command name * resolution. */ Tcl_ResolveVarProc *varResProc; /* Procedure handling variable name * resolution for variables that * can only be handled at runtime. */ Tcl_ResolveCompiledVarProc *compiledVarResProc; /* Procedure handling variable name * resolution at compile time. */ } Tcl_ResolverInfo; /* *---------------------------------------------------------------- * Data structures related to namespaces. *---------------------------------------------------------------- */ /* * The structure below defines a namespace. * Note: the first five fields must match exactly the fields in a * Tcl_Namespace structure (see tcl.h). If you change one, be sure to * change the other. */ typedef struct Namespace { char *name; /* The namespace's simple (unqualified) * name. This contains no ::'s. The name of * the global namespace is "" although "::" * is an synonym. */ char *fullName; /* The namespace's fully qualified name. * This starts with ::. */ ClientData clientData; /* An arbitrary value associated with this * namespace. */ Tcl_NamespaceDeleteProc *deleteProc; /* Procedure invoked when deleting the * namespace to, e.g., free clientData. */ struct Namespace *parentPtr; /* Points to the namespace that contains * this one. NULL if this is the global * namespace. */ Tcl_HashTable childTable; /* Contains any child namespaces. Indexed * by strings; values have type * (Namespace *). */ long nsId; /* Unique id for the namespace. */ Tcl_Interp *interp; /* The interpreter containing this * namespace. */ int flags; /* OR-ed combination of the namespace * status flags NS_DYING and NS_DEAD * listed below. */ int activationCount; /* Number of "activations" or active call * frames for this namespace that are on * the Tcl call stack. The namespace won't * be freed until activationCount becomes * zero. */ int refCount; /* Count of references by namespaceName * * objects. The namespace can't be freed * until refCount becomes zero. */ Tcl_HashTable cmdTable; /* Contains all the commands currently * registered in the namespace. Indexed by * strings; values have type (Command *). * Commands imported by Tcl_Import have * Command structures that point (via an * ImportedCmdRef structure) to the * Command structure in the source * namespace's command table. */ Tcl_HashTable varTable; /* Contains all the (global) variables * currently in this namespace. Indexed * by strings; values have type (Var *). */ char **exportArrayPtr; /* Points to an array of string patterns * specifying which commands are exported. * A pattern may include "string match" * style wildcard characters to specify * multiple commands; however, no namespace * qualifiers are allowed. NULL if no * export patterns are registered. */ int numExportPatterns; /* Number of export patterns currently * registered using "namespace export". */ int maxExportPatterns; /* Mumber of export patterns for which * space is currently allocated. */ int cmdRefEpoch; /* Incremented if a newly added command * shadows a command for which this * namespace has already cached a Command * * pointer; this causes all its cached * Command* pointers to be invalidated. */ int resolverEpoch; /* Incremented whenever the name resolution * rules change for this namespace; this * invalidates all byte codes compiled in * the namespace, causing the code to be * recompiled under the new rules. */ Tcl_ResolveCmdProc *cmdResProc; /* If non-null, this procedure overrides * the usual command resolution mechanism * in Tcl. This procedure is invoked * within Tcl_FindCommand to resolve all * command references within the namespace. */ Tcl_ResolveVarProc *varResProc; /* If non-null, this procedure overrides * the usual variable resolution mechanism * in Tcl. This procedure is invoked * within Tcl_FindNamespaceVar to resolve all * variable references within the namespace * at runtime. */ Tcl_ResolveCompiledVarProc *compiledVarResProc; /* If non-null, this procedure overrides * the usual variable resolution mechanism * in Tcl. This procedure is invoked * within LookupCompiledLocal to resolve * variable references within the namespace * at compile time. */ } Namespace; /* * Flags used to represent the status of a namespace: * * NS_DYING - 1 means Tcl_DeleteNamespace has been called to delete the * namespace but there are still active call frames on the Tcl * stack that refer to the namespace. When the last call frame * referring to it has been popped, it's variables and command * will be destroyed and it will be marked "dead" (NS_DEAD). * The namespace can no longer be looked up by name. * NS_DEAD - 1 means Tcl_DeleteNamespace has been called to delete the * namespace and no call frames still refer to it. Its * variables and command have already been destroyed. This bit * allows the namespace resolution code to recognize that the * namespace is "deleted". When the last namespaceName object * in any byte code code unit that refers to the namespace has * been freed (i.e., when the namespace's refCount is 0), the * namespace's storage will be freed. */ #define NS_DYING 0x01 #define NS_DEAD 0x02 /* * Flag passed to TclGetNamespaceForQualName to have it create all namespace * components of a namespace-qualified name that cannot be found. The new * namespaces are created within their specified parent. Note that this * flag's value must not conflict with the values of the flags * TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, and FIND_ONLY_NS (defined in * tclNamesp.c). */ #define CREATE_NS_IF_UNKNOWN 0x800 /* *---------------------------------------------------------------- * Data structures related to variables. These are used primarily * in tclVar.c *---------------------------------------------------------------- */ /* * The following structure defines a variable trace, which is used to * invoke a specific C procedure whenever certain operations are performed * on a variable. */ typedef struct VarTrace { Tcl_VarTraceProc *traceProc;/* Procedure to call when operations given * by flags are performed on variable. */ ClientData clientData; /* Argument to pass to proc. */ int flags; /* What events the trace procedure is * interested in: OR-ed combination of * TCL_TRACE_READS, TCL_TRACE_WRITES, * TCL_TRACE_UNSETS and TCL_TRACE_ARRAY. */ struct VarTrace *nextPtr; /* Next in list of traces associated with * a particular variable. */ } VarTrace; /* * When a variable trace is active (i.e. its associated procedure is * executing), one of the following structures is linked into a list * associated with the variable's interpreter. The information in * the structure is needed in order for Tcl to behave reasonably * if traces are deleted while traces are active. */ typedef struct ActiveVarTrace { struct Var *varPtr; /* Variable that's being traced. */ struct ActiveVarTrace *nextPtr; /* Next in list of all active variable * traces for the interpreter, or NULL * if no more. */ VarTrace *nextTracePtr; /* Next trace to check after current * trace procedure returns; if this * trace gets deleted, must update pointer * to avoid using free'd memory. */ } ActiveVarTrace; /* * The following structure describes an enumerative search in progress on * an array variable; this are invoked with options to the "array" * command. */ typedef struct ArraySearch { int id; /* Integer id used to distinguish among * multiple concurrent searches for the * same array. */ struct Var *varPtr; /* Pointer to array variable that's being * searched. */ Tcl_HashSearch search; /* Info kept by the hash module about * progress through the array. */ Tcl_HashEntry *nextEntry; /* Non-null means this is the next element * to be enumerated (it's leftover from * the Tcl_FirstHashEntry call or from * an "array anymore" command). NULL * means must call Tcl_NextHashEntry * to get value to return. */ struct ArraySearch *nextPtr;/* Next in list of all active searches * for this variable, or NULL if this is * the last one. */ } ArraySearch; /* * The structure below defines a variable, which associates a string name * with a Tcl_Obj value. These structures are kept in procedure call frames * (for local variables recognized by the compiler) or in the heap (for * global variables and any variable not known to the compiler). For each * Var structure in the heap, a hash table entry holds the variable name and * a pointer to the Var structure. */ typedef struct Var { union { Tcl_Obj *objPtr; /* The variable's object value. Used for * scalar variables and array elements. */ Tcl_HashTable *tablePtr;/* For array variables, this points to * information about the hash table used * to implement the associative array. * Points to malloc-ed data. */ struct Var *linkPtr; /* If this is a global variable being * referred to in a procedure, or a variable * created by "upvar", this field points to * the referenced variable's Var struct. */ } value; char *name; /* NULL if the variable is in a hashtable, * otherwise points to the variable's * name. It is used, e.g., by TclLookupVar * and "info locals". The storage for the * characters of the name is not owned by * the Var and must not be freed when * freeing the Var. */ Namespace *nsPtr; /* Points to the namespace that contains * this variable or NULL if the variable is * a local variable in a Tcl procedure. */ Tcl_HashEntry *hPtr; /* If variable is in a hashtable, either the * hash table entry that refers to this * variable or NULL if the variable has been * detached from its hash table (e.g. an * array is deleted, but some of its * elements are still referred to in * upvars). NULL if the variable is not in a * hashtable. This is used to delete an * variable from its hashtable if it is no * longer needed. */ int refCount; /* Counts number of active uses of this * variable, not including its entry in the * call frame or the hash table: 1 for each * additional variable whose linkPtr points * here, 1 for each nested trace active on * variable, and 1 if the variable is a * namespace variable. This record can't be * deleted until refCount becomes 0. */ VarTrace *tracePtr; /* First in list of all traces set for this * variable. */ ArraySearch *searchPtr; /* First in list of all searches active * for this variable, or NULL if none. */ int flags; /* Miscellaneous bits of information about * variable. See below for definitions. */ } Var; /* * Flag bits for variables. The first three (VAR_SCALAR, VAR_ARRAY, and * VAR_LINK) are mutually exclusive and give the "type" of the variable. * VAR_UNDEFINED is independent of the variable's type. * * VAR_SCALAR - 1 means this is a scalar variable and not * an array or link. The "objPtr" field points * to the variable's value, a Tcl object. * VAR_ARRAY - 1 means this is an array variable rather * than a scalar variable or link. The * "tablePtr" field points to the array's * hashtable for its elements. * VAR_LINK - 1 means this Var structure contains a * pointer to another Var structure that * either has the real value or is itself * another VAR_LINK pointer. Variables like * this come about through "upvar" and "global" * commands, or through references to variables * in enclosing namespaces. * VAR_UNDEFINED - 1 means that the variable is in the process * of being deleted. An undefined variable * logically does not exist and survives only * while it has a trace, or if it is a global * variable currently being used by some * procedure. * VAR_IN_HASHTABLE - 1 means this variable is in a hashtable and * the Var structure is malloced. 0 if it is * a local variable that was assigned a slot * in a procedure frame by the compiler so the * Var storage is part of the call frame. * VAR_TRACE_ACTIVE - 1 means that trace processing is currently * underway for a read or write access, so * new read or write accesses should not cause * trace procedures to be called and the * variable can't be deleted. * VAR_ARRAY_ELEMENT - 1 means that this variable is an array * element, so it is not legal for it to be * an array itself (the VAR_ARRAY flag had * better not be set). * VAR_NAMESPACE_VAR - 1 means that this variable was declared * as a namespace variable. This flag ensures * it persists until its namespace is * destroyed or until the variable is unset; * it will persist even if it has not been * initialized and is marked undefined. * The variable's refCount is incremented to * reflect the "reference" from its namespace. * * The following additional flags are used with the CompiledLocal type * defined below: * * VAR_ARGUMENT - 1 means that this variable holds a procedure * argument. * VAR_TEMPORARY - 1 if the local variable is an anonymous * temporary variable. Temporaries have a NULL * name. * VAR_RESOLVED - 1 if name resolution has been done for this * variable. */ #define VAR_SCALAR 0x1 #define VAR_ARRAY 0x2 #define VAR_LINK 0x4 #define VAR_UNDEFINED 0x8 #define VAR_IN_HASHTABLE 0x10 #define VAR_TRACE_ACTIVE 0x20 #define VAR_ARRAY_ELEMENT 0x40 #define VAR_NAMESPACE_VAR 0x80 #define VAR_ARGUMENT 0x100 #define VAR_TEMPORARY 0x200 #define VAR_RESOLVED 0x400 /* * Macros to ensure that various flag bits are set properly for variables. * The ANSI C "prototypes" for these macros are: * * EXTERN void TclSetVarScalar _ANSI_ARGS_((Var *varPtr)); * EXTERN void TclSetVarArray _ANSI_ARGS_((Var *varPtr)); * EXTERN void TclSetVarLink _ANSI_ARGS_((Var *varPtr)); * EXTERN void TclSetVarArrayElement _ANSI_ARGS_((Var *varPtr)); * EXTERN void TclSetVarUndefined _ANSI_ARGS_((Var *varPtr)); * EXTERN void TclClearVarUndefined _ANSI_ARGS_((Var *varPtr)); */ #define TclSetVarScalar(varPtr) \ (varPtr)->flags = ((varPtr)->flags & ~(VAR_ARRAY|VAR_LINK)) | VAR_SCALAR #define TclSetVarArray(varPtr) \ (varPtr)->flags = ((varPtr)->flags & ~(VAR_SCALAR|VAR_LINK)) | VAR_ARRAY #define TclSetVarLink(varPtr) \ (varPtr)->flags = ((varPtr)->flags & ~(VAR_SCALAR|VAR_ARRAY)) | VAR_LINK #define TclSetVarArrayElement(varPtr) \ (varPtr)->flags = ((varPtr)->flags & ~VAR_ARRAY) | VAR_ARRAY_ELEMENT #define TclSetVarUndefined(varPtr) \ (varPtr)->flags |= VAR_UNDEFINED #define TclClearVarUndefined(varPtr) \ (varPtr)->flags &= ~VAR_UNDEFINED /* * Macros to read various flag bits of variables. * The ANSI C "prototypes" for these macros are: * * EXTERN int TclIsVarScalar _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarLink _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarArray _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarUndefined _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarArrayElement _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarTemporary _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarArgument _ANSI_ARGS_((Var *varPtr)); * EXTERN int TclIsVarResolved _ANSI_ARGS_((Var *varPtr)); */ #define TclIsVarScalar(varPtr) \ ((varPtr)->flags & VAR_SCALAR) #define TclIsVarLink(varPtr) \ ((varPtr)->flags & VAR_LINK) #define TclIsVarArray(varPtr) \ ((varPtr)->flags & VAR_ARRAY) #define TclIsVarUndefined(varPtr) \ ((varPtr)->flags & VAR_UNDEFINED) #define TclIsVarArrayElement(varPtr) \ ((varPtr)->flags & VAR_ARRAY_ELEMENT) #define TclIsVarTemporary(varPtr) \ ((varPtr)->flags & VAR_TEMPORARY) #define TclIsVarArgument(varPtr) \ ((varPtr)->flags & VAR_ARGUMENT) #define TclIsVarResolved(varPtr) \ ((varPtr)->flags & VAR_RESOLVED) /* *---------------------------------------------------------------- * Data structures related to procedures. These are used primarily * in tclProc.c, tclCompile.c, and tclExecute.c. *---------------------------------------------------------------- */ /* * Forward declaration to prevent an error when the forward reference to * Command is encountered in the Proc and ImportRef types declared below. */ struct Command; /* * The variable-length structure below describes a local variable of a * procedure that was recognized by the compiler. These variables have a * name, an element in the array of compiler-assigned local variables in the * procedure's call frame, and various other items of information. If the * local variable is a formal argument, it may also have a default value. * The compiler can't recognize local variables whose names are * expressions (these names are only known at runtime when the expressions * are evaluated) or local variables that are created as a result of an * "upvar" or "uplevel" command. These other local variables are kept * separately in a hash table in the call frame. */ typedef struct CompiledLocal { struct CompiledLocal *nextPtr; /* Next compiler-recognized local variable * for this procedure, or NULL if this is * the last local. */ int nameLength; /* The number of characters in local * variable's name. Used to speed up * variable lookups. */ int frameIndex; /* Index in the array of compiler-assigned * variables in the procedure call frame. */ int flags; /* Flag bits for the local variable. Same as * the flags for the Var structure above, * although only VAR_SCALAR, VAR_ARRAY, * VAR_LINK, VAR_ARGUMENT, VAR_TEMPORARY, and * VAR_RESOLVED make sense. */ Tcl_Obj *defValuePtr; /* Pointer to the default value of an * argument, if any. NULL if not an argument * or, if an argument, no default value. */ Tcl_ResolvedVarInfo *resolveInfo; /* Customized variable resolution info * supplied by the Tcl_ResolveCompiledVarProc * associated with a namespace. Each variable * is marked by a unique ClientData tag * during compilation, and that same tag * is used to find the variable at runtime. */ char name[4]; /* Name of the local variable starts here. * If the name is NULL, this will just be * '\0'. The actual size of this field will * be large enough to hold the name. MUST * BE THE LAST FIELD IN THE STRUCTURE! */ } CompiledLocal; /* * The structure below defines a command procedure, which consists of a * collection of Tcl commands plus information about arguments and other * local variables recognized at compile time. */ typedef struct Proc { struct Interp *iPtr; /* Interpreter for which this command * is defined. */ int refCount; /* Reference count: 1 if still present * in command table plus 1 for each call * to the procedure that is currently * active. This structure can be freed * when refCount becomes zero. */ struct Command *cmdPtr; /* Points to the Command structure for * this procedure. This is used to get * the namespace in which to execute * the procedure. */ Tcl_Obj *bodyPtr; /* Points to the ByteCode object for * procedure's body command. */ int numArgs; /* Number of formal parameters. */ int numCompiledLocals; /* Count of local variables recognized by * the compiler including arguments and * temporaries. */ CompiledLocal *firstLocalPtr; /* Pointer to first of the procedure's * compiler-allocated local variables, or * NULL if none. The first numArgs entries * in this list describe the procedure's * formal arguments. */ CompiledLocal *lastLocalPtr; /* Pointer to the last allocated local * variable or NULL if none. This has * frame index (numCompiledLocals-1). */ } Proc; /* * The structure below defines a command trace. This is used to allow Tcl * clients to find out whenever a command is about to be executed. */ typedef struct Trace { int level; /* Only trace commands at nesting level * less than or equal to this. */ Tcl_CmdTraceProc *proc; /* Procedure to call to trace command. */ ClientData clientData; /* Arbitrary value to pass to proc. */ struct Trace *nextPtr; /* Next in list of traces for this interp. */ } Trace; /* * The structure below defines an entry in the assocData hash table which * is associated with an interpreter. The entry contains a pointer to a * function to call when the interpreter is deleted, and a pointer to * a user-defined piece of data. */ typedef struct AssocData { Tcl_InterpDeleteProc *proc; /* Proc to call when deleting. */ ClientData clientData; /* Value to pass to proc. */ } AssocData; /* * The structure below defines a call frame. A call frame defines a naming * context for a procedure call: its local naming scope (for local * variables) and its global naming scope (a namespace, perhaps the global * :: namespace). A call frame can also define the naming context for a * namespace eval or namespace inscope command: the namespace in which the * command's code should execute. The Tcl_CallFrame structures exist only * while procedures or namespace eval/inscope's are being executed, and * provide a kind of Tcl call stack. * * WARNING!! The structure definition must be kept consistent with the * Tcl_CallFrame structure in tcl.h. If you change one, change the other. */ typedef struct CallFrame { Namespace *nsPtr; /* Points to the namespace used to resolve * commands and global variables. */ int isProcCallFrame; /* If nonzero, the frame was pushed to * execute a Tcl procedure and may have * local vars. If 0, the frame was pushed * to execute a namespace command and var * references are treated as references to * namespace vars; varTablePtr and * compiledLocals are ignored. */ int objc; /* This and objv below describe the * arguments for this procedure call. */ Tcl_Obj *CONST *objv; /* Array of argument objects. */ struct CallFrame *callerPtr; /* Value of interp->framePtr when this * procedure was invoked (i.e. next higher * in stack of all active procedures). */ struct CallFrame *callerVarPtr; /* Value of interp->varFramePtr when this * procedure was invoked (i.e. determines * variable scoping within caller). Same * as callerPtr unless an "uplevel" command * or something equivalent was active in * the caller). */ int level; /* Level of this procedure, for "uplevel" * purposes (i.e. corresponds to nesting of * callerVarPtr's, not callerPtr's). 1 for * outermost procedure, 0 for top-level. */ Proc *procPtr; /* Points to the structure defining the * called procedure. Used to get information * such as the number of compiled local * variables (local variables assigned * entries ["slots"] in the compiledLocals * array below). */ Tcl_HashTable *varTablePtr; /* Hash table containing local variables not * recognized by the compiler, or created at * execution time through, e.g., upvar. * Initially NULL and created if needed. */ int numCompiledLocals; /* Count of local variables recognized by * the compiler including arguments. */ Var* compiledLocals; /* Points to the array of local variables * recognized by the compiler. The compiler * emits code that refers to these variables * using an index into this array. */ } CallFrame; /* *---------------------------------------------------------------- * Data structures and procedures related to TclHandles, which * are a very lightweight method of preserving enough information * to determine if an arbitrary malloc'd block has been deleted. *---------------------------------------------------------------- */ typedef VOID **TclHandle; EXTERN TclHandle TclHandleCreate _ANSI_ARGS_((VOID *ptr)); EXTERN void TclHandleFree _ANSI_ARGS_((TclHandle handle)); EXTERN TclHandle TclHandlePreserve _ANSI_ARGS_((TclHandle handle)); EXTERN void TclHandleRelease _ANSI_ARGS_((TclHandle handle)); /* *---------------------------------------------------------------- * Data structures related to history. These are used primarily * in tclHistory.c *---------------------------------------------------------------- */ /* * The structure below defines one history event (a previously-executed * command that can be re-executed in whole or in part). */ typedef struct { char *command; /* String containing previously-executed * command. */ int bytesAvl; /* Total # of bytes available at *event (not * all are necessarily in use now). */ } HistoryEvent; /* * The structure below defines a pending revision to the most recent * history event. Changes are linked together into a list and applied * during the next call to Tcl_RecordHistory. See the comments at the * beginning of tclHistory.c for information on revisions. */ typedef struct HistoryRev { int firstIndex; /* Index of the first byte to replace in * current history event. */ int lastIndex; /* Index of last byte to replace in * current history event. */ int newSize; /* Number of bytes in newBytes. */ char *newBytes; /* Replacement for the range given by * firstIndex and lastIndex (malloced). */ struct HistoryRev *nextPtr; /* Next in chain of revisions to apply, or * NULL for end of list. */ } HistoryRev; /* *---------------------------------------------------------------- * Data structures related to expressions. These are used only in * tclExpr.c. *---------------------------------------------------------------- */ /* * The data structure below defines a math function (e.g. sin or hypot) * for use in Tcl expressions. */ #define MAX_MATH_ARGS 5 typedef struct MathFunc { int builtinFuncIndex; /* If this is a builtin math function, its * index in the array of builtin functions. * (tclCompilation.h lists these indices.) * The value is -1 if this is a new function * defined by Tcl_CreateMathFunc. The value * is also -1 if a builtin function is * replaced by a Tcl_CreateMathFunc call. */ int numArgs; /* Number of arguments for function. */ Tcl_ValueType argTypes[MAX_MATH_ARGS]; /* Acceptable types for each argument. */ Tcl_MathProc *proc; /* Procedure that implements this function. * NULL if isBuiltinFunc is 1. */ ClientData clientData; /* Additional argument to pass to the * function when invoking it. NULL if * isBuiltinFunc is 1. */ } MathFunc; /* * These are a thin layer over TclpThreadKeyDataGet and TclpThreadKeyDataSet * when threads are used, or an emulation if there are no threads. These * are really internal and Tcl clients should use Tcl_GetThreadData. */ EXTERN VOID *TclThreadDataKeyGet _ANSI_ARGS_((Tcl_ThreadDataKey *keyPtr)); EXTERN void TclThreadDataKeySet _ANSI_ARGS_((Tcl_ThreadDataKey *keyPtr, VOID *data)); /* * This is a convenience macro used to initialize a thread local storage ptr. */ #define TCL_TSD_INIT(keyPtr) (ThreadSpecificData *)Tcl_GetThreadData((keyPtr), sizeof(ThreadSpecificData)) /* *---------------------------------------------------------------- * Data structures related to bytecode compilation and execution. * These are used primarily in tclCompile.c, tclExecute.c, and * tclBasic.c. *---------------------------------------------------------------- */ /* * Forward declaration to prevent errors when the forward references to * Tcl_Parse and CompileEnv are encountered in the procedure type * CompileProc declared below. */ struct CompileEnv; /* * The type of procedures called by the Tcl bytecode compiler to compile * commands. Pointers to these procedures are kept in the Command structure * describing each command. When a CompileProc returns, the interpreter's * result is set to error information, if any. In addition, the CompileProc * returns an integer value, which is one of the following: * * TCL_OK Compilation completed normally. * TCL_ERROR Compilation failed because of an error; * the interpreter's result describes what went wrong. * TCL_OUT_LINE_COMPILE Compilation failed because, e.g., the command is * too complex for effective inline compilation. The * CompileProc believes the command is legal but * should be compiled "out of line" by emitting code * to invoke its command procedure at runtime. */ #define TCL_OUT_LINE_COMPILE (TCL_CONTINUE + 1) typedef int (CompileProc) _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *compEnvPtr)); /* * The type of procedure called from the compilation hook point in * SetByteCodeFromAny. */ typedef int (CompileHookProc) _ANSI_ARGS_((Tcl_Interp *interp, struct CompileEnv *compEnvPtr, ClientData clientData)); /* * The data structure defining the execution environment for ByteCode's. * There is one ExecEnv structure per Tcl interpreter. It holds the * evaluation stack that holds command operands and results. The stack grows * towards increasing addresses. The "stackTop" member is cached by * TclExecuteByteCode in a local variable: it must be set before calling * TclExecuteByteCode and will be restored by TclExecuteByteCode before it * returns. */ typedef struct ExecEnv { Tcl_Obj **stackPtr; /* Points to the first item in the * evaluation stack on the heap. */ int stackTop; /* Index of current top of stack; -1 when * the stack is empty. */ int stackEnd; /* Index of last usable item in stack. */ } ExecEnv; /* * The definitions for the LiteralTable and LiteralEntry structures. Each * interpreter contains a LiteralTable. It is used to reduce the storage * needed for all the Tcl objects that hold the literals of scripts compiled * by the interpreter. A literal's object is shared by all the ByteCodes * that refer to the literal. Each distinct literal has one LiteralEntry * entry in the LiteralTable. A literal table is a specialized hash table * that is indexed by the literal's string representation, which may contain * null characters. * * Note that we reduce the space needed for literals by sharing literal * objects both within a ByteCode (each ByteCode contains a local * LiteralTable) and across all an interpreter's ByteCodes (with the * interpreter's global LiteralTable). */ typedef struct LiteralEntry { struct LiteralEntry *nextPtr; /* Points to next entry in this * hash bucket or NULL if end of * chain. */ Tcl_Obj *objPtr; /* Points to Tcl object that * holds the literal's bytes and * length. */ int refCount; /* If in an interpreter's global * literal table, the number of * ByteCode structures that share * the literal object; the literal * entry can be freed when refCount * drops to 0. If in a local literal * table, -1. */ } LiteralEntry; typedef struct LiteralTable { LiteralEntry **buckets; /* Pointer to bucket array. Each * element points to first entry in * bucket's hash chain, or NULL. */ LiteralEntry *staticBuckets[TCL_SMALL_HASH_TABLE]; /* Bucket array used for small * tables to avoid mallocs and * frees. */ int numBuckets; /* Total number of buckets allocated * at **buckets. */ int numEntries; /* Total number of entries present * in table. */ int rebuildSize; /* Enlarge table when numEntries * gets to be this large. */ int mask; /* Mask value used in hashing * function. */ } LiteralTable; /* * The following structure defines for each Tcl interpreter various * statistics-related information about the bytecode compiler and * interpreter's operation in that interpreter. */ #ifdef TCL_COMPILE_STATS typedef struct ByteCodeStats { long numExecutions; /* Number of ByteCodes executed. */ long numCompilations; /* Number of ByteCodes created. */ long numByteCodesFreed; /* Number of ByteCodes destroyed. */ long instructionCount[256]; /* Number of times each instruction was * executed. */ double totalSrcBytes; /* Total source bytes ever compiled. */ double totalByteCodeBytes; /* Total bytes for all ByteCodes. */ double currentSrcBytes; /* Src bytes for all current ByteCodes. */ double currentByteCodeBytes; /* Code bytes in all current ByteCodes. */ long srcCount[32]; /* Source size distribution: # of srcs of * size [2**(n-1)..2**n), n in [0..32). */ long byteCodeCount[32]; /* ByteCode size distribution. */ long lifetimeCount[32]; /* ByteCode lifetime distribution (ms). */ double currentInstBytes; /* Instruction bytes-current ByteCodes. */ double currentLitBytes; /* Current literal bytes. */ double currentExceptBytes; /* Current exception table bytes. */ double currentAuxBytes; /* Current auxiliary information bytes. */ double currentCmdMapBytes; /* Current src<->code map bytes. */ long numLiteralsCreated; /* Total literal objects ever compiled. */ double totalLitStringBytes; /* Total string bytes in all literals. */ double currentLitStringBytes; /* String bytes in current literals. */ long literalCount[32]; /* Distribution of literal string sizes. */ } ByteCodeStats; #endif /* TCL_COMPILE_STATS */ /* *---------------------------------------------------------------- * Data structures related to commands. *---------------------------------------------------------------- */ /* * An imported command is created in an namespace when it imports a "real" * command from another namespace. An imported command has a Command * structure that points (via its ClientData value) to the "real" Command * structure in the source namespace's command table. The real command * records all the imported commands that refer to it in a list of ImportRef * structures so that they can be deleted when the real command is deleted. */ typedef struct ImportRef { struct Command *importedCmdPtr; /* Points to the imported command created in * an importing namespace; this command * redirects its invocations to the "real" * command. */ struct ImportRef *nextPtr; /* Next element on the linked list of * imported commands that refer to the * "real" command. The real command deletes * these imported commands on this list when * it is deleted. */ } ImportRef; /* * Data structure used as the ClientData of imported commands: commands * created in an namespace when it imports a "real" command from another * namespace. */ typedef struct ImportedCmdData { struct Command *realCmdPtr; /* "Real" command that this imported command * refers to. */ struct Command *selfPtr; /* Pointer to this imported command. Needed * only when deleting it in order to remove * it from the real command's linked list of * imported commands that refer to it. */ } ImportedCmdData; /* * A Command structure exists for each command in a namespace. The * Tcl_Command opaque type actually refers to these structures. */ typedef struct Command { Tcl_HashEntry *hPtr; /* Pointer to the hash table entry that * refers to this command. The hash table is * either a namespace's command table or an * interpreter's hidden command table. This * pointer is used to get a command's name * from its Tcl_Command handle. NULL means * that the hash table entry has been * removed already (this can happen if * deleteProc causes the command to be * deleted or recreated). */ Namespace *nsPtr; /* Points to the namespace containing this * command. */ int refCount; /* 1 if in command hashtable plus 1 for each * reference from a CmdName Tcl object * representing a command's name in a * ByteCode instruction sequence. This * structure can be freed when refCount * becomes zero. */ int cmdEpoch; /* Incremented to invalidate any references * that point to this command when it is * renamed, deleted, hidden, or exposed. */ CompileProc *compileProc; /* Procedure called to compile command. NULL * if no compile proc exists for command. */ Tcl_ObjCmdProc *objProc; /* Object-based command procedure. */ ClientData objClientData; /* Arbitrary value passed to object proc. */ Tcl_CmdProc *proc; /* String-based command procedure. */ ClientData clientData; /* Arbitrary value passed to string proc. */ Tcl_CmdDeleteProc *deleteProc; /* Procedure invoked when deleting command * to, e.g., free all client data. */ ClientData deleteData; /* Arbitrary value passed to deleteProc. */ int deleted; /* Means that the command is in the process * of being deleted (its deleteProc is * currently executing). Other attempts to * delete the command should be ignored. */ ImportRef *importRefPtr; /* List of each imported Command created in * another namespace when this command is * imported. These imported commands * redirect invocations back to this * command. The list is used to remove all * those imported commands when deleting * this "real" command. */ } Command; /* *---------------------------------------------------------------- * Data structures related to name resolution procedures. *---------------------------------------------------------------- */ /* * The interpreter keeps a linked list of name resolution schemes. * The scheme for a namespace is consulted first, followed by the * list of schemes in an interpreter, followed by the default * name resolution in Tcl. Schemes are added/removed from the * interpreter's list by calling Tcl_AddInterpResolver and * Tcl_RemoveInterpResolver. */ typedef struct ResolverScheme { char *name; /* Name identifying this scheme. */ Tcl_ResolveCmdProc *cmdResProc; /* Procedure handling command name * resolution. */ Tcl_ResolveVarProc *varResProc; /* Procedure handling variable name * resolution for variables that * can only be handled at runtime. */ Tcl_ResolveCompiledVarProc *compiledVarResProc; /* Procedure handling variable name * resolution at compile time. */ struct ResolverScheme *nextPtr; /* Pointer to next record in linked list. */ } ResolverScheme; /* *---------------------------------------------------------------- * This structure defines an interpreter, which is a collection of * commands plus other state information related to interpreting * commands, such as variable storage. Primary responsibility for * this data structure is in tclBasic.c, but almost every Tcl * source file uses something in here. *---------------------------------------------------------------- */ typedef struct Interp { /* * Note: the first three fields must match exactly the fields in * a Tcl_Interp struct (see tcl.h). If you change one, be sure to * change the other. * * The interpreter's result is held in both the string and the * objResultPtr fields. These fields hold, respectively, the result's * string or object value. The interpreter's result is always in the * result field if that is non-empty, otherwise it is in objResultPtr. * The two fields are kept consistent unless some C code sets * interp->result directly. Programs should not access result and * objResultPtr directly; instead, they should always get and set the * result using procedures such as Tcl_SetObjResult, Tcl_GetObjResult, * and Tcl_GetStringResult. See the SetResult man page for details. */ char *result; /* If the last command returned a string * result, this points to it. Should not be * accessed directly; see comment above. */ Tcl_FreeProc *freeProc; /* Zero means a string result is statically * allocated. TCL_DYNAMIC means string * result was allocated with ckalloc and * should be freed with ckfree. Other values * give address of procedure to invoke to * free the string result. Tcl_Eval must * free it before executing next command. */ int errorLine; /* When TCL_ERROR is returned, this gives * the line number in the command where the * error occurred (1 means first line). */ struct TclStubs *stubTable; /* Pointer to the exported Tcl stub table. * On previous versions of Tcl this is a * pointer to the objResultPtr or a pointer * to a buckets array in a hash table. We * therefore have to do some careful checking * before we can use this. */ TclHandle handle; /* Handle used to keep track of when this * interp is deleted. */ Namespace *globalNsPtr; /* The interpreter's global namespace. */ Tcl_HashTable *hiddenCmdTablePtr; /* Hash table used by tclBasic.c to keep * track of hidden commands on a per-interp * basis. */ ClientData interpInfo; /* Information used by tclInterp.c to keep * track of master/slave interps on * a per-interp basis. */ Tcl_HashTable mathFuncTable;/* Contains all the math functions currently * defined for the interpreter. Indexed by * strings (function names); values have * type (MathFunc *). */ /* * Information related to procedures and variables. See tclProc.c * and tclvar.c for usage. */ int numLevels; /* Keeps track of how many nested calls to * Tcl_Eval are in progress for this * interpreter. It's used to delay deletion * of the table until all Tcl_Eval * invocations are completed. */ int maxNestingDepth; /* If numLevels exceeds this value then Tcl * assumes that infinite recursion has * occurred and it generates an error. */ CallFrame *framePtr; /* Points to top-most in stack of all nested * procedure invocations. NULL means there * are no active procedures. */ CallFrame *varFramePtr; /* Points to the call frame whose variables * are currently in use (same as framePtr * unless an "uplevel" command is * executing). NULL means no procedure is * active or "uplevel 0" is executing. */ ActiveVarTrace *activeTracePtr; /* First in list of active traces for * interp, or NULL if no active traces. */ int returnCode; /* Completion code to return if current * procedure exits with TCL_RETURN code. */ char *errorInfo; /* Value to store in errorInfo if returnCode * is TCL_ERROR. Malloc'ed, may be NULL */ char *errorCode; /* Value to store in errorCode if returnCode * is TCL_ERROR. Malloc'ed, may be NULL */ /* * Information used by Tcl_AppendResult to keep track of partial * results. See Tcl_AppendResult code for details. */ char *appendResult; /* Storage space for results generated * by Tcl_AppendResult. Malloc-ed. NULL * means not yet allocated. */ int appendAvl; /* Total amount of space available at * partialResult. */ int appendUsed; /* Number of non-null bytes currently * stored at partialResult. */ /* * Information about packages. Used only in tclPkg.c. */ Tcl_HashTable packageTable; /* Describes all of the packages loaded * in or available to this interpreter. * Keys are package names, values are * (Package *) pointers. */ char *packageUnknown; /* Command to invoke during "package * require" commands for packages that * aren't described in packageTable. * Malloc'ed, may be NULL. */ /* * Miscellaneous information: */ int cmdCount; /* Total number of times a command procedure * has been called for this interpreter. */ int evalFlags; /* Flags to control next call to Tcl_Eval. * Normally zero, but may be set before * calling Tcl_Eval. See below for valid * values. */ int termOffset; /* Offset of character just after last one * compiled or executed by Tcl_EvalObj. */ LiteralTable literalTable; /* Contains LiteralEntry's describing all * Tcl objects holding literals of scripts * compiled by the interpreter. Indexed by * the string representations of literals. * Used to avoid creating duplicate * objects. */ int compileEpoch; /* Holds the current "compilation epoch" * for this interpreter. This is * incremented to invalidate existing * ByteCodes when, e.g., a command with a * compile procedure is redefined. */ Proc *compiledProcPtr; /* If a procedure is being compiled, a * pointer to its Proc structure; otherwise, * this is NULL. Set by ObjInterpProc in * tclProc.c and used by tclCompile.c to * process local variables appropriately. */ ResolverScheme *resolverPtr; /* Linked list of name resolution schemes * added to this interpreter. Schemes * are added/removed by calling * Tcl_AddInterpResolvers and * Tcl_RemoveInterpResolver. */ char *scriptFile; /* NULL means there is no nested source * command active; otherwise this points to * the name of the file being sourced (it's * not malloc-ed: it points to an argument * to Tcl_EvalFile. */ int flags; /* Various flag bits. See below. */ long randSeed; /* Seed used for rand() function. */ Trace *tracePtr; /* List of traces for this interpreter. */ Tcl_HashTable *assocData; /* Hash table for associating data with * this interpreter. Cleaned up when * this interpreter is deleted. */ struct ExecEnv *execEnvPtr; /* Execution environment for Tcl bytecode * execution. Contains a pointer to the * Tcl evaluation stack. */ Tcl_Obj *emptyObjPtr; /* Points to an object holding an empty * string. Returned by Tcl_ObjSetVar2 when * variable traces change a variable in a * gross way. */ char resultSpace[TCL_RESULT_SIZE+1]; /* Static space holding small results. */ Tcl_Obj *objResultPtr; /* If the last command returned an object * result, this points to it. Should not be * accessed directly; see comment above. */ Tcl_ThreadId threadId; /* ID of thread that owns the interpreter */ /* * Statistical information about the bytecode compiler and interpreter's * operation. */ #ifdef TCL_COMPILE_STATS ByteCodeStats stats; /* Holds compilation and execution * statistics for this interpreter. */ #endif /* TCL_COMPILE_STATS */ } Interp; /* * EvalFlag bits for Interp structures: * * TCL_BRACKET_TERM 1 means that the current script is terminated by * a close bracket rather than the end of the string. * TCL_ALLOW_EXCEPTIONS 1 means it's OK for the script to terminate with * a code other than TCL_OK or TCL_ERROR; 0 means * codes other than these should be turned into errors. */ #define TCL_BRACKET_TERM 1 #define TCL_ALLOW_EXCEPTIONS 4 /* * Flag bits for Interp structures: * * DELETED: Non-zero means the interpreter has been deleted: * don't process any more commands for it, and destroy * the structure as soon as all nested invocations of * Tcl_Eval are done. * ERR_IN_PROGRESS: Non-zero means an error unwind is already in * progress. Zero means a command proc has been * invoked since last error occured. * ERR_ALREADY_LOGGED: Non-zero means information has already been logged * in $errorInfo for the current Tcl_Eval instance, * so Tcl_Eval needn't log it (used to implement the * "error message log" command). * ERROR_CODE_SET: Non-zero means that Tcl_SetErrorCode has been * called to record information for the current * error. Zero means Tcl_Eval must clear the * errorCode variable if an error is returned. * EXPR_INITIALIZED: Non-zero means initialization specific to * expressions has been carried out. * DONT_COMPILE_CMDS_INLINE: Non-zero means that the bytecode compiler * should not compile any commands into an inline * sequence of instructions. This is set 1, for * example, when command traces are requested. * RAND_SEED_INITIALIZED: Non-zero means that the randSeed value of the * interp has not be initialized. This is set 1 * when we first use the rand() or srand() functions. * SAFE_INTERP: Non zero means that the current interp is a * safe interp (ie it has only the safe commands * installed, less priviledge than a regular interp). * USE_EVAL_DIRECT: Non-zero means don't use the compiler or byte-code * interpreter; instead, have Tcl_EvalObj call * Tcl_EvalEx. Used primarily for testing the * new parser. */ #define DELETED 1 #define ERR_IN_PROGRESS 2 #define ERR_ALREADY_LOGGED 4 #define ERROR_CODE_SET 8 #define EXPR_INITIALIZED 0x10 #define DONT_COMPILE_CMDS_INLINE 0x20 #define RAND_SEED_INITIALIZED 0x40 #define SAFE_INTERP 0x80 #define USE_EVAL_DIRECT 0x100 /* *---------------------------------------------------------------- * Data structures related to command parsing. These are used in * tclParse.c and its clients. *---------------------------------------------------------------- */ /* * The following data structure is used by various parsing procedures * to hold information about where to store the results of parsing * (e.g. the substituted contents of a quoted argument, or the result * of a nested command). At any given time, the space available * for output is fixed, but a procedure may be called to expand the * space available if the current space runs out. */ typedef struct ParseValue { char *buffer; /* Address of first character in * output buffer. */ char *next; /* Place to store next character in * output buffer. */ char *end; /* Address of the last usable character * in the buffer. */ void (*expandProc) _ANSI_ARGS_((struct ParseValue *pvPtr, int needed)); /* Procedure to call when space runs out; * it will make more space. */ ClientData clientData; /* Arbitrary information for use of * expandProc. */ } ParseValue; /* * Maximum number of levels of nesting permitted in Tcl commands (used * to catch infinite recursion). */ #define MAX_NESTING_DEPTH 1000 /* * The macro below is used to modify a "char" value (e.g. by casting * it to an unsigned character) so that it can be used safely with * macros such as isspace. */ #define UCHAR(c) ((unsigned char) (c)) /* * This macro is used to determine the offset needed to safely allocate any * data structure in memory. Given a starting offset or size, it "rounds up" * or "aligns" the offset to the next 8-byte boundary so that any data * structure can be placed at the resulting offset without fear of an * alignment error. * * WARNING!! DO NOT USE THIS MACRO TO ALIGN POINTERS: it will produce * the wrong result on platforms that allocate addresses that are divisible * by 4 or 2. Only use it for offsets or sizes. */ #define TCL_ALIGN(x) (((int)(x) + 7) & ~7) /* * The following macros are used to specify the runtime platform * setting of the tclPlatform variable. */ typedef enum { TCL_PLATFORM_UNIX, /* Any Unix-like OS. */ TCL_PLATFORM_MAC, /* MacOS. */ TCL_PLATFORM_WINDOWS /* Any Microsoft Windows OS. */ } TclPlatformType; /* * Flags for TclInvoke: * * TCL_INVOKE_HIDDEN Invoke a hidden command; if not set, * invokes an exposed command. * TCL_INVOKE_NO_UNKNOWN If set, "unknown" is not invoked if * the command to be invoked is not found. * Only has an effect if invoking an exposed * command, i.e. if TCL_INVOKE_HIDDEN is not * also set. * TCL_INVOKE_NO_TRACEBACK Does not record traceback information if * the invoked command returns an error. Used * if the caller plans on recording its own * traceback information. */ #define TCL_INVOKE_HIDDEN (1<<0) #define TCL_INVOKE_NO_UNKNOWN (1<<1) #define TCL_INVOKE_NO_TRACEBACK (1<<2) /* * The structure used as the internal representation of Tcl list * objects. This is an array of pointers to the element objects. This array * is grown (reallocated and copied) as necessary to hold all the list's * element pointers. The array might contain more slots than currently used * to hold all element pointers. This is done to make append operations * faster. */ typedef struct List { int maxElemCount; /* Total number of element array slots. */ int elemCount; /* Current number of list elements. */ Tcl_Obj **elements; /* Array of pointers to element objects. */ } List; /* * The following types are used for getting and storing platform-specific * file attributes in tclFCmd.c and the various platform-versions of * that file. This is done to have as much common code as possible * in the file attributes code. For more information about the callbacks, * see TclFileAttrsCmd in tclFCmd.c. */ typedef int (TclGetFileAttrProc) _ANSI_ARGS_((Tcl_Interp *interp, int objIndex, CONST char *fileName, Tcl_Obj **attrObjPtrPtr)); typedef int (TclSetFileAttrProc) _ANSI_ARGS_((Tcl_Interp *interp, int objIndex, CONST char *fileName, Tcl_Obj *attrObjPtr)); typedef struct TclFileAttrProcs { TclGetFileAttrProc *getProc; /* The procedure for getting attrs. */ TclSetFileAttrProc *setProc; /* The procedure for setting attrs. */ } TclFileAttrProcs; /* * Opaque handle used in pipeline routines to encapsulate platform-dependent * state. */ typedef struct TclFile_ *TclFile; /* *---------------------------------------------------------------- * Data structures related to hooking 'TclStat(...)' and * 'TclAccess(...)'. *---------------------------------------------------------------- */ typedef int (TclStatProc_) _ANSI_ARGS_((CONST char *path, struct stat *buf)); typedef int (TclAccessProc_) _ANSI_ARGS_((CONST char *path, int mode)); typedef Tcl_Channel (TclOpenFileChannelProc_) _ANSI_ARGS_((Tcl_Interp *interp, char *fileName, char *modeString, int permissions)); typedef int (*TclCmdProcType) _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])); typedef int (*TclObjCmdProcType) _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, struct Tcl_Obj * CONST objv[])); /* * Opaque names for platform specific types. */ typedef struct TclpTime_t_ *TclpTime_t; /* * The following structure is used to pass glob type data amongst * the various glob routines and TclpMatchFilesTypes. Currently * most of the fields are ignored. However they will be used in * a future release to implement glob's ability to find files * of particular types/permissions/etc only. */ typedef struct GlobTypeData { /* Corresponds to bcdpfls as in 'find -t' */ int type; /* Corresponds to file permissions */ int perm; /* Acceptable mac type */ Tcl_Obj* macType; /* Acceptable mac creator */ Tcl_Obj* macCreator; } GlobTypeData; /* * type and permission definitions for glob command */ #define TCL_GLOB_TYPE_BLOCK (1<<0) #define TCL_GLOB_TYPE_CHAR (1<<1) #define TCL_GLOB_TYPE_DIR (1<<2) #define TCL_GLOB_TYPE_PIPE (1<<3) #define TCL_GLOB_TYPE_FILE (1<<4) #define TCL_GLOB_TYPE_LINK (1<<5) #define TCL_GLOB_TYPE_SOCK (1<<6) #define TCL_GLOB_PERM_RONLY (1<<0) #define TCL_GLOB_PERM_HIDDEN (1<<1) #define TCL_GLOB_PERM_R (1<<2) #define TCL_GLOB_PERM_W (1<<3) #define TCL_GLOB_PERM_X (1<<4) /* *---------------------------------------------------------------- * Variables shared among Tcl modules but not used by the outside world. *---------------------------------------------------------------- */ extern Tcl_Time tclBlockTime; extern int tclBlockTimeSet; extern char * tclExecutableName; extern char * tclNativeExecutableName; extern char * tclDefaultEncodingDir; extern Tcl_ChannelType tclFileChannelType; extern char * tclMemDumpFileName; extern TclPlatformType tclPlatform; extern char * tclpFileAttrStrings[]; extern CONST TclFileAttrProcs tclpFileAttrProcs[]; /* * Variables denoting the Tcl object types defined in the core. */ extern Tcl_ObjType tclBooleanType; extern Tcl_ObjType tclByteArrayType; extern Tcl_ObjType tclByteCodeType; extern Tcl_ObjType tclDoubleType; extern Tcl_ObjType tclIntType; extern Tcl_ObjType tclListType; extern Tcl_ObjType tclProcBodyType; extern Tcl_ObjType tclStringType; /* * The head of the list of free Tcl objects, and the total number of Tcl * objects ever allocated and freed. */ extern Tcl_Obj * tclFreeObjList; #ifdef TCL_COMPILE_STATS extern long tclObjsAlloced; extern long tclObjsFreed; #endif /* TCL_COMPILE_STATS */ /* * Pointer to a heap-allocated string of length zero that the Tcl core uses * as the value of an empty string representation for an object. This value * is shared by all new objects allocated by Tcl_NewObj. */ extern char * tclEmptyStringRep; /* *---------------------------------------------------------------- * Procedures shared among Tcl modules but not used by the outside * world: *---------------------------------------------------------------- */ EXTERN int TclAccess _ANSI_ARGS_((CONST char *path, int mode)); EXTERN int TclAccessDeleteProc _ANSI_ARGS_((TclAccessProc_ *proc)); EXTERN int TclAccessInsertProc _ANSI_ARGS_((TclAccessProc_ *proc)); EXTERN void TclAllocateFreeObjects _ANSI_ARGS_((void)); EXTERN int TclArraySet _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *arrayNameObj, Tcl_Obj *arrayElemObj)); EXTERN int TclCheckBadOctal _ANSI_ARGS_((Tcl_Interp *interp, char *value)); EXTERN int TclCleanupChildren _ANSI_ARGS_((Tcl_Interp *interp, int numPids, Tcl_Pid *pidPtr, Tcl_Channel errorChan)); EXTERN void TclCleanupCommand _ANSI_ARGS_((Command *cmdPtr)); EXTERN int TclCopyChannel _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Channel inChan, Tcl_Channel outChan, int toRead, Tcl_Obj *cmdPtr)); /* * TclCreatePipeline unofficially exported for use by BLT. */ EXTERN int TclCreatePipeline _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv, Tcl_Pid **pidArrayPtr, TclFile *inPipePtr, TclFile *outPipePtr, TclFile *errFilePtr)); EXTERN int TclCreateProc _ANSI_ARGS_((Tcl_Interp *interp, Namespace *nsPtr, char *procName, Tcl_Obj *argsPtr, Tcl_Obj *bodyPtr, Proc **procPtrPtr)); EXTERN void TclDeleteCompiledLocalVars _ANSI_ARGS_(( Interp *iPtr, CallFrame *framePtr)); EXTERN void TclDeleteVars _ANSI_ARGS_((Interp *iPtr, Tcl_HashTable *tablePtr)); EXTERN int TclDoGlob _ANSI_ARGS_((Tcl_Interp *interp, char *separators, Tcl_DString *headPtr, char *tail, GlobTypeData *types)); EXTERN void TclDumpMemoryInfo _ANSI_ARGS_((FILE *outFile)); EXTERN void TclExpandTokenArray _ANSI_ARGS_(( Tcl_Parse *parsePtr)); EXTERN void TclExprFloatError _ANSI_ARGS_((Tcl_Interp *interp, double value)); EXTERN int TclFileAttrsCmd _ANSI_ARGS_((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int TclFileCopyCmd _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv)) ; EXTERN int TclFileDeleteCmd _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv)); EXTERN int TclFileMakeDirsCmd _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv)) ; EXTERN int TclFileRenameCmd _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv)) ; EXTERN void TclFinalizeAllocSubsystem _ANSI_ARGS_((void)); EXTERN void TclFinalizeCompExecEnv _ANSI_ARGS_((void)); EXTERN void TclFinalizeCompilation _ANSI_ARGS_((void)); EXTERN void TclFinalizeEncodingSubsystem _ANSI_ARGS_((void)); EXTERN void TclFinalizeEnvironment _ANSI_ARGS_((void)); EXTERN void TclFinalizeExecution _ANSI_ARGS_((void)); EXTERN void TclFinalizeIOSubsystem _ANSI_ARGS_((void)); EXTERN void TclFinalizeLoad _ANSI_ARGS_((void)); EXTERN void TclFinalizeMemorySubsystem _ANSI_ARGS_((void)); EXTERN void TclFinalizeNotifier _ANSI_ARGS_((void)); EXTERN void TclFinalizeSynchronization _ANSI_ARGS_((void)); EXTERN void TclFinalizeThreadData _ANSI_ARGS_((void)); EXTERN void TclFindEncodings _ANSI_ARGS_((CONST char *argv0)); EXTERN Proc * TclFindProc _ANSI_ARGS_((Interp *iPtr, char *procName)); EXTERN int TclFormatInt _ANSI_ARGS_((char *buffer, long n)); EXTERN void TclFreePackageInfo _ANSI_ARGS_((Interp *iPtr)); EXTERN int TclGetDate _ANSI_ARGS_((char *p, unsigned long now, long zone, unsigned long *timePtr)); EXTERN Tcl_Obj * TclGetElementOfIndexedArray _ANSI_ARGS_(( Tcl_Interp *interp, int localIndex, Tcl_Obj *elemPtr, int leaveErrorMsg)); EXTERN char * TclGetExtension _ANSI_ARGS_((char *name)); EXTERN int TclGetFrame _ANSI_ARGS_((Tcl_Interp *interp, char *string, CallFrame **framePtrPtr)); EXTERN TclCmdProcType TclGetInterpProc _ANSI_ARGS_((void)); EXTERN int TclGetIntForIndex _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *objPtr, int endValue, int *indexPtr)); EXTERN Tcl_Obj * TclGetIndexedScalar _ANSI_ARGS_((Tcl_Interp *interp, int localIndex, int leaveErrorMsg)); EXTERN int TclGetLong _ANSI_ARGS_((Tcl_Interp *interp, char *string, long *longPtr)); EXTERN int TclGetLoadedPackages _ANSI_ARGS_(( Tcl_Interp *interp, char *targetName)); EXTERN int TclGetNamespaceForQualName _ANSI_ARGS_(( Tcl_Interp *interp, char *qualName, Namespace *cxtNsPtr, int flags, Namespace **nsPtrPtr, Namespace **altNsPtrPtr, Namespace **actualCxtPtrPtr, char **simpleNamePtr)); EXTERN TclObjCmdProcType TclGetObjInterpProc _ANSI_ARGS_((void)); EXTERN int TclGetOpenMode _ANSI_ARGS_((Tcl_Interp *interp, char *string, int *seekFlagPtr)); EXTERN Tcl_Command TclGetOriginalCommand _ANSI_ARGS_(( Tcl_Command command)); EXTERN int TclGlob _ANSI_ARGS_((Tcl_Interp *interp, char *pattern, char *unquotedPrefix, int globFlags, GlobTypeData* types)); EXTERN int TclGlobalInvoke _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv, int flags)); EXTERN int TclGuessPackageName _ANSI_ARGS_((char *fileName, Tcl_DString *bufPtr)); EXTERN int TclHideUnsafeCommands _ANSI_ARGS_(( Tcl_Interp *interp)); EXTERN int TclInExit _ANSI_ARGS_((void)); EXTERN Tcl_Obj * TclIncrElementOfIndexedArray _ANSI_ARGS_(( Tcl_Interp *interp, int localIndex, Tcl_Obj *elemPtr, long incrAmount)); EXTERN Tcl_Obj * TclIncrIndexedScalar _ANSI_ARGS_(( Tcl_Interp *interp, int localIndex, long incrAmount)); EXTERN Tcl_Obj * TclIncrVar2 _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, long incrAmount, int flags)); EXTERN void TclInitAlloc _ANSI_ARGS_((void)); EXTERN void TclInitCompiledLocals _ANSI_ARGS_(( Tcl_Interp *interp, CallFrame *framePtr, Namespace *nsPtr)); EXTERN void TclInitDbCkalloc _ANSI_ARGS_((void)); EXTERN void TclInitEncodingSubsystem _ANSI_ARGS_((void)); EXTERN void TclInitIOSubsystem _ANSI_ARGS_((void)); EXTERN void TclInitNamespaceSubsystem _ANSI_ARGS_((void)); EXTERN void TclInitNotifier _ANSI_ARGS_((void)); EXTERN void TclInitObjSubsystem _ANSI_ARGS_((void)); EXTERN void TclInitSubsystems _ANSI_ARGS_((CONST char *argv0)); EXTERN int TclInvoke _ANSI_ARGS_((Tcl_Interp *interp, int argc, char **argv, int flags)); EXTERN int TclInvokeObjectCommand _ANSI_ARGS_(( ClientData clientData, Tcl_Interp *interp, int argc, char **argv)); EXTERN int TclInvokeStringCommand _ANSI_ARGS_(( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int TclIsLocalScalar _ANSI_ARGS_((CONST char *src, int len)); EXTERN Proc * TclIsProc _ANSI_ARGS_((Command *cmdPtr)); EXTERN Var * TclLookupVar _ANSI_ARGS_((Tcl_Interp *interp, char *part1, char *part2, int flags, char *msg, int createPart1, int createPart2, Var **arrayPtrPtr)); EXTERN int TclMathInProgress _ANSI_ARGS_((void)); EXTERN int TclNeedSpace _ANSI_ARGS_((char *start, char *end)); EXTERN Tcl_Obj * TclNewProcBodyObj _ANSI_ARGS_((Proc *procPtr)); EXTERN int TclObjCommandComplete _ANSI_ARGS_((Tcl_Obj *cmdPtr)); EXTERN int TclObjInterpProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int TclObjInvoke _ANSI_ARGS_((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int flags)); EXTERN int TclObjInvokeGlobal _ANSI_ARGS_((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int flags)); EXTERN int TclOpenFileChannelDeleteProc _ANSI_ARGS_(( TclOpenFileChannelProc_ *proc)); EXTERN int TclOpenFileChannelInsertProc _ANSI_ARGS_(( TclOpenFileChannelProc_ *proc)); EXTERN int TclpAccess _ANSI_ARGS_((CONST char *filename, int mode)); EXTERN char * TclpAlloc _ANSI_ARGS_((unsigned int size)); EXTERN int TclpCheckStackSpace _ANSI_ARGS_((void)); EXTERN int TclpCopyFile _ANSI_ARGS_((CONST char *source, CONST char *dest)); EXTERN int TclpCopyDirectory _ANSI_ARGS_((CONST char *source, CONST char *dest, Tcl_DString *errorPtr)); EXTERN int TclpCreateDirectory _ANSI_ARGS_((CONST char *path)); EXTERN int TclpDeleteFile _ANSI_ARGS_((CONST char *path)); EXTERN void TclpExit _ANSI_ARGS_((int status)); EXTERN void TclpFinalizeCondition _ANSI_ARGS_(( Tcl_Condition *condPtr)); EXTERN void TclpFinalizeMutex _ANSI_ARGS_((Tcl_Mutex *mutexPtr)); EXTERN void TclpFinalizeThreadData _ANSI_ARGS_(( Tcl_ThreadDataKey *keyPtr)); EXTERN void TclpFinalizeThreadDataKey _ANSI_ARGS_(( Tcl_ThreadDataKey *keyPtr)); EXTERN char * TclpFindExecutable _ANSI_ARGS_(( CONST char *argv0)); EXTERN int TclpFindVariable _ANSI_ARGS_((CONST char *name, int *lengthPtr)); EXTERN void TclpFree _ANSI_ARGS_((char *ptr)); EXTERN unsigned long TclpGetClicks _ANSI_ARGS_((void)); EXTERN Tcl_Channel TclpGetDefaultStdChannel _ANSI_ARGS_((int type)); EXTERN unsigned long TclpGetSeconds _ANSI_ARGS_((void)); EXTERN void TclpGetTime _ANSI_ARGS_((Tcl_Time *time)); EXTERN int TclpGetTimeZone _ANSI_ARGS_((unsigned long time)); EXTERN char * TclpGetUserHome _ANSI_ARGS_((CONST char *name, Tcl_DString *bufferPtr)); EXTERN int TclpHasSockets _ANSI_ARGS_((Tcl_Interp *interp)); EXTERN void TclpInitLibraryPath _ANSI_ARGS_((CONST char *argv0)); EXTERN void TclpInitLock _ANSI_ARGS_((void)); EXTERN void TclpInitPlatform _ANSI_ARGS_((void)); EXTERN void TclpInitUnlock _ANSI_ARGS_((void)); EXTERN int TclpListVolumes _ANSI_ARGS_((Tcl_Interp *interp)); EXTERN void TclpMasterLock _ANSI_ARGS_((void)); EXTERN void TclpMasterUnlock _ANSI_ARGS_((void)); EXTERN int TclpMatchFiles _ANSI_ARGS_((Tcl_Interp *interp, char *separators, Tcl_DString *dirPtr, char *pattern, char *tail)); EXTERN Tcl_Channel TclpOpenFileChannel _ANSI_ARGS_((Tcl_Interp *interp, char *fileName, char *modeString, int permissions)); EXTERN char * TclpReadlink _ANSI_ARGS_((CONST char *fileName, Tcl_DString *linkPtr)); EXTERN char * TclpRealloc _ANSI_ARGS_((char *ptr, unsigned int size)); EXTERN void TclpReleaseFile _ANSI_ARGS_((TclFile file)); EXTERN int TclpRemoveDirectory _ANSI_ARGS_((CONST char *path, int recursive, Tcl_DString *errorPtr)); EXTERN int TclpRenameFile _ANSI_ARGS_((CONST char *source, CONST char *dest)); EXTERN void TclpSetInitialEncodings _ANSI_ARGS_((void)); EXTERN void TclpSetVariables _ANSI_ARGS_((Tcl_Interp *interp)); EXTERN VOID * TclpSysAlloc _ANSI_ARGS_((long size, int isBin)); EXTERN void TclpSysFree _ANSI_ARGS_((VOID *ptr)); EXTERN VOID * TclpSysRealloc _ANSI_ARGS_((VOID *cp, unsigned int size)); EXTERN void TclpUnloadFile _ANSI_ARGS_((ClientData clientData)); EXTERN char * TclPrecTraceProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, char *name1, char *name2, int flags)); EXTERN int TclPreventAliasLoop _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Interp *cmdInterp, Tcl_Command cmd)); EXTERN void TclProcCleanupProc _ANSI_ARGS_((Proc *procPtr)); EXTERN int TclProcCompileProc _ANSI_ARGS_((Tcl_Interp *interp, Proc *procPtr, Tcl_Obj *bodyPtr, Namespace *nsPtr, CONST char *description, CONST char *procName)); EXTERN void TclProcDeleteProc _ANSI_ARGS_((ClientData clientData)); EXTERN int TclProcInterpProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int argc, char **argv)); EXTERN VOID * TclpThreadDataKeyGet _ANSI_ARGS_(( Tcl_ThreadDataKey *keyPtr)); EXTERN void TclpThreadDataKeyInit _ANSI_ARGS_(( Tcl_ThreadDataKey *keyPtr)); EXTERN void TclpThreadDataKeySet _ANSI_ARGS_(( Tcl_ThreadDataKey *keyPtr, VOID *data)); EXTERN void TclpThreadExit _ANSI_ARGS_((int status)); EXTERN void TclRememberCondition _ANSI_ARGS_((Tcl_Condition *mutex)); EXTERN void TclRememberDataKey _ANSI_ARGS_((Tcl_ThreadDataKey *mutex)); EXTERN void TclRememberMutex _ANSI_ARGS_((Tcl_Mutex *mutex)); EXTERN int TclRenameCommand _ANSI_ARGS_((Tcl_Interp *interp, char *oldName, char *newName)) ; EXTERN void TclResetShadowedCmdRefs _ANSI_ARGS_(( Tcl_Interp *interp, Command *newCmdPtr)); EXTERN int TclServiceIdle _ANSI_ARGS_((void)); EXTERN Tcl_Obj * TclSetElementOfIndexedArray _ANSI_ARGS_(( Tcl_Interp *interp, int localIndex, Tcl_Obj *elemPtr, Tcl_Obj *objPtr, int leaveErrorMsg)); EXTERN Tcl_Obj * TclSetIndexedScalar _ANSI_ARGS_((Tcl_Interp *interp, int localIndex, Tcl_Obj *objPtr, int leaveErrorMsg)); EXTERN char * TclSetPreInitScript _ANSI_ARGS_((char *string)); EXTERN void TclSetupEnv _ANSI_ARGS_((Tcl_Interp *interp)); EXTERN int TclSockGetPort _ANSI_ARGS_((Tcl_Interp *interp, char *string, char *proto, int *portPtr)); EXTERN int TclSockMinimumBuffers _ANSI_ARGS_((int sock, int size)); EXTERN int TclStat _ANSI_ARGS_((CONST char *path, struct stat *buf)); EXTERN int TclStatDeleteProc _ANSI_ARGS_((TclStatProc_ *proc)); EXTERN int TclStatInsertProc _ANSI_ARGS_((TclStatProc_ *proc)); EXTERN void TclTeardownNamespace _ANSI_ARGS_((Namespace *nsPtr)); EXTERN void TclTransferResult _ANSI_ARGS_((Tcl_Interp *sourceInterp, int result, Tcl_Interp *targetInterp)); EXTERN int TclUpdateReturnInfo _ANSI_ARGS_((Interp *iPtr)); /* *---------------------------------------------------------------- * Command procedures in the generic core: *---------------------------------------------------------------- */ EXTERN int Tcl_AfterObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_AppendObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ArrayObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_BinaryObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_BreakObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_CaseObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_CatchObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_CdObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ClockObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_CloseObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ConcatObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ContinueObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_EncodingObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_EofObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ErrorObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_EvalObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ExecObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ExitObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ExprObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FblockedObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FconfigureObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FcopyObjCmd _ANSI_ARGS_((ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FileObjCmd _ANSI_ARGS_((ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FileEventObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FlushObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ForObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ForeachObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_FormatObjCmd _ANSI_ARGS_((ClientData dummy, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_GetsObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_GlobalObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_GlobObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_IfObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_IncrObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_InfoObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_InterpObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int argc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_JoinObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LappendObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LindexObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LinsertObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LlengthObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ListObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LoadObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LrangeObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LreplaceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LsearchObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_LsortObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_NamespaceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_OpenObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_PackageObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_PidObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_PutsObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_PwdObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ReadObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_RegexpObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_RegsubObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_RenameObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ReturnObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ScanObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SeekObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SetObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SplitObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SocketObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SourceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_StringObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SubstObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_SwitchObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_TellObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_TimeObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_TraceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_UnsetObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_UpdateObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_UplevelObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_UpvarObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_VariableObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_VwaitObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_WhileObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); /* *---------------------------------------------------------------- * Command procedures found only in the Mac version of the core: *---------------------------------------------------------------- */ #ifdef MAC_TCL EXTERN int Tcl_EchoCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int argc, char **argv)); EXTERN int Tcl_LsObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_BeepObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_MacSourceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); EXTERN int Tcl_ResourceObjCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])); #endif /* *---------------------------------------------------------------- * Compilation procedures for commands in the generic core: *---------------------------------------------------------------- */ EXTERN int TclCompileBreakCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileCatchCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileContinueCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileExprCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileForCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileForeachCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileIfCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileIncrCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileSetCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); EXTERN int TclCompileWhileCmd _ANSI_ARGS_((Tcl_Interp *interp, Tcl_Parse *parsePtr, struct CompileEnv *envPtr)); /* *---------------------------------------------------------------- * Macros used by the Tcl core to create and release Tcl objects. * TclNewObj(objPtr) creates a new object denoting an empty string. * TclDecrRefCount(objPtr) decrements the object's reference count, * and frees the object if its reference count is zero. * These macros are inline versions of Tcl_NewObj() and * Tcl_DecrRefCount(). Notice that the names differ in not having * a "_" after the "Tcl". Notice also that these macros reference * their argument more than once, so you should avoid calling them * with an expression that is expensive to compute or has * side effects. The ANSI C "prototypes" for these macros are: * * EXTERN void TclNewObj _ANSI_ARGS_((Tcl_Obj *objPtr)); * EXTERN void TclDecrRefCount _ANSI_ARGS_((Tcl_Obj *objPtr)); *---------------------------------------------------------------- */ #ifdef TCL_COMPILE_STATS # define TclIncrObjsAllocated() \ tclObjsAlloced++ # define TclIncrObjsFreed() \ tclObjsFreed++ #else # define TclIncrObjsAllocated() # define TclIncrObjsFreed() #endif /* TCL_COMPILE_STATS */ #ifdef TCL_MEM_DEBUG # define TclNewObj(objPtr) \ (objPtr) = (Tcl_Obj *) \ Tcl_DbCkalloc(sizeof(Tcl_Obj), __FILE__, __LINE__); \ (objPtr)->refCount = 0; \ (objPtr)->bytes = tclEmptyStringRep; \ (objPtr)->length = 0; \ (objPtr)->typePtr = NULL; \ TclIncrObjsAllocated() # define TclDbNewObj(objPtr, file, line) \ (objPtr) = (Tcl_Obj *) Tcl_DbCkalloc(sizeof(Tcl_Obj), (file), (line)); \ (objPtr)->refCount = 0; \ (objPtr)->bytes = tclEmptyStringRep; \ (objPtr)->length = 0; \ (objPtr)->typePtr = NULL; \ TclIncrObjsAllocated() # define TclDecrRefCount(objPtr) \ if (--(objPtr)->refCount <= 0) { \ if ((objPtr)->refCount < -1) \ panic("Reference count for %lx was negative: %s line %d", \ (objPtr), __FILE__, __LINE__); \ if (((objPtr)->bytes != NULL) \ && ((objPtr)->bytes != tclEmptyStringRep)) { \ ckfree((char *) (objPtr)->bytes); \ } \ if (((objPtr)->typePtr != NULL) \ && ((objPtr)->typePtr->freeIntRepProc != NULL)) { \ (objPtr)->typePtr->freeIntRepProc(objPtr); \ } \ ckfree((char *) (objPtr)); \ TclIncrObjsFreed(); \ } #else /* not TCL_MEM_DEBUG */ #ifdef TCL_THREADS extern Tcl_Mutex tclObjMutex; #endif # define TclNewObj(objPtr) \ Tcl_MutexLock(&tclObjMutex); \ if (tclFreeObjList == NULL) { \ TclAllocateFreeObjects(); \ } \ (objPtr) = tclFreeObjList; \ tclFreeObjList = (Tcl_Obj *) \ tclFreeObjList->internalRep.otherValuePtr; \ (objPtr)->refCount = 0; \ (objPtr)->bytes = tclEmptyStringRep; \ (objPtr)->length = 0; \ (objPtr)->typePtr = NULL; \ TclIncrObjsAllocated(); \ Tcl_MutexUnlock(&tclObjMutex) # define TclDecrRefCount(objPtr) \ if (--(objPtr)->refCount <= 0) { \ if (((objPtr)->bytes != NULL) \ && ((objPtr)->bytes != tclEmptyStringRep)) { \ ckfree((char *) (objPtr)->bytes); \ } \ if (((objPtr)->typePtr != NULL) \ && ((objPtr)->typePtr->freeIntRepProc != NULL)) { \ (objPtr)->typePtr->freeIntRepProc(objPtr); \ } \ Tcl_MutexLock(&tclObjMutex); \ (objPtr)->internalRep.otherValuePtr = (VOID *) tclFreeObjList; \ tclFreeObjList = (objPtr); \ TclIncrObjsFreed(); \ Tcl_MutexUnlock(&tclObjMutex); \ } #endif /* TCL_MEM_DEBUG */ /* *---------------------------------------------------------------- * Macro used by the Tcl core to set a Tcl_Obj's string representation * to a copy of the "len" bytes starting at "bytePtr". This code * works even if the byte array contains NULLs as long as the length * is correct. Because "len" is referenced multiple times, it should * be as simple an expression as possible. The ANSI C "prototype" for * this macro is: * * EXTERN void TclInitStringRep _ANSI_ARGS_((Tcl_Obj *objPtr, * char *bytePtr, int len)); *---------------------------------------------------------------- */ #define TclInitStringRep(objPtr, bytePtr, len) \ if ((len) == 0) { \ (objPtr)->bytes = tclEmptyStringRep; \ (objPtr)->length = 0; \ } else { \ (objPtr)->bytes = (char *) ckalloc((unsigned) ((len) + 1)); \ memcpy((VOID *) (objPtr)->bytes, (VOID *) (bytePtr), \ (unsigned) (len)); \ (objPtr)->bytes[len] = '\0'; \ (objPtr)->length = (len); \ } /* *---------------------------------------------------------------- * Macro used by the Tcl core to get the string representation's * byte array pointer from a Tcl_Obj. This is an inline version * of Tcl_GetString(). The macro's expression result is the string * rep's byte pointer which might be NULL. The bytes referenced by * this pointer must not be modified by the caller. * The ANSI C "prototype" for this macro is: * * EXTERN char * TclGetString _ANSI_ARGS_((Tcl_Obj *objPtr)); *---------------------------------------------------------------- */ #define TclGetString(objPtr) \ ((objPtr)->bytes? (objPtr)->bytes : Tcl_GetString((objPtr))) #include "tclIntDecls.h" # undef TCL_STORAGE_CLASS # define TCL_STORAGE_CLASS DLLIMPORT #endif /* _TCLINT */
byvernault/xnat_osirix_plugin
src/OsiriXAPI.framework/Versions/Current/Headers/tclInt.h
C
mit
111,500
/***************************************************************************** * Copyright 2001 - 2011 Broadcom Corporation. All rights reserved. * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2, available at * http://www.gnu.org/licenses/old-license/gpl-2.0.html (the "GPL"). * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a * license other than the GPL, without Broadcom's express prior written * consent. * *****************************************************************************/ /****************************************************************************/ /** * @file chal_rtc.h * * @brief RTC driver interface header file. * * @note * ****************************************************************************/ #ifndef _CHAL_RTC_H #define _CHAL_RTC_H #ifdef __cplusplus extern "C" { #endif /* ---- Include Files ---------------------------------------------------- */ #include <linux/kernel.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/io.h> #include <chal/chal_defs.h> /* --- START: CHAL compatability shim --- */ static void CHAL_REG_SETBIT32(uint32_t addr, unsigned int bits) { iowrite32(ioread32((void *)addr) | bits, (void *)addr); } #define CHAL_REG_WRITE32(x,y) iowrite32(y,x) #define CHAL_REG_READ32(x) ioread32(x) #define chal_dbg_printf(x,...) pr_debug(__VA_ARGS__) #include <mach/rdb/brcm_rdb_bbl_apb.h> #include <mach/rdb/brcm_rdb_bbl_rtc.h> #include <mach/rdb/brcm_rdb_sysmap.h> #include <mach/rdb/brcm_rdb_map.h> #define RTC_PERIODIC_TIMER_ADDR (rtc->handle->rtcBaseAddr+BBL_RTC_PER_OFFSET) #define RTC_MATCH_REGISTER_ADDR (rtc->handle->rtcBaseAddr+BBL_RTC_MATCH_OFFSET) #define RTC_CLEAR_INTR_ADDR (rtc->handle->rtcBaseAddr+BBL_RTC_CLR_INT_OFFSET) #define RTC_INTERRUPT_STATUS_ADDR (rtc->handle->rtcBaseAddr+BBL_RTC_INT_STS_OFFSET) #define RTC_CONTROL_ADDR (rtc->handle->rtcBaseAddr+BBL_RTC_CTRL_OFFSET) /* --- END: CHAL compatability shim --- */ /* ---- Public Constants and Types --------------------------------------- */ /* * Handle for RTC controller operations. */ struct chal_rtc_handle { uint32_t rtcBaseAddr; /* Base address of the RTC */ uint32_t bar; /* Base address to use for register accesses */ uint32_t wr_data; /* Data to be written into BBL APB Slave */ uint32_t rd_data; /* Data read from BBL APB Interface */ uint32_t ctrl_sts; /* APB Control & Status Register */ uint32_t int_sts; /* Status register indicating interrupt source from BBL */ }; typedef struct chal_rtc_handle CHAL_RTC_HANDLE_t; typedef uint64_t chal_rtc_TIME_t; /* Time in seconds */ /* RTC Block - CTRL */ typedef enum { CHAL_RTC_CTRL_LOCK = 0, /* lock the real-time clock counters, SET_DIV and SEC_0 */ CHAL_RTC_CTRL_UNLOCK, /* unlock the real-time clock counters, SET_DIV and SEC_0 */ CHAL_RTC_CTRL_STOP, /* halt the real-time clock */ CHAL_RTC_CTRL_RUN /* start the real-time clock */ } chal_RTC_CTRL_e; /* RTC Block - Interrupt types */ typedef enum { CHAL_RTC_INT_PER = 0, /* Periodic interrupt */ CHAL_RTC_INT_MATCH = 1, /* Match interrupt */ CHAL_RTC_INT_NONE, } chal_RTC_INT_e; /* RTC - Monotonic timer clock */ typedef enum { CHAL_RTC_MTC_LOCK = 0, /* Locks writes to MTC. Sticky bit */ CHAL_RTC_MTC_INCR /* increment MTC by INCR_AMT, even when locked */ } chal_RTC_MTC_CTRL_e; /* RTC - Periodic interrupt interval */ typedef enum { CHAL_RTC_PER_INTERVAL_125ms = 0x00000001, /* Time interval 125ms */ CHAL_RTC_PER_INTERVAL_250ms = 0x00000002, /* Time interval 250ms */ CHAL_RTC_PER_INTERVAL_500ms = 0x00000004, /* Time interval 500ms */ CHAL_RTC_PER_INTERVAL_1000ms = 0x00000008, /* Time interval 1 sec */ CHAL_RTC_PER_INTERVAL_2000ms = 0x00000010, /* Time interval 2 sec */ CHAL_RTC_PER_INTERVAL_4000ms = 0x00000020, /* Time interval 4 sec */ CHAL_RTC_PER_INTERVAL_8000ms = 0x00000040, /* Time interval 8 sec */ CHAL_RTC_PER_INTERVAL_16000ms = 0x00000080, /* Time interval 16 sec */ CHAL_RTC_PER_INTERVAL_32000ms = 0x00000100, /* Time interval 32 sec */ CHAL_RTC_PER_INTERVAL_64000ms = 0x00000200, /* Time interval 64 sec */ CHAL_RTC_PER_INTERVAL_128000ms = 0x00000400, /* Time interval 128 sec */ CHAL_RTC_PER_INTERVAL_256000ms = 0x00000800 /* Time interval 256 sec */ } chal_RTC_PER_INTERVAL_e; #define CHAL_RTC_RESET_ACCESS_STATUS 0xACCE55ED /* ---- Public Variable Externs ------------------------------------------ */ /* ---- Public Function Prototypes --------------------------------------- */ /*=========================================================================== * Functions for RTC operations. * ===========================================================================*/ /****************************************************************************/ /** * @brief Initialize RTC config structure * * @param handle (in) Pointer to the RTC initialization structure * @param bblBar (in) Location of BBL base address register * @param config (in) Location of RTC base address register * ****************************************************************************/ int chal_rtc_init(CHAL_RTC_HANDLE_t *handle, uint32_t bblBar, uint32_t rtcBar); static inline void chal_rtc_divSet(CHAL_RTC_HANDLE_t *handle, uint32_t val); static inline uint32_t chal_rtc_divGet(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_secSet(CHAL_RTC_HANDLE_t *handle, uint32_t val); static inline uint32_t chal_rtc_secGet(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_ctrlSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_CTRL_e cmd); static inline void chal_rtc_periodInterruptValSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_PER_INTERVAL_e interval); static inline uint32_t chal_rtc_periodInterruptValGet(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_matchInterruptValSet(CHAL_RTC_HANDLE_t *handle, chal_rtc_TIME_t sec); static inline uint32_t chal_rtc_matchInterruptValGet(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_intStatusClr(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt); static inline void chal_rtc_intStatusClrVal(CHAL_RTC_HANDLE_t *handle, uint32_t val); static inline int chal_rtc_intStatusGet(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt); static inline uint32_t chal_rtc_intStatusGetVal(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_intEnable(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt); static inline void chal_rtc_intEnableVal(CHAL_RTC_HANDLE_t *handle, uint32_t bitsOn); static inline void chal_rtc_intDisable(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt); static inline void chal_rtc_intDisableVal(CHAL_RTC_HANDLE_t *handle, uint32_t bitsOff ); static inline int chal_rtc_intIsEnabled(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt); static inline chal_RTC_INT_e chal_rtc_interruptStatusGet(CHAL_RTC_HANDLE_t *handle); static inline int chal_rtc_rstIsAsserted(CHAL_RTC_HANDLE_t *handle); static inline void chal_rtc_mtcCtrlSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_MTC_CTRL_e cmd); static inline void chal_rtc_mtcIncrSet(CHAL_RTC_HANDLE_t *handle, uint16_t amount); static inline void chal_rtc_mtcTimeSet(CHAL_RTC_HANDLE_t *handle, chal_rtc_TIME_t time); static inline chal_rtc_TIME_t chal_rtc_mtcTimeGet(CHAL_RTC_HANDLE_t *handle); /* ---- Private Constants and Types ---------------------------------------- */ /* ---- Public Variable Externs -------------------------------------------- */ /* ---- Private Function Prototypes ----------------------------------------- */ static inline uint32_t chal_rtc_readReg(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr); static inline void chal_rtc_readRegIE(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr); static inline void chal_rtc_writeReg(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr, uint32_t val); static inline void chal_rtc_writeRegNoWait(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr, uint32_t val); /* Macros for accessing RTC registers through the APB BBL interface*/ #define chal_rtc_REG_SET_APB_SLAVE_ADDRESS(handle, add) (CHAL_REG_WRITE32(handle->bar, add)) #define chal_rtc_REG_GET_WR_DATA(handle) (CHAL_REG_READ32(handle->wr_data)) #define chal_rtc_REG_SET_WR_DATA(handle, val) (CHAL_REG_WRITE32(handle->wr_data, val)) #define chal_rtc_REG_GET_RD_DATA(handle) (CHAL_REG_READ32(handle->rd_data)) #define chal_rtc_REG_COMMAND_WRITE(handle) (CHAL_REG_SETBIT32(handle->ctrl_sts, BBL_APB_CTRL_STS_BBL_CMD_START_MASK | BBL_APB_CTRL_STS_BBL_APB_CMD_MASK)) #define chal_rtc_REG_COMMAND_READ(handle) (CHAL_REG_SETBIT32(handle->ctrl_sts, BBL_APB_CTRL_STS_BBL_CMD_START_MASK & ~BBL_APB_CTRL_STS_BBL_APB_CMD_MASK)) #define chal_rtc_REG_IS_COMMAND_DONE(handle) (CHAL_REG_READ32(handle->ctrl_sts) & BBL_APB_CTRL_STS_BBL_CMD_DONE_MASK) #define chal_rtc_REG_COMMAND_DONE_CLEAR(handle) (CHAL_REG_SETBIT32(handle->ctrl_sts, BBL_APB_CTRL_STS_BBL_CMD_DONE_MASK)) /* ---- Public Function Prototypes ----------------------------------------- */ /****************************************************************************/ /** * @brief Set the RTC clock divider value. The clock must be set to start * running again after this is called. * * @return none */ /****************************************************************************/ static inline void chal_rtc_divSet(CHAL_RTC_HANDLE_t *handle, uint32_t val) { chal_rtc_ctrlSet(handle, CHAL_RTC_CTRL_STOP); chal_rtc_writeReg(handle, handle->rtcBaseAddr + RTC_SET_DIV_OFFSET, val); } /****************************************************************************/ /** * @brief Get the RTC clock divider value * * @return Clock divider value */ /****************************************************************************/ static inline uint32_t chal_rtc_divGet(CHAL_RTC_HANDLE_t *handle) { return ( chal_rtc_readReg (handle, handle->rtcBaseAddr + RTC_SET_DIV_OFFSET)); } /****************************************************************************/ /** * @brief Set the RTC seconds value * * @return none */ /****************************************************************************/ static inline void chal_rtc_secSet(CHAL_RTC_HANDLE_t *handle, uint32_t val) { chal_rtc_ctrlSet(handle, CHAL_RTC_CTRL_STOP); chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to SEC_0\n", val); chal_rtc_writeReg (handle, handle->rtcBaseAddr + RTC_SEC_0_OFFSET, val); } /****************************************************************************/ /** * @brief Get the RTC seconds value * * @return RTC seconds value */ /****************************************************************************/ static inline uint32_t chal_rtc_secGet(CHAL_RTC_HANDLE_t *handle) { uint32_t val = chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_SEC_0_OFFSET); return val; } /****************************************************************************/ /** * @brief Sets RTC control * * @return none */ /****************************************************************************/ static inline void chal_rtc_ctrlSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_CTRL_e cmd) { uint32_t val; uint32_t addr; addr = handle->rtcBaseAddr + RTC_CTRL_OFFSET; /* Read the data */ val = chal_rtc_readReg (handle, addr); val &= 0x3; chal_dbg_printf(CHAL_DBG_DEBUG, "Read RTC CTRL: %d\n", val); switch ( cmd ) { case CHAL_RTC_CTRL_LOCK: /* Set the RTC lock bit */ val |= RTC_CTRL_RTC_LOCK_MASK; break; case CHAL_RTC_CTRL_UNLOCK: /* Clear the RTC lock bit */ val &= ~RTC_CTRL_RTC_LOCK_MASK; break; case CHAL_RTC_CTRL_STOP: /* Set the RTC stop bit */ val |= RTC_CTRL_RTC_STOP_MASK; break; case CHAL_RTC_CTRL_RUN: /* Clear the RTC stop bit */ val &= ~RTC_CTRL_RTC_STOP_MASK; break; } /* Write the data */ chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to RTC CTRL\n", val); chal_rtc_writeReg (handle, addr, val); } /****************************************************************************/ /** * @brief Configures a periodic timer to generate timer interrupt after * certain time interval * * This function initializes a periodic timer to generate timer interrupt * after every time interval. * * @return none */ /****************************************************************************/ static inline void chal_rtc_periodInterruptValSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_PER_INTERVAL_e interval) { chal_dbg_printf(CHAL_DBG_DEBUG, "Write 0x%x to PER\n", interval); chal_rtc_writeReg(handle, handle->rtcBaseAddr + RTC_PER_OFFSET, interval); } /****************************************************************************/ /** * @brief Gets the perioic timer configuration * * @return Perioidic interrupt value */ /****************************************************************************/ static inline uint32_t chal_rtc_periodInterruptValGet(CHAL_RTC_HANDLE_t *handle) { return( chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_PER_OFFSET) ); } /****************************************************************************/ /** * @brief Configures the real time timer to generate an oneshot interrupt * * This function initializes the timer to generate one shot interrupt * after certain time period in seconds * * @return none */ /****************************************************************************/ static inline void chal_rtc_matchInterruptValSet(CHAL_RTC_HANDLE_t *handle, chal_rtc_TIME_t sec) { chal_rtc_writeReg(handle, handle->rtcBaseAddr + RTC_MATCH_OFFSET, (sec & RTC_MATCH_RTC_MATCH_MASK)); } /****************************************************************************/ /** * @brief Gets the real time timer to generate an oneshot interrupt * * This function initializes the timer to generate one shot interrupt * after certain time period in seconds * * @return Match interrupt value */ /****************************************************************************/ static inline uint32_t chal_rtc_matchInterruptValGet(CHAL_RTC_HANDLE_t *handle) { return( chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_MATCH_OFFSET) ); } /****************************************************************************/ /** * @brief Clears a RTC interrupt * * @return none */ /****************************************************************************/ static inline void chal_rtc_intStatusClr(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt) { chal_rtc_writeReg(handle, handle->rtcBaseAddr + RTC_CLR_INT_OFFSET, 1 << interrupt); } static inline void chal_rtc_intStatusClrVal(CHAL_RTC_HANDLE_t *handle, uint32_t val) { uint32_t verify = 0; chal_dbg_printf(CHAL_DBG_DEBUG, "Writing %d to CLR_INT\n", val); chal_rtc_writeReg(handle, handle->rtcBaseAddr + RTC_CLR_INT_OFFSET, val); verify = chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_CLR_INT_OFFSET); //chal_dbg_printf(CHAL_DBG_DEBUG, "Verifying CLR_INT: %d\n", verify); } /****************************************************************************/ /** * @brief Get the status of a RTC interrupt * * @return 1: an interrupt occurred * 0: no interrupt occurred */ /****************************************************************************/ static inline int chal_rtc_intStatusGet(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt) { return( ( chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_INT_STS_OFFSET) & (1<<interrupt) ) ? 1 : 0 ); } static inline uint32_t chal_rtc_intStatusGetVal(CHAL_RTC_HANDLE_t *handle) { uint32_t val = chal_rtc_readReg(handle, handle->rtcBaseAddr + RTC_INT_STS_OFFSET); return val; } /****************************************************************************/ /** * @brief Gets the status of enabled interrupts * * @return rtcHw_INTERRUPT_STATUS_NONE : On no interrupt * * rtcHw_INTERRUPT_STATUS_PERIODIC : On interrupt * rtcHw_INTERRUPT_STATUS_ONESHOT */ /****************************************************************************/ static inline chal_RTC_INT_e chal_rtc_interruptStatusGet(CHAL_RTC_HANDLE_t *handle) { if( chal_rtc_intStatusGet(handle, CHAL_RTC_INT_PER) & chal_rtc_intIsEnabled(handle, CHAL_RTC_INT_PER) ) { return CHAL_RTC_INT_PER; } else if( chal_rtc_intStatusGet(handle, CHAL_RTC_INT_MATCH) & chal_rtc_intIsEnabled(handle, CHAL_RTC_INT_MATCH) ) { return CHAL_RTC_INT_MATCH; } return CHAL_RTC_INT_NONE; } /****************************************************************************/ /** * @brief Enable/disable a RTC interrupt * * @return none */ /****************************************************************************/ static inline void chal_rtc_intEnable(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_INT_ENABLE_OFFSET; val = chal_rtc_readReg(handle, addr); val |= (1 << interrupt); chal_dbg_printf(CHAL_DBG_DEBUG, "Write INT_ENABLE: %d\n", val); chal_rtc_writeRegNoWait(handle, addr, val); // val = chal_rtc_readReg(handle, addr); // chal_dbg_printf(CHAL_DBG_DEBUG, "Read INT_ENABLE: %d\n", val); } static inline void chal_rtc_intEnableVal(CHAL_RTC_HANDLE_t *handle, uint32_t bitsOn) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_INT_ENABLE_OFFSET; val = chal_rtc_readReg (handle, addr); val |= bitsOn; chal_dbg_printf(CHAL_DBG_DEBUG, "INT_ENABLE (enabling): %d\n", val); chal_rtc_writeReg (handle, addr, val); } static inline void chal_rtc_intDisable(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_INT_ENABLE_OFFSET; val = chal_rtc_readReg(handle, addr); val &= ~(1 << interrupt); chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to INT_ENABLE (disabling)\n", val); chal_rtc_writeReg(handle, addr, val); } static inline void chal_rtc_intDisableVal(CHAL_RTC_HANDLE_t *handle, uint32_t bitsOff) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_INT_ENABLE_OFFSET; val = chal_rtc_readReg (handle, addr ); val &= ~(bitsOff); chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to INT_ENABLE (disabling)\n", val); chal_rtc_writeReg (handle, addr, val); } /****************************************************************************/ /** * @brief Check whether RTC interrupt is enabled * * @return 1: interrupt is enabled * 0: interrupt is disabled */ /****************************************************************************/ static inline int chal_rtc_intIsEnabled(CHAL_RTC_HANDLE_t *handle, chal_RTC_INT_e interrupt) { return( ( chal_rtc_readReg (handle, handle->rtcBaseAddr + RTC_INT_ENABLE_OFFSET ) & (1<<interrupt) ) ? 1 : 0 ); } /****************************************************************************/ /** * @brief Checks whether BBL reset has been asserted * * @return 1: reset is asserted * 0: reset is not asserted */ /****************************************************************************/ static inline int chal_rtc_rstIsAsserted(CHAL_RTC_HANDLE_t *handle) { return( ( chal_rtc_readReg (handle, handle->rtcBaseAddr + RTC_RESET_ACCESS_OFFSET ) == CHAL_RTC_RESET_ACCESS_STATUS ) ? 1 : 0 ); } /****************************************************************************/ /** * @brief Set monotonic counter control * * @return none */ /****************************************************************************/ static inline void chal_rtc_mtcCtrlSet(CHAL_RTC_HANDLE_t *handle, chal_RTC_MTC_CTRL_e cmd) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_MTC_CTRL_OFFSET; /* Read the data */ val = chal_rtc_readReg (handle, addr ); switch ( cmd ) { case CHAL_RTC_MTC_LOCK: /* locks monotonic counter - sticky bit */ val |= RTC_MTC_CTRL_RTC_MT_CTR_LOCK_MASK; break; case CHAL_RTC_MTC_INCR: /* increment monotonic counter by incr_amt - self clear */ val |= RTC_MTC_CTRL_RTC_MT_CTR_INCR_MASK; break; } /* Write the data */ chal_rtc_writeReg (handle, addr, val); } /****************************************************************************/ /** * @brief Set monotonic counter increment amount * * @return none */ /****************************************************************************/ static inline void chal_rtc_mtcIncrSet(CHAL_RTC_HANDLE_t *handle, uint16_t amount) { uint32_t val, addr; addr = handle->rtcBaseAddr + RTC_MTC_CTRL_OFFSET; /* Read the data */ val = chal_rtc_readReg (handle, addr ); val &= ~RTC_MTC_CTRL_RTC_MT_CTR_INCR_AMT_MASK; val |= (uint32_t) amount << RTC_MTC_CTRL_RTC_MT_CTR_INCR_AMT_SHIFT; /* Write the data */ chal_rtc_writeReg (handle, addr, val); } /****************************************************************************/ /** * @brief Sets the current time counts in seconds * * This function gets the current time counts * * @return Current time count since it started */ /****************************************************************************/ static inline void chal_rtc_mtcTimeSet(CHAL_RTC_HANDLE_t *handle, chal_rtc_TIME_t time) { chal_rtc_writeReg (handle, handle->rtcBaseAddr + RTC_MTC_MSB_OFFSET, time >> 32 ); chal_rtc_writeReg (handle, handle->rtcBaseAddr + RTC_MTC_LSB_OFFSET, time & 0xffffffff ); } /****************************************************************************/ /** * @brief Gets the current time counts in seconds * * This function gets the current time counts * * @return Current time count since it started */ /****************************************************************************/ static inline chal_rtc_TIME_t chal_rtc_mtcTimeGet(CHAL_RTC_HANDLE_t *handle) { uint32_t mtcMsb, mtcLsb; chal_rtc_TIME_t time; mtcMsb = chal_rtc_readReg (handle, handle->rtcBaseAddr + RTC_MTC_MSB_OFFSET); mtcLsb = chal_rtc_readReg (handle, handle->rtcBaseAddr + RTC_MTC_LSB_OFFSET); time = ((chal_rtc_TIME_t)mtcMsb) << 32 | (chal_rtc_TIME_t) mtcLsb; return time; } /* ==== Private Functions ================================================= */ static inline void chal_rtc_readyForCommand(CHAL_RTC_HANDLE_t *handle) { uint32_t count = 0; while (!chal_rtc_REG_IS_COMMAND_DONE(handle)) { udelay (1); count++; } /* This delay is a hack to get around a problem where RTC registers can't be read if they occur too soon after a previous read. */ // #if CFG_GLOBAL_CHIP == BCM11160 mdelay(1); // #endif chal_dbg_printf(CHAL_DBG_DEBUG, "Command completed in %d us\n", count); chal_rtc_REG_COMMAND_DONE_CLEAR(handle); } /****************************************************************************/ /** * @brief A command to read indirect RTC registers * * @return Value read */ /****************************************************************************/ static inline uint32_t chal_rtc_readReg(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr) { uint32_t ctrlStsVal = 0; uint32_t val; ctrlStsVal = CHAL_REG_READ32(handle->ctrl_sts); chal_rtc_REG_SET_APB_SLAVE_ADDRESS (handle, regAddr); /* Execute read command */ ctrlStsVal &= ~BBL_APB_CTRL_STS_BBL_APB_CMD_MASK; ctrlStsVal |= BBL_APB_CTRL_STS_BBL_CMD_START_MASK; chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to ctrl_sts\n", ctrlStsVal); CHAL_REG_WRITE32(handle->ctrl_sts, ctrlStsVal); /* Wait until command is processed */ chal_rtc_readyForCommand(handle); /* Read the data */ val = chal_rtc_REG_GET_RD_DATA(handle); return val; } /** * Reads an RTC register through the RTC APB interface but doesn't wait for the * command to complete by polling the command ready flag in status register. The * command complete interrupt is used instead and an ISR must be installed. When * the interrupt has fired then the rd_data register can be read by calling * chal_rtc_REG_GET_RD_DATA() to get the value of the register that was read. */ static inline void chal_rtc_readRegIE(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr) { uint32_t ctrlStsVal = 0; ctrlStsVal = CHAL_REG_READ32(handle->ctrl_sts); chal_rtc_REG_SET_APB_SLAVE_ADDRESS (handle, regAddr); /* Execute read command */ ctrlStsVal &= ~BBL_APB_CTRL_STS_BBL_APB_CMD_MASK; ctrlStsVal |= BBL_APB_CTRL_STS_BBL_CMD_START_MASK; /* Command ready interrupt enable is done on every command */ ctrlStsVal |= BBL_APB_CTRL_STS_APB_CMD_DONE_INT_EN_MASK; chal_dbg_printf(CHAL_DBG_DEBUG, "Write %d to ctrl_sts\n", ctrlStsVal); CHAL_REG_WRITE32(handle->ctrl_sts, ctrlStsVal); } /****************************************************************************/ /** * @brief A command to write to indirect BBL registers * * @return none */ /****************************************************************************/ static inline void chal_rtc_writeReg(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr, uint32_t val) { /* Make sure BBL interface is ready to accept commands */ chal_rtc_REG_SET_APB_SLAVE_ADDRESS(handle, regAddr); CHAL_REG_WRITE32(handle->wr_data, val); chal_rtc_REG_COMMAND_WRITE(handle); chal_rtc_readyForCommand(handle); } static inline void chal_rtc_writeRegNoWait(CHAL_RTC_HANDLE_t *handle, uint32_t regAddr, uint32_t val ) { /* Make sure BBL interface is ready to accept commands */ chal_rtc_REG_SET_APB_SLAVE_ADDRESS(handle, regAddr); CHAL_REG_WRITE32(handle->wr_data, val); chal_rtc_REG_COMMAND_WRITE(handle); } #ifdef __cplusplus } #endif #endif /* _CHAL_RTC_H */
sai9615/MY-kernel-for-grand-I9082
dragon/arch/arm/mach-island/include/chal/chal_rtc.h
C
gpl-2.0
26,117
// Copyright 2012 the V8 project authors. 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 of Google Inc. 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. #ifndef V8_PLATFORM_POSIX_H_ #define V8_PLATFORM_POSIX_H_ namespace v8 { namespace internal { // Used by platform implementation files during OS::PostSetUp(). void POSIXPostSetUp(); } } // namespace v8::internal #endif // V8_PLATFORM_POSIX_H_
teeple/pns_server
work/install/node-v0.10.25/deps/v8/src/platform-posix.h
C
gpl-2.0
1,847
# README README has been moved to [https://docs.openwrt.melmac.net/https-dns-proxy/](https://docs.openwrt.melmac.net/https-dns-proxy/).
stintel/openwrt-packages
net/https-dns-proxy/files/README.md
Markdown
gpl-2.0
137
/* Unix SMB/CIFS implementation. a composite API for finding a DC and its name Copyright (C) Volker Lendecke 2005 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "include/includes.h" #include <tevent.h> #include "lib/messaging/irpc.h" #include "librpc/gen_ndr/ndr_irpc_c.h" #include "libcli/composite/composite.h" #include "libcli/libcli.h" #include "libcli/resolve/resolve.h" #include "lib/util/tevent_ntstatus.h" #include "libcli/finddc.h" struct finddcs_nbt_state { struct tevent_context *ev; struct tevent_req *req; struct imessaging_context *msg_ctx; const char *my_netbios_name; const char *domain_name; struct dom_sid *domain_sid; struct nbtd_getdcname r; struct nbt_name_status node_status; int num_dcs; struct nbt_dc_name *dcs; uint16_t nbt_port; }; static void finddcs_nbt_name_resolved(struct composite_context *ctx); static void finddcs_nbt_getdc_replied(struct tevent_req *subreq); static void fallback_node_status(struct finddcs_nbt_state *state); static void fallback_node_status_replied(struct nbt_name_request *name_req); /* * Setup and send off the a normal name resolution for the target name. * * The domain_sid parameter is optional, and is used in the subsequent getdc request. * * This will try a GetDC request, but this may not work. It will try * a node status as a fallback, then return no name (but still include * the IP) */ struct tevent_req *finddcs_nbt_send(TALLOC_CTX *mem_ctx, const char *my_netbios_name, uint16_t nbt_port, const char *domain_name, int name_type, struct dom_sid *domain_sid, struct resolve_context *resolve_ctx, struct tevent_context *event_ctx, struct imessaging_context *msg_ctx) { struct finddcs_nbt_state *state; struct nbt_name name; struct tevent_req *req; struct composite_context *creq; req = tevent_req_create(mem_ctx, &state, struct finddcs_nbt_state); if (req == NULL) { return NULL; } state->req = req; state->ev = event_ctx; state->nbt_port = nbt_port; state->my_netbios_name = talloc_strdup(state, my_netbios_name); if (tevent_req_nomem(state->my_netbios_name, req)) { return tevent_req_post(req, event_ctx); } state->domain_name = talloc_strdup(state, domain_name); if (tevent_req_nomem(state->domain_name, req)) { return tevent_req_post(req, event_ctx); } if (domain_sid) { state->domain_sid = dom_sid_dup(state, domain_sid); if (tevent_req_nomem(state->domain_sid, req)) { return tevent_req_post(req, event_ctx); } } else { state->domain_sid = NULL; } state->msg_ctx = msg_ctx; make_nbt_name(&name, state->domain_name, name_type); creq = resolve_name_send(resolve_ctx, state, &name, event_ctx); if (tevent_req_nomem(creq, req)) { return tevent_req_post(req, event_ctx); } creq->async.fn = finddcs_nbt_name_resolved; creq->async.private_data = state; return req; } /* Having got an name query answer, fire off a GetDC request, so we * can find the target's all-important name. (Kerberos and some * netlogon operations are quite picky about names) * * The name is a courtesy, if we don't find it, don't completely fail. * * However, if the nbt server is down, fall back to a node status * request */ static void finddcs_nbt_name_resolved(struct composite_context *ctx) { struct finddcs_nbt_state *state = talloc_get_type(ctx->async.private_data, struct finddcs_nbt_state); struct tevent_req *subreq; struct dcerpc_binding_handle *irpc_handle; const char *address; NTSTATUS status; status = resolve_name_recv(ctx, state, &address); if (tevent_req_nterror(state->req, status)) { return; } /* TODO: This should try and find all the DCs, and give the * caller them in the order they responded */ state->num_dcs = 1; state->dcs = talloc_array(state, struct nbt_dc_name, state->num_dcs); if (tevent_req_nomem(state->dcs, state->req)) { return; } state->dcs[0].address = talloc_steal(state->dcs, address); /* Try and find the nbt server. Fallback to a node status * request if we can't make this happen The nbt server just * might not be running, or we may not have a messaging * context (not root etc) */ if (!state->msg_ctx) { fallback_node_status(state); return; } irpc_handle = irpc_binding_handle_by_name(state, state->msg_ctx, "nbt_server", &ndr_table_irpc); if (irpc_handle == NULL) { fallback_node_status(state); return; } state->r.in.domainname = state->domain_name; state->r.in.ip_address = state->dcs[0].address; state->r.in.my_computername = state->my_netbios_name; state->r.in.my_accountname = talloc_asprintf(state, "%s$", state->my_netbios_name); if (tevent_req_nomem(state->r.in.my_accountname, state->req)) { return; } state->r.in.account_control = ACB_WSTRUST; state->r.in.domain_sid = state->domain_sid; if (state->r.in.domain_sid == NULL) { state->r.in.domain_sid = talloc_zero(state, struct dom_sid); } subreq = dcerpc_nbtd_getdcname_r_send(state, state->ev, irpc_handle, &state->r); if (tevent_req_nomem(subreq, state->req)) { return; } tevent_req_set_callback(subreq, finddcs_nbt_getdc_replied, state); } /* Called when the GetDC request returns */ static void finddcs_nbt_getdc_replied(struct tevent_req *subreq) { struct finddcs_nbt_state *state = tevent_req_callback_data(subreq, struct finddcs_nbt_state); NTSTATUS status; status = dcerpc_nbtd_getdcname_r_recv(subreq, state); TALLOC_FREE(subreq); if (!NT_STATUS_IS_OK(status)) { fallback_node_status(state); return; } state->dcs[0].name = talloc_steal(state->dcs, state->r.out.dcname); tevent_req_done(state->req); } /* The GetDC request might not be available (such as occours when the * NBT server is down). Fallback to a node status. It is the best * hope we have... */ static void fallback_node_status(struct finddcs_nbt_state *state) { struct nbt_name_socket *nbtsock; struct nbt_name_request *name_req; state->node_status.in.name.name = "*"; state->node_status.in.name.type = NBT_NAME_CLIENT; state->node_status.in.name.scope = NULL; state->node_status.in.dest_addr = state->dcs[0].address; state->node_status.in.dest_port = state->nbt_port; state->node_status.in.timeout = 1; state->node_status.in.retries = 2; nbtsock = nbt_name_socket_init(state, state->ev); if (tevent_req_nomem(nbtsock, state->req)) { return; } name_req = nbt_name_status_send(nbtsock, &state->node_status); if (tevent_req_nomem(name_req, state->req)) { return; } name_req->async.fn = fallback_node_status_replied; name_req->async.private_data = state; } /* We have a node status reply (or perhaps a timeout) */ static void fallback_node_status_replied(struct nbt_name_request *name_req) { int i; struct finddcs_nbt_state *state = talloc_get_type(name_req->async.private_data, struct finddcs_nbt_state); NTSTATUS status; status = nbt_name_status_recv(name_req, state, &state->node_status); if (tevent_req_nterror(state->req, status)) { return; } for (i=0; i < state->node_status.out.status.num_names; i++) { int j; if (state->node_status.out.status.names[i].type == NBT_NAME_SERVER) { char *name = talloc_strndup(state->dcs, state->node_status.out.status.names[0].name, 15); /* Strip space padding */ if (name) { j = MIN(strlen(name), 15); for (; j > 0 && name[j - 1] == ' '; j--) { name[j - 1] = '\0'; } } state->dcs[0].name = name; tevent_req_done(state->req); return; } } tevent_req_nterror(state->req, NT_STATUS_NO_LOGON_SERVERS); } NTSTATUS finddcs_nbt_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx, int *num_dcs, struct nbt_dc_name **dcs) { struct finddcs_nbt_state *state = tevent_req_data(req, struct finddcs_nbt_state); bool ok; NTSTATUS status; ok = tevent_req_poll(req, state->ev); if (!ok) { talloc_free(req); return NT_STATUS_INTERNAL_ERROR; } status = tevent_req_simple_recv_ntstatus(req); if (NT_STATUS_IS_OK(status)) { *num_dcs = state->num_dcs; *dcs = talloc_steal(mem_ctx, state->dcs); } return status; } NTSTATUS finddcs_nbt(TALLOC_CTX *mem_ctx, const char *my_netbios_name, uint16_t nbt_port, const char *domain_name, int name_type, struct dom_sid *domain_sid, struct resolve_context *resolve_ctx, struct tevent_context *event_ctx, struct imessaging_context *msg_ctx, int *num_dcs, struct nbt_dc_name **dcs) { NTSTATUS status; struct tevent_req *req = finddcs_nbt_send(mem_ctx, my_netbios_name, nbt_port, domain_name, name_type, domain_sid, resolve_ctx, event_ctx, msg_ctx); status = finddcs_nbt_recv(req, mem_ctx, num_dcs, dcs); talloc_free(req); return status; }
sYnfo/samba-1
source4/libcli/finddcs_nbt.c
C
gpl-3.0
9,323
package client import ( "encoding/json" "fmt" "net/url" "text/tabwriter" "time" "github.com/docker/docker/api/types" Cli "github.com/docker/docker/cli" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/units" "github.com/docker/docker/utils" ) // CmdImages lists the images in a specified repository, or all top-level images if no repository is specified. // // Usage: docker images [OPTIONS] [REPOSITORY] func (cli *DockerCli) CmdImages(args ...string) error { cmd := Cli.Subcmd("images", []string{"[REPOSITORY[:TAG]]"}, Cli.DockerCommands["images"].Description, true) quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs") all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (default hides intermediate images)") noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") showDigests := cmd.Bool([]string{"-digests"}, false, "Show digests") flFilter := opts.NewListOpts(nil) cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") cmd.Require(flag.Max, 1) cmd.ParseFlags(args, true) // Consolidate all filter flags, and sanity check them early. // They'll get process in the daemon/server. imageFilterArgs := filters.Args{} for _, f := range flFilter.GetAll() { var err error imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs) if err != nil { return err } } matchName := cmd.Arg(0) v := url.Values{} if len(imageFilterArgs) > 0 { filterJSON, err := filters.ToParam(imageFilterArgs) if err != nil { return err } v.Set("filters", filterJSON) } if cmd.NArg() == 1 { // FIXME rename this parameter, to not be confused with the filters flag v.Set("filter", matchName) } if *all { v.Set("all", "1") } serverResp, err := cli.call("GET", "/images/json?"+v.Encode(), nil, nil) if err != nil { return err } defer serverResp.body.Close() images := []types.Image{} if err := json.NewDecoder(serverResp.body).Decode(&images); err != nil { return err } w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) if !*quiet { if *showDigests { fmt.Fprintln(w, "REPOSITORY\tTAG\tDIGEST\tIMAGE ID\tCREATED\tVIRTUAL SIZE") } else { fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE") } } for _, image := range images { ID := image.ID if !*noTrunc { ID = stringid.TruncateID(ID) } repoTags := image.RepoTags repoDigests := image.RepoDigests if len(repoTags) == 1 && repoTags[0] == "<none>:<none>" && len(repoDigests) == 1 && repoDigests[0] == "<none>@<none>" { // dangling image - clear out either repoTags or repoDigsts so we only show it once below repoDigests = []string{} } // combine the tags and digests lists tagsAndDigests := append(repoTags, repoDigests...) for _, repoAndRef := range tagsAndDigests { repo, ref := parsers.ParseRepositoryTag(repoAndRef) // default tag and digest to none - if there's a value, it'll be set below tag := "<none>" digest := "<none>" if utils.DigestReference(ref) { digest = ref } else { tag = ref } if !*quiet { if *showDigests { fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", repo, tag, digest, ID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(int64(image.Created), 0))), units.HumanSize(float64(image.VirtualSize))) } else { fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", repo, tag, ID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(int64(image.Created), 0))), units.HumanSize(float64(image.VirtualSize))) } } else { fmt.Fprintln(w, ID) } } } if !*quiet { w.Flush() } return nil }
nalind/graphc
vendor/src/github.com/docker/docker/api/client/images.go
GO
apache-2.0
3,816
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests of the tfdbg Stepper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.client import session from tensorflow.python.debug.lib.stepper import NodeStepper from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.training import gradient_descent class StepperTest(test_util.TensorFlowTestCase): def setUp(self): self.a = variables.Variable(2.0, name="a") self.b = variables.Variable(3.0, name="b") self.c = math_ops.multiply(self.a, self.b, name="c") # Should be 6.0. self.d = math_ops.multiply(self.a, self.a, name="d") # Should be 4.0. self.e = math_ops.multiply(self.d, self.c, name="e") # Should be 24.0. self.f_y = constant_op.constant(0.30, name="f_y") self.f = math_ops.div(self.b, self.f_y, name="f") # Should be 10.0. # The there nodes x, y and z form a graph with "cross-links" in. I.e., x # and y are both direct inputs to z, but x is also a direct input to y. self.x = variables.Variable(2.0, name="x") # Should be 2.0 self.y = math_ops.negative(self.x, name="y") # Should be -2.0. self.z = math_ops.multiply(self.x, self.y, name="z") # Should be -4.0. self.sess = session.Session() self.sess.run(variables.global_variables_initializer()) def tearDown(self): ops.reset_default_graph() def testContToFetchNotInTransitiveClosureShouldError(self): with NodeStepper(self.sess, "e:0") as stepper: sorted_nodes = stepper.sorted_nodes() self.assertEqual(7, len(sorted_nodes)) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("a/read")) self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("b/read")) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("c")) self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("c")) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("d")) self.assertLess(sorted_nodes.index("d"), sorted_nodes.index("e")) self.assertLess(sorted_nodes.index("c"), sorted_nodes.index("e")) self.assertSetEqual( {"e:0", "d:0", "c:0", "a/read:0", "b/read:0", "b:0", "a:0"}, set(stepper.closure_elements())) with self.assertRaisesRegexp( ValueError, "Target \"f:0\" is not in the transitive closure for the fetch of " "the stepper"): stepper.cont("f:0") def testContToNodeNameShouldReturnTensorValue(self): with NodeStepper(self.sess, "e:0") as stepper: self.assertAllClose(6.0, stepper.cont("c")) def testUsingNamesNotUsingIntermediateTensors(self): with NodeStepper(self.sess, "e:0") as stepper: # The first cont() call should have used no feeds. result = stepper.cont("c:0") self.assertAllClose(6.0, result) self.assertItemsEqual(["a/read:0", "b/read:0"], stepper.intermediate_tensor_names()) self.assertAllClose(2.0, stepper.get_tensor_value("a/read:0")) self.assertAllClose(3.0, stepper.get_tensor_value("b/read:0")) self.assertEqual({}, stepper.last_feed_types()) # The second cont() call should have used the tensor handle from the # previous cont() call. result = stepper.cont("e:0") self.assertAllClose(24.0, result) self.assertItemsEqual(["a/read:0", "b/read:0", "d:0"], stepper.intermediate_tensor_names()) self.assertAllClose(2.0, stepper.get_tensor_value("a/read:0")) self.assertAllClose(3.0, stepper.get_tensor_value("b/read:0")) self.assertAllClose(4.0, stepper.get_tensor_value("d:0")) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_HANDLE, "a/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) def testUsingNodesNotUsingIntermediateTensors(self): with NodeStepper(self.sess, self.e) as stepper: # There should be no handles before any cont() calls. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(set(), stepper.handle_node_names()) # Before the cont() call, the stepper should not have access to the value # of c:0. with self.assertRaisesRegexp( ValueError, "This stepper instance does not have access to the value of tensor " "\"c:0\""): stepper.get_tensor_value("c:0") # Using the node/tensor itself, instead of the name str, should work on # cont(). result = stepper.cont(self.c) self.assertItemsEqual(["a/read:0", "b/read:0"], stepper.intermediate_tensor_names()) self.assertAllClose(6.0, result) self.assertEqual({}, stepper.last_feed_types()) self.assertEqual(["c:0"], stepper.handle_names()) self.assertEqual({"c"}, stepper.handle_node_names()) # After the cont() call, the stepper should have access to the value of # c:0 via a tensor handle. self.assertAllClose(6.0, stepper.get_tensor_value("c:0")) result = stepper.cont(self.e) self.assertAllClose(24.0, result) self.assertItemsEqual(["a/read:0", "b/read:0", "d:0"], stepper.intermediate_tensor_names()) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_HANDLE, "a/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) def testContToTensorWithIntermediateDumpShouldUseDump(self): with NodeStepper(self.sess, ["e:0", "f:0"]) as stepper: stepper.cont("c:0") self.assertItemsEqual(["a/read:0", "b/read:0"], stepper.intermediate_tensor_names()) self.assertAllClose(2.0, stepper.get_tensor_value("a/read:0")) self.assertAllClose(3.0, stepper.get_tensor_value("b/read:0")) self.assertAllClose(2.0, stepper.cont("a/read:0")) self.assertEqual({ "a/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE }, stepper.last_feed_types()) self.assertAllClose(10.0, stepper.cont("f:0")) self.assertEqual({ "b/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE }, stepper.last_feed_types()) def testDisablingUseDumpedIntermediatesWorks(self): with NodeStepper(self.sess, ["e:0", "f:0"]) as stepper: stepper.cont("c:0") self.assertItemsEqual(["a/read:0", "b/read:0"], stepper.intermediate_tensor_names()) self.assertAllClose(2.0, stepper.get_tensor_value("a/read:0")) self.assertAllClose(3.0, stepper.get_tensor_value("b/read:0")) self.assertAllClose(10.0, stepper.cont("f:0", use_dumped_intermediates=False)) self.assertEqual({}, stepper.last_feed_types()) def testIsFeedableShouldGiveCorrectAnswers(self): with NodeStepper(self.sess, self.e) as stepper: self.assertTrue(stepper.is_feedable("a/read:0")) self.assertTrue(stepper.is_feedable("b/read:0")) self.assertTrue(stepper.is_feedable("c:0")) self.assertTrue(stepper.is_feedable("d:0")) def testOverrideValue(self): with NodeStepper(self.sess, self.e) as stepper: result = stepper.cont(self.c) self.assertAllClose(6.0, result) self.assertEqual({}, stepper.last_feed_types()) # There should be no overrides before any cont() calls. self.assertEqual([], stepper.override_names()) # Calling cont() on c again should lead to use of the handle. result = stepper.cont(self.c) self.assertAllClose(6.0, result) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_HANDLE }, stepper.last_feed_types()) # Override c:0. stepper.override_tensor("c:0", 7.0) # After the overriding, calling get_tensor_value() on c:0 should yield the # overriding value. self.assertEqual(7.0, stepper.get_tensor_value("c:0")) # Now c:0 should have only an override value, but no cached handle, # because the handle should have been invalidated. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(set(), stepper.handle_node_names()) self.assertEqual(["c:0"], stepper.override_names()) # Run a downstream tensor after the value override. result = stepper.cont(self.e) self.assertAllClose(28.0, result) # Should reflect the overriding value. # Should use override, instead of the handle. self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE, "a/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) def testOverrideValueTwice(self): with NodeStepper(self.sess, self.e) as stepper: # Override once. stepper.override_tensor("c:0", 7.0) self.assertAllClose(28.0, stepper.cont(self.e)) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE }, stepper.last_feed_types()) self.assertEqual(["e:0"], stepper.handle_names()) self.assertSetEqual({"e"}, stepper.handle_node_names()) self.assertEqual(["c:0"], stepper.override_names()) # Calling cont(self.e) again. This time the cached tensor handle of e # should be used. self.assertEqual(28.0, stepper.cont(self.e)) self.assertEqual({ "e:0": NodeStepper.FEED_TYPE_HANDLE }, stepper.last_feed_types()) # Override c again. This should have invalidated the cache for e. stepper.override_tensor("c:0", 8.0) self.assertEqual([], stepper.handle_names()) self.assertEqual(set(), stepper.handle_node_names()) self.assertEqual(["c:0"], stepper.override_names()) self.assertAllClose(32.0, stepper.cont(self.e)) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE, "d:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) def testRemoveOverrideValue(self): with NodeStepper(self.sess, self.e) as stepper: result = stepper.cont(self.c) self.assertAllClose(6.0, result) self.assertEqual({}, stepper.last_feed_types()) # The previous cont() step should have generated a cached tensor handle. self.assertEqual(["c:0"], stepper.handle_names()) self.assertSetEqual({"c"}, stepper.handle_node_names()) # Override c:0. stepper.override_tensor("c:0", 7.0) # The overriding should have invalidated the tensor handle. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(set(), stepper.handle_node_names()) self.assertEqual(["c:0"], stepper.override_names()) result = stepper.cont(self.e) self.assertAllClose(28.0, result) # Should reflect the overriding value. self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE, "a/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) # The handle to tensor e:0 should have been cached, even though its # transitive closure contains an override. self.assertIn("e:0", stepper.handle_names()) self.assertSetEqual({"e"}, stepper.handle_node_names()) # Remove the override. stepper.remove_override("c:0") # c:0 should not be in the overrides anymore. self.assertEqual([], stepper.override_names()) # Removing the override should have invalidated the tensor handle for c. self.assertNotIn("e:0", stepper.handle_names()) self.assertNotIn("e", stepper.handle_node_names()) # Should reflect the non-overriding value. self.assertAllClose(24.0, stepper.cont(self.e)) # This time, the handle to tensor e:0 should have been cached again, even # thought its transitive closure contains an override. self.assertIn("e:0", stepper.handle_names()) self.assertIn("e", stepper.handle_node_names()) # Calling cont(self.e) again should have used the tensor handle to e:0. self.assertAllClose(24.0, stepper.cont(self.e)) self.assertEqual({ "e:0": NodeStepper.FEED_TYPE_HANDLE, }, stepper.last_feed_types()) def testOverrideAndContToSameTensor(self): with NodeStepper(self.sess, self.e) as stepper: result = stepper.cont(self.c) self.assertAllClose(6.0, result) self.assertEqual({}, stepper.last_feed_types()) self.assertEqual(["c:0"], stepper.handle_names()) self.assertSetEqual({"c"}, stepper.handle_node_names()) self.assertAllClose(6.0, stepper.cont(self.c)) # The last cont() call should use the tensor handle directly. self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_HANDLE }, stepper.last_feed_types()) # Override c:0. stepper.override_tensor("c:0", 7.0) # As a result of the override, the tensor handle should have been # invalidated. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(set(), stepper.handle_node_names()) result = stepper.cont(self.c) self.assertAllClose(7.0, result) self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE }, stepper.last_feed_types()) def testFinalizeWithPreviousOverrides(self): with NodeStepper(self.sess, self.e) as stepper: stepper.override_tensor("a/read:0", 20.0) self.assertEqual(["a/read:0"], stepper.override_names()) # Should reflect the overriding value. self.assertAllClose(24000.0, stepper.cont("e:0")) self.assertEqual({ "a/read:0": NodeStepper.FEED_TYPE_OVERRIDE }, stepper.last_feed_types()) # Finalize call should have ignored the overriding value. self.assertAllClose(24.0, stepper.finalize()) def testRemoveNonexistentOverrideValue(self): with NodeStepper(self.sess, self.e) as stepper: self.assertEqual([], stepper.override_names()) with self.assertRaisesRegexp( ValueError, "No overriding value exists for tensor \"c:0\""): stepper.remove_override("c:0") def testAttemptToOverrideInvalidTensor(self): stepper = NodeStepper(self.sess, self.e) with self.assertRaisesRegexp(ValueError, "Cannot override tensor \"f:0\""): stepper.override_tensor("f:0", 42.0) def testInvalidOverrideArgumentType(self): with NodeStepper(self.sess, self.e) as stepper: with self.assertRaisesRegexp(TypeError, "Expected type str; got type"): stepper.override_tensor(self.a, 42.0) def testTransitiveClosureWithCrossLinksShouldHaveCorrectOrder(self): with NodeStepper(self.sess, "z:0") as stepper: sorted_nodes = stepper.sorted_nodes() self.assertEqual(4, len(sorted_nodes)) self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("x/read")) self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("y")) self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("z")) self.assertLess(sorted_nodes.index("y"), sorted_nodes.index("z")) def testNodeStepperConstructorShouldAllowListOrTupleOrDictOfFetches(self): for i in range(6): if i == 0: fetches = [self.e, [self.f, self.z]] elif i == 1: fetches = (self.e, (self.f, self.z)) elif i == 2: fetches = {"e": self.e, "fz": {"f": self.f, "z": self.z}} elif i == 3: fetches = ["e:0", ["f:0", "z:0"]] elif i == 4: fetches = ("e:0", ("f:0", "z:0")) elif i == 5: fetches = {"e": "e:0", "fz": {"f": "f:0", "z": "z:0"}} with NodeStepper(self.sess, fetches) as stepper: sorted_nodes = stepper.sorted_nodes() self.assertEqual(13, len(sorted_nodes)) # Check the topological order of the sorted nodes. self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("x/read")) self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("y")) self.assertLess(sorted_nodes.index("x"), sorted_nodes.index("z")) self.assertLess(sorted_nodes.index("y"), sorted_nodes.index("z")) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("a/read")) self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("b/read")) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("c")) self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("c")) self.assertLess(sorted_nodes.index("a"), sorted_nodes.index("d")) self.assertLess(sorted_nodes.index("d"), sorted_nodes.index("e")) self.assertLess(sorted_nodes.index("c"), sorted_nodes.index("e")) self.assertLess(sorted_nodes.index("b"), sorted_nodes.index("f")) self.assertLess(sorted_nodes.index("f_y"), sorted_nodes.index("f")) closure_elements = stepper.closure_elements() self.assertIn("x/read:0", closure_elements) self.assertIn("e:0", closure_elements) self.assertIn("f:0", closure_elements) self.assertEqual([0], stepper.output_slots_in_closure("x/read")) self.assertEqual([0], stepper.output_slots_in_closure("e")) self.assertEqual([0], stepper.output_slots_in_closure("f")) result = stepper.finalize() if i == 0 or i == 1 or i == 3 or i == 4: self.assertAllClose(24.0, result[0]) self.assertAllClose(10.0, result[1][0]) self.assertAllClose(-4.0, result[1][1]) elif i == 2 or i == 5: self.assertAllClose(24.0, result["e"]) self.assertAllClose(10.0, result["fz"]["f"]) self.assertAllClose(-4.0, result["fz"]["z"]) class StepperTestWithPlaceHolders(test_util.TensorFlowTestCase): def setUp(self): self.ph0 = array_ops.placeholder(dtypes.float32, shape=(2, 2), name="ph0") self.ph1 = array_ops.placeholder(dtypes.float32, shape=(2, 1), name="ph1") self.x = math_ops.matmul(self.ph0, self.ph1, name="x") self.y = math_ops.add(self.x, self.ph1, name="y") self.sess = session.Session() def tearDown(self): ops.reset_default_graph() def testGetTensorValueWorksOnPlaceholder(self): with NodeStepper( self.sess, self.y, feed_dict={ self.ph0: [[1.0, 2.0], [-3.0, 5.0]], self.ph1: [[-1.0], [0.5]] }) as stepper: self.assertAllClose([[1.0, 2.0], [-3.0, 5.0]], stepper.get_tensor_value("ph0")) self.assertAllClose([[1.0, 2.0], [-3.0, 5.0]], stepper.get_tensor_value("ph0:0")) with self.assertRaisesRegexp( KeyError, r"The name 'ph0:1' refers to a Tensor which does not exist"): stepper.get_tensor_value("ph0:1") def testIsPlaceholdersShouldGiveCorrectAnswers(self): with NodeStepper(self.sess, self.y) as stepper: self.assertTrue(stepper.is_placeholder(self.ph0.name)) self.assertTrue(stepper.is_placeholder(self.ph1.name)) self.assertFalse(stepper.is_placeholder(self.x.name)) self.assertFalse(stepper.is_placeholder(self.y.name)) with self.assertRaisesRegexp(ValueError, "A is not in the transitive closure"): self.assertFalse(stepper.is_placeholder("A")) def testPlaceholdersShouldGiveCorrectAnswers(self): with NodeStepper(self.sess, self.y) as stepper: self.assertSetEqual({"ph0", "ph1"}, set(stepper.placeholders())) def testContWithPlaceholders(self): with NodeStepper( self.sess, self.y, feed_dict={ self.ph0: [[1.0, 2.0], [-3.0, 5.0]], self.ph1: [[-1.0], [0.5]] }) as stepper: self.assertEqual(4, len(stepper.sorted_nodes())) self.assertSetEqual({"ph0:0", "ph1:0", "x:0", "y:0"}, set(stepper.closure_elements())) result = stepper.cont(self.x) self.assertAllClose([[0.0], [5.5]], result) self.assertEqual({ "ph0:0": NodeStepper.FEED_TYPE_CLIENT, "ph1:0": NodeStepper.FEED_TYPE_CLIENT, }, stepper.last_feed_types()) self.assertEqual(["x:0"], stepper.handle_names()) self.assertSetEqual({"x"}, stepper.handle_node_names()) result = stepper.cont(self.y) self.assertAllClose([[-1.0], [6.0]], result) self.assertEqual({ "x:0": NodeStepper.FEED_TYPE_HANDLE, "ph1:0": NodeStepper.FEED_TYPE_CLIENT, }, stepper.last_feed_types()) def testAttemptToContToPlaceholderWithTensorFeedKeysShouldWork(self): """Continuing to a placeholder should be allowed, using client feed.""" ph0_feed = [[1.0, 2.0], [-3.0, 5.0]] ph1_feed = [[-1.0], [0.5]] with NodeStepper( self.sess, self.y, feed_dict={ self.ph0: ph0_feed, self.ph1: ph1_feed, }) as stepper: self.assertAllClose(ph0_feed, stepper.cont(self.ph0)) self.assertEqual({ self.ph0.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) self.assertAllClose(ph1_feed, stepper.cont(self.ph1)) self.assertEqual({ self.ph1.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) ph0_node = self.sess.graph.as_graph_element("ph0") self.assertAllClose(ph0_feed, stepper.cont(ph0_node)) self.assertEqual({ self.ph0.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) self.assertAllClose([[-1.0], [6.0]], stepper.finalize()) def testAttemptToContToPlaceholderWithTensorNameFeedKeysShouldWork(self): ph0_feed = [[1.0, 2.0], [-3.0, 5.0]] ph1_feed = [[-1.0], [0.5]] with NodeStepper( self.sess, self.y, feed_dict={ self.ph0.name: ph0_feed, self.ph1.name: ph1_feed, }) as stepper: self.assertAllClose(ph0_feed, stepper.cont(self.ph0)) self.assertEqual({ self.ph0.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) self.assertAllClose(ph1_feed, stepper.cont(self.ph1)) self.assertEqual({ self.ph1.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) ph0_node = self.sess.graph.as_graph_element("ph0") self.assertAllClose(ph0_feed, stepper.cont(ph0_node)) self.assertEqual({ self.ph0.name: NodeStepper.FEED_TYPE_CLIENT }, stepper.last_feed_types()) self.assertAllClose([[-1.0], [6.0]], stepper.finalize()) class StepperAssignAddTest(test_util.TensorFlowTestCase): def setUp(self): self.v = variables.Variable(10.0, name="v") self.p = math_ops.add(self.v, self.v, name="p") self.q = math_ops.multiply(self.p, self.p, name="q") self.delta = constant_op.constant(2.0, name="delta") self.v_add = state_ops.assign_add(self.v, self.delta, name="v_add") self.v_add_plus_one = math_ops.add(self.v_add, 1.0, name="v_add_plus_one") self.sess = session.Session() self.sess.run(self.v.initializer) def tearDown(self): ops.reset_default_graph() def testLastUpdatedVariablesReturnsNoneBeforeAnyContCalls(self): with NodeStepper(self.sess, [self.q, self.v_add]) as stepper: self.assertIsNone(stepper.last_updated()) def testContToUpdateInvalidatesDumpedIntermedates(self): with NodeStepper(self.sess, [self.q, self.v_add]) as stepper: self.assertAllClose(400.0, stepper.cont("q:0")) self.assertItemsEqual(["v/read:0", "p:0"], stepper.intermediate_tensor_names()) self.assertAllClose(10.0, stepper.get_tensor_value("v/read:0")) self.assertAllClose(20.0, stepper.get_tensor_value("p:0")) self.assertAllClose( 12.0, stepper.cont( self.v_add, invalidate_from_updated_variables=True)) self.assertAllClose(12.0, self.sess.run(self.v)) self.assertSetEqual({self.v.name}, stepper.last_updated()) self.assertItemsEqual(["v:0"], stepper.dirty_variables()) # Updating the value of v by calling v_add should have invalidated the # dumped intermediate tensors for v/read:0 and p:0. self.assertItemsEqual(["delta:0"], stepper.intermediate_tensor_names()) with self.assertRaisesRegexp( ValueError, r"This stepper instance does not have access to the value of tensor " r"\"p:0\""): stepper.get_tensor_value("p:0") # The next cont to q should not have used any dumped intermediate tensors # and its result should reflect the updated value. self.assertAllClose(576.0, stepper.cont("q:0")) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual({}, stepper.last_feed_types()) def testOverridingUpstreamTensorInvalidatesDumpedIntermediates(self): with NodeStepper(self.sess, self.q) as stepper: self.assertAllClose(400.0, stepper.cont("q:0")) self.assertItemsEqual(["v/read:0", "p:0"], stepper.intermediate_tensor_names()) self.assertAllClose(10.0, stepper.get_tensor_value("v/read:0")) self.assertAllClose(20.0, stepper.get_tensor_value("p:0")) stepper.override_tensor("v/read:0", 11.0) self.assertItemsEqual(["v/read:0"], stepper.override_names()) # Overriding the upstream v/read:0 should have invalidated the dumped # intermediate tensor for the downstream p:0. self.assertItemsEqual([], stepper.intermediate_tensor_names()) # The next cont to q should not have used any dumped intermediate tensors # and its result should reflect the overriding value. self.assertAllClose(484.0, stepper.cont("q:0")) self.assertEqual({ "v/read:0": NodeStepper.FEED_TYPE_OVERRIDE }, stepper.last_feed_types()) def testRemovingOverrideToUpstreamTensorInvalidatesDumpedIntermediates(self): with NodeStepper(self.sess, self.q) as stepper: stepper.override_tensor("v/read:0", 9.0) self.assertItemsEqual(["v/read:0"], stepper.override_names()) self.assertAllClose(324.0, stepper.cont(self.q)) self.assertItemsEqual(["p:0"], stepper.intermediate_tensor_names()) stepper.remove_override("v/read:0") self.assertItemsEqual([], stepper.override_names()) # Removing the pre-existing override to v/read:0 should have invalidated # the dumped intermediate tensor. self.assertItemsEqual([], stepper.intermediate_tensor_names()) def testRepeatedCallsToAssignAddDoesNotUpdateVariableAgain(self): with NodeStepper(self.sess, self.v_add) as stepper: stepper.cont(self.v_add) self.assertSetEqual({self.v.name}, stepper.last_updated()) self.assertAllClose(12.0, stepper.cont(self.v)) stepper.cont(self.v_add) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual({"v_add:0": NodeStepper.FEED_TYPE_HANDLE}, stepper.last_feed_types()) self.assertAllClose(12.0, stepper.cont(self.v)) def testRepeatedCallsToAssignAddDownStreamDoesNotUpdateVariableAgain(self): with NodeStepper(self.sess, self.v_add_plus_one) as stepper: stepper.cont(self.v_add_plus_one) self.assertSetEqual({self.v.name}, stepper.last_updated()) self.assertAllClose(12.0, stepper.cont(self.v)) stepper.cont(self.v_add_plus_one) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual({"v_add_plus_one:0": NodeStepper.FEED_TYPE_HANDLE}, stepper.last_feed_types()) self.assertAllClose(12.0, stepper.cont(self.v)) class StepperBackwardRunTest(test_util.TensorFlowTestCase): def setUp(self): """Test setup. Structure of the forward graph: f | | ----- ----- | | d e | | | | --- --------- --- | | | a b c Construct a backward graph using the GradientDescentOptimizer. """ self.a = variables.Variable(1.0, name="a") self.b = variables.Variable(2.0, name="b") self.c = variables.Variable(4.0, name="c") self.d = math_ops.multiply(self.a, self.b, name="d") self.e = math_ops.multiply(self.b, self.c, name="e") self.f = math_ops.multiply(self.d, self.e, name="f") # Gradient descent optimizer that minimizes g. gradient_descent.GradientDescentOptimizer(0.01).minimize( self.f, name="optim") self.sess = session.Session() self.sess.run(variables.global_variables_initializer()) def tearDown(self): ops.reset_default_graph() def testContToUpdateA(self): with NodeStepper(self.sess, "optim") as stepper: result = stepper.cont("a:0") self.assertAllClose(1.0, result) self.assertEqual({}, stepper.last_feed_types()) result = stepper.cont("optim/learning_rate:0") self.assertAllClose(0.01, result) self.assertEqual({}, stepper.last_feed_types()) # Before any cont calls on ApplyGradientDescent, there should be no # "dirty" variables. self.assertEqual(set(), stepper.dirty_variables()) # First, all the two control inputs to optim. result = stepper.cont("optim/update_a/ApplyGradientDescent", invalidate_from_updated_variables=True) # Now variable a should have been marked as dirty due to the update # by optim/update_a/ApplyGradientDescent. self.assertSetEqual({"a:0"}, stepper.last_updated()) self.assertEqual({"a:0"}, stepper.dirty_variables()) self.assertIsNone(result) self.assertEqual({ "optim/learning_rate:0": NodeStepper.FEED_TYPE_HANDLE }, stepper.last_feed_types()) # Check that Variable "a" has been updated properly, but "b", "c" and "d" # remain the same. # For backprop on Variable a: # Because f = a * b * b * c, df / da = b * b * c. # 1.0 - learning_rate * b * b * c # = 1.0 - 0.01 * 2.0 * 2.0 * 4.0 = 0.84. self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(2.0, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testContToUpdateB(self): with NodeStepper(self.sess, "optim") as stepper: result = stepper.cont("optim/update_b/ApplyGradientDescent", invalidate_from_updated_variables=True) self.assertIsNone(result) self.assertSetEqual({"b:0"}, stepper.last_updated()) self.assertEqual(set(["b:0"]), stepper.dirty_variables()) # For backprop on Variable b: # Because f = a * b * b * c, df / da = 2 * a * b * c. # 2.0 - learning_rate * 2 * a * b * c # = 2.0 - 0.01 * 2 * 1.0 * 2.0 * 4.0 = 1.84 self.assertAllClose(1.0, self.sess.run(self.a)) self.assertAllClose(1.84, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testContAfterUpdateWithoutRestoringVariableValue(self): with NodeStepper(self.sess, "optim") as stepper: # First, update Variable a from 1.0 to 0.84. result = stepper.cont( "optim/update_a/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertIsNone(result) self.assertSetEqual({"a:0"}, stepper.last_updated()) self.assertEqual(set(["a:0"]), stepper.dirty_variables()) self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(2.0, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) # Tracking of the updated variables should have invalidated all # intermediate tensors downstream to a:0. self.assertNotIn("a/read:0", stepper.intermediate_tensor_names()) self.assertNotIn("d:0", stepper.intermediate_tensor_names()) # Second, update Variable b without the default restore_variable_values. result = stepper.cont( "optim/update_b/ApplyGradientDescent", restore_variable_values=False) self.assertIsNone(result) # For the backprop on Variable b under the updated value of a: # 2.0 - learning_rate * 2 * a' * b * c # = 2.0 - 0.01 * 2 * 0.84 * 2.0 * 4.0 = 1.8656 self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(1.8656, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testContNotInvalidatingFromVariableUpdatesWorksForNextUpdate(self): with NodeStepper(self.sess, "optim") as stepper: self.assertIsNone(stepper.cont( "optim/update_a/ApplyGradientDescent", invalidate_from_updated_variables=False)) # Even though invalidate_from_updated_variables is set to False, dirty # variables should still have been tracked. self.assertSetEqual({"a:0"}, stepper.last_updated()) self.assertEqual({"a:0"}, stepper.dirty_variables()) self.assertIn("a/read:0", stepper.intermediate_tensor_names()) self.assertIn("b/read:0", stepper.intermediate_tensor_names()) self.assertIn("c/read:0", stepper.intermediate_tensor_names()) self.assertIn("d:0", stepper.intermediate_tensor_names()) self.assertIn("e:0", stepper.intermediate_tensor_names()) self.assertIn("optim/learning_rate:0", stepper.intermediate_tensor_names()) self.assertNotIn("a:0", stepper.intermediate_tensor_names()) self.assertNotIn("b:0", stepper.intermediate_tensor_names()) self.assertNotIn("c:0", stepper.intermediate_tensor_names()) self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(2.0, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) # For the backprop on Variable b, the result should reflect the original # value of Variable a, even though Variable a has actually been updated. # 2.0 - learning_rate * 2 * a * b * c # = 2.0 - 0.01 * 2 * 1.0 * 2.0 * 4.0 = 1.84 self.assertIsNone(stepper.cont( "optim/update_b/ApplyGradientDescent", invalidate_from_updated_variables=False, restore_variable_values=False)) self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(1.84, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testUpdateTwiceRestoreVariable(self): with NodeStepper(self.sess, "optim") as stepper: result = stepper.cont( "optim/update_a/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertIsNone(result) self.assertSetEqual({"a:0"}, stepper.last_updated()) self.assertEqual({"a:0"}, stepper.dirty_variables()) result = stepper.cont( "optim/update_b/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertIsNone(result) # Variables a and c should have been restored and hence no longer dirty. # Variable b should have been marked as dirty. self.assertSetEqual({"b:0"}, stepper.last_updated()) self.assertEqual({"b:0"}, stepper.dirty_variables()) # The result of the update should be identitcal to as if only update_b is # run. self.assertAllClose(1.0, self.sess.run(self.a)) self.assertAllClose(1.84, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testSelectiveHandleUsageDependingOnTransitiveCleanliness(self): """Test tensor handlers are using only during clean transitive closure. "clean" means no Variables have been updated by preceding cont() calls. """ with NodeStepper(self.sess, "optim") as stepper: # First, call cont() on the two tensors on the intermediate level: e and # f. result = stepper.cont("d:0") self.assertAllClose(2.0, result) self.assertEqual({}, stepper.last_feed_types()) self.assertItemsEqual(["a/read:0", "b/read:0"], stepper.intermediate_tensor_names()) self.assertItemsEqual(["d:0"], stepper.handle_names()) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual(set(), stepper.dirty_variables()) result = stepper.cont("e:0") self.assertAllClose(8.0, result) self.assertEqual({ "b/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE }, stepper.last_feed_types()) self.assertItemsEqual(["d:0", "e:0"], stepper.handle_names()) self.assertItemsEqual(["a/read:0", "b/read:0", "c/read:0"], stepper.intermediate_tensor_names()) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual(set(), stepper.dirty_variables()) # Now run update_a, so as to let Variable a be dirty. result = stepper.cont( "optim/update_a/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertIsNone(result) # Due to the update to the value of a:0, the dumped intermediate a/read:0 # should have been invalidated. self.assertNotIn("a/read:0", stepper.intermediate_tensor_names()) self.assertSetEqual({"a:0"}, stepper.last_updated()) self.assertEqual({"a:0"}, stepper.dirty_variables()) # Now, run update_b. result = stepper.cont( "optim/update_b/ApplyGradientDescent", restore_variable_values=True) self.assertIsNone(result) # The last cont() run should have use the handle of tensor e, but not the # handle of tensor d, because the transitive closure of e is clean, # whereas that of d is dirty due to the update to a in the previous cont() # call. last_feed_types = stepper.last_feed_types() self.assertNotIn("d:0", last_feed_types) self.assertEqual(NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, last_feed_types["b/read:0"]) self.assertEqual(NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, last_feed_types["c/read:0"]) # The result of the update_b should be identical to as if no other # update_* cont() calls have occurred before. self.assertAllClose(1.0, self.sess.run(self.a)) self.assertAllClose(1.84, self.sess.run(self.b)) self.assertAllClose(4.0, self.sess.run(self.c)) def testRestoreVariableValues(self): """Test restore_variable_values() restores the old values of variables.""" with NodeStepper(self.sess, "optim") as stepper: stepper.cont( "optim/update_b/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertAllClose(1.84, self.sess.run(self.b)) stepper.restore_variable_values() self.assertAllClose(2.0, self.sess.run(self.b)) def testFinalize(self): """Test finalize() to restore variables and run the original fetch.""" with NodeStepper(self.sess, "optim") as stepper: # Invoke update_b before calling finalize. stepper.cont( "optim/update_b/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) result = stepper.finalize() self.assertIsNone(result) # The results of the Variable updates should be the same as if no cont() # call has occurred on update_b. self.assertAllClose(0.84, self.sess.run(self.a)) self.assertAllClose(1.84, self.sess.run(self.b)) self.assertAllClose(3.96, self.sess.run(self.c)) def testOverrideThenContToUpdateThenRemoveOverrideThenUpdateAgain(self): """Test cont() to update nodes after overriding tensor values.""" with NodeStepper(self.sess, "optim") as stepper: result = stepper.cont("d:0") self.assertAllClose(2.0, result) self.assertEqual({}, stepper.last_feed_types()) self.assertSetEqual(set(), stepper.last_updated()) self.assertEqual(set(), stepper.dirty_variables()) self.assertEqual(["d:0"], stepper.handle_names()) self.assertSetEqual({"d"}, stepper.handle_node_names()) # Override the value from 1.0 to 10.0. stepper.override_tensor("a/read:0", 10.0) self.assertEqual(["a/read:0"], stepper.override_names()) result = stepper.cont( "optim/update_c/ApplyGradientDescent", invalidate_from_updated_variables=True, restore_variable_values=True) self.assertIsNone(result) # The last cont() call should have not used the tensor handle to d:0, # because the transitive closure of d:0 contains an override tensor. self.assertEqual({ "a/read:0": NodeStepper.FEED_TYPE_OVERRIDE, "b/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) # The tensor handle to d:0 should have been removed due to the dirty # transitive closure. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(set(), stepper.handle_node_names()) # For this backprop on c, the overriding value of a/read:0 should have # been used: # 4.0 - learning_rate * a * b * b # = 4.0 - 0.01 * 10.0 * 2.0 * 2.0 = 3.6. self.assertAllClose(3.6, self.sess.run(self.c)) # Now remove the overriding value of a/read:0. stepper.remove_override("a/read:0") self.assertEqual([], stepper.override_names()) # Obtain the tensor handle to d:0 again. result = stepper.cont("d:0") self.assertAllClose(2.0, result) self.assertEqual(["d:0"], stepper.handle_names()) self.assertSetEqual({"d"}, stepper.handle_node_names()) self.assertNotIn("a/read:0", stepper.last_feed_types()) # Then call update_c again, without restoring c. result = stepper.cont("optim/update_c/ApplyGradientDescent", restore_variable_values=False) self.assertIsNone(result) self.assertNotIn("a/read:0", stepper.last_feed_types()) # This time, the d:0 tensor handle should have been used, because its # transitive closure is clean. self.assertEqual({ "b/read:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, "d:0": NodeStepper.FEED_TYPE_HANDLE, "optim/learning_rate:0": NodeStepper.FEED_TYPE_DUMPED_INTERMEDIATE, }, stepper.last_feed_types()) # For this backprop on c, the overriding value of a/read:0 should have # been used: # 3.6 - learning_rate * a * b * b # = 3.6 - 0.01 * 1.0 * 2.0 * 2.0 = 3.56. self.assertAllClose(3.56, self.sess.run(self.c)) def testContToNodeWithOutputTensors(self): """cont() to an op should cache its output tensors if appropriate.""" with NodeStepper(self.sess, "optim") as stepper: # In the transitive closure of the stepper, look for an op of which the # output tensor also is in the transitive closure. # Do not assume a specific op, e.g., ""gradients/e_grad/Reshape_1", # because it may vary between builds. closure_elements = stepper.closure_elements() op_with_output_in_closure = None for element_name in closure_elements: if element_name + ":0" in closure_elements: op_with_output_in_closure = str(element_name) break self.assertEqual( [0], stepper.output_slots_in_closure(op_with_output_in_closure)) self.assertIsNotNone(op_with_output_in_closure) output_tensor = op_with_output_in_closure + ":0" # The op "gradients/?_grad/Reshape_1" is in the transitive closure of the # stepper, because it is the control input to another o. However, its # output tensor "gradients/?_grad/Reshape_1:0" is also in the transitive # closure, because it is the (non-control) input of certain ops. Calling # cont() on the op should lead to the caching of the tensor handle for # the output tensor. stepper.cont(op_with_output_in_closure) self.assertEqual([output_tensor], stepper.handle_names()) self.assertSetEqual({op_with_output_in_closure}, stepper.handle_node_names()) # Do a cont() call that uses the cached tensor of # "gradients/?_grad/Reshape_1:0". stepper.cont(output_tensor) self.assertEqual({ output_tensor: NodeStepper.FEED_TYPE_HANDLE }, stepper.last_feed_types()) if __name__ == "__main__": googletest.main()
wangyum/tensorflow
tensorflow/python/debug/lib/stepper_test.py
Python
apache-2.0
45,190
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/icon.cpp // Purpose: wxIcon class // Author: Julian Smart // Modified by: 20.11.99 (VZ): don't derive from wxBitmap any more // Created: 04/01/98 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/list.h" #include "wx/utils.h" #include "wx/app.h" #include "wx/icon.h" #include "wx/bitmap.h" #include "wx/log.h" #endif #include "wx/msw/private.h" // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- wxIMPLEMENT_DYNAMIC_CLASS(wxIcon, wxGDIObject); // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxIconRefData // ---------------------------------------------------------------------------- void wxIconRefData::Free() { if ( m_hIcon ) { ::DestroyIcon((HICON) m_hIcon); m_hIcon = 0; } } // ---------------------------------------------------------------------------- // wxIcon // ---------------------------------------------------------------------------- wxIcon::wxIcon(const char bits[], int width, int height) { wxBitmap bmp(bits, width, height); CopyFromBitmap(bmp); } wxIcon::wxIcon(const wxString& iconfile, wxBitmapType type, int desiredWidth, int desiredHeight) { LoadFile(iconfile, type, desiredWidth, desiredHeight); } wxIcon::wxIcon(const wxIconLocation& loc) { // wxICOFileHandler accepts names in the format "filename;index" wxString fullname = loc.GetFileName(); if ( loc.GetIndex() ) { fullname << wxT(';') << loc.GetIndex(); } //else: 0 is default LoadFile(fullname, wxBITMAP_TYPE_ICO); } wxIcon::~wxIcon() { } wxObjectRefData *wxIcon::CloneRefData(const wxObjectRefData *dataOrig) const { const wxIconRefData * data = static_cast<const wxIconRefData *>(dataOrig); if ( !data ) return NULL; // we don't have to copy m_hIcon because we're only called from SetHICON() // which overwrites m_hIcon anyhow currently // // and if we're called from SetWidth/Height/Depth(), it doesn't make sense // to copy it neither as the handle would be inconsistent with the new size return new wxIconRefData(*data); } void wxIcon::CopyFromBitmap(const wxBitmap& bmp) { HICON hicon = wxBitmapToHICON(bmp); if ( !hicon ) { wxLogLastError(wxT("CreateIconIndirect")); } else { SetHICON((WXHICON)hicon); SetSize(bmp.GetWidth(), bmp.GetHeight()); } } void wxIcon::CreateIconFromXpm(const char* const* data) { wxBitmap bmp(data); CopyFromBitmap(bmp); } bool wxIcon::LoadFile(const wxString& filename, wxBitmapType type, int desiredWidth, int desiredHeight) { UnRef(); wxGDIImageHandler *handler = FindHandler(type); if ( !handler ) { // load via wxBitmap which, in turn, uses wxImage allowing us to // support more formats wxBitmap bmp; if ( !bmp.LoadFile(filename, type) ) return false; CopyFromBitmap(bmp); return true; } return handler->Load(this, filename, type, desiredWidth, desiredHeight); } bool wxIcon::CreateFromHICON(WXHICON icon) { SetHICON(icon); if ( !IsOk() ) return false; SetSize(wxGetHiconSize(icon)); return true; }
adouble42/nemesis-current
wxWidgets-3.1.0/src/msw/icon.cpp
C++
bsd-2-clause
4,317
module Admin::ProductPropertiesHelper # Generates the appropriate field name for attribute_fu. Normally attribute_fu handles this but we've got a # special case where we need text_field_with_autocomplete and we have to recreate attribute_fu's naming # scheme manually. def property_fu_name(product_property, number) if product_property.new_record? "product[product_property_attributes][new][#{number}][property_name]" else "product[product_property_attributes][#{product_property.id}][property_name]" end end def property_fu_value(product_property, number) if product_property.new_record? "product[product_property_attributes][new][#{number}][value]" else "product[product_property_attributes][#{product_property.id}][value]" end end end
rafarubert/loja
vendor/spree/app/helpers/admin/product_properties_helper.rb
Ruby
bsd-3-clause
812
require 'helper' class TestPhoneNumberSG < Test::Unit::TestCase def setup @tester = Faker::PhoneNumberSG end def test_voip_number assert_match /3\d{3}\s\d{4}/, @tester.voip_number end def test_fixed_line_number assert_match /6\d{3}\s\d{4}/, @tester.fixed_line_number end def test_mobile_number assert_match /8\d{3}\s\d{4}/, @tester.mobile_number end def test_mobile_or_pager_number assert_match /9\d{3}\s\d{4}/, @tester.mobile_or_pager_number end def test_international_toll_free_number assert_match /800\s\d{3}\s\d{4}/, @tester.international_toll_free_number end def test_toll_free_number assert_match /1800\s\d{3}\s\d{4}/, @tester.toll_free_number end def test_premium_service_number assert_match /1900\s\d{3}\s\d{4}/, @tester.premium_service_number end def test_phone_number 10.times do assert_match /[6,8,9]\d{3}\s\d{4}/, @tester.phone_number end end end
samirahmed/ffaker
test/test_phone_number_sg.rb
Ruby
mit
941
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2010 Google Inc. 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 of Google Inc. 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. */ WebInspector.Breakpoint = function(id, url, sourceID, lineNumber, columnNumber, condition, enabled) { this.id = id; this.url = url; this.sourceID = sourceID; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.condition = condition; this.enabled = enabled; this.locations = []; }
arise-project/ganttmonotracker
libs/OpenWebKitSharp/WebKit.resources/inspector/Breakpoint.js
JavaScript
mit
1,947
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v6.0.1 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var context_1 = require("./context/context"); var context_2 = require("./context/context"); var TemplateService = (function () { function TemplateService() { this.templateCache = {}; this.waitingCallbacks = {}; } // returns the template if it is loaded, or null if it is not loaded // but will call the callback when it is loaded TemplateService.prototype.getTemplate = function (url, callback) { var templateFromCache = this.templateCache[url]; if (templateFromCache) { return templateFromCache; } var callbackList = this.waitingCallbacks[url]; var that = this; if (!callbackList) { // first time this was called, so need a new list for callbacks callbackList = []; this.waitingCallbacks[url] = callbackList; // and also need to do the http request var client = new XMLHttpRequest(); client.onload = function () { that.handleHttpResult(this, url); }; client.open("GET", url); client.send(); } // add this callback if (callback) { callbackList.push(callback); } // caller needs to wait for template to load, so return null return null; }; TemplateService.prototype.handleHttpResult = function (httpResult, url) { if (httpResult.status !== 200 || httpResult.response === null) { console.warn('Unable to get template error ' + httpResult.status + ' - ' + url); return; } // response success, so process it // in IE9 the response is in - responseText this.templateCache[url] = httpResult.response || httpResult.responseText; // inform all listeners that this is now in the cache var callbacks = this.waitingCallbacks[url]; for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i]; // we could pass the callback the response, however we know the client of this code // is the cell renderer, and it passes the 'cellRefresh' method in as the callback // which doesn't take any parameters. callback(); } if (this.$scope) { var that = this; setTimeout(function () { that.$scope.$apply(); }, 0); } }; __decorate([ context_2.Autowired('$scope'), __metadata('design:type', Object) ], TemplateService.prototype, "$scope", void 0); TemplateService = __decorate([ context_1.Bean('templateService'), __metadata('design:paramtypes', []) ], TemplateService); return TemplateService; })(); exports.TemplateService = TemplateService;
dlueth/cdnjs
ajax/libs/ag-grid/6.0.1/lib/templateService.js
JavaScript
mit
3,730
require 'fastlane_core/string_filters' describe WordWrap do context 'wordwrapping will return an array of strings' do let(:test_string) { 'some big long string with lots of characters i think there should be more than eighty carachters here!' } it 'will return an empty array if the length is zero' do result = test_string.wordwrap(0) expect(result).to eq([]) end it 'will return an array of strings, each being <= the length passed to wordwrap' do wrap_length = 5 result = test_string.wordwrap(wrap_length) string_lengths = result.map(&:length) expect(result).to all(be_a(String)) expect(string_lengths).to all(be <= wrap_length + 1) # The +1 is to consider spaces end end end
danielbowden/fastlane
fastlane_core/spec/wordwrap_spec.rb
Ruby
mit
747
dnl Copyright 1999, 2001 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') ASM_START() PROLOGUE(mpn_sdiv_qrnnd) mtmq 5 div 0,4,6 mfmq 9 st 9,0(3) mr 3,0 br EPILOGUE(mpn_sdiv_qrnnd)
GarethNelson/BearLang
vendor/gmp-6.1.2/mpn/power/sdiv.asm
Assembly
gpl-2.0
1,245
<!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/html; charset=utf-8" /> <title>Search &mdash; django-auth-ldap 1.0.19 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '', VERSION: '1.0.19', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </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="_static/searchtools.js"></script> <link rel="top" title="django-auth-ldap 1.0.19 documentation" href="index.html" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">django-auth-ldap 1.0.19 documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">django-auth-ldap 1.0.19 documentation</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2009, Peter Sagerson. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/desktop/core/ext-py/django-auth-ldap-1.2.0/docs/archive/versions/1.0.19/search.html
HTML
gpl-2.0
3,402
#ifndef SEC_MTD_H #define SEC_MTD_H #include <mach/sec_osal.h> /************************************************************************** * MTD INTERNAL DEFINITION **************************************************************************/ typedef struct _MtdRCtx { char *buf; ASF_FILE fd; } MtdRCtx; /************************************************************************** * MTD CONFIGURATION **************************************************************************/ #define ROM_INFO_SEARCH_LEN (0x100000) #define SECRO_SEARCH_START (0x0) #define SECRO_SEARCH_LEN (0x100000) /* mtd number */ #define MTD_PL_NUM (0x0) #define MTD_SECCFG_NUM (0x3) /* indicate the search region each time */ #define ROM_INFO_SEARCH_REGION (0x2000) #define SECRO_SEARCH_REGION (0x4000) /****************************************************************************** * EXPORT FUNCTION ******************************************************************************/ extern void sec_mtd_find_partitions(void); extern unsigned int sec_mtd_read_image(char *part_name, char *buf, unsigned int off, unsigned int sz); extern unsigned int sec_mtd_get_off(char *part_name); #endif /* SEC_MTD_H */
jmztaylor/android_kernel_amazon_ariel
drivers/misc/mediatek/masp/asf_inc/sec_mtd.h
C
gpl-2.0
1,302
/* Unix SMB/CIFS implementation. SMB parameters and setup, plus a whole lot more. Copyright (C) Jeremy Allison 2006 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 3 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, see <http://www.gnu.org/licenses/>. */ #ifndef _LOCKING_H #define _LOCKING_H /* passed to br lock code - the UNLOCK_LOCK should never be stored into the tdb and is used in calculating POSIX unlock ranges only. We differentiate between PENDING read and write locks to allow posix lock downgrades to trigger a lock re-evaluation. */ enum brl_type {READ_LOCK, WRITE_LOCK, PENDING_READ_LOCK, PENDING_WRITE_LOCK, UNLOCK_LOCK}; enum brl_flavour {WINDOWS_LOCK = 0, POSIX_LOCK = 1}; #define IS_PENDING_LOCK(type) ((type) == PENDING_READ_LOCK || (type) == PENDING_WRITE_LOCK) #include "librpc/gen_ndr/server_id.h" /* This contains elements that differentiate locks. The smbpid is a client supplied pid, and is essentially the locking context for this client */ struct lock_context { uint64_t smblctx; uint32_t tid; struct server_id pid; }; struct files_struct; #include "lib/file_id.h" struct byte_range_lock; /* Internal structure in brlock.tdb. The data in brlock records is an unsorted linear array of these records. It is unnecessary to store the count as tdb provides the size of the record */ struct lock_struct { struct lock_context context; br_off start; br_off size; uint64_t fnum; enum brl_type lock_type; enum brl_flavour lock_flav; }; /**************************************************************************** This is the structure to queue to implement blocking locks. *****************************************************************************/ struct blocking_lock_record { struct blocking_lock_record *next; struct blocking_lock_record *prev; struct files_struct *fsp; struct timeval expire_time; int lock_num; uint64_t offset; uint64_t count; uint64_t smblctx; uint64_t blocking_smblctx; /* Context that blocks us. */ enum brl_flavour lock_flav; enum brl_type lock_type; struct smb_request *req; void *blr_private; /* Implementation specific. */ }; struct smbd_lock_element { uint64_t smblctx; enum brl_type brltype; uint64_t offset; uint64_t count; }; struct share_mode_lock { struct share_mode_data *data; }; #endif /* _LOCKING_H_ */
javierag/samba
source3/include/locking.h
C
gpl-3.0
2,854
class GeometricGraph<T extends Comparable<T>> { public static <K extends Comparable<K>> GeometricGraph<K> createGraph(Point<K>... points) { return null; } } class Point<T1 extends Comparable<T1>> implements Comparable<Point<T1>> { @Override public int compareTo(Point<T1> o) { return 0; } static <M extends Comparable<M>> Point<M> create(M m) { return null; } } class Graph { GeometricGraph<Integer> GEO = GeometricGraph.createGraph( Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381), Point.create(49), Point.create(73), Point.create(16), Point.create(21), Point.create(381), Point.create(49), Point.create(381) ); }
idea4bsd/idea4bsd
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/performance/PolyMethodCallArgumentPassedToVarargs.java
Java
apache-2.0
1,584
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.lang; /** * Thrown when a waiting thread is activated before the condition it was waiting * for has been satisfied. */ public class InterruptedException extends Exception { private static final long serialVersionUID = 6700697376100628473L; /** * Constructs a new {@code InterruptedException} that includes the current * stack trace. */ public InterruptedException() { } /** * Constructs a new {@code InterruptedException} with the current stack * trace and the specified detail message. * * @param detailMessage * the detail message for this exception. */ public InterruptedException(String detailMessage) { super(detailMessage); } }
JSDemos/android-sdk-20
src/java/lang/InterruptedException.java
Java
apache-2.0
1,560
/* * Copyright (c) 2016 Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA * integrated circuit in a product or a software update for such product, 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. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary or object form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * 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 HOLDER 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. * */ /**@file * * @defgroup sdk_nrf_dfu_types DFU types * @{ * @ingroup sdk_nrf_dfu */ #ifndef NRF_DFU_TYPES_H__ #define NRF_DFU_TYPES_H__ #include <stdint.h> #include <stddef.h> #include "nrf_mbr.h" #include "nrf_sdm.h" #ifdef __cplusplus extern "C" { #endif #define INIT_COMMAND_MAX_SIZE 256 /**< Maximum size of the init command stored in dfu_settings. */ /** @brief Size of a flash codepage. This value is used for calculating the size of the reserved * flash space in the bootloader region. It is checked against NRF_UICR->CODEPAGESIZE * at run time to ensure that the region is correct. */ #if defined(NRF51) #define CODE_PAGE_SIZE (PAGE_SIZE_IN_WORDS * sizeof(uint32_t)) #elif defined(NRF52) || defined(NRF52840_XXAA) #define CODE_PAGE_SIZE (MBR_PAGE_SIZE_IN_WORDS * sizeof(uint32_t)) #else #error "Architecture not set." #endif /** @brief Maximum size of a data object.*/ #if defined( NRF51 ) #define DATA_OBJECT_MAX_SIZE (CODE_PAGE_SIZE * 4) #elif defined( NRF52_SERIES ) || defined ( __SDK_DOXYGEN__ ) #define DATA_OBJECT_MAX_SIZE (CODE_PAGE_SIZE) #else #error "Architecture not set." #endif /** @brief Page location of the bootloader settings address. */ #if defined ( NRF51 ) #define BOOTLOADER_SETTINGS_ADDRESS (0x0003FC00UL) #elif defined( NRF52832_XXAA ) #define BOOTLOADER_SETTINGS_ADDRESS (0x0007F000UL) #elif defined( NRF52840_XXAA ) #define BOOTLOADER_SETTINGS_ADDRESS (0x000FF000UL) #else #error No valid target set for BOOTLOADER_SETTINGS_ADDRESS. #endif #if defined(NRF52) || defined(NRF52832) /** * @brief MBR parameters page in UICR. * * Register location in UICR where the page address of the MBR parameters page is stored (only used by the nRF52 MBR). * * @note If the value at the given location is 0xFFFFFFFF, no MBR parameters page is set. */ #define NRF_UICR_MBR_PARAMS_PAGE_ADDRESS (NRF_UICR_BASE + 0x18) /** @brief Page location of the MBR parameters page address. * */ #define NRF_MBR_PARAMS_PAGE_ADDRESS (0x0007E000UL) #endif #if defined(NRF52840_XXAA) /** * @brief MBR parameters page in UICR. * * Register location in UICR where the page address of the MBR parameters page is stored (only used by the nRF52 MBR). * * @note If the value at the given location is 0xFFFFFFFF, no MBR parameters page is set. */ #define NRF_UICR_MBR_PARAMS_PAGE_ADDRESS (NRF_UICR_BASE + 0x18) /** @brief Page location of the MBR parameters page address. * */ #define NRF_MBR_PARAMS_PAGE_ADDRESS (0x000FE000UL) #endif /** @brief Size of the flash space reserved for application data. */ #ifndef DFU_APP_DATA_RESERVED #define DFU_APP_DATA_RESERVED CODE_PAGE_SIZE * 3 #endif /** @brief Total size of the region between the SoftDevice and the bootloader. */ #define DFU_REGION_TOTAL_SIZE ((* (uint32_t *)NRF_UICR_BOOTLOADER_START_ADDRESS) - CODE_REGION_1_START) /** @brief Start address of the SoftDevice (excluding the area for the MBR). */ #define SOFTDEVICE_REGION_START MBR_SIZE /** @brief Size of the Code Region 0, found in the UICR.CLEN0 register. * * @details This value is identical to the start of Code Region 1. This value is used for * compilation safety, because the linker will fail if the application expands * into the bootloader. At run time, the bootloader uses the value found in UICR.CLEN0. */ #ifndef CODE_REGION_1_START #define CODE_REGION_1_START SD_SIZE_GET(MBR_SIZE) #endif #define NRF_DFU_CURRENT_BANK_0 0x00 #define NRF_DFU_CURRENT_BANK_1 0x01 #define NRF_DFU_BANK_LAYOUT_DUAL 0x00 #define NRF_DFU_BANK_LAYOUT_SINGLE 0x01 /** @brief DFU bank state codes. * * @details The DFU bank state indicates the content of a bank: * A valid image of a certain type or an invalid image. */ #define NRF_DFU_BANK_INVALID 0x00 /**< Invalid image. */ #define NRF_DFU_BANK_VALID_APP 0x01 /**< Valid application. */ #define NRF_DFU_BANK_VALID_SD 0xA5 /**< Valid SoftDevice. */ #define NRF_DFU_BANK_VALID_BL 0xAA /**< Valid bootloader. */ #define NRF_DFU_BANK_VALID_SD_BL 0xAC /**< Valid SoftDevice and bootloader. */ /** @brief Description of a single bank. */ #pragma pack(4) typedef struct { uint32_t image_size; /**< Size of the image in the bank. */ uint32_t image_crc; /**< CRC of the image. If set to 0, the CRC is ignored. */ uint32_t bank_code; /**< Identifier code for the bank. */ } nrf_dfu_bank_t; /**@brief DFU progress. * * Be aware of the difference between objects and firmware images. A firmware image consists of multiple objects, each of a maximum size @ref DATA_OBJECT_MAX_SIZE. */ typedef struct { uint32_t command_size; /**< The size of the current init command stored in the DFU settings. */ uint32_t command_offset; /**< The offset of the currently received init command data. The offset will increase as the init command is received. */ uint32_t command_crc; /**< The calculated CRC of the init command (calculated after the transfer is completed). */ uint32_t data_object_size; /**< The size of the last object created. Note that this size is not the size of the whole firmware image.*/ uint32_t firmware_image_crc; /**< CRC value of the current firmware (continuously calculated as data is received). */ uint32_t firmware_image_crc_last; /**< The CRC of the last executed object. */ uint32_t firmware_image_offset; /**< The offset of the current firmware image being transferred. Note that this offset is the offset in the entire firmware image and not only the current object. */ uint32_t firmware_image_offset_last;/**< The offset of the last executed object from the start of the firmware image. */ } dfu_progress_t; /**@brief DFU settings for application and bank data. */ typedef struct { uint32_t crc; /**< CRC for the stored DFU settings, not including the CRC itself. If 0xFFFFFFF, the CRC has never been calculated. */ uint32_t settings_version; /**< Version of the currect dfu settings struct layout.*/ uint32_t app_version; /**< Version of the last stored application. */ uint32_t bootloader_version; /**< Version of the last stored bootloader. */ uint32_t bank_layout; /**< Bank layout: single bank or dual bank. This value can change. */ uint32_t bank_current; /**< The bank that is currently used. */ nrf_dfu_bank_t bank_0; /**< Bank 0. */ nrf_dfu_bank_t bank_1; /**< Bank 1. */ uint32_t write_offset; /**< Write offset for the current operation. */ uint32_t sd_size; /**< SoftDevice size (if combined BL and SD). */ dfu_progress_t progress; /**< Current DFU progress. */ uint32_t enter_buttonless_dfu; uint8_t init_command[INIT_COMMAND_MAX_SIZE]; /**< Buffer for storing the init command. */ } nrf_dfu_settings_t; #pragma pack() // revert pack settings #ifdef __cplusplus } #endif #endif // NRF_DFU_TYPES_H__ /** @} */
RonEld/mbed
targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_types.h
C
apache-2.0
9,414
<html> <head> <style> progress { width: 50px; height: 50px; -webkit-appearance: none; background-color: red; /* should not be visible */ } </style> </head> <body> <progress min=0 value=30 max=100 style="-webkit-writing-mode: vertical-lr;"></progress> <progress min=0 value=30 max=100 style="-webkit-writing-mode: vertical-rl;"></progress> <progress min=0 value=30 max=100 style="-webkit-writing-mode: horizontal-tb;"></progress> <progress min=0 value=30 max=100 style="-webkit-writing-mode: horizontal-bt;"></progress> </body> </html>
hujiajie/chromium-crosswalk
third_party/WebKit/LayoutTests/fast/dom/HTMLProgressElement/progress-writing-mode.html
HTML
bsd-3-clause
543
<section id='reportsSection'> <section id='reportFilters'> <h3>{{=T("Location")}}</h3> <section class='locationFilters'> <span id='l0_report'> <label for='l0_reports'>{{=COUNTRY}}:</label> <select id='l0_reports'> <option value='' class='none'>{{=CHOOSE_COUNTRY}}</option> </select> </span> <span id='l1_report'> <label for='l1_reports'></label> <select id='l1_reports'></select> </span> <span id='l2_report'> <label for='l2_reports'></label> <select id='l2_reports'></select> </span> <span id='l3_report'> <label for='l3_reports'></label> <select id='l3_reports'></select> </span> <!-- <span id='l4_report'> <label for='l4_reports'></label> <select id='l4_reports'></select> <span id='l5_report'> <label for='l5_reports'></label> <select id='l5_reports'></select> </span>--> <span id='lx_report_throbber' class='throbber hidden'></span> </section> <h3>{{=T("Date Range")}}</h3> <section class='dateFilters'> <label for='dateFromReports'>{{=T("FROM")}}</label> <input id='dateFromReports' /> <label for='dateToReports'>{{=T("TO")}}</label> <input id='dateToReports' /> </section> <h3>{{=T("Type")}}</h3> <section class='typeFilters'> <div> <input id='indicatorsCheckbox' type='checkbox' value='indicators' checked /> <label for='indicatorsCheckbox'>{{=T("Indicators")}}</label> </div> <div> <input id='mapCheckbox' type='checkbox' value='map' checked /> <label for='mapCheckbox'>{{=T("Map")}}</label> </div> <div><input id='imagesCheckbox' type='checkbox' value='images' checked /> <label for='imagesCheckbox'>{{=T("Images")}}</label> </div> <div> <input id='reportsCheckbox' type='checkbox' value='reports' checked /> <label for='reportsCheckbox'>{{=T("Other reports")}}</label> </div> <div> <input id='demographicsCheckbox' type='checkbox' value='demographics' checked /> <label for='demographicsCheckbox'>{{=T("Demographic Data")}}</label> </div> </section> <div id='filterSubmit' class='filter'>{{=T("Filter")}}</div> </section> <section id='reportsContent'> <div id='numberReports'></div> <div id='table-container'> {{#=s3.report}} </div> <div class='approvalScreen'> <p class='thanks'>{{=T("Thank you for your approval")}}.</p> <p class='return2reports'><a href='#reports'>{{=T("Back to the main screen")}}</a></p> </div> </section> <section id='reportsHeader'> <h2>{{=T("REPORTS")}}</h2> <div id='reportsToggle'> <div class='allReports active'>{{=T("ALL REPORTS")}}</div> <div>&#124;</div> <div class='myReports'><a href="javascript:toggleReports('myReports')" title='My Reports'>{{=T("MY REPORTS")}}</a></div> </div> <div class='panelSearch'> <input id='reportTextSearch' class='rounded' type='text' name='reportsSearch' /> <div class='panelSearchSubmit'></div> </div> <div class='closePanel'></div> </section> </section>
tudorian/eden
views/vulnerability/report.html
HTML
mit
3,281
#include "../../src/gui/kernel/qplatformglcontext_qpa.h"
dulton/vlc-2.1.4.32.subproject-2013-update2
win32/include/qt4/include/QtGui/qplatformglcontext_qpa.h
C
gpl-2.0
57
/* This testcase is part of GDB, the GNU debugger. Copyright 2012-2014 Free Software Foundation, Inc. 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 3 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, see <http://www.gnu.org/licenses/>. */ class foo { public: static int bar (void) { int i = 5; bool first = true; to_the_top: /* bar:to_the_top */ while (1) { if (i == 1) { if (first) { first = false; goto to_the_top; } else goto get_out_of_here; } --i; } get_out_of_here: /* bar:get_out_of_here */ return i; } int baz (int a) { int i = a; bool first = true; to_the_top: /* baz:to_the_top */ while (1) { if (i == 1) { if (first) { first = false; goto to_the_top; } else goto get_out_of_here; } --i; } get_out_of_here: /* baz:get_out_of_here */ return i; } }; int main (void) { foo f; return f.baz (foo::bar () + 3); }
uarka/binutils
gdb/testsuite/gdb.cp/cplabel.cc
C++
gpl-2.0
1,509
/* Fujitsu MB86A16 DVB-S/DSS DC Receiver driver Copyright (C) Manu Abraham (abraham.manu@gmail.com) 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/slab.h> #include "dvb_frontend.h" #include "mb86a16.h" #include "mb86a16_priv.h" unsigned int verbose = 5; module_param(verbose, int, 0644); #define ABS(x) ((x) < 0 ? (-x) : (x)) struct mb86a16_state { struct i2c_adapter *i2c_adap; const struct mb86a16_config *config; struct dvb_frontend frontend; /* tuning parameters */ int frequency; int srate; /* Internal stuff */ int master_clk; int deci; int csel; int rsel; }; #define MB86A16_ERROR 0 #define MB86A16_NOTICE 1 #define MB86A16_INFO 2 #define MB86A16_DEBUG 3 #define dprintk(x, y, z, format, arg...) do { \ if (z) { \ if ((x > MB86A16_ERROR) && (x > y)) \ printk(KERN_ERR "%s: " format "\n", __func__, ##arg); \ else if ((x > MB86A16_NOTICE) && (x > y)) \ printk(KERN_NOTICE "%s: " format "\n", __func__, ##arg); \ else if ((x > MB86A16_INFO) && (x > y)) \ printk(KERN_INFO "%s: " format "\n", __func__, ##arg); \ else if ((x > MB86A16_DEBUG) && (x > y)) \ printk(KERN_DEBUG "%s: " format "\n", __func__, ##arg); \ } else { \ if (x > y) \ printk(format, ##arg); \ } \ } while (0) #define TRACE_IN dprintk(verbose, MB86A16_DEBUG, 1, "-->()") #define TRACE_OUT dprintk(verbose, MB86A16_DEBUG, 1, "()-->") static int mb86a16_write(struct mb86a16_state *state, u8 reg, u8 val) { int ret; u8 buf[] = { reg, val }; struct i2c_msg msg = { .addr = state->config->demod_address, .flags = 0, .buf = buf, .len = 2 }; dprintk(verbose, MB86A16_DEBUG, 1, "writing to [0x%02x],Reg[0x%02x],Data[0x%02x]", state->config->demod_address, buf[0], buf[1]); ret = i2c_transfer(state->i2c_adap, &msg, 1); return (ret != 1) ? -EREMOTEIO : 0; } static int mb86a16_read(struct mb86a16_state *state, u8 reg, u8 *val) { int ret; u8 b0[] = { reg }; u8 b1[] = { 0 }; struct i2c_msg msg[] = { { .addr = state->config->demod_address, .flags = 0, .buf = b0, .len = 1 }, { .addr = state->config->demod_address, .flags = I2C_M_RD, .buf = b1, .len = 1 } }; ret = i2c_transfer(state->i2c_adap, msg, 2); if (ret != 2) { dprintk(verbose, MB86A16_ERROR, 1, "read error(reg=0x%02x, ret=0x%i)", reg, ret); return -EREMOTEIO; } *val = b1[0]; return ret; } static int CNTM_set(struct mb86a16_state *state, unsigned char timint1, unsigned char timint2, unsigned char cnext) { unsigned char val; val = (timint1 << 4) | (timint2 << 2) | cnext; if (mb86a16_write(state, MB86A16_CNTMR, val) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int smrt_set(struct mb86a16_state *state, int rate) { int tmp ; int m ; unsigned char STOFS0, STOFS1; m = 1 << state->deci; tmp = (8192 * state->master_clk - 2 * m * rate * 8192 + state->master_clk / 2) / state->master_clk; STOFS0 = tmp & 0x0ff; STOFS1 = (tmp & 0xf00) >> 8; if (mb86a16_write(state, MB86A16_SRATE1, (state->deci << 2) | (state->csel << 1) | state->rsel) < 0) goto err; if (mb86a16_write(state, MB86A16_SRATE2, STOFS0) < 0) goto err; if (mb86a16_write(state, MB86A16_SRATE3, STOFS1) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -1; } static int srst(struct mb86a16_state *state) { if (mb86a16_write(state, MB86A16_RESET, 0x04) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int afcex_data_set(struct mb86a16_state *state, unsigned char AFCEX_L, unsigned char AFCEX_H) { if (mb86a16_write(state, MB86A16_AFCEXL, AFCEX_L) < 0) goto err; if (mb86a16_write(state, MB86A16_AFCEXH, AFCEX_H) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -1; } static int afcofs_data_set(struct mb86a16_state *state, unsigned char AFCEX_L, unsigned char AFCEX_H) { if (mb86a16_write(state, 0x58, AFCEX_L) < 0) goto err; if (mb86a16_write(state, 0x59, AFCEX_H) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int stlp_set(struct mb86a16_state *state, unsigned char STRAS, unsigned char STRBS) { if (mb86a16_write(state, MB86A16_STRFILTCOEF1, (STRBS << 3) | (STRAS)) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int Vi_set(struct mb86a16_state *state, unsigned char ETH, unsigned char VIA) { if (mb86a16_write(state, MB86A16_VISET2, 0x04) < 0) goto err; if (mb86a16_write(state, MB86A16_VISET3, 0xf5) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int initial_set(struct mb86a16_state *state) { if (stlp_set(state, 5, 7)) goto err; udelay(100); if (afcex_data_set(state, 0, 0)) goto err; udelay(100); if (afcofs_data_set(state, 0, 0)) goto err; udelay(100); if (mb86a16_write(state, MB86A16_CRLFILTCOEF1, 0x16) < 0) goto err; if (mb86a16_write(state, 0x2f, 0x21) < 0) goto err; if (mb86a16_write(state, MB86A16_VIMAG, 0x38) < 0) goto err; if (mb86a16_write(state, MB86A16_FAGCS1, 0x00) < 0) goto err; if (mb86a16_write(state, MB86A16_FAGCS2, 0x1c) < 0) goto err; if (mb86a16_write(state, MB86A16_FAGCS3, 0x20) < 0) goto err; if (mb86a16_write(state, MB86A16_FAGCS4, 0x1e) < 0) goto err; if (mb86a16_write(state, MB86A16_FAGCS5, 0x23) < 0) goto err; if (mb86a16_write(state, 0x54, 0xff) < 0) goto err; if (mb86a16_write(state, MB86A16_TSOUT, 0x00) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int S01T_set(struct mb86a16_state *state, unsigned char s1t, unsigned s0t) { if (mb86a16_write(state, 0x33, (s1t << 3) | s0t) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int EN_set(struct mb86a16_state *state, int cren, int afcen) { unsigned char val; val = 0x7a | (cren << 7) | (afcen << 2); if (mb86a16_write(state, 0x49, val) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int AFCEXEN_set(struct mb86a16_state *state, int afcexen, int smrt) { unsigned char AFCA ; if (smrt > 18875) AFCA = 4; else if (smrt > 9375) AFCA = 3; else if (smrt > 2250) AFCA = 2; else AFCA = 1; if (mb86a16_write(state, 0x2a, 0x02 | (afcexen << 5) | (AFCA << 2)) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int DAGC_data_set(struct mb86a16_state *state, unsigned char DAGCA, unsigned char DAGCW) { if (mb86a16_write(state, 0x2d, (DAGCA << 3) | DAGCW) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static void smrt_info_get(struct mb86a16_state *state, int rate) { if (rate >= 37501) { state->deci = 0; state->csel = 0; state->rsel = 0; } else if (rate >= 30001) { state->deci = 0; state->csel = 0; state->rsel = 1; } else if (rate >= 26251) { state->deci = 0; state->csel = 1; state->rsel = 0; } else if (rate >= 22501) { state->deci = 0; state->csel = 1; state->rsel = 1; } else if (rate >= 18751) { state->deci = 1; state->csel = 0; state->rsel = 0; } else if (rate >= 15001) { state->deci = 1; state->csel = 0; state->rsel = 1; } else if (rate >= 13126) { state->deci = 1; state->csel = 1; state->rsel = 0; } else if (rate >= 11251) { state->deci = 1; state->csel = 1; state->rsel = 1; } else if (rate >= 9376) { state->deci = 2; state->csel = 0; state->rsel = 0; } else if (rate >= 7501) { state->deci = 2; state->csel = 0; state->rsel = 1; } else if (rate >= 6563) { state->deci = 2; state->csel = 1; state->rsel = 0; } else if (rate >= 5626) { state->deci = 2; state->csel = 1; state->rsel = 1; } else if (rate >= 4688) { state->deci = 3; state->csel = 0; state->rsel = 0; } else if (rate >= 3751) { state->deci = 3; state->csel = 0; state->rsel = 1; } else if (rate >= 3282) { state->deci = 3; state->csel = 1; state->rsel = 0; } else if (rate >= 2814) { state->deci = 3; state->csel = 1; state->rsel = 1; } else if (rate >= 2344) { state->deci = 4; state->csel = 0; state->rsel = 0; } else if (rate >= 1876) { state->deci = 4; state->csel = 0; state->rsel = 1; } else if (rate >= 1641) { state->deci = 4; state->csel = 1; state->rsel = 0; } else if (rate >= 1407) { state->deci = 4; state->csel = 1; state->rsel = 1; } else if (rate >= 1172) { state->deci = 5; state->csel = 0; state->rsel = 0; } else if (rate >= 939) { state->deci = 5; state->csel = 0; state->rsel = 1; } else if (rate >= 821) { state->deci = 5; state->csel = 1; state->rsel = 0; } else { state->deci = 5; state->csel = 1; state->rsel = 1; } if (state->csel == 0) state->master_clk = 92000; else state->master_clk = 61333; } static int signal_det(struct mb86a16_state *state, int smrt, unsigned char *SIG) { int ret ; int smrtd ; int wait_sym ; u32 wait_t; unsigned char S[3] ; int i ; if (*SIG > 45) { if (CNTM_set(state, 2, 1, 2) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "CNTM set Error"); return -1; } wait_sym = 40000; } else { if (CNTM_set(state, 3, 1, 2) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "CNTM set Error"); return -1; } wait_sym = 80000; } for (i = 0; i < 3; i++) { if (i == 0) smrtd = smrt * 98 / 100; else if (i == 1) smrtd = smrt; else smrtd = smrt * 102 / 100; smrt_info_get(state, smrtd); smrt_set(state, smrtd); srst(state); wait_t = (wait_sym + 99 * smrtd / 100) / smrtd; if (wait_t == 0) wait_t = 1; msleep_interruptible(10); if (mb86a16_read(state, 0x37, &(S[i])) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } } if ((S[1] > S[0] * 112 / 100) && (S[1] > S[2] * 112 / 100)) { ret = 1; } else { ret = 0; } *SIG = S[1]; if (CNTM_set(state, 0, 1, 2) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "CNTM set Error"); return -1; } return ret; } static int rf_val_set(struct mb86a16_state *state, int f, int smrt, unsigned char R) { unsigned char C, F, B; int M; unsigned char rf_val[5]; int ack = -1; if (smrt > 37750) C = 1; else if (smrt > 18875) C = 2; else if (smrt > 5500) C = 3; else C = 4; if (smrt > 30500) F = 3; else if (smrt > 9375) F = 1; else if (smrt > 4625) F = 0; else F = 2; if (f < 1060) B = 0; else if (f < 1175) B = 1; else if (f < 1305) B = 2; else if (f < 1435) B = 3; else if (f < 1570) B = 4; else if (f < 1715) B = 5; else if (f < 1845) B = 6; else if (f < 1980) B = 7; else if (f < 2080) B = 8; else B = 9; M = f * (1 << R) / 2; rf_val[0] = 0x01 | (C << 3) | (F << 1); rf_val[1] = (R << 5) | ((M & 0x1f000) >> 12); rf_val[2] = (M & 0x00ff0) >> 4; rf_val[3] = ((M & 0x0000f) << 4) | B; /* Frequency Set */ if (mb86a16_write(state, 0x21, rf_val[0]) < 0) ack = 0; if (mb86a16_write(state, 0x22, rf_val[1]) < 0) ack = 0; if (mb86a16_write(state, 0x23, rf_val[2]) < 0) ack = 0; if (mb86a16_write(state, 0x24, rf_val[3]) < 0) ack = 0; if (mb86a16_write(state, 0x25, 0x01) < 0) ack = 0; if (ack == 0) { dprintk(verbose, MB86A16_ERROR, 1, "RF Setup - I2C transfer error"); return -EREMOTEIO; } return 0; } static int afcerr_chk(struct mb86a16_state *state) { unsigned char AFCM_L, AFCM_H ; int AFCM ; int afcm, afcerr ; if (mb86a16_read(state, 0x0e, &AFCM_L) != 2) goto err; if (mb86a16_read(state, 0x0f, &AFCM_H) != 2) goto err; AFCM = (AFCM_H << 8) + AFCM_L; if (AFCM > 2048) afcm = AFCM - 4096; else afcm = AFCM; afcerr = afcm * state->master_clk / 8192; return afcerr; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int dagcm_val_get(struct mb86a16_state *state) { int DAGCM; unsigned char DAGCM_H, DAGCM_L; if (mb86a16_read(state, 0x45, &DAGCM_L) != 2) goto err; if (mb86a16_read(state, 0x46, &DAGCM_H) != 2) goto err; DAGCM = (DAGCM_H << 8) + DAGCM_L; return DAGCM; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int mb86a16_read_status(struct dvb_frontend *fe, fe_status_t *status) { u8 stat, stat2; struct mb86a16_state *state = fe->demodulator_priv; *status = 0; if (mb86a16_read(state, MB86A16_SIG1, &stat) != 2) goto err; if (mb86a16_read(state, MB86A16_SIG2, &stat2) != 2) goto err; if ((stat > 25) && (stat2 > 25)) *status |= FE_HAS_SIGNAL; if ((stat > 45) && (stat2 > 45)) *status |= FE_HAS_CARRIER; if (mb86a16_read(state, MB86A16_STATUS, &stat) != 2) goto err; if (stat & 0x01) *status |= FE_HAS_SYNC; if (stat & 0x01) *status |= FE_HAS_VITERBI; if (mb86a16_read(state, MB86A16_FRAMESYNC, &stat) != 2) goto err; if ((stat & 0x0f) && (*status & FE_HAS_VITERBI)) *status |= FE_HAS_LOCK; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int sync_chk(struct mb86a16_state *state, unsigned char *VIRM) { unsigned char val; int sync; if (mb86a16_read(state, 0x0d, &val) != 2) goto err; dprintk(verbose, MB86A16_INFO, 1, "Status = %02x,", val); sync = val & 0x01; *VIRM = (val & 0x1c) >> 2; return sync; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int freqerr_chk(struct mb86a16_state *state, int fTP, int smrt, int unit) { unsigned char CRM, AFCML, AFCMH; unsigned char temp1, temp2, temp3; int crm, afcm, AFCM; int crrerr, afcerr; /* kHz */ int frqerr; /* MHz */ int afcen, afcexen = 0; int R, M, fOSC, fOSC_OFS; if (mb86a16_read(state, 0x43, &CRM) != 2) goto err; if (CRM > 127) crm = CRM - 256; else crm = CRM; crrerr = smrt * crm / 256; if (mb86a16_read(state, 0x49, &temp1) != 2) goto err; afcen = (temp1 & 0x04) >> 2; if (afcen == 0) { if (mb86a16_read(state, 0x2a, &temp1) != 2) goto err; afcexen = (temp1 & 0x20) >> 5; } if (afcen == 1) { if (mb86a16_read(state, 0x0e, &AFCML) != 2) goto err; if (mb86a16_read(state, 0x0f, &AFCMH) != 2) goto err; } else if (afcexen == 1) { if (mb86a16_read(state, 0x2b, &AFCML) != 2) goto err; if (mb86a16_read(state, 0x2c, &AFCMH) != 2) goto err; } if ((afcen == 1) || (afcexen == 1)) { smrt_info_get(state, smrt); AFCM = ((AFCMH & 0x01) << 8) + AFCML; if (AFCM > 255) afcm = AFCM - 512; else afcm = AFCM; afcerr = afcm * state->master_clk / 8192; } else afcerr = 0; if (mb86a16_read(state, 0x22, &temp1) != 2) goto err; if (mb86a16_read(state, 0x23, &temp2) != 2) goto err; if (mb86a16_read(state, 0x24, &temp3) != 2) goto err; R = (temp1 & 0xe0) >> 5; M = ((temp1 & 0x1f) << 12) + (temp2 << 4) + (temp3 >> 4); if (R == 0) fOSC = 2 * M; else fOSC = M; fOSC_OFS = fOSC - fTP; if (unit == 0) { /* MHz */ if (crrerr + afcerr + fOSC_OFS * 1000 >= 0) frqerr = (crrerr + afcerr + fOSC_OFS * 1000 + 500) / 1000; else frqerr = (crrerr + afcerr + fOSC_OFS * 1000 - 500) / 1000; } else { /* kHz */ frqerr = crrerr + afcerr + fOSC_OFS * 1000; } return frqerr; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static unsigned char vco_dev_get(struct mb86a16_state *state, int smrt) { unsigned char R; if (smrt > 9375) R = 0; else R = 1; return R; } static void swp_info_get(struct mb86a16_state *state, int fOSC_start, int smrt, int v, int R, int swp_ofs, int *fOSC, int *afcex_freq, unsigned char *AFCEX_L, unsigned char *AFCEX_H) { int AFCEX ; int crnt_swp_freq ; crnt_swp_freq = fOSC_start * 1000 + v * swp_ofs; if (R == 0) *fOSC = (crnt_swp_freq + 1000) / 2000 * 2; else *fOSC = (crnt_swp_freq + 500) / 1000; if (*fOSC >= crnt_swp_freq) *afcex_freq = *fOSC * 1000 - crnt_swp_freq; else *afcex_freq = crnt_swp_freq - *fOSC * 1000; AFCEX = *afcex_freq * 8192 / state->master_clk; *AFCEX_L = AFCEX & 0x00ff; *AFCEX_H = (AFCEX & 0x0f00) >> 8; } static int swp_freq_calcuation(struct mb86a16_state *state, int i, int v, int *V, int vmax, int vmin, int SIGMIN, int fOSC, int afcex_freq, int swp_ofs, unsigned char *SIG1) { int swp_freq ; if ((i % 2 == 1) && (v <= vmax)) { /* positive v (case 1) */ if ((v - 1 == vmin) && (*(V + 30 + v) >= 0) && (*(V + 30 + v - 1) >= 0) && (*(V + 30 + v - 1) > *(V + 30 + v)) && (*(V + 30 + v - 1) > SIGMIN)) { swp_freq = fOSC * 1000 + afcex_freq - swp_ofs; *SIG1 = *(V + 30 + v - 1); } else if ((v == vmax) && (*(V + 30 + v) >= 0) && (*(V + 30 + v - 1) >= 0) && (*(V + 30 + v) > *(V + 30 + v - 1)) && (*(V + 30 + v) > SIGMIN)) { /* (case 2) */ swp_freq = fOSC * 1000 + afcex_freq; *SIG1 = *(V + 30 + v); } else if ((*(V + 30 + v) > 0) && (*(V + 30 + v - 1) > 0) && (*(V + 30 + v - 2) > 0) && (*(V + 30 + v - 3) > 0) && (*(V + 30 + v - 1) > *(V + 30 + v)) && (*(V + 30 + v - 2) > *(V + 30 + v - 3)) && ((*(V + 30 + v - 1) > SIGMIN) || (*(V + 30 + v - 2) > SIGMIN))) { /* (case 3) */ if (*(V + 30 + v - 1) >= *(V + 30 + v - 2)) { swp_freq = fOSC * 1000 + afcex_freq - swp_ofs; *SIG1 = *(V + 30 + v - 1); } else { swp_freq = fOSC * 1000 + afcex_freq - swp_ofs * 2; *SIG1 = *(V + 30 + v - 2); } } else if ((v == vmax) && (*(V + 30 + v) >= 0) && (*(V + 30 + v - 1) >= 0) && (*(V + 30 + v - 2) >= 0) && (*(V + 30 + v) > *(V + 30 + v - 2)) && (*(V + 30 + v - 1) > *(V + 30 + v - 2)) && ((*(V + 30 + v) > SIGMIN) || (*(V + 30 + v - 1) > SIGMIN))) { /* (case 4) */ if (*(V + 30 + v) >= *(V + 30 + v - 1)) { swp_freq = fOSC * 1000 + afcex_freq; *SIG1 = *(V + 30 + v); } else { swp_freq = fOSC * 1000 + afcex_freq - swp_ofs; *SIG1 = *(V + 30 + v - 1); } } else { swp_freq = -1 ; } } else if ((i % 2 == 0) && (v >= vmin)) { /* Negative v (case 1) */ if ((*(V + 30 + v) > 0) && (*(V + 30 + v + 1) > 0) && (*(V + 30 + v + 2) > 0) && (*(V + 30 + v + 1) > *(V + 30 + v)) && (*(V + 30 + v + 1) > *(V + 30 + v + 2)) && (*(V + 30 + v + 1) > SIGMIN)) { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs; *SIG1 = *(V + 30 + v + 1); } else if ((v + 1 == vmax) && (*(V + 30 + v) >= 0) && (*(V + 30 + v + 1) >= 0) && (*(V + 30 + v + 1) > *(V + 30 + v)) && (*(V + 30 + v + 1) > SIGMIN)) { /* (case 2) */ swp_freq = fOSC * 1000 + afcex_freq + swp_ofs; *SIG1 = *(V + 30 + v); } else if ((v == vmin) && (*(V + 30 + v) > 0) && (*(V + 30 + v + 1) > 0) && (*(V + 30 + v + 2) > 0) && (*(V + 30 + v) > *(V + 30 + v + 1)) && (*(V + 30 + v) > *(V + 30 + v + 2)) && (*(V + 30 + v) > SIGMIN)) { /* (case 3) */ swp_freq = fOSC * 1000 + afcex_freq; *SIG1 = *(V + 30 + v); } else if ((*(V + 30 + v) >= 0) && (*(V + 30 + v + 1) >= 0) && (*(V + 30 + v + 2) >= 0) && (*(V + 30 + v + 3) >= 0) && (*(V + 30 + v + 1) > *(V + 30 + v)) && (*(V + 30 + v + 2) > *(V + 30 + v + 3)) && ((*(V + 30 + v + 1) > SIGMIN) || (*(V + 30 + v + 2) > SIGMIN))) { /* (case 4) */ if (*(V + 30 + v + 1) >= *(V + 30 + v + 2)) { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs; *SIG1 = *(V + 30 + v + 1); } else { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs * 2; *SIG1 = *(V + 30 + v + 2); } } else if ((*(V + 30 + v) >= 0) && (*(V + 30 + v + 1) >= 0) && (*(V + 30 + v + 2) >= 0) && (*(V + 30 + v + 3) >= 0) && (*(V + 30 + v) > *(V + 30 + v + 2)) && (*(V + 30 + v + 1) > *(V + 30 + v + 2)) && (*(V + 30 + v) > *(V + 30 + v + 3)) && (*(V + 30 + v + 1) > *(V + 30 + v + 3)) && ((*(V + 30 + v) > SIGMIN) || (*(V + 30 + v + 1) > SIGMIN))) { /* (case 5) */ if (*(V + 30 + v) >= *(V + 30 + v + 1)) { swp_freq = fOSC * 1000 + afcex_freq; *SIG1 = *(V + 30 + v); } else { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs; *SIG1 = *(V + 30 + v + 1); } } else if ((v + 2 == vmin) && (*(V + 30 + v) >= 0) && (*(V + 30 + v + 1) >= 0) && (*(V + 30 + v + 2) >= 0) && (*(V + 30 + v + 1) > *(V + 30 + v)) && (*(V + 30 + v + 2) > *(V + 30 + v)) && ((*(V + 30 + v + 1) > SIGMIN) || (*(V + 30 + v + 2) > SIGMIN))) { /* (case 6) */ if (*(V + 30 + v + 1) >= *(V + 30 + v + 2)) { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs; *SIG1 = *(V + 30 + v + 1); } else { swp_freq = fOSC * 1000 + afcex_freq + swp_ofs * 2; *SIG1 = *(V + 30 + v + 2); } } else if ((vmax == 0) && (vmin == 0) && (*(V + 30 + v) > SIGMIN)) { swp_freq = fOSC * 1000; *SIG1 = *(V + 30 + v); } else swp_freq = -1; } else swp_freq = -1; return swp_freq; } static void swp_info_get2(struct mb86a16_state *state, int smrt, int R, int swp_freq, int *afcex_freq, int *fOSC, unsigned char *AFCEX_L, unsigned char *AFCEX_H) { int AFCEX ; if (R == 0) *fOSC = (swp_freq + 1000) / 2000 * 2; else *fOSC = (swp_freq + 500) / 1000; if (*fOSC >= swp_freq) *afcex_freq = *fOSC * 1000 - swp_freq; else *afcex_freq = swp_freq - *fOSC * 1000; AFCEX = *afcex_freq * 8192 / state->master_clk; *AFCEX_L = AFCEX & 0x00ff; *AFCEX_H = (AFCEX & 0x0f00) >> 8; } static void afcex_info_get(struct mb86a16_state *state, int afcex_freq, unsigned char *AFCEX_L, unsigned char *AFCEX_H) { int AFCEX ; AFCEX = afcex_freq * 8192 / state->master_clk; *AFCEX_L = AFCEX & 0x00ff; *AFCEX_H = (AFCEX & 0x0f00) >> 8; } static int SEQ_set(struct mb86a16_state *state, unsigned char loop) { /* SLOCK0 = 0 */ if (mb86a16_write(state, 0x32, 0x02 | (loop << 2)) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } return 0; } static int iq_vt_set(struct mb86a16_state *state, unsigned char IQINV) { /* Viterbi Rate, IQ Settings */ if (mb86a16_write(state, 0x06, 0xdf | (IQINV << 5)) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } return 0; } static int FEC_srst(struct mb86a16_state *state) { if (mb86a16_write(state, MB86A16_RESET, 0x02) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } return 0; } static int S2T_set(struct mb86a16_state *state, unsigned char S2T) { if (mb86a16_write(state, 0x34, 0x70 | S2T) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } return 0; } static int S45T_set(struct mb86a16_state *state, unsigned char S4T, unsigned char S5T) { if (mb86a16_write(state, 0x35, 0x00 | (S5T << 4) | S4T) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } return 0; } static int mb86a16_set_fe(struct mb86a16_state *state) { u8 agcval, cnmval; int i, j; int fOSC = 0; int fOSC_start = 0; int wait_t; int fcp; int swp_ofs; int V[60]; u8 SIG1MIN; unsigned char CREN, AFCEN, AFCEXEN; unsigned char SIG1; unsigned char TIMINT1, TIMINT2, TIMEXT; unsigned char S0T, S1T; unsigned char S2T; /* unsigned char S2T, S3T; */ unsigned char S4T, S5T; unsigned char AFCEX_L, AFCEX_H; unsigned char R; unsigned char VIRM; unsigned char ETH, VIA; unsigned char junk; int loop; int ftemp; int v, vmax, vmin; int vmax_his, vmin_his; int swp_freq, prev_swp_freq[20]; int prev_freq_num; int signal_dupl; int afcex_freq; int signal; int afcerr; int temp_freq, delta_freq; int dagcm[4]; int smrt_d; /* int freq_err; */ int n; int ret = -1; int sync; dprintk(verbose, MB86A16_INFO, 1, "freq=%d Mhz, symbrt=%d Ksps", state->frequency, state->srate); fcp = 3000; swp_ofs = state->srate / 4; for (i = 0; i < 60; i++) V[i] = -1; for (i = 0; i < 20; i++) prev_swp_freq[i] = 0; SIG1MIN = 25; for (n = 0; ((n < 3) && (ret == -1)); n++) { SEQ_set(state, 0); iq_vt_set(state, 0); CREN = 0; AFCEN = 0; AFCEXEN = 1; TIMINT1 = 0; TIMINT2 = 1; TIMEXT = 2; S1T = 0; S0T = 0; if (initial_set(state) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "initial set failed"); return -1; } if (DAGC_data_set(state, 3, 2) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "DAGC data set error"); return -1; } if (EN_set(state, CREN, AFCEN) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "EN set error"); return -1; /* (0, 0) */ } if (AFCEXEN_set(state, AFCEXEN, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "AFCEXEN set error"); return -1; /* (1, smrt) = (1, symbolrate) */ } if (CNTM_set(state, TIMINT1, TIMINT2, TIMEXT) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "CNTM set error"); return -1; /* (0, 1, 2) */ } if (S01T_set(state, S1T, S0T) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "S01T set error"); return -1; /* (0, 0) */ } smrt_info_get(state, state->srate); if (smrt_set(state, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "smrt info get error"); return -1; } R = vco_dev_get(state, state->srate); if (R == 1) fOSC_start = state->frequency; else if (R == 0) { if (state->frequency % 2 == 0) { fOSC_start = state->frequency; } else { fOSC_start = state->frequency + 1; if (fOSC_start > 2150) fOSC_start = state->frequency - 1; } } loop = 1; ftemp = fOSC_start * 1000; vmax = 0 ; while (loop == 1) { ftemp = ftemp + swp_ofs; vmax++; /* Upper bound */ if (ftemp > 2150000) { loop = 0; vmax--; } else { if ((ftemp == 2150000) || (ftemp - state->frequency * 1000 >= fcp + state->srate / 4)) loop = 0; } } loop = 1; ftemp = fOSC_start * 1000; vmin = 0 ; while (loop == 1) { ftemp = ftemp - swp_ofs; vmin--; /* Lower bound */ if (ftemp < 950000) { loop = 0; vmin++; } else { if ((ftemp == 950000) || (state->frequency * 1000 - ftemp >= fcp + state->srate / 4)) loop = 0; } } wait_t = (8000 + state->srate / 2) / state->srate; if (wait_t == 0) wait_t = 1; i = 0; j = 0; prev_freq_num = 0; loop = 1; signal = 0; vmax_his = 0; vmin_his = 0; v = 0; while (loop == 1) { swp_info_get(state, fOSC_start, state->srate, v, R, swp_ofs, &fOSC, &afcex_freq, &AFCEX_L, &AFCEX_H); udelay(100); if (rf_val_set(state, fOSC, state->srate, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set error"); return -1; } udelay(100); if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set error"); return -1; } if (srst(state) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "srst error"); return -1; } msleep_interruptible(wait_t); if (mb86a16_read(state, 0x37, &SIG1) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -1; } V[30 + v] = SIG1 ; swp_freq = swp_freq_calcuation(state, i, v, V, vmax, vmin, SIG1MIN, fOSC, afcex_freq, swp_ofs, &SIG1); /* changed */ signal_dupl = 0; for (j = 0; j < prev_freq_num; j++) { if ((ABS(prev_swp_freq[j] - swp_freq)) < (swp_ofs * 3 / 2)) { signal_dupl = 1; dprintk(verbose, MB86A16_INFO, 1, "Probably Duplicate Signal, j = %d", j); } } if ((signal_dupl == 0) && (swp_freq > 0) && (ABS(swp_freq - state->frequency * 1000) < fcp + state->srate / 6)) { dprintk(verbose, MB86A16_DEBUG, 1, "------ Signal detect ------ [swp_freq=[%07d, srate=%05d]]", swp_freq, state->srate); prev_swp_freq[prev_freq_num] = swp_freq; prev_freq_num++; swp_info_get2(state, state->srate, R, swp_freq, &afcex_freq, &fOSC, &AFCEX_L, &AFCEX_H); if (rf_val_set(state, fOSC, state->srate, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set error"); return -1; } if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set error"); return -1; } signal = signal_det(state, state->srate, &SIG1); if (signal == 1) { dprintk(verbose, MB86A16_ERROR, 1, "***** Signal Found *****"); loop = 0; } else { dprintk(verbose, MB86A16_ERROR, 1, "!!!!! No signal !!!!!, try again..."); smrt_info_get(state, state->srate); if (smrt_set(state, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "smrt set error"); return -1; } } } if (v > vmax) vmax_his = 1 ; if (v < vmin) vmin_his = 1 ; i++; if ((i % 2 == 1) && (vmax_his == 1)) i++; if ((i % 2 == 0) && (vmin_his == 1)) i++; if (i % 2 == 1) v = (i + 1) / 2; else v = -i / 2; if ((vmax_his == 1) && (vmin_his == 1)) loop = 0 ; } if (signal == 1) { dprintk(verbose, MB86A16_INFO, 1, " Start Freq Error Check"); S1T = 7 ; S0T = 1 ; CREN = 0 ; AFCEN = 1 ; AFCEXEN = 0 ; if (S01T_set(state, S1T, S0T) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "S01T set error"); return -1; } smrt_info_get(state, state->srate); if (smrt_set(state, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "smrt set error"); return -1; } if (EN_set(state, CREN, AFCEN) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "EN set error"); return -1; } if (AFCEXEN_set(state, AFCEXEN, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "AFCEXEN set error"); return -1; } afcex_info_get(state, afcex_freq, &AFCEX_L, &AFCEX_H); if (afcofs_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "AFCOFS data set error"); return -1; } if (srst(state) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "srst error"); return -1; } /* delay 4~200 */ wait_t = 200000 / state->master_clk + 200000 / state->srate; msleep(wait_t); afcerr = afcerr_chk(state); if (afcerr == -1) return -1; swp_freq = fOSC * 1000 + afcerr ; AFCEXEN = 1 ; if (state->srate >= 1500) smrt_d = state->srate / 3; else smrt_d = state->srate / 2; smrt_info_get(state, smrt_d); if (smrt_set(state, smrt_d) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "smrt set error"); return -1; } if (AFCEXEN_set(state, AFCEXEN, smrt_d) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "AFCEXEN set error"); return -1; } R = vco_dev_get(state, smrt_d); if (DAGC_data_set(state, 2, 0) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "DAGC data set error"); return -1; } for (i = 0; i < 3; i++) { temp_freq = swp_freq + (i - 1) * state->srate / 8; swp_info_get2(state, smrt_d, R, temp_freq, &afcex_freq, &fOSC, &AFCEX_L, &AFCEX_H); if (rf_val_set(state, fOSC, smrt_d, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set error"); return -1; } if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set error"); return -1; } wait_t = 200000 / state->master_clk + 40000 / smrt_d; msleep(wait_t); dagcm[i] = dagcm_val_get(state); } if ((dagcm[0] > dagcm[1]) && (dagcm[0] > dagcm[2]) && (dagcm[0] - dagcm[1] > 2 * (dagcm[2] - dagcm[1]))) { temp_freq = swp_freq - 2 * state->srate / 8; swp_info_get2(state, smrt_d, R, temp_freq, &afcex_freq, &fOSC, &AFCEX_L, &AFCEX_H); if (rf_val_set(state, fOSC, smrt_d, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set error"); return -1; } if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set"); return -1; } wait_t = 200000 / state->master_clk + 40000 / smrt_d; msleep(wait_t); dagcm[3] = dagcm_val_get(state); if (dagcm[3] > dagcm[1]) delta_freq = (dagcm[2] - dagcm[0] + dagcm[1] - dagcm[3]) * state->srate / 300; else delta_freq = 0; } else if ((dagcm[2] > dagcm[1]) && (dagcm[2] > dagcm[0]) && (dagcm[2] - dagcm[1] > 2 * (dagcm[0] - dagcm[1]))) { temp_freq = swp_freq + 2 * state->srate / 8; swp_info_get2(state, smrt_d, R, temp_freq, &afcex_freq, &fOSC, &AFCEX_L, &AFCEX_H); if (rf_val_set(state, fOSC, smrt_d, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set"); return -1; } if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set"); return -1; } wait_t = 200000 / state->master_clk + 40000 / smrt_d; msleep(wait_t); dagcm[3] = dagcm_val_get(state); if (dagcm[3] > dagcm[1]) delta_freq = (dagcm[2] - dagcm[0] + dagcm[3] - dagcm[1]) * state->srate / 300; else delta_freq = 0 ; } else { delta_freq = 0 ; } dprintk(verbose, MB86A16_INFO, 1, "SWEEP Frequency = %d", swp_freq); swp_freq += delta_freq; dprintk(verbose, MB86A16_INFO, 1, "Adjusting .., DELTA Freq = %d, SWEEP Freq=%d", delta_freq, swp_freq); if (ABS(state->frequency * 1000 - swp_freq) > 3800) { dprintk(verbose, MB86A16_INFO, 1, "NO -- SIGNAL !"); } else { S1T = 0; S0T = 3; CREN = 1; AFCEN = 0; AFCEXEN = 1; if (S01T_set(state, S1T, S0T) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "S01T set error"); return -1; } if (DAGC_data_set(state, 0, 0) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "DAGC data set error"); return -1; } R = vco_dev_get(state, state->srate); smrt_info_get(state, state->srate); if (smrt_set(state, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "smrt set error"); return -1; } if (EN_set(state, CREN, AFCEN) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "EN set error"); return -1; } if (AFCEXEN_set(state, AFCEXEN, state->srate) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "AFCEXEN set error"); return -1; } swp_info_get2(state, state->srate, R, swp_freq, &afcex_freq, &fOSC, &AFCEX_L, &AFCEX_H); if (rf_val_set(state, fOSC, state->srate, R) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "rf val set error"); return -1; } if (afcex_data_set(state, AFCEX_L, AFCEX_H) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "afcex data set error"); return -1; } if (srst(state) < 0) { dprintk(verbose, MB86A16_ERROR, 1, "srst error"); return -1; } wait_t = 7 + (10000 + state->srate / 2) / state->srate; if (wait_t == 0) wait_t = 1; msleep_interruptible(wait_t); if (mb86a16_read(state, 0x37, &SIG1) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } if (SIG1 > 110) { S2T = 4; S4T = 1; S5T = 6; ETH = 4; VIA = 6; wait_t = 7 + (917504 + state->srate / 2) / state->srate; } else if (SIG1 > 105) { S2T = 4; S4T = 2; S5T = 8; ETH = 7; VIA = 2; wait_t = 7 + (1048576 + state->srate / 2) / state->srate; } else if (SIG1 > 85) { S2T = 5; S4T = 2; S5T = 8; ETH = 7; VIA = 2; wait_t = 7 + (1310720 + state->srate / 2) / state->srate; } else if (SIG1 > 65) { S2T = 6; S4T = 2; S5T = 8; ETH = 7; VIA = 2; wait_t = 7 + (1572864 + state->srate / 2) / state->srate; } else { S2T = 7; S4T = 2; S5T = 8; ETH = 7; VIA = 2; wait_t = 7 + (2097152 + state->srate / 2) / state->srate; } wait_t *= 2; /* FOS */ S2T_set(state, S2T); S45T_set(state, S4T, S5T); Vi_set(state, ETH, VIA); srst(state); msleep_interruptible(wait_t); sync = sync_chk(state, &VIRM); dprintk(verbose, MB86A16_INFO, 1, "-------- Viterbi=[%d] SYNC=[%d] ---------", VIRM, sync); if (VIRM) { if (VIRM == 4) { /* 5/6 */ if (SIG1 > 110) wait_t = (786432 + state->srate / 2) / state->srate; else wait_t = (1572864 + state->srate / 2) / state->srate; if (state->srate < 5000) msleep_interruptible(wait_t); else msleep_interruptible(wait_t); if (sync_chk(state, &junk) == 0) { iq_vt_set(state, 1); FEC_srst(state); } } /* 1/2, 2/3, 3/4, 7/8 */ if (SIG1 > 110) wait_t = (786432 + state->srate / 2) / state->srate; else wait_t = (1572864 + state->srate / 2) / state->srate; msleep_interruptible(wait_t); SEQ_set(state, 1); } else { dprintk(verbose, MB86A16_INFO, 1, "NO -- SYNC"); SEQ_set(state, 1); ret = -1; } } } else { dprintk(verbose, MB86A16_INFO, 1, "NO -- SIGNAL"); ret = -1; } sync = sync_chk(state, &junk); if (sync) { dprintk(verbose, MB86A16_INFO, 1, "******* SYNC *******"); freqerr_chk(state, state->frequency, state->srate, 1); ret = 0; break; } } mb86a16_read(state, 0x15, &agcval); mb86a16_read(state, 0x26, &cnmval); dprintk(verbose, MB86A16_INFO, 1, "AGC = %02x CNM = %02x", agcval, cnmval); return ret; } static int mb86a16_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *cmd) { struct mb86a16_state *state = fe->demodulator_priv; int i; u8 regs; if (mb86a16_write(state, MB86A16_DCC1, MB86A16_DCC1_DISTA) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, 0x00) < 0) goto err; if (mb86a16_write(state, MB86A16_TONEOUT2, 0x04) < 0) goto err; regs = 0x18; if (cmd->msg_len > 5 || cmd->msg_len < 4) return -EINVAL; for (i = 0; i < cmd->msg_len; i++) { if (mb86a16_write(state, regs, cmd->msg[i]) < 0) goto err; regs++; } i += 0x90; msleep_interruptible(10); if (mb86a16_write(state, MB86A16_DCC1, i) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, MB86A16_DCCOUT_DISEN) < 0) goto err; return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int mb86a16_send_diseqc_burst(struct dvb_frontend *fe, fe_sec_mini_cmd_t burst) { struct mb86a16_state *state = fe->demodulator_priv; switch (burst) { case SEC_MINI_A: if (mb86a16_write(state, MB86A16_DCC1, MB86A16_DCC1_DISTA | MB86A16_DCC1_TBEN | MB86A16_DCC1_TBO) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, MB86A16_DCCOUT_DISEN) < 0) goto err; break; case SEC_MINI_B: if (mb86a16_write(state, MB86A16_DCC1, MB86A16_DCC1_DISTA | MB86A16_DCC1_TBEN) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, MB86A16_DCCOUT_DISEN) < 0) goto err; break; } return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int mb86a16_set_tone(struct dvb_frontend *fe, fe_sec_tone_mode_t tone) { struct mb86a16_state *state = fe->demodulator_priv; switch (tone) { case SEC_TONE_ON: if (mb86a16_write(state, MB86A16_TONEOUT2, 0x00) < 0) goto err; if (mb86a16_write(state, MB86A16_DCC1, MB86A16_DCC1_DISTA | MB86A16_DCC1_CTOE) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, MB86A16_DCCOUT_DISEN) < 0) goto err; break; case SEC_TONE_OFF: if (mb86a16_write(state, MB86A16_TONEOUT2, 0x04) < 0) goto err; if (mb86a16_write(state, MB86A16_DCC1, MB86A16_DCC1_DISTA) < 0) goto err; if (mb86a16_write(state, MB86A16_DCCOUT, 0x00) < 0) goto err; break; default: return -EINVAL; } return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static enum dvbfe_search mb86a16_search(struct dvb_frontend *fe, struct dvb_frontend_parameters *p) { struct mb86a16_state *state = fe->demodulator_priv; state->frequency = p->frequency / 1000; state->srate = p->u.qpsk.symbol_rate / 1000; if (!mb86a16_set_fe(state)) { dprintk(verbose, MB86A16_ERROR, 1, "Succesfully acquired LOCK"); return DVBFE_ALGO_SEARCH_SUCCESS; } dprintk(verbose, MB86A16_ERROR, 1, "Lock acquisition failed!"); return DVBFE_ALGO_SEARCH_FAILED; } static void mb86a16_release(struct dvb_frontend *fe) { struct mb86a16_state *state = fe->demodulator_priv; kfree(state); } static int mb86a16_init(struct dvb_frontend *fe) { return 0; } static int mb86a16_sleep(struct dvb_frontend *fe) { return 0; } static int mb86a16_read_ber(struct dvb_frontend *fe, u32 *ber) { u8 ber_mon, ber_tab, ber_lsb, ber_mid, ber_msb, ber_tim, ber_rst; u32 timer; struct mb86a16_state *state = fe->demodulator_priv; *ber = 0; if (mb86a16_read(state, MB86A16_BERMON, &ber_mon) != 2) goto err; if (mb86a16_read(state, MB86A16_BERTAB, &ber_tab) != 2) goto err; if (mb86a16_read(state, MB86A16_BERLSB, &ber_lsb) != 2) goto err; if (mb86a16_read(state, MB86A16_BERMID, &ber_mid) != 2) goto err; if (mb86a16_read(state, MB86A16_BERMSB, &ber_msb) != 2) goto err; /* BER monitor invalid when BER_EN = 0 */ if (ber_mon & 0x04) { /* coarse, fast calculation */ *ber = ber_tab & 0x1f; dprintk(verbose, MB86A16_DEBUG, 1, "BER coarse=[0x%02x]", *ber); if (ber_mon & 0x01) { /* * BER_SEL = 1, The monitored BER is the estimated * value with a Reed-Solomon decoder error amount at * the deinterleaver output. * monitored BER is expressed as a 20 bit output in total */ ber_rst = ber_mon >> 3; *ber = (((ber_msb << 8) | ber_mid) << 8) | ber_lsb; if (ber_rst == 0) timer = 12500000; if (ber_rst == 1) timer = 25000000; if (ber_rst == 2) timer = 50000000; if (ber_rst == 3) timer = 100000000; *ber /= timer; dprintk(verbose, MB86A16_DEBUG, 1, "BER fine=[0x%02x]", *ber); } else { /* * BER_SEL = 0, The monitored BER is the estimated * value with a Viterbi decoder error amount at the * QPSK demodulator output. * monitored BER is expressed as a 24 bit output in total */ ber_tim = ber_mon >> 1; *ber = (((ber_msb << 8) | ber_mid) << 8) | ber_lsb; if (ber_tim == 0) timer = 16; if (ber_tim == 1) timer = 24; *ber /= 2 ^ timer; dprintk(verbose, MB86A16_DEBUG, 1, "BER fine=[0x%02x]", *ber); } } return 0; err: dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } static int mb86a16_read_signal_strength(struct dvb_frontend *fe, u16 *strength) { u8 agcm = 0; struct mb86a16_state *state = fe->demodulator_priv; *strength = 0; if (mb86a16_read(state, MB86A16_AGCM, &agcm) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } *strength = ((0xff - agcm) * 100) / 256; dprintk(verbose, MB86A16_DEBUG, 1, "Signal strength=[%d %%]", (u8) *strength); *strength = (0xffff - 0xff) + agcm; return 0; } struct cnr { u8 cn_reg; u8 cn_val; }; static const struct cnr cnr_tab[] = { { 35, 2 }, { 40, 3 }, { 50, 4 }, { 60, 5 }, { 70, 6 }, { 80, 7 }, { 92, 8 }, { 103, 9 }, { 115, 10 }, { 138, 12 }, { 162, 15 }, { 180, 18 }, { 185, 19 }, { 189, 20 }, { 195, 22 }, { 199, 24 }, { 201, 25 }, { 202, 26 }, { 203, 27 }, { 205, 28 }, { 208, 30 } }; static int mb86a16_read_snr(struct dvb_frontend *fe, u16 *snr) { struct mb86a16_state *state = fe->demodulator_priv; int i = 0; int low_tide = 2, high_tide = 30, q_level; u8 cn; *snr = 0; if (mb86a16_read(state, 0x26, &cn) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } for (i = 0; i < ARRAY_SIZE(cnr_tab); i++) { if (cn < cnr_tab[i].cn_reg) { *snr = cnr_tab[i].cn_val; break; } } q_level = (*snr * 100) / (high_tide - low_tide); dprintk(verbose, MB86A16_ERROR, 1, "SNR (Quality) = [%d dB], Level=%d %%", *snr, q_level); *snr = (0xffff - 0xff) + *snr; return 0; } static int mb86a16_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks) { u8 dist; struct mb86a16_state *state = fe->demodulator_priv; if (mb86a16_read(state, MB86A16_DISTMON, &dist) != 2) { dprintk(verbose, MB86A16_ERROR, 1, "I2C transfer error"); return -EREMOTEIO; } *ucblocks = dist; return 0; } static enum dvbfe_algo mb86a16_frontend_algo(struct dvb_frontend *fe) { return DVBFE_ALGO_CUSTOM; } static struct dvb_frontend_ops mb86a16_ops = { .info = { .name = "Fujitsu MB86A16 DVB-S", .type = FE_QPSK, .frequency_min = 950000, .frequency_max = 2150000, .frequency_stepsize = 3000, .frequency_tolerance = 0, .symbol_rate_min = 1000000, .symbol_rate_max = 45000000, .symbol_rate_tolerance = 500, .caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_QPSK | FE_CAN_FEC_AUTO }, .release = mb86a16_release, .get_frontend_algo = mb86a16_frontend_algo, .search = mb86a16_search, .init = mb86a16_init, .sleep = mb86a16_sleep, .read_status = mb86a16_read_status, .read_ber = mb86a16_read_ber, .read_signal_strength = mb86a16_read_signal_strength, .read_snr = mb86a16_read_snr, .read_ucblocks = mb86a16_read_ucblocks, .diseqc_send_master_cmd = mb86a16_send_diseqc_msg, .diseqc_send_burst = mb86a16_send_diseqc_burst, .set_tone = mb86a16_set_tone, }; struct dvb_frontend *mb86a16_attach(const struct mb86a16_config *config, struct i2c_adapter *i2c_adap) { u8 dev_id = 0; struct mb86a16_state *state = NULL; state = kmalloc(sizeof(struct mb86a16_state), GFP_KERNEL); if (state == NULL) goto error; state->config = config; state->i2c_adap = i2c_adap; mb86a16_read(state, 0x7f, &dev_id); if (dev_id != 0xfe) goto error; memcpy(&state->frontend.ops, &mb86a16_ops, sizeof(struct dvb_frontend_ops)); state->frontend.demodulator_priv = state; state->frontend.ops.set_voltage = state->config->set_voltage; return &state->frontend; error: kfree(state); return NULL; } EXPORT_SYMBOL(mb86a16_attach); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Manu Abraham");
wkritzinger/asuswrt-merlin
release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/media/dvb/frontends/mb86a16.c
C
gpl-2.0
46,755
#include <lib/dvb/tstools.h> #include <lib/dvb/specs.h> #include <lib/base/eerror.h> #include <lib/base/cachedtssource.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> static const int m_maxrange = 256*1024; DEFINE_REF(eTSFileSectionReader); eTSFileSectionReader::eTSFileSectionReader(eMainloop *context) { sectionSize = 0; } eTSFileSectionReader::~eTSFileSectionReader() { } void eTSFileSectionReader::data(unsigned char *packet, unsigned int size) { if (sectionSize + size <= sizeof(sectionData)) { memcpy(&sectionData[sectionSize], packet, size); sectionSize += size; } if (sectionSize >= (unsigned int)(3 + ((sectionData[1] & 0x0f) << 8) + sectionData[2])) { sectionSize = 0; read(sectionData); } } RESULT eTSFileSectionReader::start(const eDVBSectionFilterMask &mask) { sectionSize = 0; return 0; } RESULT eTSFileSectionReader::stop() { sectionSize = 0; return 0; } RESULT eTSFileSectionReader::connectRead(const Slot1<void,const uint8_t*> &r, ePtr<eConnection> &conn) { conn = new eConnection(this, read.connect(r)); return 0; } eDVBTSTools::eDVBTSTools(): m_pid(-1), m_begin_valid (0), m_end_valid(0), m_samples_taken(0), m_last_filelength(0), m_futile(0) { } void eDVBTSTools::closeSource() { m_source = NULL; } eDVBTSTools::~eDVBTSTools() { closeSource(); } int eDVBTSTools::openFile(const char *filename, int nostreaminfo) { eRawFile *f = new eRawFile(); ePtr<iTsSource> src = f; if (f->open(filename) < 0) return -1; src = new eCachedSource(src); setSource(src, nostreaminfo ? NULL : filename); return 0; } void eDVBTSTools::setSource(ePtr<iTsSource> &source, const char *stream_info_filename) { closeSource(); m_source = source; if (stream_info_filename) { eDebug("loading streaminfo for %s", stream_info_filename); m_streaminfo.load(stream_info_filename); } m_samples_taken = 0; } /* getPTS extracts a pts value from any PID at a given offset. */ int eDVBTSTools::getPTS(off_t &offset, pts_t &pts, int fixed) { if (m_streaminfo.getPTS(offset, pts) == 0) return 0; // Okay, the cache had it if (m_streaminfo.hasStructure()) { off_t local_offset = offset; unsigned long long data; if (m_streaminfo.getStructureEntryFirst(local_offset, data) == 0) { for(int retries = 8; retries != 0; --retries) { if ((data & 0x1000000) != 0) { pts = data >> 31; if (pts == 0) { // obsolete data that happens to have a '1' there continue; } eDebug("eDVBTSTools::getPTS got it from sc file offset=%llu pts=%llu", local_offset, pts); if (fixed && fixupPTS(local_offset, pts)) { eDebug("But failed to fixup!"); break; } offset = local_offset; return 0; } else { eDebug("No PTS, try next"); } if (m_streaminfo.getStructureEntryNext(local_offset, data, 1) != 0) { eDebug("Cannot find next structure entry"); break; } } } } if (!m_source || !m_source->valid()) return -1; offset -= offset % 188; int left = m_maxrange; int resync_failed_counter = 64; while (left >= 188) { unsigned char packet[188]; if (m_source->read(offset, packet, 188) != 188) { eDebug("read error"); return -1; } left -= 188; offset += 188; if (packet[0] != 0x47) { const unsigned char* match = (const unsigned char*)memchr(packet+1, 0x47, 188-1); if (match != NULL) { eDebug("resync %d", match - packet); offset += (match - packet) - 188; } else { eDebug("resync failed"); if (resync_failed_counter == 0) { eDebug("Too many resync failures, probably not a valid stream"); return -1; } --resync_failed_counter; } continue; } int pid = ((packet[1] << 8) | packet[2]) & 0x1FFF; int pusi = !!(packet[1] & 0x40); // printf("PID %04x, PUSI %d\n", pid, pusi); unsigned char *payload; /* check for adaption field */ if (packet[3] & 0x20) { if (packet[4] >= 183) continue; if (packet[4]) { if (packet[5] & 0x10) /* PCR present */ { pts = ((unsigned long long)(packet[ 6]&0xFF)) << 25; pts |= ((unsigned long long)(packet[ 7]&0xFF)) << 17; pts |= ((unsigned long long)(packet[ 8]&0xFE)) << 9; pts |= ((unsigned long long)(packet[ 9]&0xFF)) << 1; pts |= ((unsigned long long)(packet[10]&0x80)) >> 7; offset -= 188; eDebug("PCR %16llx found at %lld pid %02x (%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x)", pts, offset, pid, packet[0], packet[1], packet[2], packet[3], packet[4], packet[5], packet[6], packet[7], packet[8], packet[9], packet[10]); if (fixed && fixupPTS(offset, pts)) return -1; return 0; } } payload = packet + packet[4] + 4 + 1; } else payload = packet + 4; /* if (m_pid >= 0) if (pid != m_pid) continue; */ if (!pusi) continue; /* somehow not a startcode. (this is invalid, since pusi was set.) ignore it. */ if (payload[0] || payload[1] || (payload[2] != 1)) continue; if (payload[3] == 0xFD) { // stream use extension mechanism defined in ISO 13818-1 Amendment 2 if (payload[7] & 1) // PES extension flag { int offs = 0; if (payload[7] & 0x80) // pts avail offs += 5; if (payload[7] & 0x40) // dts avail offs += 5; if (payload[7] & 0x20) // escr avail offs += 6; if (payload[7] & 0x10) // es rate offs += 3; if (payload[7] & 0x8) // dsm trickmode offs += 1; if (payload[7] & 0x4) // additional copy info offs += 1; if (payload[7] & 0x2) // crc offs += 2; if (payload[8] < offs) continue; uint8_t pef = payload[9+offs++]; // pes extension field if (pef & 1) // pes extension flag 2 { if (pef & 0x80) // private data flag offs += 16; if (pef & 0x40) // pack header field flag offs += 1; if (pef & 0x20) // program packet sequence counter flag offs += 2; if (pef & 0x10) // P-STD buffer flag offs += 2; if (payload[8] < offs) continue; uint8_t stream_id_extension_len = payload[9+offs++] & 0x7F; if (stream_id_extension_len >= 1) { if (payload[8] < (offs + stream_id_extension_len) ) continue; if (payload[9+offs] & 0x80) // stream_id_extension_bit (should not set) continue; switch (payload[9+offs]) { case 0x55 ... 0x5f: // VC-1 break; case 0x71: // AC3 / DTS break; case 0x72: // DTS - HD break; default: eDebug("skip unknwn stream_id_extension %02x\n", payload[9+offs]); continue; } } else continue; } else continue; } else continue; } /* drop non-audio, non-video packets because other streams can be non-compliant.*/ else if (((payload[3] & 0xE0) != 0xC0) && // audio ((payload[3] & 0xF0) != 0xE0)) // video continue; if (payload[7] & 0x80) /* PTS */ { pts = ((unsigned long long)(payload[ 9]&0xE)) << 29; pts |= ((unsigned long long)(payload[10]&0xFF)) << 22; pts |= ((unsigned long long)(payload[11]&0xFE)) << 14; pts |= ((unsigned long long)(payload[12]&0xFF)) << 7; pts |= ((unsigned long long)(payload[13]&0xFE)) >> 1; offset -= 188; eDebug("PTS %16llx found at %lld pid %02x stream: %02x", pts, offset, pid, payload[3]); /* convert to zero-based */ if (fixed && fixupPTS(offset, pts)) return -1; return 0; } } return -1; } int eDVBTSTools::fixupPTS(const off_t &offset, pts_t &now) { if (m_streaminfo.fixupPTS(offset, now) == 0) { return 0; } else { /* for the simple case, we assume one epoch, with up to one wrap around in the middle. */ calcBegin(); if (!m_begin_valid) { eDebug("eDVBTSTools::fixupPTS begin not valid, can't fixup"); return -1; } pts_t pos = m_pts_begin; if ((now < pos) && ((pos - now) < 90000 * 10)) { pos = 0; return 0; } if (now < pos) /* wrap around */ now = now + 0x200000000LL - pos; else now -= pos; return 0; } eDebug("eDVBTSTools::fixupPTS failed!"); return -1; } int eDVBTSTools::getOffset(off_t &offset, pts_t &pts, int marg) { if (m_streaminfo.hasAccessPoints()) { if ((pts >= m_pts_end) && (marg > 0) && m_end_valid) offset = m_offset_end; else offset = m_streaminfo.getAccessPoint(pts, marg); return 0; } else { calcBeginAndEnd(); if (!m_begin_valid) return -1; if (!m_end_valid) return -1; if (!m_samples_taken) takeSamples(); if (!m_samples.empty()) { int maxtries = 5; pts_t p = -1; while (maxtries--) { /* search entry before and after */ std::map<pts_t, off_t>::const_iterator l = m_samples.lower_bound(pts); std::map<pts_t, off_t>::const_iterator u = l; if (l != m_samples.begin()) --l; /* we could have seeked beyond the end */ if (u == m_samples.end()) { /* use last segment for interpolation. */ if (l != m_samples.begin()) { --u; --l; } } /* if we don't have enough points */ if (u == m_samples.end()) break; pts_t pts_diff = u->first - l->first; off_t offset_diff = u->second - l->second; if (offset_diff < 0) { eDebug("something went wrong when taking samples."); m_samples.clear(); takeSamples(); continue; } eDebug("using: %llu:%llu -> %llu:%llu", l->first, u->first, l->second, u->second); int bitrate; if (pts_diff) bitrate = offset_diff * 90000 * 8 / pts_diff; else bitrate = 0; offset = l->second; offset += ((pts - l->first) * (pts_t)bitrate) / 8ULL / 90000ULL; offset -= offset % 188; if (offset > m_offset_end) { /* * NOTE: the bitrate calculation can be way off, especially when the pts difference is small. * So the calculated offset might be far ahead of the end of the file. * When that happens, avoid poisoning our sample list (m_samples) with an invalid value, * which could eventually cause (timeshift) playback to be stopped. * Because the file could be growing (timeshift), instead of returning the currently known end * of file offset, we return an offset 1MB ahead of the end of the file. * This allows jumping to the live point of the timeshift, for instance. */ offset = m_offset_end + 1024 * 1024; return 0; } p = pts; if (!takeSample(offset, p)) { int diff = (p - pts) / 90; eDebug("calculated diff %d ms", diff); if (abs(diff) > 300) { eDebug("diff to big, refining"); continue; } } else eDebug("no sample taken, refinement not possible."); break; } /* if even the first sample couldn't be taken, fall back. */ /* otherwise, return most refined result. */ if (p != -1) { pts = p; eDebug("aborting. Taking %llu as offset for %lld", offset, pts); return 0; } } int bitrate = calcBitrate(); offset = pts * (pts_t)bitrate / 8ULL / 90000ULL; eDebug("fallback, bitrate=%d, results in %016llx", bitrate, offset); offset -= offset % 188; return 0; } } int eDVBTSTools::getNextAccessPoint(pts_t &ts, const pts_t &start, int direction) { return m_streaminfo.getNextAccessPoint(ts, start, direction); } void eDVBTSTools::calcBegin() { if (!m_source || !m_source->valid()) return; if (!(m_begin_valid || m_futile)) { // Just ask streaminfo if (m_streaminfo.getFirstFrame(m_offset_begin, m_pts_begin) == 0) { off_t begin = m_offset_begin; pts_t pts = m_pts_begin; if (m_streaminfo.fixupPTS(begin, pts) == 0) { eDebug("[@ML] m_streaminfo.getLastFrame returned %llu, %llu (%us), fixup to: %llu, %llu (%us)", m_offset_begin, m_pts_begin, (unsigned int)(m_pts_begin/90000), begin, pts, (unsigned int)(pts/90000)); } m_begin_valid = 1; } else { m_offset_begin = 0; if (!getPTS(m_offset_begin, m_pts_begin)) m_begin_valid = 1; else m_futile = 1; } if (m_begin_valid) { /* * We've just calculated the begin position, which will have an effect on the * calculated length. * (when the end position had been determined before the begin position, the length * will be invalid) * So we force the end position to be (re-)calculated after the begin position has * been determined, in order to ensure m_pts_length will be corrected. */ m_end_valid = 0; } } } static pts_t pts_diff(pts_t low, pts_t high) { high -= low; if (high < 0) high += 0x200000000LL; return high; } void eDVBTSTools::calcEnd() { if (!m_source || !m_source->valid()) return; // If there's a structure file, the calculation is much smarter, so we can try more often off_t threshold = m_streaminfo.hasStructure() ? 100*1024 : 1024*1024; off_t end = m_source->length(); if (llabs(end - m_last_filelength) > threshold) { m_last_filelength = end; m_end_valid = 0; m_futile = 0; // eDebug("file size changed, recalc length"); } int maxiter = 10; if (!m_end_valid) { off_t offset = m_offset_end = m_last_filelength; pts_t pts = m_pts_end; if (m_streaminfo.getLastFrame(offset, pts) == 0) { m_offset_end = offset; m_pts_length = m_pts_end = pts; end = m_offset_end; if (m_streaminfo.fixupPTS(end, m_pts_length) != 0) { /* Not enough structure info, estimate */ m_pts_length = pts_diff(m_pts_begin, m_pts_end); } m_end_valid = 1; } else { eDebug("[@ML] m_streaminfo.getLastFrame failed, fallback"); while (!(m_end_valid || m_futile)) { if (!--maxiter) { m_futile = 1; return; } m_offset_end -= m_maxrange; if (m_offset_end < 0) m_offset_end = 0; offset = m_offset_end; pts = m_pts_end; if (!getPTS(offset, pts)) { offset = m_offset_end; m_pts_end = pts; m_pts_length = pts_diff(m_pts_begin, m_pts_end); m_end_valid = 1; } if (!m_offset_end) { m_futile = 1; break; } } } } } void eDVBTSTools::calcBeginAndEnd() { calcBegin(); calcEnd(); } int eDVBTSTools::calcLen(pts_t &len) { calcBeginAndEnd(); if (!(m_begin_valid && m_end_valid)) return -1; len = m_pts_length; return 0; } int eDVBTSTools::calcBitrate() { pts_t len_in_pts; if (calcLen(len_in_pts) != 0) return -1; off_t len_in_bytes = m_offset_end - m_offset_begin; if (!len_in_pts) return -1; unsigned long long bitrate = len_in_bytes * 90000 * 8 / len_in_pts; if ((bitrate < 10000) || (bitrate > 100000000)) return -1; return bitrate; } /* pts, off */ void eDVBTSTools::takeSamples() { m_samples_taken = 1; m_samples.clear(); int retries=2; calcBeginAndEnd(); if (!(m_begin_valid && m_end_valid)) return; int nr_samples = 30; off_t bytes_per_sample = (m_offset_end - m_offset_begin) / (long long)nr_samples; if (bytes_per_sample < 40*1024*1024) bytes_per_sample = 40*1024*1024; bytes_per_sample -= bytes_per_sample % 188; eDebug("samples step %lld, pts begin %llu, pts end %llu, offs begin %lld, offs end %lld:", bytes_per_sample, m_pts_begin, m_pts_end, m_offset_begin, m_offset_end); for (off_t offset = m_offset_begin; offset < m_offset_end;) { pts_t p; if (takeSample(offset, p) && retries--) continue; retries = 2; offset += bytes_per_sample; } m_samples[0] = m_offset_begin; m_samples[m_pts_end - m_pts_begin] = m_offset_end; } /* returns 0 when a sample was taken. */ int eDVBTSTools::takeSample(off_t off, pts_t &p) { off_t offset_org = off; if (!eDVBTSTools::getPTS(off, p, 1)) { /* as we are happily mixing PTS and PCR values (no comment, please), we might end up with some "negative" segments. so check if this new sample is between the previous and the next field*/ std::map<pts_t, off_t>::const_iterator l = m_samples.lower_bound(p); std::map<pts_t, off_t>::const_iterator u = l; if (l != m_samples.begin()) { --l; if (u != m_samples.end()) { if ((l->second > off) || (u->second < off)) { eDebug("ignoring sample %lld %lld %lld (%llu %llu %llu)", l->second, off, u->second, l->first, p, u->first); return 1; } } } eDebug("adding sample %lld: pts %llu -> pos %lld (diff %lld bytes)", offset_org, p, off, off-offset_org); m_samples[p] = off; return 0; } return -1; } int eDVBTSTools::findPMT(eDVBPMTParser::program &program) { int pmtpid = -1; ePtr<iDVBSectionReader> sectionreader; eDVBPMTParser::clearProgramInfo(program); /* FIXME: this will be factored out soon! */ if (!m_source || !m_source->valid()) { eDebug(" file not valid"); return -1; } off_t position=0; m_pmtready = false; for (int attempts_left = (5*1024*1024)/188; attempts_left != 0; --attempts_left) { unsigned char packet[188]; int ret = m_source->read(position, packet, 188); if (ret != 188) { eDebug("read error"); break; } position += 188; if (packet[0] != 0x47) { int i = 0; while (i < 188) { if (packet[i] == 0x47) break; --position; ++i; } continue; } if (pmtpid < 0 && !(packet[1] & 0x40)) /* pusi */ continue; /* ok, now we have a PES header or section header*/ unsigned char *sec; /* check for adaption field */ if (packet[3] & 0x20) { if (packet[4] >= 183) continue; sec = packet + packet[4] + 4 + 1; } else sec = packet + 4; if (pmtpid < 0) { if (sec[0]) /* table pointer, assumed to be 0 */ continue; if (sec[1] == 0x02) /* program map section */ { pmtpid = ((packet[1] << 8) | packet[2]) & 0x1FFF; int sid = (sec[4] << 8) | sec[5]; sectionreader = new eTSFileSectionReader(eApp); m_PMT.begin(eApp, eDVBPMTSpec(pmtpid, sid), sectionreader); ((eTSFileSectionReader*)(iDVBSectionReader*)sectionreader)->data(&sec[1], 188 - (sec + 1 - packet)); } } else if (pmtpid == (((packet[1] << 8) | packet[2]) & 0x1FFF)) { ((eTSFileSectionReader*)(iDVBSectionReader*)sectionreader)->data(sec, 188 - (sec - packet)); } if (m_pmtready) { program = m_program; return 0; } } m_PMT.stop(); return -1; } int eDVBTSTools::findFrame(off_t &_offset, size_t &len, int &direction, int frame_types) { // eDebug("trying to find iFrame at %llu", offset); if (!m_streaminfo.hasStructure()) { // eDebug("can't get next iframe without streaminfo"); return -1; } off_t offset = _offset; int nr_frames = 0; bool is_mpeg2 = false; /* let's find the iframe before the given offset */ if (direction < 0) offset--; unsigned long long longdata; if (m_streaminfo.getStructureEntryFirst(offset, longdata) != 0) { eDebug("findFrame: getStructureEntryFirst failed"); return -1; } if (direction == 0) { // Special case, move an extra frame ahead if (m_streaminfo.getStructureEntryNext(offset, longdata, 1) != 0) return -1; direction = 1; } while (1) { unsigned int data = (unsigned int)longdata; // only the lower bits are interesting /* data is usually the start code in the lower 8 bit, and the next byte <<8. we extract the picture type from there */ /* we know that we aren't recording startcode 0x09 for mpeg2, so this is safe */ /* TODO: check frame_types */ // is_frame if (((data & 0xFF) == 0x0009) || ((data & 0xFF) == 0x00)) /* H.264 UAD or MPEG2 start code */ { ++nr_frames; if ((data & 0xE0FF) == 0x0009) /* H.264 NAL unit access delimiter with I-frame*/ { break; } if ((data & 0x3800FF) == 0x080000) /* MPEG2 picture start code with I-frame */ { is_mpeg2 = true; break; } } if (m_streaminfo.getStructureEntryNext(offset, longdata, direction) != 0) return -1; } off_t start = offset; /* let's find the next frame after the given offset */ unsigned int data; do { if (m_streaminfo.getStructureEntryNext(offset, longdata, 1)) { eDebug("get next failed"); return -1; } data = ((unsigned int)longdata) & 0xFF; } while ((data != 0x09) && (data != 0x00)); /* next frame */ if (is_mpeg2) { // Seek back to sequence start (appears to be needed for e.g. a few TCM streams) while (nr_frames) { if (m_streaminfo.getStructureEntryNext(start, longdata, -1)) { eDebug("Failed to find MPEG2 start frame"); break; } if ((((unsigned int)longdata) & 0xFF) == 0xB3) /* sequence start or previous frame */ break; --nr_frames; } } /* make sure we've ended up in the right direction, ignore the result if we didn't */ if ((direction >= 0 && start < _offset) || (direction < 0 && start > _offset)) return -1; len = offset - start; _offset = start; if (direction < 0) direction = -nr_frames; else direction = nr_frames; // eDebug("result: offset=%llu, len: %ld", offset, (int)len); return 0; } int eDVBTSTools::findNextPicture(off_t &offset, size_t &len, int &distance, int frame_types) { int nr_frames, direction; // eDebug("trying to move %d frames at %llu", distance, offset); frame_types = frametypeI; /* TODO: intelligent "allow IP frames when not crossing an I-Frame */ off_t new_offset = offset; size_t new_len = len; int first = 1; if (distance > 0) { direction = 0; nr_frames = 0; } else { direction = -1; nr_frames = -1; distance = -distance+1; } while (distance > 0) { int dir = direction; if (findFrame(new_offset, new_len, dir, frame_types)) { // eDebug("findFrame failed!\n"); return -1; } distance -= abs(dir); // eDebug("we moved %d, %d to go frames (now at %llu)", dir, distance, new_offset); if (distance >= 0 || direction == 0) { first = 0; offset = new_offset; len = new_len; nr_frames += abs(dir); } else if (first) { first = 0; offset = new_offset; len = new_len; nr_frames += abs(dir) + distance; // never jump forward during rewind } } distance = (direction < 0) ? -nr_frames : nr_frames; // eDebug("in total, we moved %d frames", nr_frames); return 0; } void eDVBTSTools::PMTready(int error) { if (!error) { if (getProgramInfo(m_program) >= 0) { m_PMT.stop(); m_pmtready = true; } } }
sklnet/opendroid-enigma2
lib/dvb/tstools.cpp
C++
gpl-2.0
22,055
#============================================================================ # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser 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 #============================================================================ # Copyright (C) 2006 Anthony Liguori <aliguori@us.ibm.com> # Copyright (C) 2007 XenSource Inc. #============================================================================ from httplib import FakeSocket, HTTPConnection, HTTP import socket import string import xmlrpclib from types import StringTypes from sys import hexversion try: import SSHTransport ssh_enabled = True except ImportError: # SSHTransport is disabled on Python <2.4, because it uses the subprocess # package. ssh_enabled = False # A new ServerProxy that also supports httpu urls. An http URL comes in the # form: # # httpu:///absolute/path/to/socket.sock # # It assumes that the RPC handler is /RPC2. This probably needs to be improved class HTTPUnixConnection(HTTPConnection): def connect(self): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(self.host) class HTTPUnix(HTTP): _connection_class = HTTPUnixConnection class UnixTransport(xmlrpclib.Transport): def request(self, host, handler, request_body, verbose=0): self.__handler = handler return xmlrpclib.Transport.request(self, host, '/RPC2', request_body, verbose) def make_connection(self, host): if hexversion < 0x02070000: # python 2.6 or earlier return HTTPUnix(self.__handler) else: # xmlrpclib.Transport changed in python 2.7 return HTTPUnixConnection(self.__handler) # We need our own transport for HTTPS, because xmlrpclib.SafeTransport is # broken -- it does not handle ERROR_ZERO_RETURN properly. class HTTPSTransport(xmlrpclib.SafeTransport): def _parse_response(self, file, sock): p, u = self.getparser() while 1: try: if sock: response = sock.recv(1024) else: response = file.read(1024) except socket.sslerror, exn: if exn[0] == socket.SSL_ERROR_ZERO_RETURN: break raise if not response: break if self.verbose: print 'body:', repr(response) p.feed(response) file.close() p.close() return u.close() # See xmlrpclib2.TCPXMLRPCServer._marshalled_dispatch. def conv_string(x): if isinstance(x, StringTypes): s = string.replace(x, "'", r"\047") exec "s = '" + s + "'" return s else: return x class ServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=1): if transport == None: (protocol, rest) = uri.split(':', 1) if protocol == 'httpu': uri = 'http:' + rest transport = UnixTransport() elif protocol == 'https': transport = HTTPSTransport() elif protocol == 'ssh': global ssh_enabled if ssh_enabled: (transport, uri) = SSHTransport.getHTTPURI(uri) else: raise ValueError( "SSH transport not supported on Python <2.4.") xmlrpclib.ServerProxy.__init__(self, uri, transport, encoding, verbose, allow_none) def __request(self, methodname, params): response = xmlrpclib.ServerProxy.__request(self, methodname, params) if isinstance(response, tuple): return tuple([conv_string(x) for x in response]) else: return conv_string(response)
flexiant/xen
tools/python/xen/util/xmlrpcclient.py
Python
gpl-2.0
4,533